diff --git a/.github/workflows/oasis-canary.yml b/.github/workflows/oasis-canary.yml new file mode 100644 index 0000000000000..b131f2995c486 --- /dev/null +++ b/.github/workflows/oasis-canary.yml @@ -0,0 +1,736 @@ +name: Oasis Release Canary + +on: + workflow_dispatch: + inputs: + release_tag: + description: Existing release tag to run (vX.Y.Z.N) + required: true + type: string + +permissions: + contents: write + +env: + OBJDIR: obj-oasis-canary + PRODUCT: Firefox + BUILD_TARGET: Darwin_aarch64-gcc3 + LOCALE: en-US + RING: oasis-canary + OASIS_RCODESIGN_VERSION: 0.27.0 + +jobs: + build-sign-release: + runs-on: macos-15 + environment: canary-signing + steps: + - name: Checkout selected ref + uses: actions/checkout@v4 + with: + ref: ${{ github.event_name == 'workflow_dispatch' && format('refs/tags/{0}', inputs.release_tag) || github.ref }} + + - name: Resolve version from tag + id: version + run: | + set -euo pipefail + if [ "${GITHUB_EVENT_NAME}" = "workflow_dispatch" ]; then + TAG="${{ inputs.release_tag }}" + else + TAG="${GITHUB_REF_NAME}" + fi + if ! [[ "${TAG}" =~ ^v[0-9]+(\.[0-9]+){3}$ ]]; then + echo "Tag must match vX.Y.Z.N (numeric dot notation)." >&2 + exit 1 + fi + VERSION="${TAG#v}" + if ! [[ "${VERSION}" =~ ^[0-9]+(\.[0-9]+){3}$ ]]; then + echo "Version must match X.Y.Z.N (numeric dot notation)." >&2 + exit 1 + fi + echo "tag=${TAG}" >> "${GITHUB_OUTPUT}" + echo "version=${VERSION}" >> "${GITHUB_OUTPUT}" + + - name: Export build overrides + env: + OASIS_UPDATE_SERVICE_URL: ${{ secrets.OASIS_UPDATE_SERVICE_URL }} + run: | + set -euo pipefail + if [ -z "${OASIS_UPDATE_SERVICE_URL:-}" ]; then + echo "Missing OASIS_UPDATE_SERVICE_URL for build overrides." >&2 + exit 1 + fi + VERSION="${{ steps.version.outputs.version }}" + UPDATE_URL="${OASIS_UPDATE_SERVICE_URL%/}/update/6/%PRODUCT%/%VERSION%/%BUILD_ID%/%BUILD_TARGET%/%LOCALE%/%CHANNEL%/%OS_VERSION%/%SYSTEM_CAPABILITIES%/%DISTRIBUTION%/%DISTRIBUTION_VERSION%/update.xml" + echo "OASIS_APP_VERSION=${VERSION}" >> "${GITHUB_ENV}" + echo "OASIS_APP_VERSION_DISPLAY=${VERSION}" >> "${GITHUB_ENV}" + echo "MOZ_APPUPDATE_URL=${UPDATE_URL}" >> "${GITHUB_ENV}" + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: "20" + cache: npm + cache-dependency-path: | + browser/base/content/assistant/build/package-lock.json + browser/base/content/assistant/ui-preact/package-lock.json + + - name: Restore rcodesign cache + uses: actions/cache@v4 + with: + path: ~/.local/rcodesign + key: ${{ runner.os }}-${{ runner.arch }}-rcodesign-${{ env.OASIS_RCODESIGN_VERSION }}-v1 + + - name: Build assistant bundles + run: | + set -euo pipefail + npm ci --prefix browser/base/content/assistant/ui-preact + npm run build --prefix browser/base/content/assistant/ui-preact + npm ci --prefix browser/base/content/assistant/build + npm run build --prefix browser/base/content/assistant/build + + - name: Create CI mozconfig + run: | + set -euo pipefail + CI_MOZCONFIG="${RUNNER_TEMP}/mozconfig-oasis-canary" + cat > "${CI_MOZCONFIG}" <<'EOF' + mk_add_options MOZ_OBJDIR=@TOPSRCDIR@/obj-oasis-canary + ac_add_options --enable-application=browser + ac_add_options --with-branding=browser/branding/custom + ac_add_options --enable-release + ac_add_options --disable-debug + ac_add_options --enable-optimize + ac_add_options --disable-crashreporter + ac_add_options --enable-updater + ac_add_options --enable-update-channel=oasis-canary + export MOZ_INCLUDE_SOURCE_INFO= + export MOZ_DISABLE_SOURCE_INFO=1 + EOF + echo "MOZCONFIG=${CI_MOZCONFIG}" >> "${GITHUB_ENV}" + + - name: Select Xcode 26.2 + run: | + set -euo pipefail + XCODE_DEVELOPER_DIR="/Applications/Xcode_26.2.app/Contents/Developer" + if [ ! -d "${XCODE_DEVELOPER_DIR}" ]; then + echo "Missing Xcode 26.2 at ${XCODE_DEVELOPER_DIR}" >&2 + exit 1 + fi + sudo xcode-select -s "${XCODE_DEVELOPER_DIR}" + xcodebuild -version + xcrun --sdk macosx --show-sdk-version + + - name: Install rcodesign + run: | + set -euo pipefail + case "${RUNNER_ARCH}" in + ARM64) + PRIMARY_ARCH="aarch64-apple-darwin" + FALLBACK_ARCH="x86_64-apple-darwin" + ;; + X64) + PRIMARY_ARCH="x86_64-apple-darwin" + FALLBACK_ARCH="aarch64-apple-darwin" + ;; + *) + echo "Unsupported RUNNER_ARCH: ${RUNNER_ARCH}" >&2 + exit 1 + ;; + esac + + RELEASE_BASE="https://github.com/indygreg/apple-platform-rs/releases/download/apple-codesign%2F${OASIS_RCODESIGN_VERSION}" + INSTALL_ROOT="${HOME}/.local/rcodesign/${OASIS_RCODESIGN_VERSION}" + + install_rcodesign() { + local target_arch="$1" + local install_dir="${INSTALL_ROOT}/${target_arch}" + local tar_name="apple-codesign-${OASIS_RCODESIGN_VERSION}-${target_arch}.tar.gz" + local tar_url="${RELEASE_BASE}/${tar_name}" + local sha_url="${tar_url}.sha256" + + mkdir -p "${install_dir}" + if [ -x "${install_dir}/rcodesign" ]; then + echo "Using cached rcodesign from ${install_dir}" + export PATH="${install_dir}:${PATH}" + echo "${install_dir}" >> "${GITHUB_PATH}" + echo "OASIS_RCODESIGN_BIN=${install_dir}/rcodesign" >> "${GITHUB_ENV}" + return 0 + fi + + tmpdir="$(mktemp -d)" + + curl -fL "${tar_url}" -o "${tmpdir}/${tar_name}" || { + rm -rf "${tmpdir}" + return 1 + } + curl -fL "${sha_url}" -o "${tmpdir}/${tar_name}.sha256" || { + rm -rf "${tmpdir}" + return 1 + } + + expected_sha="$(awk '{print $1}' "${tmpdir}/${tar_name}.sha256" | tr -d '\r\n')" + if ! [[ "${expected_sha}" =~ ^[0-9a-fA-F]{64}$ ]]; then + echo "Invalid SHA256 content in ${tar_name}.sha256: ${expected_sha}" >&2 + rm -rf "${tmpdir}" + return 1 + fi + actual_sha="$(shasum -a 256 "${tmpdir}/${tar_name}" | awk '{print $1}')" + if [ "${actual_sha}" != "${expected_sha}" ]; then + echo "SHA256 mismatch for ${tar_name}" >&2 + echo "Expected: ${expected_sha}" >&2 + echo "Actual: ${actual_sha}" >&2 + rm -rf "${tmpdir}" + return 1 + fi + + tar -xzf "${tmpdir}/${tar_name}" -C "${tmpdir}" || { + rm -rf "${tmpdir}" + return 1 + } + rcodesign_path="$(find "${tmpdir}" -type f -name rcodesign | head -n1)" + if [ -z "${rcodesign_path}" ]; then + echo "rcodesign binary missing from ${tar_name}" >&2 + rm -rf "${tmpdir}" + return 1 + fi + + cp "${rcodesign_path}" "${install_dir}/rcodesign" || { + rm -rf "${tmpdir}" + return 1 + } + chmod 755 "${install_dir}/rcodesign" + rm -rf "${tmpdir}" + export PATH="${install_dir}:${PATH}" + echo "${install_dir}" >> "${GITHUB_PATH}" + echo "OASIS_RCODESIGN_BIN=${install_dir}/rcodesign" >> "${GITHUB_ENV}" + return 0 + } + + if ! install_rcodesign "${PRIMARY_ARCH}"; then + echo "Primary rcodesign archive failed, trying fallback ${FALLBACK_ARCH}." >&2 + install_rcodesign "${FALLBACK_ARCH}" + fi + + command -v rcodesign + rcodesign --version + + - name: Probe rcodesign CLI + run: | + set -euo pipefail + if ! rcodesign sign --help | grep -Eq -- "--entitlements-xml-(path|file)"; then + echo "Installed rcodesign is missing entitlements XML flag support." >&2 + exit 1 + fi + if ! rcodesign sign --help | grep -q -- "--p12-password-file"; then + echo "Installed rcodesign is missing --p12-password-file support." >&2 + exit 1 + fi + + - name: Prepare Apple signing keychain + env: + OASIS_APPLE_DEVELOPER_ID_P12_B64: ${{ secrets.OASIS_APPLE_DEVELOPER_ID_P12_B64 }} + OASIS_APPLE_DEVELOPER_ID_P12_PASSWORD: ${{ secrets.OASIS_APPLE_DEVELOPER_ID_P12_PASSWORD }} + run: | + set -euo pipefail + if [ -z "${OASIS_APPLE_DEVELOPER_ID_P12_B64}" ] || [ -z "${OASIS_APPLE_DEVELOPER_ID_P12_PASSWORD}" ]; then + echo "Missing Apple Developer ID certificate secrets." >&2 + exit 1 + fi + KEYCHAIN_PATH="${RUNNER_TEMP}/oasis-signing.keychain-db" + KEYCHAIN_PASSWORD="$(python3 -c 'import secrets; print(secrets.token_urlsafe(32))')" + P12_PATH="${RUNNER_TEMP}/oasis-developer-id.p12" + P12_PASSWORD_FILE="${RUNNER_TEMP}/oasis-developer-id-password.txt" + + # Decode the P12 from secrets + python3 -c 'import base64, os, sys; sys.stdout.buffer.write(base64.b64decode(os.environ["OASIS_APPLE_DEVELOPER_ID_P12_B64"]))' > "${P12_PATH}" + printf '%s' "${OASIS_APPLE_DEVELOPER_ID_P12_PASSWORD}" > "${P12_PASSWORD_FILE}" + chmod 600 "${P12_PATH}" "${P12_PASSWORD_FILE}" + + # Create and configure the temporary keychain + ORIGINAL_KEYCHAINS="$(security list-keychains -d user | tr -d '"')" + security create-keychain -p "${KEYCHAIN_PASSWORD}" "${KEYCHAIN_PATH}" + security set-keychain-settings -lut 21600 "${KEYCHAIN_PATH}" + security unlock-keychain -p "${KEYCHAIN_PASSWORD}" "${KEYCHAIN_PATH}" + + # Add to keychain search list + security list-keychains -d user -s "${KEYCHAIN_PATH}" ${ORIGINAL_KEYCHAINS} + security default-keychain -d user -s "${KEYCHAIN_PATH}" + + # Import the certificate/key (allow codesign access) + security import "${P12_PATH}" -k "${KEYCHAIN_PATH}" -P "${OASIS_APPLE_DEVELOPER_ID_P12_PASSWORD}" -A -T /usr/bin/codesign -T /usr/bin/security + security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "${KEYCHAIN_PASSWORD}" "${KEYCHAIN_PATH}" + + # Export env vars for cleanup + echo "OASIS_APPLE_KEYCHAIN_PATH=${KEYCHAIN_PATH}" >> "${GITHUB_ENV}" + echo "OASIS_APPLE_KEYCHAIN_PASSWORD=${KEYCHAIN_PASSWORD}" >> "${GITHUB_ENV}" + echo "OASIS_APPLE_DEVELOPER_ID_P12_PATH=${P12_PATH}" >> "${GITHUB_ENV}" + echo "OASIS_APPLE_DEVELOPER_ID_P12_PASSWORD_FILE=${P12_PASSWORD_FILE}" >> "${GITHUB_ENV}" + echo "OASIS_APPLE_KEYCHAIN_ORIGINAL_LIST<> "${GITHUB_ENV}" + echo "${ORIGINAL_KEYCHAINS}" >> "${GITHUB_ENV}" + echo "EOF" >> "${GITHUB_ENV}" + + - name: Validate PKCS12 with password file + run: | + set -euo pipefail + openssl pkcs12 \ + -in "${OASIS_APPLE_DEVELOPER_ID_P12_PATH}" \ + -passin "file:${OASIS_APPLE_DEVELOPER_ID_P12_PASSWORD_FILE}" \ + -nokeys -noout >/dev/null + + - name: Build and stage package + run: | + set -euo pipefail + unset MOZ_AUTOMATION + # 1. Build binaries + ./mach build + + # 2. Stage package (resolves symlinks, creates dist/firefox structure) + # We use make directly to bypass mach package's DMG creation logic for now + make -C "${OBJDIR}/browser/installer" stage-package + + # 3. Resolve variables needed for packaging + # We extract these from the make environment + MOZ_PKG_DIR=$(make -s -C "${OBJDIR}/browser/installer" echo-variable-MOZ_PKG_DIR) + APP_NAME=$(make -s -C "${OBJDIR}/browser/installer" echo-variable-_APPNAME) + PACKAGE=$(make -s -C "${OBJDIR}/browser/installer" echo-variable-PACKAGE) + VOLUME_NAME=$(make -s -C "${OBJDIR}/browser/installer" echo-variable-MOZ_APP_DISPLAYNAME) + DSSTORE_PATH=$(make -s -C "${OBJDIR}/browser/installer" echo-variable-MOZ_PKG_MAC_DSSTORE || true) + BACKGROUND_PATH=$(make -s -C "${OBJDIR}/browser/installer" echo-variable-MOZ_PKG_MAC_BACKGROUND || true) + ICON_PATH=$(make -s -C "${OBJDIR}/browser/installer" echo-variable-MOZ_PKG_MAC_ICON || true) + + PKG_APP="${OBJDIR}/dist/${MOZ_PKG_DIR}/${APP_NAME}" + DMG_PATH="${OBJDIR}/dist/${PACKAGE}" + + echo "PKG_APP=${PKG_APP}" >> "${GITHUB_ENV}" + echo "DMG_PATH=${DMG_PATH}" >> "${GITHUB_ENV}" + echo "MOZ_PKG_DIR=${MOZ_PKG_DIR}" >> "${GITHUB_ENV}" + echo "VOLUME_NAME=${VOLUME_NAME}" >> "${GITHUB_ENV}" + echo "DSSTORE_PATH=${DSSTORE_PATH}" >> "${GITHUB_ENV}" + echo "BACKGROUND_PATH=${BACKGROUND_PATH}" >> "${GITHUB_ENV}" + echo "ICON_PATH=${ICON_PATH}" >> "${GITHUB_ENV}" + + - name: Verify staged version + id: meta + run: | + set -euo pipefail + APP_INI="${PKG_APP}/Contents/Resources/application.ini" + EXPECTED_VERSION="${{ steps.version.outputs.version }}" + VERSION="$(awk -F= '/^Version=/{print $2}' "${APP_INI}")" + BUILD_ID="$(awk -F= '/^BuildID=/{print $2}' "${APP_INI}")" + + if [ "${VERSION}" != "${EXPECTED_VERSION}" ]; then + echo "Staged version mismatch: expected ${EXPECTED_VERSION}, got ${VERSION}" >&2 + exit 1 + fi + EXECUTABLE_PATH="" + for candidate in Oasis firefox firefox-bin; do + if [ -f "${PKG_APP}/Contents/MacOS/${candidate}" ]; then + EXECUTABLE_PATH="${PKG_APP}/Contents/MacOS/${candidate}" + break + fi + done + if [ -z "${EXECUTABLE_PATH}" ]; then + echo "Could not find executable under ${PKG_APP}/Contents/MacOS" >&2 + exit 1 + fi + echo "version=${VERSION}" >> "${GITHUB_OUTPUT}" + echo "build_id=${BUILD_ID}" >> "${GITHUB_OUTPUT}" + echo "executable_path=${EXECUTABLE_PATH}" >> "${GITHUB_OUTPUT}" + + - name: Validate staged update URL + env: + OASIS_UPDATE_SERVICE_URL: ${{ secrets.OASIS_UPDATE_SERVICE_URL }} + run: | + set -euo pipefail + if [ -z "${OASIS_UPDATE_SERVICE_URL:-}" ]; then + echo "Missing OASIS_UPDATE_SERVICE_URL secret for update URL validation." >&2 + exit 1 + fi + + APP_INI="${PKG_APP}/Contents/Resources/application.ini" + UPDATE_URL="$(awk -F= '/^URL=/{print $2; exit}' "${APP_INI}")" + if [ -z "${UPDATE_URL}" ]; then + echo "App update URL missing in ${APP_INI}" >&2 + exit 1 + fi + if [[ "${UPDATE_URL}" == *"aus5.mozilla.org"* ]]; then + echo "App update URL still points to Mozilla AUS: ${UPDATE_URL}" >&2 + exit 1 + fi + + SERVICE_BASE="${OASIS_UPDATE_SERVICE_URL%/}" + EXPECTED_PREFIX="${SERVICE_BASE}/update/6/" + if [[ "${UPDATE_URL}" != "${EXPECTED_PREFIX}"* ]]; then + echo "App update URL does not point to Oasis update service." >&2 + echo "Expected prefix: ${EXPECTED_PREFIX}" >&2 + echo "Actual URL: ${UPDATE_URL}" >&2 + exit 1 + fi + if [[ "${UPDATE_URL}" != *"/%CHANNEL%/"* ]]; then + echo "App update URL missing %CHANNEL% placeholder: ${UPDATE_URL}" >&2 + exit 1 + fi + + echo "Validated update URL: ${UPDATE_URL}" + + - name: Prepare and sign app bundle (rcodesign) + run: | + set -euo pipefail + + find "${PKG_APP}" \( -name ".mkdir.done" -o -name "*.done" \) -delete + + if find "${PKG_APP}" -type l -print -quit | grep -q .; then + echo "Refusing to sign app with symlinks still present: ${PKG_APP}" >&2 + find "${PKG_APP}" -type l | head -n 20 >&2 || true + exit 1 + fi + + ./mach macos-sign \ + -a "${PKG_APP}" \ + -r \ + -f "${OASIS_APPLE_DEVELOPER_ID_P12_PATH}" \ + -p "${OASIS_APPLE_DEVELOPER_ID_P12_PASSWORD_FILE}" \ + -e production-without-restricted \ + -c release \ + -v + + codesign --verify --deep --strict --verbose=2 "${PKG_APP}" + + - name: Prepare notary API key + env: + OASIS_APPLE_API_KEY_ID: ${{ secrets.OASIS_APPLE_API_KEY_ID }} + OASIS_APPLE_API_ISSUER: ${{ secrets.OASIS_APPLE_API_ISSUER }} + OASIS_APPLE_API_KEY_P8_B64: ${{ secrets.OASIS_APPLE_API_KEY_P8_B64 }} + run: | + set -euo pipefail + if [ -z "${OASIS_APPLE_API_KEY_ID}" ] || [ -z "${OASIS_APPLE_API_ISSUER}" ] || [ -z "${OASIS_APPLE_API_KEY_P8_B64}" ]; then + echo "Missing one or more App Store Connect API key secrets." >&2 + exit 1 + fi + NOTARY_KEY_PATH="${RUNNER_TEMP}/AuthKey_${OASIS_APPLE_API_KEY_ID}.p8" + python3 -c 'import base64, os, sys; sys.stdout.buffer.write(base64.b64decode(os.environ["OASIS_APPLE_API_KEY_P8_B64"]))' > "${NOTARY_KEY_PATH}" + chmod 600 "${NOTARY_KEY_PATH}" + echo "OASIS_NOTARY_KEY_PATH=${NOTARY_KEY_PATH}" >> "${GITHUB_ENV}" + echo "OASIS_APPLE_API_KEY_ID=${OASIS_APPLE_API_KEY_ID}" >> "${GITHUB_ENV}" + echo "OASIS_APPLE_API_ISSUER=${OASIS_APPLE_API_ISSUER}" >> "${GITHUB_ENV}" + + - name: Notarize and staple app bundle + run: | + set -euo pipefail + if [ -z "${OASIS_NOTARY_KEY_PATH:-}" ] || [ -z "${OASIS_APPLE_API_KEY_ID:-}" ] || [ -z "${OASIS_APPLE_API_ISSUER:-}" ]; then + echo "Missing API key notarization inputs." >&2 + exit 1 + fi + VERSION="${{ steps.meta.outputs.version }}" + NOTARY_ZIP="${RUNNER_TEMP}/oasis-app-notary-${VERSION}.zip" + + # Create zip for notarization + ditto -c -k --keepParent "${PKG_APP}" "${NOTARY_ZIP}" + + # Validation checks + ZIP_SIZE="$(stat -f%z "${NOTARY_ZIP}")" + if [ "${ZIP_SIZE}" -lt 52428800 ]; then + echo "ZIP payload too small." >&2; exit 1 + fi + if command -v zipinfo >/dev/null 2>&1; then + ZIP_ENTRIES="$(zipinfo -1 "${NOTARY_ZIP}")" + else + ZIP_ENTRIES="$(unzip -Z1 "${NOTARY_ZIP}")" + fi + if echo "${ZIP_ENTRIES}" | grep -q "^__MACOSX/"; then + echo "ZIP payload contains __MACOSX, refusing notarization submit." >&2 + exit 1 + fi + if ! echo "${ZIP_ENTRIES}" | grep -Eq '/Contents/MacOS/(Oasis|firefox|firefox-bin)$'; then + echo "ZIP payload missing expected executable under Contents/MacOS." >&2 + echo "${ZIP_ENTRIES}" | grep '/Contents/MacOS/' | head -n 30 >&2 || true + exit 1 + fi + + max_attempts=12 + backoffs=(30 60 120 180 240 300 300 300 300 300 300) + RETRYABLE_NOTARY_RE='statusCode: 50[0-4]|HTTP status code: 50[0-4]|UNEXPECTED_ERROR|HTTP status code: 408|HTTP status code: 429|NSURLErrorDomain Code=-(1001|1003|1004|1005|1006|1009)|The Internet connection appears to be offline|No network route|timed out|network connection was lost|cannot find host|could not resolve host' + attempt=1 + while true; do + notary_log="$(mktemp)" + if xcrun notarytool submit "${NOTARY_ZIP}" \ + --key "${OASIS_NOTARY_KEY_PATH}" \ + --key-id "${OASIS_APPLE_API_KEY_ID}" \ + --issuer "${OASIS_APPLE_API_ISSUER}" \ + --wait --verbose > "${notary_log}" 2>&1 + then + cat "${notary_log}" + rm -f "${notary_log}" + break + fi + cat "${notary_log}" >&2 + if ! grep -Eiq "${RETRYABLE_NOTARY_RE}" "${notary_log}"; then + echo "Non-retryable notarization failure." >&2 + rm -f "${notary_log}" + exit 1 + fi + if [ "${attempt}" -ge "${max_attempts}" ]; then + echo "Notarization failed after ${attempt} attempts." >&2 + rm -f "${notary_log}" + exit 1 + fi + sleep_seconds="${backoffs[$((attempt - 1))]}" + echo "Notarization attempt ${attempt} failed with transient notarization/network error. Retrying in ${sleep_seconds}s..." >&2 + rm -f "${notary_log}" + sleep "${sleep_seconds}" + attempt=$((attempt + 1)) + done + + # Staple + xcrun stapler staple "${PKG_APP}" + xcrun stapler validate "${PKG_APP}" + spctl -a -vv "${PKG_APP}" + echo "OASIS_APPLE_NOTARY_APP_ZIP=${NOTARY_ZIP}" >> "${GITHUB_ENV}" + + - name: Record post-notarization executable hash + id: golden_hash + run: | + set -euo pipefail + HASH="$(shasum -a 256 "${{ steps.meta.outputs.executable_path }}" | awk '{print $1}')" + echo "hash=${HASH}" >> "${GITHUB_OUTPUT}" + + - name: Create signed DMG + env: + OASIS_APPLE_SIGNING_IDENTITY: ${{ secrets.OASIS_APPLE_SIGNING_IDENTITY }} + run: | + set -euo pipefail + if [ -z "${OASIS_APPLE_SIGNING_IDENTITY}" ]; then + echo "Missing OASIS_APPLE_SIGNING_IDENTITY for DMG signing." >&2 + exit 1 + fi + + # Create DMG using Mozilla tool + # This wraps the ALREADY SIGNED/NOTARIZED app from PKG_APP + args=() + if [ -n "${DSSTORE_PATH:-}" ]; then + args+=(--dsstore "${DSSTORE_PATH}") + fi + if [ -n "${BACKGROUND_PATH:-}" ]; then + args+=(--background "${BACKGROUND_PATH}") + fi + if [ -n "${ICON_PATH:-}" ]; then + args+=(--icon "${ICON_PATH}") + fi + if [ -n "${VOLUME_NAME:-}" ]; then + args+=(--volume-name "${VOLUME_NAME}") + fi + + ./mach python -m mozbuild.action.make_dmg "${args[@]}" \ + "${OBJDIR}/dist/${MOZ_PKG_DIR}" \ + "${DMG_PATH}" + + # Sign the DMG container (Requires Keychain/codesign) + codesign --keychain "${OASIS_APPLE_KEYCHAIN_PATH}" --force --timestamp --sign "${OASIS_APPLE_SIGNING_IDENTITY}" "${DMG_PATH}" + codesign -dv --verbose=4 "${DMG_PATH}" + + - name: Notarize and staple DMG + run: | + set -euo pipefail + if [ -z "${OASIS_NOTARY_KEY_PATH:-}" ] || [ -z "${OASIS_APPLE_API_KEY_ID:-}" ] || [ -z "${OASIS_APPLE_API_ISSUER:-}" ]; then + echo "Missing API key notarization inputs." >&2 + exit 1 + fi + + max_attempts=12 + backoffs=(30 60 120 180 240 300 300 300 300 300 300) + RETRYABLE_NOTARY_RE='statusCode: 50[0-4]|HTTP status code: 50[0-4]|UNEXPECTED_ERROR|HTTP status code: 408|HTTP status code: 429|NSURLErrorDomain Code=-(1001|1003|1004|1005|1006|1009)|The Internet connection appears to be offline|No network route|timed out|network connection was lost|cannot find host|could not resolve host' + attempt=1 + while true; do + notary_log="$(mktemp)" + if xcrun notarytool submit "${DMG_PATH}" \ + --key "${OASIS_NOTARY_KEY_PATH}" \ + --key-id "${OASIS_APPLE_API_KEY_ID}" \ + --issuer "${OASIS_APPLE_API_ISSUER}" \ + --wait --verbose > "${notary_log}" 2>&1 + then + cat "${notary_log}" + rm -f "${notary_log}" + break + fi + cat "${notary_log}" >&2 + if ! grep -Eiq "${RETRYABLE_NOTARY_RE}" "${notary_log}"; then + echo "Non-retryable notarization failure." >&2 + rm -f "${notary_log}" + exit 1 + fi + if [ "${attempt}" -ge "${max_attempts}" ]; then + echo "Notarization failed after ${attempt} attempts." >&2 + rm -f "${notary_log}" + exit 1 + fi + sleep_seconds="${backoffs[$((attempt - 1))]}" + echo "Notarization attempt ${attempt} failed with transient notarization/network error. Retrying in ${sleep_seconds}s..." >&2 + rm -f "${notary_log}" + sleep "${sleep_seconds}" + attempt=$((attempt + 1)) + done + + # Staple DMG + xcrun stapler staple "${DMG_PATH}" + xcrun stapler validate "${DMG_PATH}" + + - name: Verify golden executable hash before MAR + run: | + set -euo pipefail + EXPECTED_HASH="${{ steps.golden_hash.outputs.hash }}" + CURRENT_HASH="$(shasum -a 256 "${{ steps.meta.outputs.executable_path }}" | awk '{print $1}')" + if [ "${CURRENT_HASH}" != "${EXPECTED_HASH}" ]; then + echo "Golden executable changed after app notarization; refusing MAR build." >&2 + echo "Expected: ${EXPECTED_HASH}" >&2 + echo "Actual: ${CURRENT_HASH}" >&2 + exit 1 + fi + + - name: Check updater cert material + env: + ALLOW_DEV_OASIS_CERTS: ${{ vars.ALLOW_DEV_OASIS_CERTS }} + run: | + set -euo pipefail + scripts/update-signing/check-oasis-cert-material.sh + + - name: Build complete MAR + id: mar + run: | + set -euo pipefail + VERSION="${{ steps.meta.outputs.version }}" + UPDATE_DIR="${OBJDIR}/dist/update" + mkdir -p "${UPDATE_DIR}" + UNSIGNED_MAR="${UPDATE_DIR}/oasis-${VERSION}-${BUILD_TARGET}-${LOCALE}.complete.mar" + SIGNED_MAR="${UPDATE_DIR}/oasis-${VERSION}-${BUILD_TARGET}-${LOCALE}.signed.complete.mar" + + # Use the GOLDEN APP (PKG_APP) which is signed/stapled + scripts/update-signing/build-complete-mar.sh \ + "${OBJDIR}" \ + "${PKG_APP}" \ + "${UNSIGNED_MAR}" \ + "${VERSION}" \ + "${RING}" + + echo "unsigned_mar=${UNSIGNED_MAR}" >> "${GITHUB_OUTPUT}" + echo "signed_mar=${SIGNED_MAR}" >> "${GITHUB_OUTPUT}" + + - name: Sign and verify MAR + env: + OASIS_MAR_SIGNING_CERT_NICKNAME: ${{ secrets.OASIS_MAR_SIGNING_CERT_NICKNAME }} + OASIS_MAR_SIGNING_P12_B64: ${{ secrets.OASIS_MAR_SIGNING_P12_B64 }} + OASIS_MAR_SIGNING_P12_PASSWORD: ${{ secrets.OASIS_MAR_SIGNING_P12_PASSWORD }} + run: | + set -euo pipefail + if [ -z "${OASIS_MAR_SIGNING_CERT_NICKNAME}" ] || [ -z "${OASIS_MAR_SIGNING_P12_B64}" ] || [ -z "${OASIS_MAR_SIGNING_P12_PASSWORD}" ]; then + echo "Missing one or more signing secrets." >&2 + exit 1 + fi + NSS_DB_DIR="${RUNNER_TEMP}/oasis-nssdb" + P12_PATH="${RUNNER_TEMP}/oasis-signing.p12" + mkdir -p "${NSS_DB_DIR}" + python3 -c 'import base64, os, sys; sys.stdout.buffer.write(base64.b64decode(os.environ["OASIS_MAR_SIGNING_P12_B64"]))' > "${P12_PATH}" + "${OBJDIR}/dist/bin/certutil" -N -d "sql:${NSS_DB_DIR}" --empty-password + "${OBJDIR}/dist/bin/pk12util" -i "${P12_PATH}" -d "sql:${NSS_DB_DIR}" -W "${OASIS_MAR_SIGNING_P12_PASSWORD}" + scripts/update-signing/sign-mar.sh \ + "${OBJDIR}" \ + "${{ steps.mar.outputs.unsigned_mar }}" \ + "${{ steps.mar.outputs.signed_mar }}" \ + "${NSS_DB_DIR}" \ + "${OASIS_MAR_SIGNING_CERT_NICKNAME}" + scripts/update-signing/verify-mar.sh \ + "${OBJDIR}" \ + "${{ steps.mar.outputs.signed_mar }}" \ + toolkit/mozapps/update/updater/oasis_primary.der + rm -f "${P12_PATH}" + rm -rf "${NSS_DB_DIR}" + + - name: Prepare canary release metadata + id: release_meta + run: | + set -euo pipefail + VERSION="${{ steps.meta.outputs.version }}" + SAFE_TARGET="$(echo "${BUILD_TARGET}" | tr '/ ' '__')" + TAG="canary" + ASSET_NAME="oasis-${VERSION}-${SAFE_TARGET}-${LOCALE}.signed.complete.mar" + DMG_ASSET_NAME="oasis-${VERSION}-${SAFE_TARGET}-${LOCALE}.mac.dmg" + MAR_URL="https://github.com/${{ github.repository }}/releases/download/${TAG}/${ASSET_NAME}" + DMG_URL="https://github.com/${{ github.repository }}/releases/download/${TAG}/${DMG_ASSET_NAME}" + echo "tag=${TAG}" >> "${GITHUB_OUTPUT}" + echo "asset_name=${ASSET_NAME}" >> "${GITHUB_OUTPUT}" + echo "dmg_asset_name=${DMG_ASSET_NAME}" >> "${GITHUB_OUTPUT}" + echo "mar_url=${MAR_URL}" >> "${GITHUB_OUTPUT}" + echo "dmg_url=${DMG_URL}" >> "${GITHUB_OUTPUT}" + + - name: Ensure canary release exists + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + TAG="${{ steps.release_meta.outputs.tag }}" + if gh release view "${TAG}" > /dev/null 2>&1; then + gh release edit "${TAG}" --title "Canary Builds" --prerelease + else + gh release create "${TAG}" \ + --title "Canary Builds" \ + --notes "Rolling canary artifacts. Assets are appended by automation." \ + --prerelease + fi + + - name: Upload assets to canary release + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + TAG="${{ steps.release_meta.outputs.tag }}" + ASSET_NAME="${{ steps.release_meta.outputs.asset_name }}" + DMG_ASSET_NAME="${{ steps.release_meta.outputs.dmg_asset_name }}" + SIGNED_MAR="${{ steps.mar.outputs.signed_mar }}" + PACKAGED_DMG="${DMG_PATH}" + gh release upload "${TAG}" \ + "${SIGNED_MAR}#${ASSET_NAME}" \ + "${PACKAGED_DMG}#${DMG_ASSET_NAME}" \ + --clobber + + - name: Register artifact and move ring pointer + env: + OASIS_ADMIN_TOKEN: ${{ secrets.OASIS_UPDATE_ADMIN_TOKEN }} + OASIS_UPDATE_SERVICE_URL: ${{ secrets.OASIS_UPDATE_SERVICE_URL }} + run: | + set -euo pipefail + VERSION="${{ steps.meta.outputs.version }}" + BUILD_ID="${{ steps.meta.outputs.build_id }}" + python3 tools/oasis-update-service/publish_update.py \ + --service "${OASIS_UPDATE_SERVICE_URL}" \ + --admin-token "${OASIS_ADMIN_TOKEN}" \ + --product "${PRODUCT}" \ + --version "${VERSION}" \ + --build-id "${BUILD_ID}" \ + --build-target "${BUILD_TARGET}" \ + --locale "${LOCALE}" \ + --mar-url "${{ steps.release_meta.outputs.mar_url }}" \ + --mar-path "${{ steps.mar.outputs.signed_mar }}" \ + --ring "${RING}" \ + --actor github-actions \ + --reason "canary bucket publish (run ${GITHUB_RUN_ID}, source tag ${{ steps.version.outputs.tag }}, sha ${GITHUB_SHA})" + + - name: Print release asset URLs + run: | + set -euo pipefail + echo "MAR: ${{ steps.release_meta.outputs.mar_url }}" + echo "DMG: ${{ steps.release_meta.outputs.dmg_url }}" + + - name: Cleanup signing and notarization material + if: always() + run: | + set +e + # Keychain cleanup + if [ -n "${OASIS_APPLE_KEYCHAIN_ORIGINAL_LIST:-}" ]; then + security list-keychains -d user -s ${OASIS_APPLE_KEYCHAIN_ORIGINAL_LIST} + fi + if [ -n "${OASIS_APPLE_KEYCHAIN_PATH:-}" ]; then + security default-keychain -d user -s login.keychain-db + security delete-keychain "${OASIS_APPLE_KEYCHAIN_PATH}" + fi + rm -f "${OASIS_APPLE_DEVELOPER_ID_P12_PATH:-}" + rm -f "${OASIS_APPLE_DEVELOPER_ID_P12_PASSWORD_FILE:-}" + rm -f "${OASIS_APPLE_NOTARY_APP_ZIP:-}" + rm -f "${OASIS_NOTARY_KEY_PATH:-}" diff --git a/.github/workflows/oasis-release.yml b/.github/workflows/oasis-release.yml new file mode 100644 index 0000000000000..c6f1a03897e54 --- /dev/null +++ b/.github/workflows/oasis-release.yml @@ -0,0 +1,706 @@ +name: Oasis Release Publish + +on: + workflow_dispatch: + inputs: + release_tag: + description: Existing release tag to run (vX.Y.Z.N) + required: true + type: string + +permissions: + contents: write + +env: + OBJDIR: obj-oasis-release + PRODUCT: Firefox + BUILD_TARGET: Darwin_aarch64-gcc3 + LOCALE: en-US + RING: oasis-stable + OASIS_RCODESIGN_VERSION: 0.27.0 + +jobs: + build-sign-release: + runs-on: macos-15 + environment: canary-signing + steps: + - name: Checkout selected ref + uses: actions/checkout@v4 + with: + ref: ${{ github.event_name == 'workflow_dispatch' && format('refs/tags/{0}', inputs.release_tag) || github.ref }} + + - name: Resolve version from tag + id: version + run: | + set -euo pipefail + if [ "${GITHUB_EVENT_NAME}" = "workflow_dispatch" ]; then + TAG="${{ inputs.release_tag }}" + else + TAG="${GITHUB_REF_NAME}" + fi + if ! [[ "${TAG}" =~ ^v[0-9]+(\.[0-9]+){3}$ ]]; then + echo "Tag must match vX.Y.Z.N (numeric dot notation)." >&2 + exit 1 + fi + VERSION="${TAG#v}" + if ! [[ "${VERSION}" =~ ^[0-9]+(\.[0-9]+){3}$ ]]; then + echo "Version must match X.Y.Z.N (numeric dot notation)." >&2 + exit 1 + fi + echo "tag=${TAG}" >> "${GITHUB_OUTPUT}" + echo "version=${VERSION}" >> "${GITHUB_OUTPUT}" + + - name: Export build overrides + env: + OASIS_UPDATE_SERVICE_URL: ${{ secrets.OASIS_UPDATE_SERVICE_URL }} + run: | + set -euo pipefail + if [ -z "${OASIS_UPDATE_SERVICE_URL:-}" ]; then + echo "Missing OASIS_UPDATE_SERVICE_URL for build overrides." >&2 + exit 1 + fi + VERSION="${{ steps.version.outputs.version }}" + UPDATE_URL="${OASIS_UPDATE_SERVICE_URL%/}/update/6/%PRODUCT%/%VERSION%/%BUILD_ID%/%BUILD_TARGET%/%LOCALE%/%CHANNEL%/%OS_VERSION%/%SYSTEM_CAPABILITIES%/%DISTRIBUTION%/%DISTRIBUTION_VERSION%/update.xml" + echo "OASIS_APP_VERSION=${VERSION}" >> "${GITHUB_ENV}" + echo "OASIS_APP_VERSION_DISPLAY=${VERSION}" >> "${GITHUB_ENV}" + echo "MOZ_APPUPDATE_URL=${UPDATE_URL}" >> "${GITHUB_ENV}" + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: "20" + cache: npm + cache-dependency-path: | + browser/base/content/assistant/build/package-lock.json + browser/base/content/assistant/ui-preact/package-lock.json + + - name: Restore rcodesign cache + uses: actions/cache@v4 + with: + path: ~/.local/rcodesign + key: ${{ runner.os }}-${{ runner.arch }}-rcodesign-${{ env.OASIS_RCODESIGN_VERSION }}-v1 + + - name: Build assistant bundles + run: | + set -euo pipefail + npm ci --prefix browser/base/content/assistant/ui-preact + npm run build --prefix browser/base/content/assistant/ui-preact + npm ci --prefix browser/base/content/assistant/build + npm run build --prefix browser/base/content/assistant/build + + - name: Create CI mozconfig + run: | + set -euo pipefail + CI_MOZCONFIG="${RUNNER_TEMP}/mozconfig-oasis-release" + cat > "${CI_MOZCONFIG}" <<'EOF' + mk_add_options MOZ_OBJDIR=@TOPSRCDIR@/obj-oasis-release + ac_add_options --enable-application=browser + ac_add_options --with-branding=browser/branding/custom + ac_add_options --enable-release + ac_add_options --disable-debug + ac_add_options --enable-optimize + ac_add_options --disable-crashreporter + ac_add_options --enable-updater + ac_add_options --enable-update-channel=oasis-stable + export MOZ_INCLUDE_SOURCE_INFO= + export MOZ_DISABLE_SOURCE_INFO=1 + EOF + echo "MOZCONFIG=${CI_MOZCONFIG}" >> "${GITHUB_ENV}" + + - name: Select Xcode 26.2 + run: | + set -euo pipefail + XCODE_DEVELOPER_DIR="/Applications/Xcode_26.2.app/Contents/Developer" + if [ ! -d "${XCODE_DEVELOPER_DIR}" ]; then + echo "Missing Xcode 26.2 at ${XCODE_DEVELOPER_DIR}" >&2 + exit 1 + fi + sudo xcode-select -s "${XCODE_DEVELOPER_DIR}" + xcodebuild -version + xcrun --sdk macosx --show-sdk-version + + - name: Install rcodesign + run: | + set -euo pipefail + case "${RUNNER_ARCH}" in + ARM64) + PRIMARY_ARCH="aarch64-apple-darwin" + FALLBACK_ARCH="x86_64-apple-darwin" + ;; + X64) + PRIMARY_ARCH="x86_64-apple-darwin" + FALLBACK_ARCH="aarch64-apple-darwin" + ;; + *) + echo "Unsupported RUNNER_ARCH: ${RUNNER_ARCH}" >&2 + exit 1 + ;; + esac + + RELEASE_BASE="https://github.com/indygreg/apple-platform-rs/releases/download/apple-codesign%2F${OASIS_RCODESIGN_VERSION}" + INSTALL_ROOT="${HOME}/.local/rcodesign/${OASIS_RCODESIGN_VERSION}" + + install_rcodesign() { + local target_arch="$1" + local install_dir="${INSTALL_ROOT}/${target_arch}" + local tar_name="apple-codesign-${OASIS_RCODESIGN_VERSION}-${target_arch}.tar.gz" + local tar_url="${RELEASE_BASE}/${tar_name}" + local sha_url="${tar_url}.sha256" + + mkdir -p "${install_dir}" + if [ -x "${install_dir}/rcodesign" ]; then + echo "Using cached rcodesign from ${install_dir}" + export PATH="${install_dir}:${PATH}" + echo "${install_dir}" >> "${GITHUB_PATH}" + echo "OASIS_RCODESIGN_BIN=${install_dir}/rcodesign" >> "${GITHUB_ENV}" + return 0 + fi + + tmpdir="$(mktemp -d)" + + curl -fL "${tar_url}" -o "${tmpdir}/${tar_name}" || { + rm -rf "${tmpdir}" + return 1 + } + curl -fL "${sha_url}" -o "${tmpdir}/${tar_name}.sha256" || { + rm -rf "${tmpdir}" + return 1 + } + + expected_sha="$(awk '{print $1}' "${tmpdir}/${tar_name}.sha256" | tr -d '\r\n')" + if ! [[ "${expected_sha}" =~ ^[0-9a-fA-F]{64}$ ]]; then + echo "Invalid SHA256 content in ${tar_name}.sha256: ${expected_sha}" >&2 + rm -rf "${tmpdir}" + return 1 + fi + actual_sha="$(shasum -a 256 "${tmpdir}/${tar_name}" | awk '{print $1}')" + if [ "${actual_sha}" != "${expected_sha}" ]; then + echo "SHA256 mismatch for ${tar_name}" >&2 + echo "Expected: ${expected_sha}" >&2 + echo "Actual: ${actual_sha}" >&2 + rm -rf "${tmpdir}" + return 1 + fi + + tar -xzf "${tmpdir}/${tar_name}" -C "${tmpdir}" || { + rm -rf "${tmpdir}" + return 1 + } + rcodesign_path="$(find "${tmpdir}" -type f -name rcodesign | head -n1)" + if [ -z "${rcodesign_path}" ]; then + echo "rcodesign binary missing from ${tar_name}" >&2 + rm -rf "${tmpdir}" + return 1 + fi + + cp "${rcodesign_path}" "${install_dir}/rcodesign" || { + rm -rf "${tmpdir}" + return 1 + } + chmod 755 "${install_dir}/rcodesign" + rm -rf "${tmpdir}" + export PATH="${install_dir}:${PATH}" + echo "${install_dir}" >> "${GITHUB_PATH}" + echo "OASIS_RCODESIGN_BIN=${install_dir}/rcodesign" >> "${GITHUB_ENV}" + return 0 + } + + if ! install_rcodesign "${PRIMARY_ARCH}"; then + echo "Primary rcodesign archive failed, trying fallback ${FALLBACK_ARCH}." >&2 + install_rcodesign "${FALLBACK_ARCH}" + fi + + command -v rcodesign + rcodesign --version + + - name: Probe rcodesign CLI + run: | + set -euo pipefail + if ! rcodesign sign --help | grep -Eq -- "--entitlements-xml-(path|file)"; then + echo "Installed rcodesign is missing entitlements XML flag support." >&2 + exit 1 + fi + if ! rcodesign sign --help | grep -q -- "--p12-password-file"; then + echo "Installed rcodesign is missing --p12-password-file support." >&2 + exit 1 + fi + + - name: Prepare Apple signing keychain + env: + OASIS_APPLE_DEVELOPER_ID_P12_B64: ${{ secrets.OASIS_APPLE_DEVELOPER_ID_P12_B64 }} + OASIS_APPLE_DEVELOPER_ID_P12_PASSWORD: ${{ secrets.OASIS_APPLE_DEVELOPER_ID_P12_PASSWORD }} + run: | + set -euo pipefail + if [ -z "${OASIS_APPLE_DEVELOPER_ID_P12_B64}" ] || [ -z "${OASIS_APPLE_DEVELOPER_ID_P12_PASSWORD}" ]; then + echo "Missing Apple Developer ID certificate secrets." >&2 + exit 1 + fi + KEYCHAIN_PATH="${RUNNER_TEMP}/oasis-signing.keychain-db" + KEYCHAIN_PASSWORD="$(python3 -c 'import secrets; print(secrets.token_urlsafe(32))')" + P12_PATH="${RUNNER_TEMP}/oasis-developer-id.p12" + P12_PASSWORD_FILE="${RUNNER_TEMP}/oasis-developer-id-password.txt" + + # Decode the P12 from secrets + python3 -c 'import base64, os, sys; sys.stdout.buffer.write(base64.b64decode(os.environ["OASIS_APPLE_DEVELOPER_ID_P12_B64"]))' > "${P12_PATH}" + printf '%s' "${OASIS_APPLE_DEVELOPER_ID_P12_PASSWORD}" > "${P12_PASSWORD_FILE}" + chmod 600 "${P12_PATH}" "${P12_PASSWORD_FILE}" + + # Create and configure the temporary keychain + ORIGINAL_KEYCHAINS="$(security list-keychains -d user | tr -d '"')" + security create-keychain -p "${KEYCHAIN_PASSWORD}" "${KEYCHAIN_PATH}" + security set-keychain-settings -lut 21600 "${KEYCHAIN_PATH}" + security unlock-keychain -p "${KEYCHAIN_PASSWORD}" "${KEYCHAIN_PATH}" + + # Add to keychain search list + security list-keychains -d user -s "${KEYCHAIN_PATH}" ${ORIGINAL_KEYCHAINS} + security default-keychain -d user -s "${KEYCHAIN_PATH}" + + # Import the certificate/key (allow codesign access) + security import "${P12_PATH}" -k "${KEYCHAIN_PATH}" -P "${OASIS_APPLE_DEVELOPER_ID_P12_PASSWORD}" -A -T /usr/bin/codesign -T /usr/bin/security + security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "${KEYCHAIN_PASSWORD}" "${KEYCHAIN_PATH}" + + # Export env vars for cleanup + echo "OASIS_APPLE_KEYCHAIN_PATH=${KEYCHAIN_PATH}" >> "${GITHUB_ENV}" + echo "OASIS_APPLE_KEYCHAIN_PASSWORD=${KEYCHAIN_PASSWORD}" >> "${GITHUB_ENV}" + echo "OASIS_APPLE_DEVELOPER_ID_P12_PATH=${P12_PATH}" >> "${GITHUB_ENV}" + echo "OASIS_APPLE_DEVELOPER_ID_P12_PASSWORD_FILE=${P12_PASSWORD_FILE}" >> "${GITHUB_ENV}" + echo "OASIS_APPLE_KEYCHAIN_ORIGINAL_LIST<> "${GITHUB_ENV}" + echo "${ORIGINAL_KEYCHAINS}" >> "${GITHUB_ENV}" + echo "EOF" >> "${GITHUB_ENV}" + + - name: Validate PKCS12 with password file + run: | + set -euo pipefail + openssl pkcs12 \ + -in "${OASIS_APPLE_DEVELOPER_ID_P12_PATH}" \ + -passin "file:${OASIS_APPLE_DEVELOPER_ID_P12_PASSWORD_FILE}" \ + -nokeys -noout >/dev/null + + - name: Build and stage package + run: | + set -euo pipefail + unset MOZ_AUTOMATION + # 1. Build binaries + ./mach build + + # 2. Stage package (resolves symlinks, creates dist/firefox structure) + # We use make directly to bypass mach package's DMG creation logic for now + make -C "${OBJDIR}/browser/installer" stage-package + + # 3. Resolve variables needed for packaging + # We extract these from the make environment + MOZ_PKG_DIR=$(make -s -C "${OBJDIR}/browser/installer" echo-variable-MOZ_PKG_DIR) + APP_NAME=$(make -s -C "${OBJDIR}/browser/installer" echo-variable-_APPNAME) + PACKAGE=$(make -s -C "${OBJDIR}/browser/installer" echo-variable-PACKAGE) + VOLUME_NAME=$(make -s -C "${OBJDIR}/browser/installer" echo-variable-MOZ_APP_DISPLAYNAME) + DSSTORE_PATH=$(make -s -C "${OBJDIR}/browser/installer" echo-variable-MOZ_PKG_MAC_DSSTORE || true) + BACKGROUND_PATH=$(make -s -C "${OBJDIR}/browser/installer" echo-variable-MOZ_PKG_MAC_BACKGROUND || true) + ICON_PATH=$(make -s -C "${OBJDIR}/browser/installer" echo-variable-MOZ_PKG_MAC_ICON || true) + + PKG_APP="${OBJDIR}/dist/${MOZ_PKG_DIR}/${APP_NAME}" + DMG_PATH="${OBJDIR}/dist/${PACKAGE}" + + echo "PKG_APP=${PKG_APP}" >> "${GITHUB_ENV}" + echo "DMG_PATH=${DMG_PATH}" >> "${GITHUB_ENV}" + echo "MOZ_PKG_DIR=${MOZ_PKG_DIR}" >> "${GITHUB_ENV}" + echo "VOLUME_NAME=${VOLUME_NAME}" >> "${GITHUB_ENV}" + echo "DSSTORE_PATH=${DSSTORE_PATH}" >> "${GITHUB_ENV}" + echo "BACKGROUND_PATH=${BACKGROUND_PATH}" >> "${GITHUB_ENV}" + echo "ICON_PATH=${ICON_PATH}" >> "${GITHUB_ENV}" + + - name: Verify staged version + id: meta + run: | + set -euo pipefail + APP_INI="${PKG_APP}/Contents/Resources/application.ini" + EXPECTED_VERSION="${{ steps.version.outputs.version }}" + VERSION="$(awk -F= '/^Version=/{print $2}' "${APP_INI}")" + BUILD_ID="$(awk -F= '/^BuildID=/{print $2}' "${APP_INI}")" + + if [ "${VERSION}" != "${EXPECTED_VERSION}" ]; then + echo "Staged version mismatch: expected ${EXPECTED_VERSION}, got ${VERSION}" >&2 + exit 1 + fi + EXECUTABLE_PATH="" + for candidate in Oasis firefox firefox-bin; do + if [ -f "${PKG_APP}/Contents/MacOS/${candidate}" ]; then + EXECUTABLE_PATH="${PKG_APP}/Contents/MacOS/${candidate}" + break + fi + done + if [ -z "${EXECUTABLE_PATH}" ]; then + echo "Could not find executable under ${PKG_APP}/Contents/MacOS" >&2 + exit 1 + fi + echo "version=${VERSION}" >> "${GITHUB_OUTPUT}" + echo "build_id=${BUILD_ID}" >> "${GITHUB_OUTPUT}" + echo "executable_path=${EXECUTABLE_PATH}" >> "${GITHUB_OUTPUT}" + + - name: Validate staged update URL + env: + OASIS_UPDATE_SERVICE_URL: ${{ secrets.OASIS_UPDATE_SERVICE_URL }} + run: | + set -euo pipefail + if [ -z "${OASIS_UPDATE_SERVICE_URL:-}" ]; then + echo "Missing OASIS_UPDATE_SERVICE_URL secret for update URL validation." >&2 + exit 1 + fi + + APP_INI="${PKG_APP}/Contents/Resources/application.ini" + UPDATE_URL="$(awk -F= '/^URL=/{print $2; exit}' "${APP_INI}")" + if [ -z "${UPDATE_URL}" ]; then + echo "App update URL missing in ${APP_INI}" >&2 + exit 1 + fi + if [[ "${UPDATE_URL}" == *"aus5.mozilla.org"* ]]; then + echo "App update URL still points to Mozilla AUS: ${UPDATE_URL}" >&2 + exit 1 + fi + + SERVICE_BASE="${OASIS_UPDATE_SERVICE_URL%/}" + EXPECTED_PREFIX="${SERVICE_BASE}/update/6/" + if [[ "${UPDATE_URL}" != "${EXPECTED_PREFIX}"* ]]; then + echo "App update URL does not point to Oasis update service." >&2 + echo "Expected prefix: ${EXPECTED_PREFIX}" >&2 + echo "Actual URL: ${UPDATE_URL}" >&2 + exit 1 + fi + if [[ "${UPDATE_URL}" != *"/%CHANNEL%/"* ]]; then + echo "App update URL missing %CHANNEL% placeholder: ${UPDATE_URL}" >&2 + exit 1 + fi + + echo "Validated update URL: ${UPDATE_URL}" + + - name: Prepare and sign app bundle (rcodesign) + run: | + set -euo pipefail + + find "${PKG_APP}" \( -name ".mkdir.done" -o -name "*.done" \) -delete + + if find "${PKG_APP}" -type l -print -quit | grep -q .; then + echo "Refusing to sign app with symlinks still present: ${PKG_APP}" >&2 + find "${PKG_APP}" -type l | head -n 20 >&2 || true + exit 1 + fi + + ./mach macos-sign \ + -a "${PKG_APP}" \ + -r \ + -f "${OASIS_APPLE_DEVELOPER_ID_P12_PATH}" \ + -p "${OASIS_APPLE_DEVELOPER_ID_P12_PASSWORD_FILE}" \ + -e production-without-restricted \ + -c release \ + -v + + codesign --verify --deep --strict --verbose=2 "${PKG_APP}" + + - name: Prepare notary API key + env: + OASIS_APPLE_API_KEY_ID: ${{ secrets.OASIS_APPLE_API_KEY_ID }} + OASIS_APPLE_API_ISSUER: ${{ secrets.OASIS_APPLE_API_ISSUER }} + OASIS_APPLE_API_KEY_P8_B64: ${{ secrets.OASIS_APPLE_API_KEY_P8_B64 }} + run: | + set -euo pipefail + if [ -z "${OASIS_APPLE_API_KEY_ID}" ] || [ -z "${OASIS_APPLE_API_ISSUER}" ] || [ -z "${OASIS_APPLE_API_KEY_P8_B64}" ]; then + echo "Missing one or more App Store Connect API key secrets." >&2 + exit 1 + fi + NOTARY_KEY_PATH="${RUNNER_TEMP}/AuthKey_${OASIS_APPLE_API_KEY_ID}.p8" + python3 -c 'import base64, os, sys; sys.stdout.buffer.write(base64.b64decode(os.environ["OASIS_APPLE_API_KEY_P8_B64"]))' > "${NOTARY_KEY_PATH}" + chmod 600 "${NOTARY_KEY_PATH}" + echo "OASIS_NOTARY_KEY_PATH=${NOTARY_KEY_PATH}" >> "${GITHUB_ENV}" + echo "OASIS_APPLE_API_KEY_ID=${OASIS_APPLE_API_KEY_ID}" >> "${GITHUB_ENV}" + echo "OASIS_APPLE_API_ISSUER=${OASIS_APPLE_API_ISSUER}" >> "${GITHUB_ENV}" + + - name: Notarize and staple app bundle + run: | + set -euo pipefail + if [ -z "${OASIS_NOTARY_KEY_PATH:-}" ] || [ -z "${OASIS_APPLE_API_KEY_ID:-}" ] || [ -z "${OASIS_APPLE_API_ISSUER:-}" ]; then + echo "Missing API key notarization inputs." >&2 + exit 1 + fi + VERSION="${{ steps.meta.outputs.version }}" + NOTARY_ZIP="${RUNNER_TEMP}/oasis-app-notary-${VERSION}.zip" + + # Create zip for notarization + ditto -c -k --keepParent "${PKG_APP}" "${NOTARY_ZIP}" + + # Validation checks + ZIP_SIZE="$(stat -f%z "${NOTARY_ZIP}")" + if [ "${ZIP_SIZE}" -lt 52428800 ]; then + echo "ZIP payload too small." >&2; exit 1 + fi + if command -v zipinfo >/dev/null 2>&1; then + ZIP_ENTRIES="$(zipinfo -1 "${NOTARY_ZIP}")" + else + ZIP_ENTRIES="$(unzip -Z1 "${NOTARY_ZIP}")" + fi + if echo "${ZIP_ENTRIES}" | grep -q "^__MACOSX/"; then + echo "ZIP payload contains __MACOSX, refusing notarization submit." >&2 + exit 1 + fi + if ! echo "${ZIP_ENTRIES}" | grep -Eq '/Contents/MacOS/(Oasis|firefox|firefox-bin)$'; then + echo "ZIP payload missing expected executable under Contents/MacOS." >&2 + echo "${ZIP_ENTRIES}" | grep '/Contents/MacOS/' | head -n 30 >&2 || true + exit 1 + fi + + max_attempts=12 + backoffs=(30 60 120 180 240 300 300 300 300 300 300) + RETRYABLE_NOTARY_RE='statusCode: 50[0-4]|HTTP status code: 50[0-4]|UNEXPECTED_ERROR|HTTP status code: 408|HTTP status code: 429|NSURLErrorDomain Code=-(1001|1003|1004|1005|1006|1009)|The Internet connection appears to be offline|No network route|timed out|network connection was lost|cannot find host|could not resolve host' + attempt=1 + while true; do + notary_log="$(mktemp)" + if xcrun notarytool submit "${NOTARY_ZIP}" \ + --key "${OASIS_NOTARY_KEY_PATH}" \ + --key-id "${OASIS_APPLE_API_KEY_ID}" \ + --issuer "${OASIS_APPLE_API_ISSUER}" \ + --wait --verbose > "${notary_log}" 2>&1 + then + cat "${notary_log}" + rm -f "${notary_log}" + break + fi + cat "${notary_log}" >&2 + if ! grep -Eiq "${RETRYABLE_NOTARY_RE}" "${notary_log}"; then + echo "Non-retryable notarization failure." >&2 + rm -f "${notary_log}" + exit 1 + fi + if [ "${attempt}" -ge "${max_attempts}" ]; then + echo "Notarization failed after ${attempt} attempts." >&2 + rm -f "${notary_log}" + exit 1 + fi + sleep_seconds="${backoffs[$((attempt - 1))]}" + echo "Notarization attempt ${attempt} failed with transient notarization/network error. Retrying in ${sleep_seconds}s..." >&2 + rm -f "${notary_log}" + sleep "${sleep_seconds}" + attempt=$((attempt + 1)) + done + + # Staple + xcrun stapler staple "${PKG_APP}" + xcrun stapler validate "${PKG_APP}" + spctl -a -vv "${PKG_APP}" + echo "OASIS_APPLE_NOTARY_APP_ZIP=${NOTARY_ZIP}" >> "${GITHUB_ENV}" + + - name: Record post-notarization executable hash + id: golden_hash + run: | + set -euo pipefail + HASH="$(shasum -a 256 "${{ steps.meta.outputs.executable_path }}" | awk '{print $1}')" + echo "hash=${HASH}" >> "${GITHUB_OUTPUT}" + + - name: Create signed DMG + env: + OASIS_APPLE_SIGNING_IDENTITY: ${{ secrets.OASIS_APPLE_SIGNING_IDENTITY }} + run: | + set -euo pipefail + if [ -z "${OASIS_APPLE_SIGNING_IDENTITY}" ]; then + echo "Missing OASIS_APPLE_SIGNING_IDENTITY for DMG signing." >&2 + exit 1 + fi + + # Create DMG using Mozilla tool + # This wraps the ALREADY SIGNED/NOTARIZED app from PKG_APP + args=() + if [ -n "${DSSTORE_PATH:-}" ]; then + args+=(--dsstore "${DSSTORE_PATH}") + fi + if [ -n "${BACKGROUND_PATH:-}" ]; then + args+=(--background "${BACKGROUND_PATH}") + fi + if [ -n "${ICON_PATH:-}" ]; then + args+=(--icon "${ICON_PATH}") + fi + if [ -n "${VOLUME_NAME:-}" ]; then + args+=(--volume-name "${VOLUME_NAME}") + fi + + ./mach python -m mozbuild.action.make_dmg "${args[@]}" \ + "${OBJDIR}/dist/${MOZ_PKG_DIR}" \ + "${DMG_PATH}" + + # Sign the DMG container (Requires Keychain/codesign) + codesign --keychain "${OASIS_APPLE_KEYCHAIN_PATH}" --force --timestamp --sign "${OASIS_APPLE_SIGNING_IDENTITY}" "${DMG_PATH}" + codesign -dv --verbose=4 "${DMG_PATH}" + + - name: Notarize and staple DMG + run: | + set -euo pipefail + if [ -z "${OASIS_NOTARY_KEY_PATH:-}" ] || [ -z "${OASIS_APPLE_API_KEY_ID:-}" ] || [ -z "${OASIS_APPLE_API_ISSUER:-}" ]; then + echo "Missing API key notarization inputs." >&2 + exit 1 + fi + + max_attempts=12 + backoffs=(30 60 120 180 240 300 300 300 300 300 300) + RETRYABLE_NOTARY_RE='statusCode: 50[0-4]|HTTP status code: 50[0-4]|UNEXPECTED_ERROR|HTTP status code: 408|HTTP status code: 429|NSURLErrorDomain Code=-(1001|1003|1004|1005|1006|1009)|The Internet connection appears to be offline|No network route|timed out|network connection was lost|cannot find host|could not resolve host' + attempt=1 + while true; do + notary_log="$(mktemp)" + if xcrun notarytool submit "${DMG_PATH}" \ + --key "${OASIS_NOTARY_KEY_PATH}" \ + --key-id "${OASIS_APPLE_API_KEY_ID}" \ + --issuer "${OASIS_APPLE_API_ISSUER}" \ + --wait --verbose > "${notary_log}" 2>&1 + then + cat "${notary_log}" + rm -f "${notary_log}" + break + fi + cat "${notary_log}" >&2 + if ! grep -Eiq "${RETRYABLE_NOTARY_RE}" "${notary_log}"; then + echo "Non-retryable notarization failure." >&2 + rm -f "${notary_log}" + exit 1 + fi + if [ "${attempt}" -ge "${max_attempts}" ]; then + echo "Notarization failed after ${attempt} attempts." >&2 + rm -f "${notary_log}" + exit 1 + fi + sleep_seconds="${backoffs[$((attempt - 1))]}" + echo "Notarization attempt ${attempt} failed with transient notarization/network error. Retrying in ${sleep_seconds}s..." >&2 + rm -f "${notary_log}" + sleep "${sleep_seconds}" + attempt=$((attempt + 1)) + done + + # Staple DMG + xcrun stapler staple "${DMG_PATH}" + xcrun stapler validate "${DMG_PATH}" + + - name: Verify golden executable hash before MAR + run: | + set -euo pipefail + EXPECTED_HASH="${{ steps.golden_hash.outputs.hash }}" + CURRENT_HASH="$(shasum -a 256 "${{ steps.meta.outputs.executable_path }}" | awk '{print $1}')" + if [ "${CURRENT_HASH}" != "${EXPECTED_HASH}" ]; then + echo "Golden executable changed after app notarization; refusing MAR build." >&2 + echo "Expected: ${EXPECTED_HASH}" >&2 + echo "Actual: ${CURRENT_HASH}" >&2 + exit 1 + fi + + - name: Check updater cert material + env: + ALLOW_DEV_OASIS_CERTS: ${{ vars.ALLOW_DEV_OASIS_CERTS }} + run: | + set -euo pipefail + scripts/update-signing/check-oasis-cert-material.sh + + - name: Build complete MAR + id: mar + run: | + set -euo pipefail + VERSION="${{ steps.meta.outputs.version }}" + UPDATE_DIR="${OBJDIR}/dist/update" + mkdir -p "${UPDATE_DIR}" + UNSIGNED_MAR="${UPDATE_DIR}/oasis-${VERSION}-${BUILD_TARGET}-${LOCALE}.complete.mar" + SIGNED_MAR="${UPDATE_DIR}/oasis-${VERSION}-${BUILD_TARGET}-${LOCALE}.signed.complete.mar" + + # Use the GOLDEN APP (PKG_APP) which is signed/stapled + scripts/update-signing/build-complete-mar.sh \ + "${OBJDIR}" \ + "${PKG_APP}" \ + "${UNSIGNED_MAR}" \ + "${VERSION}" \ + "${RING}" + + echo "unsigned_mar=${UNSIGNED_MAR}" >> "${GITHUB_OUTPUT}" + echo "signed_mar=${SIGNED_MAR}" >> "${GITHUB_OUTPUT}" + + - name: Sign and verify MAR + env: + OASIS_MAR_SIGNING_CERT_NICKNAME: ${{ secrets.OASIS_MAR_SIGNING_CERT_NICKNAME }} + OASIS_MAR_SIGNING_P12_B64: ${{ secrets.OASIS_MAR_SIGNING_P12_B64 }} + OASIS_MAR_SIGNING_P12_PASSWORD: ${{ secrets.OASIS_MAR_SIGNING_P12_PASSWORD }} + run: | + set -euo pipefail + if [ -z "${OASIS_MAR_SIGNING_CERT_NICKNAME}" ] || [ -z "${OASIS_MAR_SIGNING_P12_B64}" ] || [ -z "${OASIS_MAR_SIGNING_P12_PASSWORD}" ]; then + echo "Missing one or more signing secrets." >&2 + exit 1 + fi + NSS_DB_DIR="${RUNNER_TEMP}/oasis-nssdb" + P12_PATH="${RUNNER_TEMP}/oasis-signing.p12" + mkdir -p "${NSS_DB_DIR}" + python3 -c 'import base64, os, sys; sys.stdout.buffer.write(base64.b64decode(os.environ["OASIS_MAR_SIGNING_P12_B64"]))' > "${P12_PATH}" + "${OBJDIR}/dist/bin/certutil" -N -d "sql:${NSS_DB_DIR}" --empty-password + "${OBJDIR}/dist/bin/pk12util" -i "${P12_PATH}" -d "sql:${NSS_DB_DIR}" -W "${OASIS_MAR_SIGNING_P12_PASSWORD}" + scripts/update-signing/sign-mar.sh \ + "${OBJDIR}" \ + "${{ steps.mar.outputs.unsigned_mar }}" \ + "${{ steps.mar.outputs.signed_mar }}" \ + "${NSS_DB_DIR}" \ + "${OASIS_MAR_SIGNING_CERT_NICKNAME}" + scripts/update-signing/verify-mar.sh \ + "${OBJDIR}" \ + "${{ steps.mar.outputs.signed_mar }}" \ + toolkit/mozapps/update/updater/oasis_primary.der + rm -f "${P12_PATH}" + rm -rf "${NSS_DB_DIR}" + + - name: Prepare release metadata + id: release_meta + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + VERSION="${{ steps.meta.outputs.version }}" + SAFE_TARGET="$(echo "${BUILD_TARGET}" | tr '/ ' '__')" + TAG="${{ steps.version.outputs.tag }}" + ASSET_NAME="oasis-${VERSION}-${SAFE_TARGET}-${LOCALE}.signed.complete.mar" + DMG_ASSET_NAME="oasis-${VERSION}-${SAFE_TARGET}-${LOCALE}.mac.dmg" + if gh release view "${TAG}" > /dev/null 2>&1; then + echo "Release ${TAG} already exists. Publish a new version instead of mutating an existing release." >&2 + exit 1 + fi + MAR_URL="https://github.com/${{ github.repository }}/releases/download/${TAG}/${ASSET_NAME}" + DMG_URL="https://github.com/${{ github.repository }}/releases/download/${TAG}/${DMG_ASSET_NAME}" + echo "tag=${TAG}" >> "${GITHUB_OUTPUT}" + echo "asset_name=${ASSET_NAME}" >> "${GITHUB_OUTPUT}" + echo "dmg_asset_name=${DMG_ASSET_NAME}" >> "${GITHUB_OUTPUT}" + echo "mar_url=${MAR_URL}" >> "${GITHUB_OUTPUT}" + echo "dmg_url=${DMG_URL}" >> "${GITHUB_OUTPUT}" + + - name: Create GitHub Release + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + TAG="${{ steps.release_meta.outputs.tag }}" + ASSET_NAME="${{ steps.release_meta.outputs.asset_name }}" + DMG_ASSET_NAME="${{ steps.release_meta.outputs.dmg_asset_name }}" + SIGNED_MAR="${{ steps.mar.outputs.signed_mar }}" + PACKAGED_DMG="${DMG_PATH}" + gh release create "${TAG}" \ + "${SIGNED_MAR}#${ASSET_NAME}" \ + "${PACKAGED_DMG}#${DMG_ASSET_NAME}" \ + --title "${TAG}" \ + --notes "Oasis release ${TAG}" + + - name: Print release asset URLs + run: | + set -euo pipefail + echo "MAR: ${{ steps.release_meta.outputs.mar_url }}" + echo "DMG: ${{ steps.release_meta.outputs.dmg_url }}" + + - name: Cleanup signing and notarization material + if: always() + run: | + set +e + # Keychain cleanup + if [ -n "${OASIS_APPLE_KEYCHAIN_ORIGINAL_LIST:-}" ]; then + security list-keychains -d user -s ${OASIS_APPLE_KEYCHAIN_ORIGINAL_LIST} + fi + if [ -n "${OASIS_APPLE_KEYCHAIN_PATH:-}" ]; then + security default-keychain -d user -s login.keychain-db + security delete-keychain "${OASIS_APPLE_KEYCHAIN_PATH}" + fi + rm -f "${OASIS_APPLE_DEVELOPER_ID_P12_PATH:-}" + rm -f "${OASIS_APPLE_DEVELOPER_ID_P12_PASSWORD_FILE:-}" + rm -f "${OASIS_APPLE_NOTARY_APP_ZIP:-}" + rm -f "${OASIS_NOTARY_KEY_PATH:-}" diff --git a/.github/workflows/oasis-stable-promote.yml b/.github/workflows/oasis-stable-promote.yml new file mode 100644 index 0000000000000..a59d4a128f6fa --- /dev/null +++ b/.github/workflows/oasis-stable-promote.yml @@ -0,0 +1,119 @@ +name: Oasis Stable Ring Promote + +on: + workflow_dispatch: + inputs: + target_version: + description: Version to promote to oasis-stable (X.Y.Z.N) + required: true + type: string + build_target: + description: Build target to validate + required: false + default: Darwin_aarch64-gcc3 + type: string + locale: + description: Locale to validate + required: false + default: en-US + type: string + actor: + description: Audit actor label + required: false + default: github-actions + type: string + reason: + description: Audit reason + required: false + default: manual stable promotion + type: string + +permissions: + contents: read + +env: + PRODUCT: Firefox + +jobs: + promote-stable: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Validate version format + run: | + set -euo pipefail + VERSION="${{ inputs.target_version }}" + if ! [[ "${VERSION}" =~ ^[0-9]+(\.[0-9]+){3}$ ]]; then + echo "Version must match X.Y.Z.N (numeric dot notation)." >&2 + exit 1 + fi + + - name: Verify canary release asset exists + id: release + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + VERSION="${{ inputs.target_version }}" + BUILD_TARGET="${{ inputs.build_target }}" + LOCALE="${{ inputs.locale }}" + SAFE_TARGET="$(echo "${BUILD_TARGET}" | tr '/ ' '__')" + TAG="canary" + ASSET_NAME="oasis-${VERSION}-${SAFE_TARGET}-${LOCALE}.signed.complete.mar" + RELEASE_JSON="$(mktemp)" + gh release view "${TAG}" --json tagName,assets > "${RELEASE_JSON}" + if ! python3 -c 'import json, sys; payload = json.load(open(sys.argv[1], "r", encoding="utf-8")); asset_name = sys.argv[2]; sys.exit(0 if any(a.get("name") == asset_name for a in payload.get("assets", [])) else 1)' "${RELEASE_JSON}" "${ASSET_NAME}" + then + echo "Expected canary bucket asset ${ASSET_NAME} was not found under release ${TAG}." >&2 + exit 1 + fi + echo "tag=${TAG}" >> "${GITHUB_OUTPUT}" + echo "asset_name=${ASSET_NAME}" >> "${GITHUB_OUTPUT}" + rm -f "${RELEASE_JSON}" + + - name: Verify canary currently resolves target artifact + env: + OASIS_ADMIN_TOKEN: ${{ secrets.OASIS_UPDATE_ADMIN_TOKEN }} + OASIS_UPDATE_SERVICE_URL: ${{ secrets.OASIS_UPDATE_SERVICE_URL }} + run: | + set -euo pipefail + SERVICE_BASE="${OASIS_UPDATE_SERVICE_URL%/}" + TARGET_VERSION="${{ inputs.target_version }}" + EXPECTED_MAR_URL="https://github.com/${{ github.repository }}/releases/download/${{ steps.release.outputs.tag }}/${{ steps.release.outputs.asset_name }}" + + RING_JSON="$(curl -fsS -H "Authorization: Bearer ${OASIS_ADMIN_TOKEN}" "${SERVICE_BASE}/admin/rings/oasis-canary")" + CURRENT_CANARY="$(python3 -c 'import json,sys; print(json.loads(sys.stdin.read())["target_version"])' <<<"${RING_JSON}")" + if [ "${CURRENT_CANARY}" != "${TARGET_VERSION}" ]; then + echo "Canary ring points to ${CURRENT_CANARY}, expected ${TARGET_VERSION} before stable promotion." >&2 + exit 1 + fi + + UPDATE_URL="${SERVICE_BASE}/update/6/${PRODUCT}/0.0.0.0/0/${{ inputs.build_target }}/${{ inputs.locale }}/oasis-canary/Linux/default/default/update.xml" + UPDATE_XML="$(curl -fsS "${UPDATE_URL}")" + ACTUAL_MAR_URL="$(python3 -c 'import sys,xml.etree.ElementTree as ET; root = ET.fromstring(sys.stdin.read()); patch = root.find("./update/patch"); print(patch.attrib["URL"] if patch is not None else "")' <<<"${UPDATE_XML}")" + if [ -z "${ACTUAL_MAR_URL}" ]; then + echo "Canary update XML did not contain a patch URL for ${TARGET_VERSION}/${{ inputs.build_target }}/${{ inputs.locale }}." >&2 + exit 1 + fi + if [ "${ACTUAL_MAR_URL}" != "${EXPECTED_MAR_URL}" ]; then + echo "Canary artifact URL mismatch." >&2 + echo "Expected: ${EXPECTED_MAR_URL}" >&2 + echo "Actual: ${ACTUAL_MAR_URL}" >&2 + exit 1 + fi + + - name: Update stable ring pointer + env: + OASIS_ADMIN_TOKEN: ${{ secrets.OASIS_UPDATE_ADMIN_TOKEN }} + OASIS_UPDATE_SERVICE_URL: ${{ secrets.OASIS_UPDATE_SERVICE_URL }} + run: | + set -euo pipefail + python3 tools/oasis-update-service/publish_update.py \ + --service "${OASIS_UPDATE_SERVICE_URL}" \ + --admin-token "${OASIS_ADMIN_TOKEN}" \ + --version "${{ inputs.target_version }}" \ + --ring oasis-stable \ + --actor "${{ inputs.actor }}" \ + --reason "${{ inputs.reason }} (run ${GITHUB_RUN_ID}, source canary bucket)" diff --git a/.gitignore b/.gitignore index 4feeb7bfb9374..ad827b1698e2a 100644 --- a/.gitignore +++ b/.gitignore @@ -17,6 +17,11 @@ tags *.gcov *.tsbuildinfo compile_commands.json +*.env + +# Local Apple signing assets (never commit) +/developer_id.p12 +/p12_password.txt # emacs backup files in any directory. # lint-ignore-next-line: syntax-difference @@ -104,6 +109,17 @@ tools/lint/stylelint/stylelint-plugin-mozilla/node_modules/ tools/terser/node_modules/ browser/components/asrouter/node_modules/ browser/components/aboutwelcome/node_modules/ + +# Oasis assistant: local-only npm artifacts (platform esbuild, devDependencies, Lambda deps) +browser/base/content/assistant/ui-preact/node_modules/@esbuild/darwin-*/ +browser/base/content/assistant/ui-preact/node_modules/@esbuild/linux-*/ +browser/base/content/assistant/ui-preact/node_modules/@esbuild/freebsd-*/ +browser/base/content/assistant/ui-preact/node_modules/@esbuild/android-*/ +browser/base/content/assistant/ui-preact/node_modules/typescript/ +browser/base/content/assistant/ui-preact/node_modules/.bin/tsc +browser/base/content/assistant/ui-preact/node_modules/.bin/tsserver +browser/base/content/assistant/lambda/voice-runtime/node_modules/ + browser/extensions/newtab/node_modules/ tools/ts/node_modules/ testing/xpcshell/moz-http2/node_modules/ @@ -393,6 +409,10 @@ toolkit/crashreporter/minidump-analyzer/target/ # Ignore mozperftest artifacts folder /artifacts/ +# Distribution packages (generated files) +Oasis-Browser-*.dmg +Oasis-Browser-*.zip + # Ignore personal preferences files CLAUDE.local.md .claude/settings.local.json @@ -400,3 +420,11 @@ CLAUDE.local.md # Ignore .json.gz (typically profiles) in the root directory # lint-ignore-next-line: git-only /*.json.gz +\n# Gemini files\ngemini.md\n.gemini/ + +# Ignore tour directory +tour/ + +# Ignore Python profiling files +*.cProfile +*.pstats diff --git a/.lto.o/0.arm64.lto.o b/.lto.o/0.arm64.lto.o new file mode 100644 index 0000000000000..45008c435d4d2 Binary files /dev/null and b/.lto.o/0.arm64.lto.o differ diff --git a/.lto.o/1.arm64.lto.o b/.lto.o/1.arm64.lto.o new file mode 100644 index 0000000000000..6ee1490778979 Binary files /dev/null and b/.lto.o/1.arm64.lto.o differ diff --git a/.lto.o/10.arm64.lto.o b/.lto.o/10.arm64.lto.o new file mode 100644 index 0000000000000..9820cca19383a Binary files /dev/null and b/.lto.o/10.arm64.lto.o differ diff --git a/.lto.o/100.arm64.lto.o b/.lto.o/100.arm64.lto.o new file mode 100644 index 0000000000000..26590a0b6ba13 Binary files /dev/null and b/.lto.o/100.arm64.lto.o differ diff --git a/.lto.o/101.arm64.lto.o b/.lto.o/101.arm64.lto.o new file mode 100644 index 0000000000000..7f6b01b0024ee Binary files /dev/null and b/.lto.o/101.arm64.lto.o differ diff --git a/.lto.o/102.arm64.lto.o b/.lto.o/102.arm64.lto.o new file mode 100644 index 0000000000000..bff1c07f3dce7 Binary files /dev/null and b/.lto.o/102.arm64.lto.o differ diff --git a/.lto.o/103.arm64.lto.o b/.lto.o/103.arm64.lto.o new file mode 100644 index 0000000000000..99c4c46b14104 Binary files /dev/null and b/.lto.o/103.arm64.lto.o differ diff --git a/.lto.o/104.arm64.lto.o b/.lto.o/104.arm64.lto.o new file mode 100644 index 0000000000000..2c13d9dd898f4 Binary files /dev/null and b/.lto.o/104.arm64.lto.o differ diff --git a/.lto.o/105.arm64.lto.o b/.lto.o/105.arm64.lto.o new file mode 100644 index 0000000000000..72e69821ce2dc Binary files /dev/null and b/.lto.o/105.arm64.lto.o differ diff --git a/.lto.o/106.arm64.lto.o b/.lto.o/106.arm64.lto.o new file mode 100644 index 0000000000000..d900d8db31c91 Binary files /dev/null and b/.lto.o/106.arm64.lto.o differ diff --git a/.lto.o/107.arm64.lto.o b/.lto.o/107.arm64.lto.o new file mode 100644 index 0000000000000..693e18d1eb200 Binary files /dev/null and b/.lto.o/107.arm64.lto.o differ diff --git a/.lto.o/108.arm64.lto.o b/.lto.o/108.arm64.lto.o new file mode 100644 index 0000000000000..8dfec7fb8fac4 Binary files /dev/null and b/.lto.o/108.arm64.lto.o differ diff --git a/.lto.o/109.arm64.lto.o b/.lto.o/109.arm64.lto.o new file mode 100644 index 0000000000000..31c44cea8abc7 Binary files /dev/null and b/.lto.o/109.arm64.lto.o differ diff --git a/.lto.o/11.arm64.lto.o b/.lto.o/11.arm64.lto.o new file mode 100644 index 0000000000000..ca02ca4d84f99 Binary files /dev/null and b/.lto.o/11.arm64.lto.o differ diff --git a/.lto.o/12.arm64.lto.o b/.lto.o/12.arm64.lto.o new file mode 100644 index 0000000000000..34a05092bd36d Binary files /dev/null and b/.lto.o/12.arm64.lto.o differ diff --git a/.lto.o/13.arm64.lto.o b/.lto.o/13.arm64.lto.o new file mode 100644 index 0000000000000..267e364426ffa Binary files /dev/null and b/.lto.o/13.arm64.lto.o differ diff --git a/.lto.o/14.arm64.lto.o b/.lto.o/14.arm64.lto.o new file mode 100644 index 0000000000000..15f1286bb9b9a Binary files /dev/null and b/.lto.o/14.arm64.lto.o differ diff --git a/.lto.o/15.arm64.lto.o b/.lto.o/15.arm64.lto.o new file mode 100644 index 0000000000000..ae327fc68ded3 Binary files /dev/null and b/.lto.o/15.arm64.lto.o differ diff --git a/.lto.o/16.arm64.lto.o b/.lto.o/16.arm64.lto.o new file mode 100644 index 0000000000000..b302fcad5274a Binary files /dev/null and b/.lto.o/16.arm64.lto.o differ diff --git a/.lto.o/17.arm64.lto.o b/.lto.o/17.arm64.lto.o new file mode 100644 index 0000000000000..b76a4ab352cce Binary files /dev/null and b/.lto.o/17.arm64.lto.o differ diff --git a/.lto.o/18.arm64.lto.o b/.lto.o/18.arm64.lto.o new file mode 100644 index 0000000000000..058fd1f00a747 Binary files /dev/null and b/.lto.o/18.arm64.lto.o differ diff --git a/.lto.o/19.arm64.lto.o b/.lto.o/19.arm64.lto.o new file mode 100644 index 0000000000000..f1ee67439516f Binary files /dev/null and b/.lto.o/19.arm64.lto.o differ diff --git a/.lto.o/2.arm64.lto.o b/.lto.o/2.arm64.lto.o new file mode 100644 index 0000000000000..28608678a369c Binary files /dev/null and b/.lto.o/2.arm64.lto.o differ diff --git a/.lto.o/20.arm64.lto.o b/.lto.o/20.arm64.lto.o new file mode 100644 index 0000000000000..fa089ed3ca984 Binary files /dev/null and b/.lto.o/20.arm64.lto.o differ diff --git a/.lto.o/21.arm64.lto.o b/.lto.o/21.arm64.lto.o new file mode 100644 index 0000000000000..6108292484ff6 Binary files /dev/null and b/.lto.o/21.arm64.lto.o differ diff --git a/.lto.o/22.arm64.lto.o b/.lto.o/22.arm64.lto.o new file mode 100644 index 0000000000000..aaf7ea53d3383 Binary files /dev/null and b/.lto.o/22.arm64.lto.o differ diff --git a/.lto.o/23.arm64.lto.o b/.lto.o/23.arm64.lto.o new file mode 100644 index 0000000000000..d7cc924def1c5 Binary files /dev/null and b/.lto.o/23.arm64.lto.o differ diff --git a/.lto.o/24.arm64.lto.o b/.lto.o/24.arm64.lto.o new file mode 100644 index 0000000000000..1c0cc111ff884 Binary files /dev/null and b/.lto.o/24.arm64.lto.o differ diff --git a/.lto.o/25.arm64.lto.o b/.lto.o/25.arm64.lto.o new file mode 100644 index 0000000000000..496fb74f6ad5e Binary files /dev/null and b/.lto.o/25.arm64.lto.o differ diff --git a/.lto.o/26.arm64.lto.o b/.lto.o/26.arm64.lto.o new file mode 100644 index 0000000000000..7b664a0351a7d Binary files /dev/null and b/.lto.o/26.arm64.lto.o differ diff --git a/.lto.o/27.arm64.lto.o b/.lto.o/27.arm64.lto.o new file mode 100644 index 0000000000000..93aeea5ca6fc6 Binary files /dev/null and b/.lto.o/27.arm64.lto.o differ diff --git a/.lto.o/28.arm64.lto.o b/.lto.o/28.arm64.lto.o new file mode 100644 index 0000000000000..7e47643b20dc3 Binary files /dev/null and b/.lto.o/28.arm64.lto.o differ diff --git a/.lto.o/29.arm64.lto.o b/.lto.o/29.arm64.lto.o new file mode 100644 index 0000000000000..5ea715202421c Binary files /dev/null and b/.lto.o/29.arm64.lto.o differ diff --git a/.lto.o/3.arm64.lto.o b/.lto.o/3.arm64.lto.o new file mode 100644 index 0000000000000..bbfd9a064947e Binary files /dev/null and b/.lto.o/3.arm64.lto.o differ diff --git a/.lto.o/30.arm64.lto.o b/.lto.o/30.arm64.lto.o new file mode 100644 index 0000000000000..af7cf0d1709e0 Binary files /dev/null and b/.lto.o/30.arm64.lto.o differ diff --git a/.lto.o/31.arm64.lto.o b/.lto.o/31.arm64.lto.o new file mode 100644 index 0000000000000..94819faf5fce1 Binary files /dev/null and b/.lto.o/31.arm64.lto.o differ diff --git a/.lto.o/32.arm64.lto.o b/.lto.o/32.arm64.lto.o new file mode 100644 index 0000000000000..9f68790611000 Binary files /dev/null and b/.lto.o/32.arm64.lto.o differ diff --git a/.lto.o/33.arm64.lto.o b/.lto.o/33.arm64.lto.o new file mode 100644 index 0000000000000..9ff3c58c55908 Binary files /dev/null and b/.lto.o/33.arm64.lto.o differ diff --git a/.lto.o/34.arm64.lto.o b/.lto.o/34.arm64.lto.o new file mode 100644 index 0000000000000..34af619ea692a Binary files /dev/null and b/.lto.o/34.arm64.lto.o differ diff --git a/.lto.o/35.arm64.lto.o b/.lto.o/35.arm64.lto.o new file mode 100644 index 0000000000000..cf0d807cf5b25 Binary files /dev/null and b/.lto.o/35.arm64.lto.o differ diff --git a/.lto.o/36.arm64.lto.o b/.lto.o/36.arm64.lto.o new file mode 100644 index 0000000000000..a70663f12d2ff Binary files /dev/null and b/.lto.o/36.arm64.lto.o differ diff --git a/.lto.o/37.arm64.lto.o b/.lto.o/37.arm64.lto.o new file mode 100644 index 0000000000000..c1198db084a2c Binary files /dev/null and b/.lto.o/37.arm64.lto.o differ diff --git a/.lto.o/38.arm64.lto.o b/.lto.o/38.arm64.lto.o new file mode 100644 index 0000000000000..84b655ff90ec3 Binary files /dev/null and b/.lto.o/38.arm64.lto.o differ diff --git a/.lto.o/39.arm64.lto.o b/.lto.o/39.arm64.lto.o new file mode 100644 index 0000000000000..aec8d07aa1b91 Binary files /dev/null and b/.lto.o/39.arm64.lto.o differ diff --git a/.lto.o/4.arm64.lto.o b/.lto.o/4.arm64.lto.o new file mode 100644 index 0000000000000..2b0475aabca3a Binary files /dev/null and b/.lto.o/4.arm64.lto.o differ diff --git a/.lto.o/40.arm64.lto.o b/.lto.o/40.arm64.lto.o new file mode 100644 index 0000000000000..57cc717929523 Binary files /dev/null and b/.lto.o/40.arm64.lto.o differ diff --git a/.lto.o/41.arm64.lto.o b/.lto.o/41.arm64.lto.o new file mode 100644 index 0000000000000..55a28ead5d1e9 Binary files /dev/null and b/.lto.o/41.arm64.lto.o differ diff --git a/.lto.o/42.arm64.lto.o b/.lto.o/42.arm64.lto.o new file mode 100644 index 0000000000000..040e1a70d68c0 Binary files /dev/null and b/.lto.o/42.arm64.lto.o differ diff --git a/.lto.o/43.arm64.lto.o b/.lto.o/43.arm64.lto.o new file mode 100644 index 0000000000000..00397a91e8733 Binary files /dev/null and b/.lto.o/43.arm64.lto.o differ diff --git a/.lto.o/44.arm64.lto.o b/.lto.o/44.arm64.lto.o new file mode 100644 index 0000000000000..a4dc30eca8175 Binary files /dev/null and b/.lto.o/44.arm64.lto.o differ diff --git a/.lto.o/45.arm64.lto.o b/.lto.o/45.arm64.lto.o new file mode 100644 index 0000000000000..8a52878a64212 Binary files /dev/null and b/.lto.o/45.arm64.lto.o differ diff --git a/.lto.o/46.arm64.lto.o b/.lto.o/46.arm64.lto.o new file mode 100644 index 0000000000000..10822586e74c8 Binary files /dev/null and b/.lto.o/46.arm64.lto.o differ diff --git a/.lto.o/47.arm64.lto.o b/.lto.o/47.arm64.lto.o new file mode 100644 index 0000000000000..6afdf35b77a9c Binary files /dev/null and b/.lto.o/47.arm64.lto.o differ diff --git a/.lto.o/48.arm64.lto.o b/.lto.o/48.arm64.lto.o new file mode 100644 index 0000000000000..8cdba3db6513b Binary files /dev/null and b/.lto.o/48.arm64.lto.o differ diff --git a/.lto.o/49.arm64.lto.o b/.lto.o/49.arm64.lto.o new file mode 100644 index 0000000000000..3bcffa72bae15 Binary files /dev/null and b/.lto.o/49.arm64.lto.o differ diff --git a/.lto.o/5.arm64.lto.o b/.lto.o/5.arm64.lto.o new file mode 100644 index 0000000000000..118975295fe19 Binary files /dev/null and b/.lto.o/5.arm64.lto.o differ diff --git a/.lto.o/50.arm64.lto.o b/.lto.o/50.arm64.lto.o new file mode 100644 index 0000000000000..bc4b19c97b7d3 Binary files /dev/null and b/.lto.o/50.arm64.lto.o differ diff --git a/.lto.o/51.arm64.lto.o b/.lto.o/51.arm64.lto.o new file mode 100644 index 0000000000000..b40b749c0db66 Binary files /dev/null and b/.lto.o/51.arm64.lto.o differ diff --git a/.lto.o/52.arm64.lto.o b/.lto.o/52.arm64.lto.o new file mode 100644 index 0000000000000..ae5c7abc5f16a Binary files /dev/null and b/.lto.o/52.arm64.lto.o differ diff --git a/.lto.o/53.arm64.lto.o b/.lto.o/53.arm64.lto.o new file mode 100644 index 0000000000000..2a37f1582a47c Binary files /dev/null and b/.lto.o/53.arm64.lto.o differ diff --git a/.lto.o/54.arm64.lto.o b/.lto.o/54.arm64.lto.o new file mode 100644 index 0000000000000..e60eb5edc517a Binary files /dev/null and b/.lto.o/54.arm64.lto.o differ diff --git a/.lto.o/55.arm64.lto.o b/.lto.o/55.arm64.lto.o new file mode 100644 index 0000000000000..7c1afd559c350 Binary files /dev/null and b/.lto.o/55.arm64.lto.o differ diff --git a/.lto.o/56.arm64.lto.o b/.lto.o/56.arm64.lto.o new file mode 100644 index 0000000000000..ef51be6832ffb Binary files /dev/null and b/.lto.o/56.arm64.lto.o differ diff --git a/.lto.o/57.arm64.lto.o b/.lto.o/57.arm64.lto.o new file mode 100644 index 0000000000000..f1446bab1e8bc Binary files /dev/null and b/.lto.o/57.arm64.lto.o differ diff --git a/.lto.o/58.arm64.lto.o b/.lto.o/58.arm64.lto.o new file mode 100644 index 0000000000000..f8d94f4e4444e Binary files /dev/null and b/.lto.o/58.arm64.lto.o differ diff --git a/.lto.o/59.arm64.lto.o b/.lto.o/59.arm64.lto.o new file mode 100644 index 0000000000000..d6199520a2878 Binary files /dev/null and b/.lto.o/59.arm64.lto.o differ diff --git a/.lto.o/6.arm64.lto.o b/.lto.o/6.arm64.lto.o new file mode 100644 index 0000000000000..2ae5d7c1d1f9c Binary files /dev/null and b/.lto.o/6.arm64.lto.o differ diff --git a/.lto.o/60.arm64.lto.o b/.lto.o/60.arm64.lto.o new file mode 100644 index 0000000000000..265d4e3c0913a Binary files /dev/null and b/.lto.o/60.arm64.lto.o differ diff --git a/.lto.o/61.arm64.lto.o b/.lto.o/61.arm64.lto.o new file mode 100644 index 0000000000000..928a21e71f61d Binary files /dev/null and b/.lto.o/61.arm64.lto.o differ diff --git a/.lto.o/62.arm64.lto.o b/.lto.o/62.arm64.lto.o new file mode 100644 index 0000000000000..a72c523083383 Binary files /dev/null and b/.lto.o/62.arm64.lto.o differ diff --git a/.lto.o/63.arm64.lto.o b/.lto.o/63.arm64.lto.o new file mode 100644 index 0000000000000..46e92e38b4cc5 Binary files /dev/null and b/.lto.o/63.arm64.lto.o differ diff --git a/.lto.o/64.arm64.lto.o b/.lto.o/64.arm64.lto.o new file mode 100644 index 0000000000000..947522a9757f9 Binary files /dev/null and b/.lto.o/64.arm64.lto.o differ diff --git a/.lto.o/65.arm64.lto.o b/.lto.o/65.arm64.lto.o new file mode 100644 index 0000000000000..0df4887afce07 Binary files /dev/null and b/.lto.o/65.arm64.lto.o differ diff --git a/.lto.o/66.arm64.lto.o b/.lto.o/66.arm64.lto.o new file mode 100644 index 0000000000000..ed459617b6cd4 Binary files /dev/null and b/.lto.o/66.arm64.lto.o differ diff --git a/.lto.o/67.arm64.lto.o b/.lto.o/67.arm64.lto.o new file mode 100644 index 0000000000000..07fac395713ae Binary files /dev/null and b/.lto.o/67.arm64.lto.o differ diff --git a/.lto.o/68.arm64.lto.o b/.lto.o/68.arm64.lto.o new file mode 100644 index 0000000000000..122a7c02efe32 Binary files /dev/null and b/.lto.o/68.arm64.lto.o differ diff --git a/.lto.o/69.arm64.lto.o b/.lto.o/69.arm64.lto.o new file mode 100644 index 0000000000000..56fe8f07412db Binary files /dev/null and b/.lto.o/69.arm64.lto.o differ diff --git a/.lto.o/7.arm64.lto.o b/.lto.o/7.arm64.lto.o new file mode 100644 index 0000000000000..5fea53faf59f5 Binary files /dev/null and b/.lto.o/7.arm64.lto.o differ diff --git a/.lto.o/70.arm64.lto.o b/.lto.o/70.arm64.lto.o new file mode 100644 index 0000000000000..e696c735fe911 Binary files /dev/null and b/.lto.o/70.arm64.lto.o differ diff --git a/.lto.o/71.arm64.lto.o b/.lto.o/71.arm64.lto.o new file mode 100644 index 0000000000000..246e9c908fb99 Binary files /dev/null and b/.lto.o/71.arm64.lto.o differ diff --git a/.lto.o/72.arm64.lto.o b/.lto.o/72.arm64.lto.o new file mode 100644 index 0000000000000..34f9728e41d9a Binary files /dev/null and b/.lto.o/72.arm64.lto.o differ diff --git a/.lto.o/73.arm64.lto.o b/.lto.o/73.arm64.lto.o new file mode 100644 index 0000000000000..f7b1a0d91c6ba Binary files /dev/null and b/.lto.o/73.arm64.lto.o differ diff --git a/.lto.o/74.arm64.lto.o b/.lto.o/74.arm64.lto.o new file mode 100644 index 0000000000000..ec6680fa593d6 Binary files /dev/null and b/.lto.o/74.arm64.lto.o differ diff --git a/.lto.o/75.arm64.lto.o b/.lto.o/75.arm64.lto.o new file mode 100644 index 0000000000000..e056d403af836 Binary files /dev/null and b/.lto.o/75.arm64.lto.o differ diff --git a/.lto.o/76.arm64.lto.o b/.lto.o/76.arm64.lto.o new file mode 100644 index 0000000000000..3d9342de6526a Binary files /dev/null and b/.lto.o/76.arm64.lto.o differ diff --git a/.lto.o/77.arm64.lto.o b/.lto.o/77.arm64.lto.o new file mode 100644 index 0000000000000..6bfe99914d04f Binary files /dev/null and b/.lto.o/77.arm64.lto.o differ diff --git a/.lto.o/78.arm64.lto.o b/.lto.o/78.arm64.lto.o new file mode 100644 index 0000000000000..99e581949fa09 Binary files /dev/null and b/.lto.o/78.arm64.lto.o differ diff --git a/.lto.o/79.arm64.lto.o b/.lto.o/79.arm64.lto.o new file mode 100644 index 0000000000000..ddca9a6fa4377 Binary files /dev/null and b/.lto.o/79.arm64.lto.o differ diff --git a/.lto.o/8.arm64.lto.o b/.lto.o/8.arm64.lto.o new file mode 100644 index 0000000000000..8fdc58b0dee92 Binary files /dev/null and b/.lto.o/8.arm64.lto.o differ diff --git a/.lto.o/80.arm64.lto.o b/.lto.o/80.arm64.lto.o new file mode 100644 index 0000000000000..5da5b05d5e205 Binary files /dev/null and b/.lto.o/80.arm64.lto.o differ diff --git a/.lto.o/81.arm64.lto.o b/.lto.o/81.arm64.lto.o new file mode 100644 index 0000000000000..2a9da9f91fe88 Binary files /dev/null and b/.lto.o/81.arm64.lto.o differ diff --git a/.lto.o/82.arm64.lto.o b/.lto.o/82.arm64.lto.o new file mode 100644 index 0000000000000..03bbf9b18c595 Binary files /dev/null and b/.lto.o/82.arm64.lto.o differ diff --git a/.lto.o/83.arm64.lto.o b/.lto.o/83.arm64.lto.o new file mode 100644 index 0000000000000..c2d72d58ad5e7 Binary files /dev/null and b/.lto.o/83.arm64.lto.o differ diff --git a/.lto.o/84.arm64.lto.o b/.lto.o/84.arm64.lto.o new file mode 100644 index 0000000000000..524816e9dae9b Binary files /dev/null and b/.lto.o/84.arm64.lto.o differ diff --git a/.lto.o/85.arm64.lto.o b/.lto.o/85.arm64.lto.o new file mode 100644 index 0000000000000..c3bc62c400d63 Binary files /dev/null and b/.lto.o/85.arm64.lto.o differ diff --git a/.lto.o/86.arm64.lto.o b/.lto.o/86.arm64.lto.o new file mode 100644 index 0000000000000..b1812171adb8e Binary files /dev/null and b/.lto.o/86.arm64.lto.o differ diff --git a/.lto.o/87.arm64.lto.o b/.lto.o/87.arm64.lto.o new file mode 100644 index 0000000000000..936f61b1b24bd Binary files /dev/null and b/.lto.o/87.arm64.lto.o differ diff --git a/.lto.o/88.arm64.lto.o b/.lto.o/88.arm64.lto.o new file mode 100644 index 0000000000000..172d4ad592779 Binary files /dev/null and b/.lto.o/88.arm64.lto.o differ diff --git a/.lto.o/89.arm64.lto.o b/.lto.o/89.arm64.lto.o new file mode 100644 index 0000000000000..80968ca5710c2 Binary files /dev/null and b/.lto.o/89.arm64.lto.o differ diff --git a/.lto.o/9.arm64.lto.o b/.lto.o/9.arm64.lto.o new file mode 100644 index 0000000000000..d27fb11e7345a Binary files /dev/null and b/.lto.o/9.arm64.lto.o differ diff --git a/.lto.o/90.arm64.lto.o b/.lto.o/90.arm64.lto.o new file mode 100644 index 0000000000000..ca7abd330bb41 Binary files /dev/null and b/.lto.o/90.arm64.lto.o differ diff --git a/.lto.o/91.arm64.lto.o b/.lto.o/91.arm64.lto.o new file mode 100644 index 0000000000000..494235ef2e32a Binary files /dev/null and b/.lto.o/91.arm64.lto.o differ diff --git a/.lto.o/92.arm64.lto.o b/.lto.o/92.arm64.lto.o new file mode 100644 index 0000000000000..072fdc306738b Binary files /dev/null and b/.lto.o/92.arm64.lto.o differ diff --git a/.lto.o/93.arm64.lto.o b/.lto.o/93.arm64.lto.o new file mode 100644 index 0000000000000..1626724f7780a Binary files /dev/null and b/.lto.o/93.arm64.lto.o differ diff --git a/.lto.o/94.arm64.lto.o b/.lto.o/94.arm64.lto.o new file mode 100644 index 0000000000000..fbcc0ee4a291a Binary files /dev/null and b/.lto.o/94.arm64.lto.o differ diff --git a/.lto.o/95.arm64.lto.o b/.lto.o/95.arm64.lto.o new file mode 100644 index 0000000000000..91cf2b9084888 Binary files /dev/null and b/.lto.o/95.arm64.lto.o differ diff --git a/.lto.o/96.arm64.lto.o b/.lto.o/96.arm64.lto.o new file mode 100644 index 0000000000000..d236eec7d2b70 Binary files /dev/null and b/.lto.o/96.arm64.lto.o differ diff --git a/.lto.o/97.arm64.lto.o b/.lto.o/97.arm64.lto.o new file mode 100644 index 0000000000000..1812d07eca638 Binary files /dev/null and b/.lto.o/97.arm64.lto.o differ diff --git a/.lto.o/98.arm64.lto.o b/.lto.o/98.arm64.lto.o new file mode 100644 index 0000000000000..027005a7de481 Binary files /dev/null and b/.lto.o/98.arm64.lto.o differ diff --git a/.lto.o/99.arm64.lto.o b/.lto.o/99.arm64.lto.o new file mode 100644 index 0000000000000..8823ff033fa4e Binary files /dev/null and b/.lto.o/99.arm64.lto.o differ diff --git a/BUILD_GUIDE.md b/BUILD_GUIDE.md new file mode 100644 index 0000000000000..ea8b1d4e843ba --- /dev/null +++ b/BUILD_GUIDE.md @@ -0,0 +1,288 @@ +# Firefox Oasis Browser Build Guide + +This guide explains how to build the Firefox Oasis browser with the AI assistant feature enabled. + +## Prerequisites + +- macOS (recent versions; Apple Silicon and Intel are both used in development) +- Node.js and npm installed +- Python 3 +- Git +- Sufficient disk space (Firefox builds require several GB; object directories can be large) + +## Overview + +Building Oasis involves **three outputs** you should refresh when working on the assistant: + +1. **`assistant.bundle.js`** — Core assistant logic (LangGraph, commands, services). Built from `browser/base/content/assistant/build`. +2. **`assistant.ui.bundle.js`** (and **`assistant.ui.bundle.css`**) — Preact sidebar UI. Built from `browser/base/content/assistant/ui-preact`. +3. **The browser** — Packaged via `./mach build` from the repository root. + +Always run **`npm install` / `npm run build`** in both assistant projects when setting up a new clone or after deleting `node_modules`. Then run **`./mach build`** so packaged resources pick up the bundles. + +## Step 1: Build the assistant core bundle + +The main assistant is a TypeScript project bundled with esbuild. + +### Navigate and install + +```bash +cd browser/base/content/assistant/build +npm install +``` + +Dependencies include esbuild, TypeScript, AWS signing helpers, LangChain-related packages, and the Supabase client. + +**Platform binaries**: If you see errors about the wrong platform (for example Windows esbuild on macOS), remove the folder and reinstall: + +```bash +rm -rf node_modules +npm install +``` + +### Build + +```bash +npm run build +``` + +This runs `node esbuild.config.mjs`, compiles `src/`, and writes **`../assistant.bundle.js`** (parent directory is `browser/base/content/assistant/`). + +**Embedding assets (ORT WASM + local MiniLM weights)** are vendored under `browser/base/content/assistant/embedding-assets/` and packaged via `browser/base/jar.mn`. After upgrading `@huggingface/transformers`, run `npm run sync-embedding-assets` then `npm run build:embedding-worker`, and update `jar.mn` if the sync script adds or renames files. + +You should see output similar to: + +``` +../assistant.bundle.js 2.5mb +Done in …ms +``` + +Exact size varies with features and dependencies. + +## Step 2: Build the Preact assistant UI + +The sidebar chat UI is a separate small npm package. + +```bash +cd browser/base/content/assistant/ui-preact +npm install +npm run build +``` + +This produces **`../dist/assistant.ui.bundle.js`** and **`../dist/assistant.ui.bundle.css`**. + +If you change only the core bundle and not the Preact app, you can skip this step. If you change React/Preact components, styles, or hooks under `ui-preact/src/`, you must run this build before `./mach build` (or before testing with a dev workflow that loads the updated files). + +## Step 3: Build the Firefox browser + +### Repository root + +```bash +cd /path/to/firefox-oasis +``` + +Use your actual clone path instead of `/path/to/firefox-oasis`. + +### Branding asset on macOS + +Before a full browser build, ensure the custom branding asset exists: + +```bash +# Only if the file is missing +cp browser/branding/unofficial/Assets.car browser/branding/custom/Assets.car +``` + +Without **`browser/branding/custom/Assets.car`**, macOS builds can fail during packaging steps that expect this file. + +### Run the build + +```bash +./mach build +``` + +Run all **`mach`** commands from the **repository root**, not from subdirectories. + +The build configures the tree, compiles native and JS code, links, and packages the application. First-time or clean builds often take **on the order of 15–25 minutes** depending on CPU, disk, and whether the object directory was empty. Incremental rebuilds are usually much faster. + +You should eventually see: + +``` +Your build was successful! +``` + +Compiler warnings are common; many are suppressed or benign. Fix errors that stop the build. + +### Troubleshooting `./mach build` + +- **Stale mach locks** (rare): + ```bash + rm -f ~/.mozbuild/srcdirs/firefox-oasis-*/_virtualenvs/mach.lock + ``` +- **Missing `Assets.car`**: See the branding step above. +- **Disk space**: Ensure enough free space for `obj-*` and `dist` outputs. + +## Step 4: Run the browser + +```bash +./mach run +``` + +### Opening the assistant + +- Toolbar: **Oasis Assistant** (use **Customize Toolbar** if it is hidden). +- Menu: **View → Sidebar → Oasis Assistant** (exact labels may match your localization). + +### Using the assistant + +- Sign in if your deployment requires authentication for chat and voice APIs. +- Type a message and send, or use voice controls if enabled in your build. + +**Voice input (composer mic)**: Recording is **push-to-talk**. Start with one tap on the microphone; **tap again** to stop, transcribe, and send. The UI should indicate when to tap again. + +**Voice Agent** (full-screen voice mode, when present): Follow on-screen hints; you may tap the orb to finish a listening phase depending on your version. + +## Clean build from scratch (optional) + +Use this when you want a pristine dependency tree and object directory (for example before a release or after strange link or packaging errors). + +```bash +# Assistant bundles — fresh node_modules +cd browser/base/content/assistant/build +rm -rf node_modules && npm install && npm run build + +cd ../ui-preact +rm -rf node_modules && npm install && npm run build + +# Browser — full object directory wipe, then build +cd /path/to/firefox-oasis +./mach --no-interactive clobber objdir --full +./mach build +``` + +A full clobber forces a complete recompile; allow significantly more time than an incremental `./mach build`. + +## Architecture overview + +### Layout (simplified) + +``` +firefox-oasis/ +├── browser/base/content/assistant/ +│ ├── assistant.bundle.js # from build/ (esbuild) +│ ├── dist/ +│ │ ├── assistant.ui.bundle.js # from ui-preact (esbuild) +│ │ └── assistant.ui.bundle.css +│ ├── build/ +│ │ ├── src/ # assistant TypeScript +│ │ ├── package.json +│ │ └── esbuild.config.mjs +│ ├── ui-preact/ +│ │ ├── src/ # Preact UI +│ │ └── package.json +│ ├── assistant.xhtml +│ ├── assistant.ui.js +│ └── bootstrap.js +└── browser/components/sidebar/ + └── browser-sidebar.js # sidebar registration +``` + +### Integration points + +1. **Sidebar**: `browser/components/sidebar/browser-sidebar.js` registers the assistant panel. +2. **Preference**: `browser.sidebar.oasis_assistant.enabled` (default `true`) in `browser/app/profile/firefox.js`. +3. **Toolbar**: Assistant control in `browser/base/content/navigator-toolbox.inc.xhtml` (or equivalent in your branch). +4. **Bootstrap**: `browser/base/content/assistant/bootstrap.js` connects toolbar behavior to the sidebar. + +### Build flow + +``` +Edit assistant/build/src → npm run build → assistant.bundle.js +Edit ui-preact/src → npm run build → dist/assistant.ui.bundle.* +./mach build → resources packaged into the browser +./mach run → test +``` + +## Common issues + +### Assistant UI or bundle does not reflect your edits + +Rebuild the relevant npm project (`build` and/or `ui-preact`), then run `./mach build` so the packaged browser includes the new files. + +### Sidebar missing or broken + +- Confirm `browser.sidebar.oasis_assistant.enabled` is `true`. +- Open the **Browser Console** (e.g. **Tools → Browser Tools → Browser Console**) and check for load errors for `assistant.bundle.js` or `assistant.ui.bundle.js`. + +### Authentication or API errors + +- Check console and network for failed requests. +- Verify Supabase and proxy endpoints in your environment (for example `assistant/build/src/config/env.ts` and related config), without committing secrets. + +## Development workflow (typical) + +**Assistant backend / tools only** + +```bash +cd browser/base/content/assistant/build +npm run build +cd /path/to/firefox-oasis +./mach build +./mach run +``` + +**Preact UI only** + +```bash +cd browser/base/content/assistant/ui-preact +npm run build +cd /path/to/firefox-oasis +./mach build +./mach run +``` + +During rapid UI iteration, your team may use a workflow that reloads bundles without a full browser rebuild; for a **packaged** tree, `./mach build` is the reliable path. + +**Chrome / browser files outside `assistant/`** + +```bash +./mach build +./mach run +``` + +## Quick reference + +```bash +# Full assistant artifacts + browser (from repo root) +cd browser/base/content/assistant/build && npm install && npm run build +cd ../ui-preact && npm install && npm run build +cd /path/to/firefox-oasis +test -f browser/branding/custom/Assets.car || cp browser/branding/unofficial/Assets.car browser/branding/custom/Assets.car +./mach build +./mach run +``` + +```bash +# Assistant core only +cd browser/base/content/assistant/build && npm run build +``` + +```bash +# Preact UI only +cd browser/base/content/assistant/ui-preact && npm run build +``` + +```bash +# Browser only (after other changes) +cd /path/to/firefox-oasis && ./mach build +``` + +## Additional resources + +- Firefox build documentation: https://firefox-source-docs.mozilla.org/setup/ +- Assistant TypeScript: `browser/base/content/assistant/build/src/` +- Preact UI: `browser/base/content/assistant/ui-preact/src/` +- Sidebar: `browser/components/sidebar/browser-sidebar.js` + +--- + +**Last updated**: March 2026 (Preact build step, clean-build notes, voice UX hint). diff --git a/README.md b/README.md index 01457dc06666d..0e94021d451aa 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,13 @@ -![Firefox Browser](./docs/readme/readme-banner.svg) +

+ Oasis +

-[Firefox](https://firefox.com/) is a fast, reliable and private web browser from the non-profit [Mozilla organization](https://mozilla.org/). +**Agentic browser by [Kahana](https://kahana.co).** -### Contributing +Built on Firefox with Oasis-native AI workflows for browsing, reasoning, and action. -To learn how to contribute to Firefox read the [Firefox Contributors' Quick Reference document](https://firefox-source-docs.mozilla.org/contributing/contribution_quickref.html). +## Contributing +- Open issues and pull requests in this repository for Oasis changes. We use [bugzilla.mozilla.org](https://bugzilla.mozilla.org/) as our issue tracker, please file bugs there. @@ -16,3 +19,33 @@ We use [bugzilla.mozilla.org](https://bugzilla.mozilla.org/) as our issue tracke If you have a question about developing Firefox, and can't find the solution on [Firefox Source Docs](https://firefox-source-docs.mozilla.org/), you can try asking your question on Matrix at chat.mozilla.org in the [Introduction channel](https://chat.mozilla.org/#/room/#introduction:mozilla.org). + +### Release Process (Oasis Canary) + +Oasis Canary releases are automated via GitHub Actions using a fail-closed pipeline to ensure security and launch safety. + +#### Release Trigger +1. **Push Tag:** `v*` (e.g., `v135.0.0.1`). +2. **Manual Dispatch:** Rerun existing tag via `workflow_dispatch` input `release_tag`. + +#### Pipeline Stages +1. **Build:** Compiles Firefox with custom branding. +2. **Stage Package:** Creates the raw application bundle structure (resolving symlinks). +3. **Sign & Notarize (App):** + * Uses `rcodesign` to sign the App Bundle using the Developer ID Application certificate. + * Submits to Apple Notarization Service. + * **Fail-Closed Gate:** If notarization fails, the workflow exits. + * Staples the notarization ticket to the App Bundle. +4. **Package DMG:** + * Wraps the *signed and notarized* App Bundle into a DMG. + * Applies branding (background, icons, DS_Store). +5. **Sign & Notarize (DMG):** + * Signs the DMG container itself. + * Submits DMG to Apple Notarization Service. + * **Fail-Closed Gate:** If DMG notarization fails, the workflow exits. +6. **MAR Generation:** + * Generates the Mozilla ARchive (MAR) from the signed/notarized App Bundle. + * Signs the MAR with the Oasis Release Certificate. +7. **Publish:** + * Creates a GitHub Release with the signed DMG and MAR. + * Updates the Supabase update ring pointer only if all previous steps succeeded. diff --git a/README_NOTARIZATION.md b/README_NOTARIZATION.md new file mode 100644 index 0000000000000..2794325081b05 --- /dev/null +++ b/README_NOTARIZATION.md @@ -0,0 +1,46 @@ +# 🍎 Oasis Browser - Release & Notarization + +## 🎯 Quick Start for Team Members + +### For Release & Notarization: +```bash +# Navigate to the notarization directory +cd notarization + +# Follow the complete guide +open docs/NOTARIZATION_SUCCESS_GUIDE.md +``` + +### Prerequisites: +1. **Apple Developer Account** with Developer ID Application certificate +2. **Certificate File** (`developer_id.p12`) - Place in `notarization/` directory +3. **App Store Connect API Key** for notarization +4. **Built Firefox Application** in `obj-*/dist/` directory + +## 📚 Complete Documentation + +### 🏆 Main Guide +- **[notarization/docs/NOTARIZATION_SUCCESS_GUIDE.md](notarization/docs/NOTARIZATION_SUCCESS_GUIDE.md)** - Complete 50+ page guide + +### 🛠️ Quick Commands +```bash +# Run notarization +cd notarization && ./scripts/resolve_symlinks_and_sign.sh + +# Test before notarization +cd notarization && ./scripts/pre_notarization_test.sh +``` + +## 🔐 Security Notes + +- **Certificate files are NOT in the repository** (security) +- **Place your `developer_id.p12` in `notarization/` directory** +- **Set permissions**: `chmod 600 notarization/developer_id.p12` + +## ✅ Success Rate: 100% + +The notarization process has been fully tested and documented with a 100% success rate. + +--- + +**For complete instructions, see**: [notarization/README.md](notarization/README.md) diff --git a/RELEASE_GUIDE.md b/RELEASE_GUIDE.md new file mode 100644 index 0000000000000..81401efdcf834 --- /dev/null +++ b/RELEASE_GUIDE.md @@ -0,0 +1,261 @@ +# Oasis Browser Release Guide + +## 🎯 Overview + +This guide documents the complete process for building, signing, and packaging the Oasis Browser for distribution. The Oasis Browser is a custom Firefox variant with enhanced branding and privacy features. + +## 📋 Prerequisites + +### System Requirements +- **macOS**: 10.15+ (Catalina or later) +- **RAM**: 8GB minimum, 16GB recommended +- **Storage**: 20GB free space minimum +- **CPU**: Multi-core processor recommended + +### Required Software +```bash +# Install Xcode Command Line Tools +xcode-select --install + +# Install Homebrew (if not already installed) +/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" + +# Install Python 3 +brew install python@3.11 + +# Install Mercurial (for source control) +brew install mercurial +``` + +### Apple Developer Account +- **Apple ID**: Required for code signing +- **Developer ID Application Certificate**: For code signing +- **App-Specific Password**: For notarization (optional) + +## 🚀 Build Process + +### 1. Repository Setup +```bash +# Clone the repository +git clone https://github.com/Kahana-LLC/firefox-oasis.git +cd firefox-oasis + +# Check current branch +git branch --show-current +# Should be on: release-v1.2.0 +``` + +### 2. Build Environment +```bash +# Bootstrap the build environment +./mach bootstrap --no-interactive + +# Verify setup +./mach doctor +# Should show: "Your system is ready to build Firefox!" +``` + +### 3. Build the Browser +```bash +# Clean any previous builds (optional) +./mach clobber + +# Configure for development +./mach configure + +# Build Oasis Browser +./mach build +# This will take 30-60 minutes depending on your system +``` + +### 4. Test the Build +```bash +# Run the browser to test +./mach run + +# Or run directly +open obj-aarch64-apple-darwin24.6.0/dist/Oasis.app +``` + +## 📦 Packaging Process + +### 1. Create Unsigned DMG +```bash +# Make the script executable +chmod +x create_simple_dmg.sh + +# Create unsigned DMG +./create_simple_dmg.sh +``` + +**Output**: `Oasis-Browser-1.2.0-YYYYMMDD.dmg` + +### 2. Create Code-Signed DMG (Recommended) +```bash +# Make the script executable +chmod +x create_signed_dmg_only.sh + +# Create code-signed DMG +./create_signed_dmg_only.sh +``` + +**Output**: `Oasis-Browser-1.2.0-Signed-YYYYMMDD.dmg` + +## 🔐 Code Signing Setup + +### 1. Verify Developer Certificate +```bash +# Check available certificates +security find-identity -v -p codesigning + +# Should show: "Developer ID Application: Adam Richard Kershner (NV6BDYHYA5)" +``` + +### 2. Update Signing Configuration +Edit `create_signed_dmg_only.sh` and update: +- `DEVELOPER_ID`: Your Developer ID certificate name +- `APPLE_ID`: Your Apple ID email +- `TEAM_ID`: Your Apple Developer Team ID + +### 3. Signing Process +The signing script will: +1. Create a copy of the app for signing +2. Remove problematic files that can't be signed +3. Sign all dylibs, executables, and app bundles +4. Sign the main app bundle +5. Create a DMG with the signed app + +## 📁 File Structure + +### Key Files Created +``` +firefox-oasis/ +├── create_simple_dmg.sh # Creates unsigned DMG +├── create_signed_dmg_only.sh # Creates code-signed DMG +├── entitlements.plist # Code signing entitlements +├── RELEASE_GUIDE.md # This guide +└── obj-aarch64-apple-darwin24.6.0/ + └── dist/ + ├── Oasis.app # Built application + └── Oasis-Signed.app # Code-signed application +``` + +### DMG Contents +- **Oasis Browser.app**: The main application +- **Applications**: Symbolic link to Applications folder +- **README.txt**: Installation instructions + +## 🎨 Branding Features + +The Oasis Browser includes the following custom branding: +- **App Name**: "Oasis Browser" instead of Firefox +- **Custom Icons**: Oasis-specific app icons +- **Enhanced Privacy**: Privacy-focused features +- **Custom Branding**: Throughout the user interface + +## 📋 Release Checklist + +### Before Building +- [ ] Verify you're on the correct branch (`release-v1.2.0`) +- [ ] Ensure all branding changes are committed +- [ ] Clean any previous builds if needed + +### Build Process +- [ ] Run `./mach bootstrap --no-interactive` +- [ ] Run `./mach configure` +- [ ] Run `./mach build` +- [ ] Test the build with `./mach run` + +### Packaging +- [ ] Create unsigned DMG with `./create_simple_dmg.sh` +- [ ] Create signed DMG with `./create_signed_dmg_only.sh` +- [ ] Test both DMGs on a clean macOS system + +### Distribution +- [ ] Verify DMG opens correctly +- [ ] Test installation process +- [ ] Verify app launches without errors +- [ ] Share DMG with team members + +## 🔧 Troubleshooting + +### Build Issues +```bash +# Clean and rebuild +./mach clobber +./mach configure +./mach build +``` + +### Signing Issues +```bash +# Check certificate +security find-identity -v -p codesigning + +# Verify app structure +codesign --verify --verbose obj-aarch64-apple-darwin24.6.0/dist/Oasis-Signed.app +``` + +### DMG Issues +```bash +# Check DMG integrity +hdiutil verify Oasis-Browser-*.dmg + +# Mount and test +hdiutil attach Oasis-Browser-*.dmg +``` + +## 📊 Release Information + +### Current Release +- **Version**: 1.2.0 +- **Build Date**: September 12, 2024 +- **Branch**: release-v1.2.0 +- **Status**: Code Signed ✅ + +### File Sizes +- **Unsigned DMG**: ~211MB +- **Signed DMG**: ~212MB +- **App Bundle**: ~200MB + +## 🚀 Future Releases + +### Version Updates +1. Update version numbers in scripts +2. Update branch name if needed +3. Follow the same build process +4. Test thoroughly before distribution + +### Script Maintenance +- Update `DEVELOPER_ID` if certificate changes +- Update `APPLE_ID` if Apple ID changes +- Update `TEAM_ID` if team changes +- Test scripts on clean macOS system + +## 📞 Support + +### Getting Help +- **Documentation**: Check this guide first +- **Issues**: File bugs on GitHub Issues +- **Community**: Contact the development team + +### Common Questions + +**Q: Why is the app not notarized?** +A: The current build is code-signed but not notarized. This provides good security while avoiding the complexity of notarization. Users may see a one-time security warning. + +**Q: Can I notarize the app?** +A: Yes, but it requires additional setup and may have issues with the complex Firefox build structure. The current code-signed version works well for most use cases. + +**Q: How do I update the branding?** +A: Modify the branding files in the `browser/branding/` directory and rebuild. + +## 🎉 Success! + +You now have a complete, working Oasis Browser that can be distributed to team members. The code-signed DMG provides a professional installation experience with minimal security warnings. + +--- + +**Last Updated**: September 12, 2024 +**Version**: 1.2.0 +**Status**: Production Ready ✅ diff --git a/SUPABASE_AUTH_IMPLEMENTATION_GUIDE.md b/SUPABASE_AUTH_IMPLEMENTATION_GUIDE.md new file mode 100644 index 0000000000000..5e05548e9a5f7 --- /dev/null +++ b/SUPABASE_AUTH_IMPLEMENTATION_GUIDE.md @@ -0,0 +1,1093 @@ +# Supabase Authentication Implementation Guide + +## Overview + +This guide provides complete information for re-implementing the Supabase authentication system from the Oasis Electron browser in any other project. It includes all necessary configuration, database schema, authentication methods, and implementation details. + +## Table of Contents + +1. [Environment Configuration](#environment-configuration) +2. [Database Schema](#database-schema) +3. [Supabase Project Setup](#supabase-project-setup) +4. [Authentication Service Implementation](#authentication-service-implementation) +5. [OAuth Flow Implementation](#oauth-flow-implementation) +6. [Session Management](#session-management) +7. [Error Handling](#error-handling) +8. [Usage Examples](#usage-examples) +9. [Security Considerations](#security-considerations) + +## Environment Configuration + +### Required Environment Variables + +Create a `.env` file with the following variables: + +```env +# Supabase Configuration +SUPABASE_URL=https://wvclepquxxczgrukfqyr.supabase.co +SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Ind2Y2xlcHF1eHhjemdydWtmcXlyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTUwODU5OTksImV4cCI6MjA3MDY2MTk5OX0.T-hZ_8QxtVnOt0mtCY_Zch87SYEcsyQZwnvvFAtZiNY + +# Google OAuth Configuration (Optional - for OAuth flow) +GOOGLE_CLIENT_ID=your_google_client_id +GOOGLE_CLIENT_SECRET=your_google_client_secret + +# Application Configuration +APP_VERSION=1.0.0 +LOG_LEVEL=info +``` + +**ℹ️ Note about Supabase Anon Key:** +- The anon key is designed to be public and safe to include in client-side code +- Data access is controlled by Row Level Security (RLS) policies +- Supabase has built-in rate limiting to prevent abuse +- This key can be safely committed to version control + +### Environment Configuration Class + +```typescript +// config/env.ts +import * as dotenv from 'dotenv'; + +// Load environment variables +dotenv.config(); + +export const ENV = { + // Supabase configuration + SUPABASE_URL: process.env.SUPABASE_URL || '', + SUPABASE_ANON_KEY: process.env.SUPABASE_ANON_KEY || '', + + // Google OAuth configuration + GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID || '', + GOOGLE_CLIENT_SECRET: process.env.GOOGLE_CLIENT_SECRET || '', + + // Application configuration + APP_VERSION: process.env.APP_VERSION || '1.0.0', + LOG_LEVEL: process.env.LOG_LEVEL || 'info', + + // Validate environment variables + validate(): void { + if (!this.SUPABASE_URL) { + throw new Error('SUPABASE_URL is required'); + } + if (!this.SUPABASE_ANON_KEY) { + throw new Error('SUPABASE_ANON_KEY is required'); + } + } +}; +``` + +## Database Schema + +### Required Supabase Tables + +#### 1. Users Table + +```sql +-- Create users table +CREATE TABLE users ( + user_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + name TEXT, + email TEXT UNIQUE NOT NULL, + password_hash TEXT, -- Handled by Supabase Auth + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + last_login TIMESTAMP WITH TIME ZONE, + status TEXT DEFAULT 'active' CHECK (status IN ('active', 'suspended')) +); + +-- Create index for email lookups +CREATE INDEX idx_users_email ON users(email); + +-- Enable Row Level Security +ALTER TABLE users ENABLE ROW LEVEL SECURITY; + +-- Create policy for users to access their own data +CREATE POLICY "Users can view own profile" ON users + FOR SELECT USING (auth.uid() = user_id); + +CREATE POLICY "Users can update own profile" ON users + FOR UPDATE USING (auth.uid() = user_id); + +CREATE POLICY "Users can insert own profile" ON users + FOR INSERT WITH CHECK (auth.uid() = user_id); +``` + +After OAuth, a row must exist in `public.users` with `user_id = auth.uid()` so `llm_usage` and other foreign keys succeed. Prefer an `AFTER INSERT` trigger on `auth.users` (security definer) that upserts into `public.users`; see [`supabase/migrations/20260412000000_oasis_auth_users_sync.sql`](supabase/migrations/20260412000000_oasis_auth_users_sync.sql). Deploy [`supabase/migrations/20260412100000_oasis_assist_chain_complete.sql`](supabase/migrations/20260412100000_oasis_assist_chain_complete.sql) for grants, missing RLS policies, `sessions` UPDATE, `ensure_user_profile` RPC, backfill, and `llm_usage` column fixes. Read-only checks: [`supabase/verify_assist_chain.sql`](supabase/verify_assist_chain.sql). + +The browser calls `ensure_user_profile` after sign-in so a profile row exists even if client-side `INSERT` into `users` is blocked by RLS during rollout. + +Idempotent backfill (also included in the migration above): + +```sql +INSERT INTO public.users (user_id, email, name, password_hash, status) +SELECT + au.id, + COALESCE(au.email, ''), + COALESCE( + NULLIF(BTRIM(au.raw_user_meta_data->>'full_name'), ''), + NULLIF(BTRIM(au.raw_user_meta_data->>'name'), ''), + NULLIF(BTRIM(SPLIT_PART(COALESCE(au.email, ''), '@', 1)), '') + ), + '', + 'active' +FROM auth.users au +ON CONFLICT (user_id) DO UPDATE SET + email = CASE + WHEN EXCLUDED.email IS NOT NULL AND BTRIM(EXCLUDED.email) <> '' THEN EXCLUDED.email + ELSE public.users.email + END, + name = COALESCE( + NULLIF(BTRIM(EXCLUDED.name), ''), + public.users.name + ); +``` + +**Manual E2E after deploy:** sign in, confirm a row in `public.users` for your UUID, run an assist chat request, and confirm no HTTP500 with `usage_record_failed` in the network log. + +#### 2. Sessions Table + +```sql +-- Create sessions table +CREATE TABLE sessions ( + session_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID REFERENCES users(user_id) ON DELETE CASCADE, + started_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + ended_at TIMESTAMP WITH TIME ZONE, + device_info JSONB +); + +-- Create index for user sessions +CREATE INDEX idx_sessions_user_id ON sessions(user_id); + +-- Enable Row Level Security +ALTER TABLE sessions ENABLE ROW LEVEL SECURITY; + +-- Create policy for users to access their own sessions +CREATE POLICY "Users can view own sessions" ON sessions + FOR SELECT USING (auth.uid() = user_id); + +CREATE POLICY "Users can insert own sessions" ON sessions + FOR INSERT WITH CHECK (auth.uid() = user_id); + +CREATE POLICY "Users can update own sessions" ON sessions + FOR UPDATE USING (auth.uid() = user_id); +``` + +#### 3. LLM Usage Table (Optional - for AI features) + +```sql +-- Create llm_usage table for tracking AI assistant usage +CREATE TABLE llm_usage ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID REFERENCES users(user_id) ON DELETE CASCADE, + tokens_used INTEGER NOT NULL DEFAULT 0, + usage_count INTEGER DEFAULT 1, + prompt_summary TEXT, + model_used TEXT, + success BOOLEAN DEFAULT true, + latency_ms INTEGER, + command_type TEXT, + user_intent TEXT, + input_tokens INTEGER, + output_tokens INTEGER, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); + +-- Create index for user usage tracking +CREATE INDEX idx_llm_usage_user_id ON llm_usage(user_id); + +-- Enable Row Level Security +ALTER TABLE llm_usage ENABLE ROW LEVEL SECURITY; + +-- Create policy for users to access their own usage data +CREATE POLICY "Users can view own usage" ON llm_usage + FOR SELECT USING (auth.uid() = user_id); + +CREATE POLICY "Users can insert own usage" ON llm_usage + FOR INSERT WITH CHECK (auth.uid() = user_id); +``` + +#### 4. Bookmarks History Table (Optional - for browser features) + +```sql +-- Create bookmarks_history table +CREATE TABLE bookmarks_history ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID REFERENCES users(user_id) ON DELETE CASCADE, + url TEXT NOT NULL, + title TEXT, + is_bookmarked BOOLEAN DEFAULT false, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); + +-- Create index for user bookmarks +CREATE INDEX idx_bookmarks_user_id ON bookmarks_history(user_id); + +-- Enable Row Level Security +ALTER TABLE bookmarks_history ENABLE ROW LEVEL SECURITY; + +-- Create policy for users to access their own bookmarks +CREATE POLICY "Users can view own bookmarks" ON bookmarks_history + FOR SELECT USING (auth.uid() = user_id); + +CREATE POLICY "Users can insert own bookmarks" ON bookmarks_history + FOR INSERT WITH CHECK (auth.uid() = user_id); +``` + +## Supabase Project Setup + +### 1. Supabase Project Configuration + +- **Project URL**: `https://wvclepquxxczgrukfqyr.supabase.co` +- **Anon Key**: `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Ind2Y2xlcHF1eHhjemdydWtmcXlyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTUwODU5OTksImV4cCI6MjA3MDY2MTk5OX0.T-hZ_8QxtVnOt0mtCY_Zch87SYEcsyQZwnvvFAtZiNY` + +### 2. Authentication Providers Setup + +In your Supabase dashboard: + +1. Go to Authentication > Providers +2. Enable Email provider +3. Enable Google OAuth provider +4. Configure Google OAuth with your client credentials +5. Set redirect URLs for your application + +### 3. Custom Protocol Setup (for OAuth) + +For the OAuth flow, configure a custom protocol handler: +- **Protocol**: `kahana://auth-callback` +- **Redirect URL**: `kahana://auth-callback` + +## Authentication Service Implementation + +### TypeScript Interfaces + +```typescript +// types/auth.ts +import { User, Session, AuthError } from '@supabase/supabase-js'; + +export interface UserProfile { + user_id: string; + name?: string; + email: string; + created_at: string; + last_login?: string; + status: 'active' | 'suspended'; +} + +export interface UserSession { + session_id: string; + user_id: string; + started_at: string; + ended_at?: string; + device_info?: { + platform: string; + version: string; + userAgent?: string; + }; +} + +export interface AuthState { + user: User | null; + session: Session | null; + isAuthenticated: boolean; +} +``` + +### Main Authentication Service + +```typescript +// services/SupabaseAuth.ts +import { createClient, SupabaseClient, User, Session, AuthError } from '@supabase/supabase-js'; +import { ENV } from '../config/env'; +import { UserProfile, UserSession, AuthState } from '../types/auth'; + +export class SupabaseAuth { + private static instance: SupabaseAuth; + private supabase: SupabaseClient; + private currentSession: UserSession | null = null; + private authStateCallbacks: Array<(state: AuthState) => void> = []; + + private constructor() { + // Initialize Supabase client + this.supabase = createClient(ENV.SUPABASE_URL, ENV.SUPABASE_ANON_KEY); + + // Set up auth state change listener + this.supabase.auth.onAuthStateChange((event, session) => { + console.log('Auth state changed:', event); + this.handleAuthStateChange(event, session); + }); + } + + public static getInstance(): SupabaseAuth { + if (!SupabaseAuth.instance) { + SupabaseAuth.instance = new SupabaseAuth(); + } + return SupabaseAuth.instance; + } + + // Email/Password Authentication + public async signInWithEmail(email: string, password: string): Promise<{ user: User | null; error: AuthError | null }> { + try { + console.log('Attempting email sign in for:', email); + + const { data, error } = await this.supabase.auth.signInWithPassword({ + email, + password + }); + + if (error) { + console.error('Email sign in error:', error.message); + return { user: null, error }; + } + + if (data.user) { + await this.updateLastLogin(data.user.id); + await this.createSession(data.user.id); + console.log('Email sign in successful for user:', data.user.id); + } + + return { user: data.user, error: null }; + } catch (error) { + console.error('Sign in error:', error); + return { user: null, error: error as AuthError }; + } + } + + public async signUp(email: string, password: string, name?: string): Promise<{ user: User | null; error: AuthError | null }> { + try { + console.log('Attempting sign up for:', email); + + const { data, error } = await this.supabase.auth.signUp({ + email, + password, + options: { + data: { + name: name || email.split('@')[0] + } + } + }); + + if (error) { + console.error('Sign up error:', error.message); + return { user: null, error }; + } + + if (data.user) { + // Create user profile in our custom users table + await this.createUserProfile(data.user, name); + console.log('Sign up successful for user:', data.user.id); + } + + return { user: data.user, error: null }; + } catch (error) { + console.error('Sign up error:', error); + return { user: null, error: error as AuthError }; + } + } + + public async signOut(): Promise<{ error: AuthError | null }> { + try { + console.log('Attempting sign out'); + + // End current session if exists + if (this.currentSession) { + await this.endSession(this.currentSession.session_id); + } + + const { error } = await this.supabase.auth.signOut(); + + if (error) { + console.error('Sign out error:', error.message); + return { error }; + } + + this.currentSession = null; + console.log('Sign out successful'); + return { error: null }; + } catch (error) { + console.error('Sign out error:', error); + return { error: error as AuthError }; + } + } + + // Session Management + public async getCurrentUser(): Promise { + const { data: { user } } = await this.supabase.auth.getUser(); + return user; + } + + public async getSession(): Promise { + const { data: { session } } = await this.supabase.auth.getSession(); + return session; + } + + public async isAuthenticated(): Promise { + const user = await this.getCurrentUser(); + return user !== null; + } + + // User Profile Management + public async getUserProfile(): Promise { + try { + const user = await this.getCurrentUser(); + if (!user) return null; + + const { data, error } = await this.supabase + .from('users') + .select('*') + .eq('user_id', user.id) + .single(); + + if (error) { + console.error('Error fetching user profile:', error.message); + return null; + } + + return data as UserProfile; + } catch (error) { + console.error('Error fetching user profile:', error); + return null; + } + } + + public async updateUserProfile(updates: Partial): Promise<{ error: string | null }> { + try { + const user = await this.getCurrentUser(); + if (!user) { + return { error: 'No authenticated user' }; + } + + const { error } = await this.supabase + .from('users') + .update(updates) + .eq('user_id', user.id); + + if (error) { + console.error('Error updating user profile:', error.message); + return { error: error.message }; + } + + return { error: null }; + } catch (error) { + console.error('Error updating user profile:', error); + return { error: error instanceof Error ? error.message : 'Unknown error' }; + } + } + + // Password Management + public async updatePassword(newPassword: string): Promise<{ error: AuthError | null }> { + try { + const { error } = await this.supabase.auth.updateUser({ + password: newPassword + }); + + if (error) { + console.error('Error updating password:', error.message); + return { error }; + } + + return { error: null }; + } catch (error) { + console.error('Error updating password:', error); + return { error: error as AuthError }; + } + } + + public async resetPassword(email: string): Promise<{ error: AuthError | null }> { + try { + const { error } = await this.supabase.auth.resetPasswordForEmail(email); + + if (error) { + console.error('Error sending password reset:', error.message); + return { error }; + } + + return { error: null }; + } catch (error) { + console.error('Error sending password reset:', error); + return { error: error as AuthError }; + } + } + + // Auth State Management + public onAuthStateChange(callback: (state: AuthState) => void): void { + this.authStateCallbacks.push(callback); + } + + private async handleAuthStateChange(event: string, session: Session | null): Promise { + const user = session?.user || null; + const authState: AuthState = { + user, + session, + isAuthenticated: user !== null + }; + + // Notify all callbacks + this.authStateCallbacks.forEach(callback => { + try { + callback(authState); + } catch (error) { + console.error('Error in auth state callback:', error); + } + }); + + // Handle session creation/destruction + if (event === 'SIGNED_IN' && user) { + await this.createSession(user.id); + } else if (event === 'SIGNED_OUT' && this.currentSession) { + await this.endSession(this.currentSession.session_id); + this.currentSession = null; + } + } + + // Database Operations + private async createUserProfile(user: User, name?: string): Promise { + try { + const { error } = await this.supabase + .from('users') + .insert({ + user_id: user.id, + email: user.email!, + name: name || user.user_metadata?.name || user.email!.split('@')[0], + password_hash: '', // Supabase handles this + status: 'active' + }); + + if (error) { + console.error('Error creating user profile:', error.message); + } else { + console.log('User profile created successfully'); + } + } catch (error) { + console.error('Error creating user profile:', error); + } + } + + private async updateLastLogin(userId: string): Promise { + try { + const { error } = await this.supabase + .from('users') + .update({ last_login: new Date().toISOString() }) + .eq('user_id', userId); + + if (error) { + console.error('Error updating last login:', error.message); + } + } catch (error) { + console.error('Error updating last login:', error); + } + } + + private async createSession(userId: string): Promise { + try { + const deviceInfo = { + platform: typeof window !== 'undefined' ? 'browser' : 'server', + version: ENV.APP_VERSION, + userAgent: typeof window !== 'undefined' ? window.navigator.userAgent : 'Server' + }; + + const { data, error } = await this.supabase + .from('sessions') + .insert({ + user_id: userId, + device_info: deviceInfo + }) + .select() + .single(); + + if (error) { + console.error('Error creating session:', error.message); + } else if (data) { + this.currentSession = data as UserSession; + console.log('Session created:', data.session_id); + } + } catch (error) { + console.error('Error creating session:', error); + } + } + + private async endSession(sessionId: string): Promise { + try { + const { error } = await this.supabase + .from('sessions') + .update({ ended_at: new Date().toISOString() }) + .eq('session_id', sessionId); + + if (error) { + console.error('Error ending session:', error.message); + } else { + console.log('Session ended:', sessionId); + } + } catch (error) { + console.error('Error ending session:', error); + } + } + + // Utility Methods + public handleAuthError(error: AuthError): string { + switch (error.message) { + case 'Invalid login credentials': + return 'Invalid email or password. Please try again.'; + case 'Email not confirmed': + return 'Please check your email and click the confirmation link.'; + case 'User already registered': + return 'An account with this email already exists.'; + case 'Password should be at least 6 characters': + return 'Password must be at least 6 characters long.'; + case 'Unable to validate email address: invalid format': + return 'Please enter a valid email address.'; + default: + return error.message || 'An unexpected error occurred. Please try again.'; + } + } + + // Check if email exists in database + public async checkEmailExists(email: string): Promise<{ exists: boolean; user?: UserProfile; error?: string }> { + try { + const { data, error } = await this.supabase + .from('users') + .select('user_id, name, email, created_at, status') + .eq('email', email.toLowerCase().trim()) + .single(); + + if (error) { + // PGRST116 means no rows found, which is expected for new users + if (error.code === 'PGRST116') { + return { exists: false }; + } + console.error('Email check error:', error.message); + return { exists: false, error: 'Database error' }; + } + + return { exists: true, user: data as UserProfile }; + } catch (error) { + console.error('Email verification error:', error); + return { exists: false, error: 'Verification failed' }; + } + } +} + +// Export singleton instance +export const supabaseAuth = SupabaseAuth.getInstance(); +``` + +## OAuth Flow Implementation + +### Google OAuth with Custom Protocol + +```typescript +// Add to SupabaseAuth class +public async signInWithGoogle(): Promise<{ user: User | null; error: AuthError | null }> { + try { + console.log('Attempting Google sign in with OAuth flow'); + + // Check if user is already authenticated + const currentUser = await this.getCurrentUser(); + if (currentUser) { + console.log('User already authenticated:', currentUser.id); + return { user: currentUser, error: null }; + } + + // Generate OAuth URL with Supabase + const { data, error } = await this.supabase.auth.signInWithOAuth({ + provider: 'google', + options: { + skipBrowserRedirect: true, + // Use a custom protocol the app can handle + redirectTo: 'kahana://auth-callback', + // Request consent prompt and offline access for refresh token + queryParams: { + prompt: 'select_account', + access_type: 'offline', + include_granted_scopes: 'true', + response_type: 'code' + } + } + }); + + if (error || !data.url) { + console.error('Failed to generate OAuth URL:', error); + return { user: null, error: error || { message: 'Failed to generate OAuth URL', status: 500 } as AuthError }; + } + + console.log('Generated OAuth URL, opening in browser...'); + + // Open the OAuth URL in browser + if (typeof window !== 'undefined') { + window.open(data.url, '_blank'); + } + + // Return a success message indicating OAuth was initiated + return { user: null, error: null }; + + } catch (error) { + console.error('Google sign in error:', error); + return { user: null, error: error as AuthError }; + } +} + +/** + * Handle OAuth redirect deep link (e.g., kahana://auth-callback?code=...) + * Exchanges the code for a session or sets the session from hash tokens. + */ +public async handleOAuthRedirectCallback(callbackUrl: string): Promise<{ success: boolean; error?: string }> { + try { + console.log('Handling OAuth redirect callback:', callbackUrl); + const urlObj = new URL(callbackUrl); + if (urlObj.protocol !== 'kahana:') { + console.warn('Invalid protocol in callback URL:', urlObj.protocol); + return { success: false, error: 'Invalid protocol' }; + } + + // Prefer PKCE code exchange + const authCode = urlObj.searchParams.get('code'); + const errorParam = urlObj.searchParams.get('error'); + const errorDescription = urlObj.searchParams.get('error_description'); + + if (errorParam) { + console.error('OAuth redirect contained error:', errorParam, errorDescription); + return { success: false, error: errorDescription || errorParam }; + } + + if (authCode) { + console.log('Exchanging auth code for session...'); + const { data, error } = await this.supabase.auth.exchangeCodeForSession(authCode); + if (error) { + console.error('Failed to exchange code for session:', error.message); + return { success: false, error: error.message }; + } else { + console.log('Exchanged code for session for user:', data.user?.id); + + // Ensure user profile exists + if (data.user) { + const existingProfile = await this.getUserProfile(); + if (!existingProfile) { + await this.createUserProfile(data.user, data.user.user_metadata?.name); + console.log('Created user profile from OAuth callback'); + } + + // Update last login and create session + await this.updateLastLogin(data.user.id); + await this.createSession(data.user.id); + } + + return { success: true }; + } + } + + // Fallback: handle implicit flow fragments (access_token in hash) + if (urlObj.hash && urlObj.hash.startsWith('#')) { + console.log('Handling implicit flow with hash tokens...'); + const hashParams = new URLSearchParams(urlObj.hash.substring(1)); + const accessToken = hashParams.get('access_token'); + const refreshToken = hashParams.get('refresh_token'); + if (accessToken && refreshToken) { + const { data, error } = await this.supabase.auth.setSession({ + access_token: accessToken, + refresh_token: refreshToken + }); + if (error) { + console.error('Failed to set session from hash tokens:', error.message); + return { success: false, error: error.message }; + } else { + console.log('Set session from hash tokens for user:', data.user?.id); + + // Ensure user profile exists + if (data.user) { + const existingProfile = await this.getUserProfile(); + if (!existingProfile) { + await this.createUserProfile(data.user, data.user.user_metadata?.name); + console.log('Created user profile from hash tokens'); + } + + // Update last login and create session + await this.updateLastLogin(data.user.id); + await this.createSession(data.user.id); + } + + return { success: true }; + } + } else { + console.warn('OAuth redirect missing tokens in hash'); + return { success: false, error: 'Missing tokens in hash' }; + } + } + + console.warn('No valid OAuth response found in callback'); + return { success: false, error: 'No valid OAuth response' }; + + } catch (error) { + console.error('Error handling OAuth redirect callback:', error); + return { success: false, error: error instanceof Error ? error.message : 'Unknown error' }; + } +} +``` + +### Custom Protocol Handler (Electron) + +For Electron applications, register the custom protocol: + +```typescript +// main.ts (Electron main process) +import { app, protocol } from 'electron'; +import { supabaseAuth } from './services/SupabaseAuth'; + +// Register custom protocol +app.setAsDefaultProtocolClient('kahana'); + +// Handle protocol URLs +app.on('open-url', async (event, url) => { + event.preventDefault(); + console.log('Received protocol URL:', url); + + if (url.startsWith('kahana://auth-callback')) { + const result = await supabaseAuth.handleOAuthRedirectCallback(url); + if (result.success) { + console.log('OAuth authentication successful'); + } else { + console.error('OAuth authentication failed:', result.error); + } + } +}); + +// Handle protocol URLs on Windows +app.on('second-instance', async (event, commandLine, workingDirectory) => { + const url = commandLine.find(arg => arg.startsWith('kahana://')); + if (url) { + console.log('Received protocol URL from second instance:', url); + + if (url.startsWith('kahana://auth-callback')) { + const result = await supabaseAuth.handleOAuthRedirectCallback(url); + if (result.success) { + console.log('OAuth authentication successful'); + } else { + console.error('OAuth authentication failed:', result.error); + } + } + } +}); +``` + +## Session Management + +### Session Tracking + +The authentication service automatically tracks user sessions in the database. Each session includes: + +- **Session ID**: Unique identifier +- **User ID**: Reference to the user +- **Start Time**: When the session began +- **End Time**: When the session ended (null for active sessions) +- **Device Info**: Platform, version, and user agent information + +### Session Lifecycle + +1. **Session Creation**: Automatically created when user signs in +2. **Session Updates**: Last login time updated on each authentication +3. **Session Termination**: Automatically ended when user signs out + +## Error Handling + +### Common Authentication Errors + +```typescript +// Error handling utility +export const handleAuthError = (error: AuthError): string => { + switch (error.message) { + case 'Invalid login credentials': + return 'Invalid email or password. Please try again.'; + case 'Email not confirmed': + return 'Please check your email and click the confirmation link.'; + case 'User already registered': + return 'An account with this email already exists.'; + case 'Password should be at least 6 characters': + return 'Password must be at least 6 characters long.'; + case 'Unable to validate email address: invalid format': + return 'Please enter a valid email address.'; + case 'Too many requests': + return 'Too many attempts. Please try again later.'; + default: + return error.message || 'An unexpected error occurred. Please try again.'; + } +}; +``` + +## Usage Examples + +### Basic Authentication Flow + +```typescript +import { supabaseAuth } from './services/SupabaseAuth'; + +// Sign up a new user +const signUpUser = async (email: string, password: string, name: string) => { + const { user, error } = await supabaseAuth.signUp(email, password, name); + + if (error) { + console.error('Sign up failed:', supabaseAuth.handleAuthError(error)); + return false; + } + + console.log('User signed up successfully:', user?.id); + return true; +}; + +// Sign in existing user +const signInUser = async (email: string, password: string) => { + const { user, error } = await supabaseAuth.signInWithEmail(email, password); + + if (error) { + console.error('Sign in failed:', supabaseAuth.handleAuthError(error)); + return false; + } + + console.log('User signed in successfully:', user?.id); + return true; +}; + +// Sign in with Google OAuth +const signInWithGoogle = async () => { + const { user, error } = await supabaseAuth.signInWithGoogle(); + + if (error) { + console.error('Google sign in failed:', supabaseAuth.handleAuthError(error)); + return false; + } + + console.log('Google sign in initiated'); + return true; +}; + +// Check authentication status +const checkAuthStatus = async () => { + const isAuthenticated = await supabaseAuth.isAuthenticated(); + const user = await supabaseAuth.getCurrentUser(); + const profile = await supabaseAuth.getUserProfile(); + + console.log('Auth status:', { isAuthenticated, user: user?.id, profile }); + return { isAuthenticated, user, profile }; +}; + +// Sign out +const signOutUser = async () => { + const { error } = await supabaseAuth.signOut(); + + if (error) { + console.error('Sign out failed:', supabaseAuth.handleAuthError(error)); + return false; + } + + console.log('User signed out successfully'); + return true; +}; +``` + +### Auth State Monitoring + +```typescript +// Listen for authentication state changes +supabaseAuth.onAuthStateChange((authState) => { + console.log('Auth state changed:', authState); + + if (authState.isAuthenticated) { + console.log('User is authenticated:', authState.user?.email); + // Update UI to show authenticated state + } else { + console.log('User is not authenticated'); + // Update UI to show unauthenticated state + } +}); +``` + +### User Profile Management + +```typescript +// Get user profile +const getUserProfile = async () => { + const profile = await supabaseAuth.getUserProfile(); + + if (profile) { + console.log('User profile:', profile); + return profile; + } else { + console.log('No user profile found'); + return null; + } +}; + +// Update user profile +const updateProfile = async (updates: Partial) => { + const { error } = await supabaseAuth.updateUserProfile(updates); + + if (error) { + console.error('Profile update failed:', error); + return false; + } + + console.log('Profile updated successfully'); + return true; +}; +``` + +## Security Considerations + +### 1. Environment Variables +- Never commit `.env` files to version control +- Use different credentials for development and production +- Rotate API keys regularly + +### 2. Row Level Security (RLS) +- All database tables have RLS enabled +- Users can only access their own data +- Policies are enforced at the database level + +### 3. Session Management +- Sessions are tracked in the database +- Automatic session cleanup on sign out +- Device information is logged for security + +### 4. OAuth Security +- Use PKCE flow for OAuth +- Validate redirect URLs +- Handle OAuth errors gracefully + +### 5. Password Security +- Passwords are handled by Supabase Auth +- Minimum 6 character requirement +- Password reset functionality included + +## Dependencies + +### Required NPM Packages + +```json +{ + "dependencies": { + "@supabase/supabase-js": "^2.38.0", + "dotenv": "^16.3.1" + }, + "devDependencies": { + "@types/node": "^20.0.0", + "typescript": "^5.0.0" + } +} +``` + +### Installation + +```bash +npm install @supabase/supabase-js dotenv +npm install -D @types/node typescript +``` + +## Conclusion + +This guide provides everything needed to re-implement the Supabase authentication system in any project. The implementation includes: + +- Complete database schema with RLS policies +- Full authentication service with all methods +- OAuth flow with custom protocol handling +- Session management and tracking +- Error handling and user feedback +- Security best practices + +The authentication system is production-ready and includes all the features from the original Oasis browser implementation. diff --git a/browser/app/profile/firefox.js b/browser/app/profile/firefox.js index fe944ec1c17c0..24ed5ea60200f 100644 --- a/browser/app/profile/firefox.js +++ b/browser/app/profile/firefox.js @@ -1546,10 +1546,10 @@ pref("toolkit.datacollection.infoURL", "https://www.mozilla.org/legal/privacy/firefox.html"); // base URL for web-based support pages -pref("app.support.baseURL", "https://support.mozilla.org/1/firefox/%VERSION%/%OS%/%LOCALE%/"); +pref("app.support.baseURL", "https://kahana.co/docs"); // base url for web-based feedback pages -pref("app.feedback.baseURL", "https://ideas.mozilla.org/"); +pref("app.feedback.baseURL", "https://kahana.co/oasis-feedback-survey"); pref("security.certerrors.permanentOverride", true); pref("security.certerrors.mitm.priming.enabled", true); @@ -2118,11 +2118,35 @@ pref("browser.newtabpage.trainhopAddon.xpiBaseURL", "https://archive.mozilla.org pref("browser.newtabpage.sponsor-protection.enabled", true); -// Separate about welcome -pref("browser.aboutwelcome.enabled", true); +// Separate about welcome (disabled for Oasis: onboarding uses NTP + docked assistant) +pref("browser.aboutwelcome.enabled", false); // Used to set multistage welcome UX pref("browser.aboutwelcome.screens", ""); +// Oasis custom welcome screen +pref("browser.oasis.welcome.enabled", true); +pref("browser.oasis.welcome.didSee", false); +pref("browser.oasis.welcome.completed", false); +pref("browser.oasis.welcome.useAboutWelcomePage", false); +pref("browser.oasis.welcome.shownNtpAssistantLanding", false); +pref("browser.oasis.postAuthOpenAssistant", true); +pref("browser.oasis.onboarding.guidedFlowEnabled", true); +pref("browser.oasis.onboarding.migrationCompleted", false); +pref("browser.oasis.onboarding.postMigrationTipShown", false); +pref("browser.oasis.onboarding.checklistDismissed", false); +pref("browser.oasis.onboarding.oauthAttemptStarted", false); +pref("browser.oasis.onboarding.importOptOut", false); +pref("browser.oasis.onboarding.firstAiTurnComplete", false); +pref( + "datareporting.policy.firstRunURL", + "https://kahana.co/privacy-policy#personal-data-collect" +); +pref("browser.oasis.user.name", ""); +pref("browser.oasis.import.history", false); +pref("browser.oasis.import.bookmarks", false); +pref("browser.oasis.import.extensions", false); +pref("browser.oasis.import.cookies", false); + // Disable singleProfile messaging mitigation (Bug 1963213) for multiProfile feature users pref("messaging-system.profile.singleProfileMessaging.disable", true); @@ -2187,8 +2211,8 @@ pref("pdfjs.previousHandler.alwaysAskBeforeHandling", false); // Try to convert PDFs sent as octet-stream pref("pdfjs.handleOctetStream", true); -// Is the sidebar positioned ahead of the content browser -pref("sidebar.position_start", true); +// When true, sidebar is on the start edge (left in LTR); when false, on the end edge (right in LTR). +pref("sidebar.position_start", false); #ifdef NIGHTLY_BUILD pref("sidebar.revamp", true); // This is nightly only for now, as we need to address bug 1933527 and bug 1934039. @@ -2208,12 +2232,13 @@ pref("sidebar.animation.expand-on-hover.delay-duration-ms", 200); pref("sidebar.main.tools", ""); pref("sidebar.installed.extensions", ""); pref("sidebar.verticalTabs", false); +pref("browser.sidebar.oasis_assistant.enabled", true); pref("sidebar.verticalTabs.dragToPinPromo.dismissed", false); pref("sidebar.visibility", "always-show"); // Sidebar UI state is stored per-window via session restore. Use this pref // as a backup to restore the sidebar UI state when a user has PPB mode on // or has history cleared on browser close. -pref("sidebar.backupState", "{}"); +pref("sidebar.backupState", "{\"command\":\"viewOasisAssistantSidebar\",\"panelOpen\":true}"); pref("sidebar.expandOnHover", true); pref("sidebar.old-sidebar.has-used", false); pref("sidebar.new-sidebar.has-used", false); @@ -2691,11 +2716,8 @@ pref("browser.tabs.fadeOutExplicitlyUnloadedTabs", true); pref("browser.tabs.fadeOutUnloadedTabs", false); // Whether tabs can be "split" or displayed side by side at once. -#ifdef NIGHTLY_BUILD - pref("browser.tabs.splitView.enabled", true); -#else - pref("browser.tabs.splitView.enabled", false); -#endif +// Oasis: enabled on all builds so assistant add_split_view works. +pref("browser.tabs.splitView.enabled", true); // Whether SVG favicons should be safely re-encoded using the moz-remote-image:// protocol. pref("browser.tabs.remoteSVGIconDecoding", false); @@ -3479,7 +3501,7 @@ pref("browser.mailto.dualPrompt.dismissNotNowMinutes", 525600); // one year pref("browser.mailto.dualPrompt.dismissXClickMinutes", 1440); // one day // Pref to initialize the BackupService soon after startup. -pref("browser.backup.enabled", true); +pref("browser.backup.enabled", false); // Pref to control whether scheduled backups run or not. pref("browser.backup.scheduled.enabled", false); @@ -3568,7 +3590,12 @@ pref("browser.ipProtection.log", false); pref("browser.ipProtection.guardian.endpoint", "https://vpn.mozilla.org/"); pref("browser.ipProtection.added", false); -// Pref to enable aboug:glean redesign. + +// Oasis Assistant defaults +pref("oasis.assistant.anthropic_api_key", "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"); +pref("oasis.assistant.model", "claude-3-5-sonnet-20240620"); +pref("oasis.assistant.temperature", "0.3"); +pref("oasis.assistant.maxTokens", "200"); pref("about.glean.redesign.enabled", false); // Forward Rust component logs to the JS console (comma separate list of crate names) diff --git a/browser/base/content/appmenu-viewcache.inc.xhtml b/browser/base/content/appmenu-viewcache.inc.xhtml index 00c4b3b0712f5..8a663b4be28f6 100644 --- a/browser/base/content/appmenu-viewcache.inc.xhtml +++ b/browser/base/content/appmenu-viewcache.inc.xhtml @@ -690,7 +690,7 @@ diff --git a/browser/base/content/assistant/AssistantSession.sys.mjs b/browser/base/content/assistant/AssistantSession.sys.mjs new file mode 100644 index 0000000000000..2b39aefa22315 --- /dev/null +++ b/browser/base/content/assistant/AssistantSession.sys.mjs @@ -0,0 +1,110 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +/* eslint-env mozilla/sys.mjs */ + +const MAX_TURNS = 12; +const CAP = MAX_TURNS * 2; + +function contentOf(msg) { + if (msg == null) { + return ""; + } + if (typeof msg === "string") { + return msg; + } + const c = msg.content; + if (typeof c === "string") { + return c; + } + if (Array.isArray(c)) { + return c + .map(part => { + if (typeof part === "string") { + return part; + } + if (part && typeof part === "object" && "text" in part) { + return String(part.text ?? ""); + } + return ""; + }) + .join(""); + } + return String(c ?? ""); +} + +function normalizeTurn(msg, defaultType) { + const text = contentOf(msg); + let t = defaultType; + if (msg && typeof msg === "object") { + if (msg.type === "human" || msg.type === "ai") { + t = msg.type; + } else if (typeof msg._getType === "function") { + const gt = msg._getType(); + if (gt === "human" || gt === "ai") { + t = gt; + } + } + } + return { type: t, content: text }; +} + +function normalizePlainList(messages) { + const list = Array.isArray(messages) ? messages : []; + const out = []; + for (const m of list) { + const role = + m && typeof m === "object" && (m.type === "ai" || m.type === "human") + ? m.type + : "human"; + out.push(normalizeTurn(m, role)); + } + if (out.length > CAP) { + out.splice(0, out.length - CAP); + } + return out; +} + +export const AssistantSession = { + _messages: [], + + get messages() { + return [...this._messages]; + }, + + addTurn(userMsg, aiMsg) { + const human = normalizeTurn(userMsg, "human"); + const ai = normalizeTurn(aiMsg, "ai"); + this._messages.push( + { type: "human", content: human.content }, + { type: "ai", content: ai.content } + ); + + if (this._messages.length > CAP) { + this._messages.splice(0, this._messages.length - CAP); + } + + this._notify(); + }, + + setSession(messages) { + this._messages = normalizePlainList(messages); + this._notify(); + }, + + clear() { + this._messages = []; + this._notify(); + }, + + _notify() { + try { + if (Services.obs) { + Services.obs.notifyObservers(null, "oasis-session-updated"); + } + } catch (e) { + console.error("AssistantSession: Failed to notify observers", e); + } + }, +}; diff --git a/browser/base/content/assistant/TRAINING_STREAKS_TOKENS_SUPABASE_HANDOFF.md b/browser/base/content/assistant/TRAINING_STREAKS_TOKENS_SUPABASE_HANDOFF.md new file mode 100644 index 0000000000000..dc7b5dfc5041d --- /dev/null +++ b/browser/base/content/assistant/TRAINING_STREAKS_TOKENS_SUPABASE_HANDOFF.md @@ -0,0 +1,73 @@ +# Training streaks and token rewards: Supabase handoff + +Engineering brief for moving training streaks, badge progression, and training-linked token grants off the client and onto Supabase (and any billing / usage service). + +## Current client behavior (Firefox assistant UI) + +- **Training submit:** Successful insert into `feedback_events` (existing table) triggers `recordTrainingSubmission()` in [`ui-preact/src/utils/trainingProgress.ts`](ui-preact/src/utils/trainingProgress.ts). +- **Persistence today:** Progress is stored in **browser `localStorage`** under key `oasis_training_progress_v1` via `TrainingProgressStore` (`load` / `save`). The module is written so a **Supabase-backed store** can replace `localTrainingProgressStore` without changing milestone math in the UI layer. +- **State surfaced in UI:** `App.tsx` keeps `trainingProgress` in React state, updated from `onTrainingSubmitted` after each successful training. **Training gallery** (mascot) calls `loadTrainingProgress()` when opened, so it can look stale if local writes fail, caches differ, or multiple profiles/devices are used. +- **Token messaging:** Copy references a configurable bonus (`TRAINING_BONUS_COMMANDS` in [`ui-preact/src/utils/trainingRewards.ts`](ui-preact/src/utils/trainingRewards.ts)) and opens [Oasis pricing](https://kahana.co/oasis-pricing). **No server credit is applied yet**; messaging is product-facing only until an API exists. + +## Why Supabase + +- Streaks and token balances should be **authoritative on the server**, tied to `user_id`, resilient across devices, and auditable. +- **Tokens** (AI command allowance) should reconcile with subscription / entitlements and daily or monthly caps as product defines them. + +## Product rules (reference) + +- **Streak:** At least one saved training per **local calendar day** counts toward the streak; missing a day resets current streak. Multiple trainings the same day increase **total trainings** but do not increase streak length for that day. +- **Training bonus:** Each qualifying training grants a small **bonus** toward the user’s **daily** AI command allowance (exact amount and cap TBD with billing). +- **Badges:** Milestone-based levels (streak and submission tracks) as in `TRAINING_BADGES` / `STREAK_MILESTONES` / `SUBMISSION_MILESTONES` in `trainingProgress.ts` (tunable server-side). + +## Suggested data model (draft for discussion) + +Design is intentionally minimal; adjust to your existing auth and usage tables. + +### Option A: Dedicated profile row per user + +Table e.g. `user_training_profile`: + +| Column | Notes | +|--------|--------| +| `user_id` | PK, FK to auth.users | +| `total_trainings` | Count of credited training events | +| `current_streak_days` | Derived or updated on each event | +| `longest_streak_days` | Max of historical streak | +| `last_training_date` | Date key `YYYY-MM-DD` in user’s timezone or UTC policy | +| `badge_levels` | JSONB mirroring `badgeLevels` or normalized child table | +| `updated_at` | | + +### Option B: Event log + materialized view + +- Append-only `training_credit_events` (or extend `feedback_events` with server-side triggers): `user_id`, `feedback_event_id`, `credited_at`, `bonus_commands_granted`, `date_key` used for streak. +- Nightly or on-write aggregation into `user_training_profile` for fast reads. + +### Token / usage + +- Prefer **one source of truth** for “commands remaining today” (existing usage service if any). +- Training bonus should **increment** a balance or reduce “consumed today” via a single transactional RPC, e.g. `apply_training_bonus(user_id, feedback_event_id)` to avoid double-credit. + +## Server integration points + +1. **On successful `feedback_events` insert:** Edge function, DB trigger, or app server validates the row and calls logic to update streak profile and grant bonus commands (idempotent on `feedback_event_id`). +2. **Client read:** Gallery and post-submit UI should fetch profile (and optional “trainings today”) from Supabase instead of `localStorage`, or merge server state as canonical. +3. **Client write:** Stop treating `localStorage` as authoritative; optionally keep a **cache** for offline UX with explicit “syncing” state. + +## Client changes (follow-up PR) + +- Implement `TrainingProgressStore` (or parallel loader) that reads/writes via Supabase. +- After training success, use **server-returned** streak and balance in `onTrainingSubmitted` payload where possible. +- Call `subscriptionService?.forceRefresh` (or equivalent) when the backend returns an updated allowance. +- Align copy with actual policy (daily vs monthly caps) from API. + +## Telemetry (already in client) + +Non-breaking events: `training_progress_updated`, `training_badge_unlocked`, `training_gallery_opened`, plus existing `feedback_*`. Consider server-side events for `training_bonus_applied` and streak transitions when Supabase owns state. + +## Open questions for tomorrow’s session + +1. Timezone for `date_key`: user locale, account setting, or UTC only? +2. Idempotency: one bonus per `feedback_event_id`? +3. Relationship between **pricing page** tiers and daily command caps vs training bonus caps. +4. Whether badge definitions live in code, remote config, or DB. diff --git a/browser/base/content/assistant/VOICE_INPUT_SETUP.md b/browser/base/content/assistant/VOICE_INPUT_SETUP.md new file mode 100644 index 0000000000000..d3574d3fcbd1c --- /dev/null +++ b/browser/base/content/assistant/VOICE_INPUT_SETUP.md @@ -0,0 +1,208 @@ +# Voice Input Setup Guide + +**Developer onboarding (clone, branches, bundles, local testing):** [`docs/voice/README.md`](../../../../docs/voice/README.md) + +## Overview +The voice input feature uses a microphone button in the assistant UI to record audio, send it to your AWS Lambda function for transcription via Deepgram (with Gemini fallback), and populate the input field with the transcribed text. + +## Architecture + +``` +User clicks mic → Records audio → Sends to Lambda → Deepgram/Gemini → Returns transcript → Fills input +``` + +## Frontend Components + +### 1. Voice Input Service (`src/services/voiceInput.ts`) +- Handles microphone access via `navigator.mediaDevices.getUserMedia()` +- Records audio using `MediaRecorder` API +- Converts recorded audio to base64 +- Sends to the voice Lambda via `transcribeAudio()` in `proxyClient.ts` + +### 2. Proxy Client (`src/proxyClient.ts`) +- `transcribeAudio(audioBlob, meta?)` - Sends audio to the voice endpoint with `op: "transcribe"`. Optional `meta` (`source: "orb" | "composer"`, `utteranceSeq`) is used for console correlation only. +- Uses the authenticated `postSigned()` method for voice-only operations +- Includes Supabase JWT token in Authorization header + +### 3. UI Integration (`assistant.ui.js`) +- Microphone button (🎤) added next to Stop and Clear Context buttons +- Click to start recording → shows (⏹️) and red background +- Click again to stop → shows loading (⏳) → transcribes → fills input field +- Displays status messages in the log + +## Backend Lambda Configuration + +### Environment Variables Required +```bash +DEEPGRAM_API_KEY= +GEMINI_API_KEY= +``` + +### Client Endpoint Configuration +```bash +OASIS_TRANSCRIBE_URL= +``` +Set this in `browser/base/content/assistant/build/.env.local` for local overrides. + +### Request Format +```json +{ + "op": "transcribe", + "audio": "", + "mimeType": "audio/webm;codecs=opus" +} +``` + +### Response Format +```json +{ + "transcript": "This is the transcribed text", + "confidence": 0.92 +} +``` + +`confidence` is **optional**. When present, the client logs it with transcribe responses; it is reserved for future gating. + +### Supported Audio Formats +The frontend attempts these MIME types in order: +1. `audio/webm;codecs=opus` (preferred) +2. `audio/webm` +3. `audio/ogg;codecs=opus` +4. `audio/mp4` + +## Lambda Function Structure + +Your current lambda already handles the `transcribe` operation correctly: + +1. ✅ Accepts `op: "transcribe"` +2. ✅ Expects `audio` (base64), `mimeType`, and optional `language` +3. ✅ Uses Deepgram first, falls back to Gemini +4. ✅ Returns `{ transcript: "..." }` (optional `confidence` number) + +## How to Test + +1. **Build the frontend:** + ```bash + cd browser/base/content/assistant/build + npm run build + ``` + +2. **Rebuild Firefox:** + ```bash + cd /Users/ashwinjohn/Projects/firefox-oasis + ./mach build + ``` + +3. **Run Firefox and open the assistant sidebar** + +4. **Test the microphone:** + - Ensure you're signed in (authentication required) + - Click the 🎤 button + - Grant microphone permissions when prompted + - Speak clearly + - Click ⏹️ to stop recording + - Watch the input field populate with transcribed text + +## Developer: verbose assistant logs + +Voice and assistant code use `assistantLogger`. **`debug` / `info`** lines are hidden unless the Firefox pref **`browser.oasis.assistant.debug`** is **true**. + +1. Open `about:config`. +2. Add or set **`browser.oasis.assistant.debug`** to **true** (Boolean). +3. Reload the assistant sidebar and watch the **Browser Console** for `[Assistant:voice]` and other scoped messages (including VAD-style diagnostics where implemented). + +**Warn** and **error** logs are not gated and appear in normal builds. + +### Console scopes (filter in DevTools) + +Messages use the prefix `[Assistant:]`. Common voice-related scopes: + +| Scope | What it covers | +|-------|----------------| +| `voice` | Segment lifecycle (`segment_started`, `segment_finished`, `arm_next_segment`), transcribe `debug` lines with `source` / `utteranceSeq` | +| `voice-state` | FSM transitions (`transition`), `listening_phase` (echo guard vs capturing) | +| `voice-vad` | RMS ticks (throttled), `first_speech_in_segment` (after **3** consecutive above-threshold frames), `silence_window_complete`, precise prime | +| `voice-mic` | `MediaStreamTrack.enabled` toggles on the capture stream (tracks stay **disabled** while **thinking** and **speaking** on the orb) | +| `voice-input` | Composer push-to-talk: `recording_started` (device `label` / `deviceId`), `sending_transcribe`, `recording_cancelled` | + +### Hands-free orb: spoken replies vs chat-only + +In the voice overlay, **Replies** can be **Spoken** (default) or **Chat**. **Chat** turns off text-to-speech for the orb: the assistant still hears you and runs the same pipeline, but answers **stream into the main chat** as text (using the same `runAssistantStream` chunks as typed messages). **Spoken** mode still **appends** the user transcript and final assistant reply to the chat after each TTS turn (for a single auditable timeline). The choice is stored in `localStorage` under **`oasis.voice.orbSpokenReplies`** (`1` / `0`). This is separate from the composer toolbar control that auto-reads aloud after you send from the mic button. + +**Auto short transcript discard (orb):** If VAD ends a segment automatically and the transcript is **very short** (under **5** characters) and not on a small allowlist of commands, the client shows an error and does **not** run the assistant (reduces junk ASR → model derailment). **Manual** orb stop does not apply this gate. + +### `utteranceSeq` (orb) + +For the hands-free orb, **`utteranceSeq` increments each time a new `MediaRecorder` segment starts** (see `segment_started` / `segment_finished` in the console). Use the same number to tie together VAD events, segment end reason (`silence_vad`, `manual_stop`, `discard_too_small`, `aborted`), and `transcribe request` / `transcribe response` lines (with `source: "orb"`). + +Composer push-to-talk uses a separate counter in **`voice-input`** logs (`source: "composer"` on transcribe). + +### Debugging phantom transcripts + +If the assistant reacts to speech you did not say: + +1. Set **`browser.oasis.assistant.debug`** to **true** and open the **Browser Console**. +2. Reproduce the issue; find the **`utteranceSeq`** for the bad turn. +3. Inspect the sequence for that seq: + - **`voice-vad` `first_speech_in_segment`**: note `rms` vs quiet floor (spurious crossing suggests noise or echo). + - **`segment_finished`**: check `endReason`, `blobBytes`, and `durationMs` (tiny or odd clips often confuse STT). + - **`transcribe response`** / **`transcribe request`**: compare `transcriptPreview` to the audio you expected. +4. For composer-only issues, filter **`voice-input`** and confirm **`recording_started`** `tracks` match the intended microphone (e.g. laptop vs USB). + +## Troubleshooting + +### "Failed to access microphone" +- Grant microphone permissions in Firefox +- Check `about:permissions` in Firefox +- On macOS, check System Preferences → Security & Privacy → Microphone + +### "Transcription failed" +- Check browser console for errors +- Verify `DEEPGRAM_API_KEY` is set in lambda +- Check lambda CloudWatch logs +- Ensure lambda has correct IAM permissions + +### Transcribe returns HTTP 403 `{"Message":"Forbidden"}` +This usually means the **Lambda function URL uses AWS IAM auth**. The client signs requests with **SigV4** using credentials from **`COGNITO_IDENTITY_POOL_ID`** (same values as in `build/.env.defaults` / `build/.env.local`), and sends the Supabase session JWT in the **`x-oasis-authorization: Bearer …`** header (not `Authorization`, which SigV4 uses for the AWS signature). + +- In **API Gateway / Lambda URL** console, confirm auth mode (IAM vs NONE). +- The **Cognito identity pool** must allow **guest (unauthenticated)** identities if you are not wiring logins, and the **guest IAM role** must be allowed to invoke that function URL (resource policy / IAM). +- In Lambda, read the app JWT from **`event.headers["x-oasis-authorization"]`** (or the lowercased key your runtime exposes) if you still validate Supabase users server-side. + +### "Please sign in to use voice input" +- User must be authenticated with Supabase +- Check that JWT token is being sent in Authorization header + +### Audio quality issues +- Deepgram works best with clear, noise-free audio +- Consider adding `language` parameter if not English +- Gemini fallback is slower but may work better for accented speech + +## Advanced Configuration + +### Add language selection (optional) +Modify `proxyClient.ts` to pass language: +```typescript +return postSigned("transcribe", { + audio: base64Audio, + mimeType: audioBlob.type, + language: "en-US" // or user-selected language +}); +``` + +### Force Gemini provider (optional) +Set lambda environment variable: +```bash +TRANSCRIBE_PROVIDER=gemini +``` + +## Integration with TTS (Future) + +Your lambda can also handle text-to-speech. To add TTS playback: + +1. Add a speaker button in the UI +2. Create `textToSpeech()` function in `proxyClient.ts` +3. Add TTS handler in lambda for `op: "tts"` +4. Play returned audio using Web Audio API + +Example TTS implementation already included in `proxyClient.ts` (ready to use when backend is implemented). diff --git a/browser/base/content/assistant/assistant.bridge.js b/browser/base/content/assistant/assistant.bridge.js new file mode 100644 index 0000000000000..154abcdcfdf2d --- /dev/null +++ b/browser/base/content/assistant/assistant.bridge.js @@ -0,0 +1,69 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +// Privileged shim - runs in chrome (privileged) context +(function () { + const Services = + window.Services || + ChromeUtils.import("resource://gre/modules/Services.jsm").Services; + + function normalizeAssistantOpenTabUrl(url) { + if (!url) { + return url; + } + if (/^[a-z][a-z0-9+.-]*:/i.test(url)) { + return url; + } + if (/^https?:\/\//i.test(url)) { + return url; + } + return `https://${url}`; + } + + window.assistantBridge = { + openTab(url) { + try { + const fixed = normalizeAssistantOpenTabUrl(url); + try { + const win = Services.wm.getMostRecentWindow("navigator:browser"); + if (win?.openTrustedLinkIn) { + win.openTrustedLinkIn(fixed, "tab"); + return true; + } + if (win?.openWebLinkIn) { + win.openWebLinkIn(fixed, "tab", {}); + return true; + } + if (win?.gBrowser?.addTrustedTab) { + win.gBrowser.selectedTab = win.gBrowser.addTrustedTab(fixed, { + inBackground: false, + }); + return true; + } + if (win?.gBrowser) { + win.gBrowser.selectedTab = win.gBrowser.addTab(fixed, { + triggeringPrincipal: + Services.scriptSecurityManager.getSystemPrincipal(), + inBackground: false, + }); + return true; + } + } catch (e) { + console.warn( + "assistantBridge: failed to open tab via browser window", + e + ); + } + const opened = window.open(fixed); + return !!opened; + } catch (e) { + console.error("assistantBridge.openTab error", e); + return false; + } + }, + getAuthState() { + return window.oasisAuthState || { isAuthenticated: false, user: null }; + }, + }; +})(); diff --git a/browser/base/content/assistant/assistant.bundle.js b/browser/base/content/assistant/assistant.bundle.js new file mode 100644 index 0000000000000..c2a511e7095aa --- /dev/null +++ b/browser/base/content/assistant/assistant.bundle.js @@ -0,0 +1,66106 @@ +"use strict"; +(() => { + var __create = Object.create; + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __getProtoOf = Object.getPrototypeOf; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; + }; + var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; + }; + var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); + }; + var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; + }; + var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + + // node_modules/decamelize/index.js + var require_decamelize = __commonJS({ + "node_modules/decamelize/index.js"(exports, module) { + "use strict"; + module.exports = function(str, sep) { + if (typeof str !== "string") { + throw new TypeError("Expected a string"); + } + sep = typeof sep === "undefined" ? "_" : sep; + return str.replace(/([a-z\d])([A-Z])/g, "$1" + sep + "$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g, "$1" + sep + "$2").toLowerCase(); + }; + } + }); + + // node_modules/camelcase/index.js + var require_camelcase = __commonJS({ + "node_modules/camelcase/index.js"(exports, module) { + "use strict"; + var UPPERCASE = /[\p{Lu}]/u; + var LOWERCASE = /[\p{Ll}]/u; + var LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu; + var IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u; + var SEPARATORS = /[_.\- ]+/; + var LEADING_SEPARATORS = new RegExp("^" + SEPARATORS.source); + var SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, "gu"); + var NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER.source, "gu"); + var preserveCamelCase = (string2, toLowerCase, toUpperCase) => { + let isLastCharLower = false; + let isLastCharUpper = false; + let isLastLastCharUpper = false; + for (let i2 = 0; i2 < string2.length; i2++) { + const character = string2[i2]; + if (isLastCharLower && UPPERCASE.test(character)) { + string2 = string2.slice(0, i2) + "-" + string2.slice(i2); + isLastCharLower = false; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = true; + i2++; + } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) { + string2 = string2.slice(0, i2 - 1) + "-" + string2.slice(i2 - 1); + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = false; + isLastCharLower = true; + } else { + isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character; + } + } + return string2; + }; + var preserveConsecutiveUppercase = (input, toLowerCase) => { + LEADING_CAPITAL.lastIndex = 0; + return input.replace(LEADING_CAPITAL, (m1) => toLowerCase(m1)); + }; + var postProcess = (input, toUpperCase) => { + SEPARATORS_AND_IDENTIFIER.lastIndex = 0; + NUMBERS_AND_IDENTIFIER.lastIndex = 0; + return input.replace(SEPARATORS_AND_IDENTIFIER, (_2, identifier) => toUpperCase(identifier)).replace(NUMBERS_AND_IDENTIFIER, (m3) => toUpperCase(m3)); + }; + var camelCase2 = (input, options) => { + if (!(typeof input === "string" || Array.isArray(input))) { + throw new TypeError("Expected the input to be `string | string[]`"); + } + options = { + pascalCase: false, + preserveConsecutiveUppercase: false, + ...options + }; + if (Array.isArray(input)) { + input = input.map((x3) => x3.trim()).filter((x3) => x3.length).join("-"); + } else { + input = input.trim(); + } + if (input.length === 0) { + return ""; + } + const toLowerCase = options.locale === false ? (string2) => string2.toLowerCase() : (string2) => string2.toLocaleLowerCase(options.locale); + const toUpperCase = options.locale === false ? (string2) => string2.toUpperCase() : (string2) => string2.toLocaleUpperCase(options.locale); + if (input.length === 1) { + return options.pascalCase ? toUpperCase(input) : toLowerCase(input); + } + const hasUpperCase = input !== toLowerCase(input); + if (hasUpperCase) { + input = preserveCamelCase(input, toLowerCase, toUpperCase); + } + input = input.replace(LEADING_SEPARATORS, ""); + if (options.preserveConsecutiveUppercase) { + input = preserveConsecutiveUppercase(input, toLowerCase); + } else { + input = toLowerCase(input); + } + if (options.pascalCase) { + input = toUpperCase(input.charAt(0)) + input.slice(1); + } + return postProcess(input, toUpperCase); + }; + module.exports = camelCase2; + module.exports.default = camelCase2; + } + }); + + // node_modules/retry/lib/retry_operation.js + var require_retry_operation = __commonJS({ + "node_modules/retry/lib/retry_operation.js"(exports, module) { + function RetryOperation(timeouts, options) { + if (typeof options === "boolean") { + options = { forever: options }; + } + this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); + this._timeouts = timeouts; + this._options = options || {}; + this._maxRetryTime = options && options.maxRetryTime || Infinity; + this._fn = null; + this._errors = []; + this._attempts = 1; + this._operationTimeout = null; + this._operationTimeoutCb = null; + this._timeout = null; + this._operationStart = null; + this._timer = null; + if (this._options.forever) { + this._cachedTimeouts = this._timeouts.slice(0); + } + } + module.exports = RetryOperation; + RetryOperation.prototype.reset = function() { + this._attempts = 1; + this._timeouts = this._originalTimeouts.slice(0); + }; + RetryOperation.prototype.stop = function() { + if (this._timeout) { + clearTimeout(this._timeout); + } + if (this._timer) { + clearTimeout(this._timer); + } + this._timeouts = []; + this._cachedTimeouts = null; + }; + RetryOperation.prototype.retry = function(err) { + if (this._timeout) { + clearTimeout(this._timeout); + } + if (!err) { + return false; + } + var currentTime = (/* @__PURE__ */ new Date()).getTime(); + if (err && currentTime - this._operationStart >= this._maxRetryTime) { + this._errors.push(err); + this._errors.unshift(new Error("RetryOperation timeout occurred")); + return false; + } + this._errors.push(err); + var timeout = this._timeouts.shift(); + if (timeout === void 0) { + if (this._cachedTimeouts) { + this._errors.splice(0, this._errors.length - 1); + timeout = this._cachedTimeouts.slice(-1); + } else { + return false; + } + } + var self2 = this; + this._timer = setTimeout(function() { + self2._attempts++; + if (self2._operationTimeoutCb) { + self2._timeout = setTimeout(function() { + self2._operationTimeoutCb(self2._attempts); + }, self2._operationTimeout); + if (self2._options.unref) { + self2._timeout.unref(); + } + } + self2._fn(self2._attempts); + }, timeout); + if (this._options.unref) { + this._timer.unref(); + } + return true; + }; + RetryOperation.prototype.attempt = function(fn, timeoutOps) { + this._fn = fn; + if (timeoutOps) { + if (timeoutOps.timeout) { + this._operationTimeout = timeoutOps.timeout; + } + if (timeoutOps.cb) { + this._operationTimeoutCb = timeoutOps.cb; + } + } + var self2 = this; + if (this._operationTimeoutCb) { + this._timeout = setTimeout(function() { + self2._operationTimeoutCb(); + }, self2._operationTimeout); + } + this._operationStart = (/* @__PURE__ */ new Date()).getTime(); + this._fn(this._attempts); + }; + RetryOperation.prototype.try = function(fn) { + console.log("Using RetryOperation.try() is deprecated"); + this.attempt(fn); + }; + RetryOperation.prototype.start = function(fn) { + console.log("Using RetryOperation.start() is deprecated"); + this.attempt(fn); + }; + RetryOperation.prototype.start = RetryOperation.prototype.try; + RetryOperation.prototype.errors = function() { + return this._errors; + }; + RetryOperation.prototype.attempts = function() { + return this._attempts; + }; + RetryOperation.prototype.mainError = function() { + if (this._errors.length === 0) { + return null; + } + var counts = {}; + var mainError = null; + var mainErrorCount = 0; + for (var i2 = 0; i2 < this._errors.length; i2++) { + var error = this._errors[i2]; + var message = error.message; + var count3 = (counts[message] || 0) + 1; + counts[message] = count3; + if (count3 >= mainErrorCount) { + mainError = error; + mainErrorCount = count3; + } + } + return mainError; + }; + } + }); + + // node_modules/retry/lib/retry.js + var require_retry = __commonJS({ + "node_modules/retry/lib/retry.js"(exports) { + var RetryOperation = require_retry_operation(); + exports.operation = function(options) { + var timeouts = exports.timeouts(options); + return new RetryOperation(timeouts, { + forever: options && (options.forever || options.retries === Infinity), + unref: options && options.unref, + maxRetryTime: options && options.maxRetryTime + }); + }; + exports.timeouts = function(options) { + if (options instanceof Array) { + return [].concat(options); + } + var opts = { + retries: 10, + factor: 2, + minTimeout: 1 * 1e3, + maxTimeout: Infinity, + randomize: false + }; + for (var key in options) { + opts[key] = options[key]; + } + if (opts.minTimeout > opts.maxTimeout) { + throw new Error("minTimeout is greater than maxTimeout"); + } + var timeouts = []; + for (var i2 = 0; i2 < opts.retries; i2++) { + timeouts.push(this.createTimeout(i2, opts)); + } + if (options && options.forever && !timeouts.length) { + timeouts.push(this.createTimeout(i2, opts)); + } + timeouts.sort(function(a2, b3) { + return a2 - b3; + }); + return timeouts; + }; + exports.createTimeout = function(attempt, opts) { + var random = opts.randomize ? Math.random() + 1 : 1; + var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); + timeout = Math.min(timeout, opts.maxTimeout); + return timeout; + }; + exports.wrap = function(obj, options, methods) { + if (options instanceof Array) { + methods = options; + options = null; + } + if (!methods) { + methods = []; + for (var key in obj) { + if (typeof obj[key] === "function") { + methods.push(key); + } + } + } + for (var i2 = 0; i2 < methods.length; i2++) { + var method = methods[i2]; + var original = obj[method]; + obj[method] = function retryWrapper(original2) { + var op = exports.operation(options); + var args = Array.prototype.slice.call(arguments, 1); + var callback = args.pop(); + args.push(function(err) { + if (op.retry(err)) { + return; + } + if (err) { + arguments[0] = op.mainError(); + } + callback.apply(this, arguments); + }); + op.attempt(function() { + original2.apply(obj, args); + }); + }.bind(obj, original); + obj[method].options = options; + } + }; + } + }); + + // node_modules/retry/index.js + var require_retry2 = __commonJS({ + "node_modules/retry/index.js"(exports, module) { + module.exports = require_retry(); + } + }); + + // node_modules/p-retry/index.js + var require_p_retry = __commonJS({ + "node_modules/p-retry/index.js"(exports, module) { + "use strict"; + var retry = require_retry2(); + var networkErrorMsgs = [ + "Failed to fetch", + // Chrome + "NetworkError when attempting to fetch resource.", + // Firefox + "The Internet connection appears to be offline.", + // Safari + "Network request failed" + // `cross-fetch` + ]; + var AbortError = class extends Error { + constructor(message) { + super(); + if (message instanceof Error) { + this.originalError = message; + ({ message } = message); + } else { + this.originalError = new Error(message); + this.originalError.stack = this.stack; + } + this.name = "AbortError"; + this.message = message; + } + }; + var decorateErrorWithCounts = (error, attemptNumber, options) => { + const retriesLeft = options.retries - (attemptNumber - 1); + error.attemptNumber = attemptNumber; + error.retriesLeft = retriesLeft; + return error; + }; + var isNetworkError = (errorMessage) => networkErrorMsgs.includes(errorMessage); + var pRetry4 = (input, options) => new Promise((resolve, reject) => { + options = { + onFailedAttempt: () => { + }, + retries: 10, + ...options + }; + const operation = retry.operation(options); + operation.attempt(async (attemptNumber) => { + try { + resolve(await input(attemptNumber)); + } catch (error) { + if (!(error instanceof Error)) { + reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`)); + return; + } + if (error instanceof AbortError) { + operation.stop(); + reject(error.originalError); + } else if (error instanceof TypeError && !isNetworkError(error.message)) { + operation.stop(); + reject(error); + } else { + decorateErrorWithCounts(error, attemptNumber, options); + try { + await options.onFailedAttempt(error); + } catch (error2) { + reject(error2); + return; + } + if (!operation.retry(error)) { + reject(operation.mainError()); + } + } + } + }); + }); + module.exports = pRetry4; + module.exports.default = pRetry4; + module.exports.AbortError = AbortError; + } + }); + + // node_modules/eventemitter3/index.js + var require_eventemitter3 = __commonJS({ + "node_modules/eventemitter3/index.js"(exports, module) { + "use strict"; + var has = Object.prototype.hasOwnProperty; + var prefix = "~"; + function Events() { + } + if (Object.create) { + Events.prototype = /* @__PURE__ */ Object.create(null); + if (!new Events().__proto__) prefix = false; + } + function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; + } + function addListener(emitter, event, fn, context, once) { + if (typeof fn !== "function") { + throw new TypeError("The listener must be a function"); + } + var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event; + if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; + else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); + else emitter._events[evt] = [emitter._events[evt], listener]; + return emitter; + } + function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) emitter._events = new Events(); + else delete emitter._events[evt]; + } + function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; + } + EventEmitter.prototype.eventNames = function eventNames() { + var names = [], events, name; + if (this._eventsCount === 0) return names; + for (name in events = this._events) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + return names; + }; + EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event, handlers = this._events[evt]; + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; + for (var i2 = 0, l2 = handlers.length, ee = new Array(l2); i2 < l2; i2++) { + ee[i2] = handlers[i2].fn; + } + return ee; + }; + EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event, listeners = this._events[evt]; + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; + }; + EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + if (!this._events[evt]) return false; + var listeners = this._events[evt], len = arguments.length, args, i2; + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, void 0, true); + switch (len) { + case 1: + return listeners.fn.call(listeners.context), true; + case 2: + return listeners.fn.call(listeners.context, a1), true; + case 3: + return listeners.fn.call(listeners.context, a1, a2), true; + case 4: + return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: + return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: + return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + for (i2 = 1, args = new Array(len - 1); i2 < len; i2++) { + args[i2 - 1] = arguments[i2]; + } + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length, j3; + for (i2 = 0; i2 < length; i2++) { + if (listeners[i2].once) this.removeListener(event, listeners[i2].fn, void 0, true); + switch (len) { + case 1: + listeners[i2].fn.call(listeners[i2].context); + break; + case 2: + listeners[i2].fn.call(listeners[i2].context, a1); + break; + case 3: + listeners[i2].fn.call(listeners[i2].context, a1, a2); + break; + case 4: + listeners[i2].fn.call(listeners[i2].context, a1, a2, a3); + break; + default: + if (!args) for (j3 = 1, args = new Array(len - 1); j3 < len; j3++) { + args[j3 - 1] = arguments[j3]; + } + listeners[i2].fn.apply(listeners[i2].context, args); + } + } + } + return true; + }; + EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); + }; + EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); + }; + EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + if (!this._events[evt]) return this; + if (!fn) { + clearEvent(this, evt); + return this; + } + var listeners = this._events[evt]; + if (listeners.fn) { + if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) { + clearEvent(this, evt); + } + } else { + for (var i2 = 0, events = [], length = listeners.length; i2 < length; i2++) { + if (listeners[i2].fn !== fn || once && !listeners[i2].once || context && listeners[i2].context !== context) { + events.push(listeners[i2]); + } + } + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); + } + return this; + }; + EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; + } + return this; + }; + EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + EventEmitter.prototype.addListener = EventEmitter.prototype.on; + EventEmitter.prefixed = prefix; + EventEmitter.EventEmitter = EventEmitter; + if ("undefined" !== typeof module) { + module.exports = EventEmitter; + } + } + }); + + // node_modules/p-finally/index.js + var require_p_finally = __commonJS({ + "node_modules/p-finally/index.js"(exports, module) { + "use strict"; + module.exports = (promise, onFinally) => { + onFinally = onFinally || (() => { + }); + return promise.then( + (val) => new Promise((resolve) => { + resolve(onFinally()); + }).then(() => val), + (err) => new Promise((resolve) => { + resolve(onFinally()); + }).then(() => { + throw err; + }) + ); + }; + } + }); + + // node_modules/p-timeout/index.js + var require_p_timeout = __commonJS({ + "node_modules/p-timeout/index.js"(exports, module) { + "use strict"; + var pFinally = require_p_finally(); + var TimeoutError = class extends Error { + constructor(message) { + super(message); + this.name = "TimeoutError"; + } + }; + var pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reject) => { + if (typeof milliseconds !== "number" || milliseconds < 0) { + throw new TypeError("Expected `milliseconds` to be a positive number"); + } + if (milliseconds === Infinity) { + resolve(promise); + return; + } + const timer = setTimeout(() => { + if (typeof fallback === "function") { + try { + resolve(fallback()); + } catch (error) { + reject(error); + } + return; + } + const message = typeof fallback === "string" ? fallback : `Promise timed out after ${milliseconds} milliseconds`; + const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message); + if (typeof promise.cancel === "function") { + promise.cancel(); + } + reject(timeoutError); + }, milliseconds); + pFinally( + // eslint-disable-next-line promise/prefer-await-to-then + promise.then(resolve, reject), + () => { + clearTimeout(timer); + } + ); + }); + module.exports = pTimeout; + module.exports.default = pTimeout; + module.exports.TimeoutError = TimeoutError; + } + }); + + // node_modules/p-queue/dist/lower-bound.js + var require_lower_bound = __commonJS({ + "node_modules/p-queue/dist/lower-bound.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + function lowerBound(array, value, comparator) { + let first = 0; + let count3 = array.length; + while (count3 > 0) { + const step = count3 / 2 | 0; + let it = first + step; + if (comparator(array[it], value) <= 0) { + first = ++it; + count3 -= step + 1; + } else { + count3 = step; + } + } + return first; + } + exports.default = lowerBound; + } + }); + + // node_modules/p-queue/dist/priority-queue.js + var require_priority_queue = __commonJS({ + "node_modules/p-queue/dist/priority-queue.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var lower_bound_1 = require_lower_bound(); + var PriorityQueue = class { + constructor() { + this._queue = []; + } + enqueue(run, options) { + options = Object.assign({ priority: 0 }, options); + const element = { + priority: options.priority, + run + }; + if (this.size && this._queue[this.size - 1].priority >= options.priority) { + this._queue.push(element); + return; + } + const index2 = lower_bound_1.default(this._queue, element, (a2, b3) => b3.priority - a2.priority); + this._queue.splice(index2, 0, element); + } + dequeue() { + const item = this._queue.shift(); + return item === null || item === void 0 ? void 0 : item.run; + } + filter(options) { + return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run); + } + get size() { + return this._queue.length; + } + }; + exports.default = PriorityQueue; + } + }); + + // node_modules/p-queue/dist/index.js + var require_dist = __commonJS({ + "node_modules/p-queue/dist/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var EventEmitter = require_eventemitter3(); + var p_timeout_1 = require_p_timeout(); + var priority_queue_1 = require_priority_queue(); + var empty = () => { + }; + var timeoutError = new p_timeout_1.TimeoutError(); + var PQueue = class extends EventEmitter { + constructor(options) { + var _a, _b, _c, _d; + super(); + this._intervalCount = 0; + this._intervalEnd = 0; + this._pendingCount = 0; + this._resolveEmpty = empty; + this._resolveIdle = empty; + options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options); + if (!(typeof options.intervalCap === "number" && options.intervalCap >= 1)) { + throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ""}\` (${typeof options.intervalCap})`); + } + if (options.interval === void 0 || !(Number.isFinite(options.interval) && options.interval >= 0)) { + throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ""}\` (${typeof options.interval})`); + } + this._carryoverConcurrencyCount = options.carryoverConcurrencyCount; + this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0; + this._intervalCap = options.intervalCap; + this._interval = options.interval; + this._queue = new options.queueClass(); + this._queueClass = options.queueClass; + this.concurrency = options.concurrency; + this._timeout = options.timeout; + this._throwOnTimeout = options.throwOnTimeout === true; + this._isPaused = options.autoStart === false; + } + get _doesIntervalAllowAnother() { + return this._isIntervalIgnored || this._intervalCount < this._intervalCap; + } + get _doesConcurrentAllowAnother() { + return this._pendingCount < this._concurrency; + } + _next() { + this._pendingCount--; + this._tryToStartAnother(); + this.emit("next"); + } + _resolvePromises() { + this._resolveEmpty(); + this._resolveEmpty = empty; + if (this._pendingCount === 0) { + this._resolveIdle(); + this._resolveIdle = empty; + this.emit("idle"); + } + } + _onResumeInterval() { + this._onInterval(); + this._initializeIntervalIfNeeded(); + this._timeoutId = void 0; + } + _isIntervalPaused() { + const now2 = Date.now(); + if (this._intervalId === void 0) { + const delay = this._intervalEnd - now2; + if (delay < 0) { + this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; + } else { + if (this._timeoutId === void 0) { + this._timeoutId = setTimeout(() => { + this._onResumeInterval(); + }, delay); + } + return true; + } + } + return false; + } + _tryToStartAnother() { + if (this._queue.size === 0) { + if (this._intervalId) { + clearInterval(this._intervalId); + } + this._intervalId = void 0; + this._resolvePromises(); + return false; + } + if (!this._isPaused) { + const canInitializeInterval = !this._isIntervalPaused(); + if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) { + const job = this._queue.dequeue(); + if (!job) { + return false; + } + this.emit("active"); + job(); + if (canInitializeInterval) { + this._initializeIntervalIfNeeded(); + } + return true; + } + } + return false; + } + _initializeIntervalIfNeeded() { + if (this._isIntervalIgnored || this._intervalId !== void 0) { + return; + } + this._intervalId = setInterval(() => { + this._onInterval(); + }, this._interval); + this._intervalEnd = Date.now() + this._interval; + } + _onInterval() { + if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) { + clearInterval(this._intervalId); + this._intervalId = void 0; + } + this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; + this._processQueue(); + } + /** + Executes all queued functions until it reaches the limit. + */ + _processQueue() { + while (this._tryToStartAnother()) { + } + } + get concurrency() { + return this._concurrency; + } + set concurrency(newConcurrency) { + if (!(typeof newConcurrency === "number" && newConcurrency >= 1)) { + throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`); + } + this._concurrency = newConcurrency; + this._processQueue(); + } + /** + Adds a sync or async task to the queue. Always returns a promise. + */ + async add(fn, options = {}) { + return new Promise((resolve, reject) => { + const run = async () => { + this._pendingCount++; + this._intervalCount++; + try { + const operation = this._timeout === void 0 && options.timeout === void 0 ? fn() : p_timeout_1.default(Promise.resolve(fn()), options.timeout === void 0 ? this._timeout : options.timeout, () => { + if (options.throwOnTimeout === void 0 ? this._throwOnTimeout : options.throwOnTimeout) { + reject(timeoutError); + } + return void 0; + }); + resolve(await operation); + } catch (error) { + reject(error); + } + this._next(); + }; + this._queue.enqueue(run, options); + this._tryToStartAnother(); + this.emit("add"); + }); + } + /** + Same as `.add()`, but accepts an array of sync or async functions. + + @returns A promise that resolves when all functions are resolved. + */ + async addAll(functions, options) { + return Promise.all(functions.map(async (function_) => this.add(function_, options))); + } + /** + Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.) + */ + start() { + if (!this._isPaused) { + return this; + } + this._isPaused = false; + this._processQueue(); + return this; + } + /** + Put queue execution on hold. + */ + pause() { + this._isPaused = true; + } + /** + Clear the queue. + */ + clear() { + this._queue = new this._queueClass(); + } + /** + Can be called multiple times. Useful if you for example add additional items at a later time. + + @returns A promise that settles when the queue becomes empty. + */ + async onEmpty() { + if (this._queue.size === 0) { + return; + } + return new Promise((resolve) => { + const existingResolve = this._resolveEmpty; + this._resolveEmpty = () => { + existingResolve(); + resolve(); + }; + }); + } + /** + The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet. + + @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`. + */ + async onIdle() { + if (this._pendingCount === 0 && this._queue.size === 0) { + return; + } + return new Promise((resolve) => { + const existingResolve = this._resolveIdle; + this._resolveIdle = () => { + existingResolve(); + resolve(); + }; + }); + } + /** + Size of the queue. + */ + get size() { + return this._queue.size; + } + /** + Size of the queue, filtered by the given options. + + For example, this can be used to find the number of items remaining in the queue with a specific priority level. + */ + sizeBy(options) { + return this._queue.filter(options).length; + } + /** + Number of pending promises. + */ + get pending() { + return this._pendingCount; + } + /** + Whether the queue is currently paused. + */ + get isPaused() { + return this._isPaused; + } + get timeout() { + return this._timeout; + } + /** + Set the timeout for future operations. + */ + set timeout(milliseconds) { + this._timeout = milliseconds; + } + }; + exports.default = PQueue; + } + }); + + // node_modules/semver/internal/constants.js + var require_constants = __commonJS({ + "node_modules/semver/internal/constants.js"(exports, module) { + "use strict"; + var SEMVER_SPEC_VERSION = "2.0.0"; + var MAX_LENGTH = 256; + var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ + 9007199254740991; + var MAX_SAFE_COMPONENT_LENGTH = 16; + var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6; + var RELEASE_TYPES = [ + "major", + "premajor", + "minor", + "preminor", + "patch", + "prepatch", + "prerelease" + ]; + module.exports = { + MAX_LENGTH, + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_SAFE_INTEGER, + RELEASE_TYPES, + SEMVER_SPEC_VERSION, + FLAG_INCLUDE_PRERELEASE: 1, + FLAG_LOOSE: 2 + }; + } + }); + + // node_modules/semver/internal/debug.js + var require_debug = __commonJS({ + "node_modules/semver/internal/debug.js"(exports, module) { + "use strict"; + var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => { + }; + module.exports = debug; + } + }); + + // node_modules/semver/internal/re.js + var require_re = __commonJS({ + "node_modules/semver/internal/re.js"(exports, module) { + "use strict"; + var { + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_LENGTH + } = require_constants(); + var debug = require_debug(); + exports = module.exports = {}; + var re2 = exports.re = []; + var safeRe = exports.safeRe = []; + var src = exports.src = []; + var safeSrc = exports.safeSrc = []; + var t2 = exports.t = {}; + var R = 0; + var LETTERDASHNUMBER = "[a-zA-Z0-9-]"; + var safeRegexReplacements = [ + ["\\s", 1], + ["\\d", MAX_LENGTH], + [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH] + ]; + var makeSafeRegex = (value) => { + for (const [token, max] of safeRegexReplacements) { + value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`); + } + return value; + }; + var createToken = (name, value, isGlobal) => { + const safe = makeSafeRegex(value); + const index2 = R++; + debug(name, index2, value); + t2[name] = index2; + src[index2] = value; + safeSrc[index2] = safe; + re2[index2] = new RegExp(value, isGlobal ? "g" : void 0); + safeRe[index2] = new RegExp(safe, isGlobal ? "g" : void 0); + }; + createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*"); + createToken("NUMERICIDENTIFIERLOOSE", "\\d+"); + createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`); + createToken("MAINVERSION", `(${src[t2.NUMERICIDENTIFIER]})\\.(${src[t2.NUMERICIDENTIFIER]})\\.(${src[t2.NUMERICIDENTIFIER]})`); + createToken("MAINVERSIONLOOSE", `(${src[t2.NUMERICIDENTIFIERLOOSE]})\\.(${src[t2.NUMERICIDENTIFIERLOOSE]})\\.(${src[t2.NUMERICIDENTIFIERLOOSE]})`); + createToken("PRERELEASEIDENTIFIER", `(?:${src[t2.NONNUMERICIDENTIFIER]}|${src[t2.NUMERICIDENTIFIER]})`); + createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t2.NONNUMERICIDENTIFIER]}|${src[t2.NUMERICIDENTIFIERLOOSE]})`); + createToken("PRERELEASE", `(?:-(${src[t2.PRERELEASEIDENTIFIER]}(?:\\.${src[t2.PRERELEASEIDENTIFIER]})*))`); + createToken("PRERELEASELOOSE", `(?:-?(${src[t2.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t2.PRERELEASEIDENTIFIERLOOSE]})*))`); + createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`); + createToken("BUILD", `(?:\\+(${src[t2.BUILDIDENTIFIER]}(?:\\.${src[t2.BUILDIDENTIFIER]})*))`); + createToken("FULLPLAIN", `v?${src[t2.MAINVERSION]}${src[t2.PRERELEASE]}?${src[t2.BUILD]}?`); + createToken("FULL", `^${src[t2.FULLPLAIN]}$`); + createToken("LOOSEPLAIN", `[v=\\s]*${src[t2.MAINVERSIONLOOSE]}${src[t2.PRERELEASELOOSE]}?${src[t2.BUILD]}?`); + createToken("LOOSE", `^${src[t2.LOOSEPLAIN]}$`); + createToken("GTLT", "((?:<|>)?=?)"); + createToken("XRANGEIDENTIFIERLOOSE", `${src[t2.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); + createToken("XRANGEIDENTIFIER", `${src[t2.NUMERICIDENTIFIER]}|x|X|\\*`); + createToken("XRANGEPLAIN", `[v=\\s]*(${src[t2.XRANGEIDENTIFIER]})(?:\\.(${src[t2.XRANGEIDENTIFIER]})(?:\\.(${src[t2.XRANGEIDENTIFIER]})(?:${src[t2.PRERELEASE]})?${src[t2.BUILD]}?)?)?`); + createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t2.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t2.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t2.XRANGEIDENTIFIERLOOSE]})(?:${src[t2.PRERELEASELOOSE]})?${src[t2.BUILD]}?)?)?`); + createToken("XRANGE", `^${src[t2.GTLT]}\\s*${src[t2.XRANGEPLAIN]}$`); + createToken("XRANGELOOSE", `^${src[t2.GTLT]}\\s*${src[t2.XRANGEPLAINLOOSE]}$`); + createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`); + createToken("COERCE", `${src[t2.COERCEPLAIN]}(?:$|[^\\d])`); + createToken("COERCEFULL", src[t2.COERCEPLAIN] + `(?:${src[t2.PRERELEASE]})?(?:${src[t2.BUILD]})?(?:$|[^\\d])`); + createToken("COERCERTL", src[t2.COERCE], true); + createToken("COERCERTLFULL", src[t2.COERCEFULL], true); + createToken("LONETILDE", "(?:~>?)"); + createToken("TILDETRIM", `(\\s*)${src[t2.LONETILDE]}\\s+`, true); + exports.tildeTrimReplace = "$1~"; + createToken("TILDE", `^${src[t2.LONETILDE]}${src[t2.XRANGEPLAIN]}$`); + createToken("TILDELOOSE", `^${src[t2.LONETILDE]}${src[t2.XRANGEPLAINLOOSE]}$`); + createToken("LONECARET", "(?:\\^)"); + createToken("CARETTRIM", `(\\s*)${src[t2.LONECARET]}\\s+`, true); + exports.caretTrimReplace = "$1^"; + createToken("CARET", `^${src[t2.LONECARET]}${src[t2.XRANGEPLAIN]}$`); + createToken("CARETLOOSE", `^${src[t2.LONECARET]}${src[t2.XRANGEPLAINLOOSE]}$`); + createToken("COMPARATORLOOSE", `^${src[t2.GTLT]}\\s*(${src[t2.LOOSEPLAIN]})$|^$`); + createToken("COMPARATOR", `^${src[t2.GTLT]}\\s*(${src[t2.FULLPLAIN]})$|^$`); + createToken("COMPARATORTRIM", `(\\s*)${src[t2.GTLT]}\\s*(${src[t2.LOOSEPLAIN]}|${src[t2.XRANGEPLAIN]})`, true); + exports.comparatorTrimReplace = "$1$2$3"; + createToken("HYPHENRANGE", `^\\s*(${src[t2.XRANGEPLAIN]})\\s+-\\s+(${src[t2.XRANGEPLAIN]})\\s*$`); + createToken("HYPHENRANGELOOSE", `^\\s*(${src[t2.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t2.XRANGEPLAINLOOSE]})\\s*$`); + createToken("STAR", "(<|>)?=?\\s*\\*"); + createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$"); + createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$"); + } + }); + + // node_modules/semver/internal/parse-options.js + var require_parse_options = __commonJS({ + "node_modules/semver/internal/parse-options.js"(exports, module) { + "use strict"; + var looseOption = Object.freeze({ loose: true }); + var emptyOpts = Object.freeze({}); + var parseOptions2 = (options) => { + if (!options) { + return emptyOpts; + } + if (typeof options !== "object") { + return looseOption; + } + return options; + }; + module.exports = parseOptions2; + } + }); + + // node_modules/semver/internal/identifiers.js + var require_identifiers = __commonJS({ + "node_modules/semver/internal/identifiers.js"(exports, module) { + "use strict"; + var numeric = /^[0-9]+$/; + var compareIdentifiers = (a2, b3) => { + if (typeof a2 === "number" && typeof b3 === "number") { + return a2 === b3 ? 0 : a2 < b3 ? -1 : 1; + } + const anum = numeric.test(a2); + const bnum = numeric.test(b3); + if (anum && bnum) { + a2 = +a2; + b3 = +b3; + } + return a2 === b3 ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a2 < b3 ? -1 : 1; + }; + var rcompareIdentifiers = (a2, b3) => compareIdentifiers(b3, a2); + module.exports = { + compareIdentifiers, + rcompareIdentifiers + }; + } + }); + + // node_modules/semver/classes/semver.js + var require_semver = __commonJS({ + "node_modules/semver/classes/semver.js"(exports, module) { + "use strict"; + var debug = require_debug(); + var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants(); + var { safeRe: re2, t: t2 } = require_re(); + var parseOptions2 = require_parse_options(); + var { compareIdentifiers } = require_identifiers(); + var SemVer = class _SemVer { + constructor(version, options) { + options = parseOptions2(options); + if (version instanceof _SemVer) { + if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { + return version; + } else { + version = version.version; + } + } else if (typeof version !== "string") { + throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`); + } + if (version.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ); + } + debug("SemVer", version, options); + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + const m3 = version.trim().match(options.loose ? re2[t2.LOOSE] : re2[t2.FULL]); + if (!m3) { + throw new TypeError(`Invalid Version: ${version}`); + } + this.raw = version; + this.major = +m3[1]; + this.minor = +m3[2]; + this.patch = +m3[3]; + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError("Invalid major version"); + } + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError("Invalid minor version"); + } + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError("Invalid patch version"); + } + if (!m3[4]) { + this.prerelease = []; + } else { + this.prerelease = m3[4].split(".").map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num; + } + } + return id; + }); + } + this.build = m3[5] ? m3[5].split(".") : []; + this.format(); + } + format() { + this.version = `${this.major}.${this.minor}.${this.patch}`; + if (this.prerelease.length) { + this.version += `-${this.prerelease.join(".")}`; + } + return this.version; + } + toString() { + return this.version; + } + compare(other) { + debug("SemVer.compare", this.version, this.options, other); + if (!(other instanceof _SemVer)) { + if (typeof other === "string" && other === this.version) { + return 0; + } + other = new _SemVer(other, this.options); + } + if (other.version === this.version) { + return 0; + } + return this.compareMain(other) || this.comparePre(other); + } + compareMain(other) { + if (!(other instanceof _SemVer)) { + other = new _SemVer(other, this.options); + } + if (this.major < other.major) { + return -1; + } + if (this.major > other.major) { + return 1; + } + if (this.minor < other.minor) { + return -1; + } + if (this.minor > other.minor) { + return 1; + } + if (this.patch < other.patch) { + return -1; + } + if (this.patch > other.patch) { + return 1; + } + return 0; + } + comparePre(other) { + if (!(other instanceof _SemVer)) { + other = new _SemVer(other, this.options); + } + if (this.prerelease.length && !other.prerelease.length) { + return -1; + } else if (!this.prerelease.length && other.prerelease.length) { + return 1; + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0; + } + let i2 = 0; + do { + const a2 = this.prerelease[i2]; + const b3 = other.prerelease[i2]; + debug("prerelease compare", i2, a2, b3); + if (a2 === void 0 && b3 === void 0) { + return 0; + } else if (b3 === void 0) { + return 1; + } else if (a2 === void 0) { + return -1; + } else if (a2 === b3) { + continue; + } else { + return compareIdentifiers(a2, b3); + } + } while (++i2); + } + compareBuild(other) { + if (!(other instanceof _SemVer)) { + other = new _SemVer(other, this.options); + } + let i2 = 0; + do { + const a2 = this.build[i2]; + const b3 = other.build[i2]; + debug("build compare", i2, a2, b3); + if (a2 === void 0 && b3 === void 0) { + return 0; + } else if (b3 === void 0) { + return 1; + } else if (a2 === void 0) { + return -1; + } else if (a2 === b3) { + continue; + } else { + return compareIdentifiers(a2, b3); + } + } while (++i2); + } + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc(release, identifier, identifierBase) { + if (release.startsWith("pre")) { + if (!identifier && identifierBase === false) { + throw new Error("invalid increment argument: identifier is empty"); + } + if (identifier) { + const match = `-${identifier}`.match(this.options.loose ? re2[t2.PRERELEASELOOSE] : re2[t2.PRERELEASE]); + if (!match || match[1] !== identifier) { + throw new Error(`invalid identifier: ${identifier}`); + } + } + } + switch (release) { + case "premajor": + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc("pre", identifier, identifierBase); + break; + case "preminor": + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc("pre", identifier, identifierBase); + break; + case "prepatch": + this.prerelease.length = 0; + this.inc("patch", identifier, identifierBase); + this.inc("pre", identifier, identifierBase); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case "prerelease": + if (this.prerelease.length === 0) { + this.inc("patch", identifier, identifierBase); + } + this.inc("pre", identifier, identifierBase); + break; + case "release": + if (this.prerelease.length === 0) { + throw new Error(`version ${this.raw} is not a prerelease`); + } + this.prerelease.length = 0; + break; + case "major": + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { + this.major++; + } + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + case "minor": + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; + } + this.patch = 0; + this.prerelease = []; + break; + case "patch": + if (this.prerelease.length === 0) { + this.patch++; + } + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case "pre": { + const base = Number(identifierBase) ? 1 : 0; + if (this.prerelease.length === 0) { + this.prerelease = [base]; + } else { + let i2 = this.prerelease.length; + while (--i2 >= 0) { + if (typeof this.prerelease[i2] === "number") { + this.prerelease[i2]++; + i2 = -2; + } + } + if (i2 === -1) { + if (identifier === this.prerelease.join(".") && identifierBase === false) { + throw new Error("invalid increment argument: identifier already exists"); + } + this.prerelease.push(base); + } + } + if (identifier) { + let prerelease = [identifier, base]; + if (identifierBase === false) { + prerelease = [identifier]; + } + if (compareIdentifiers(this.prerelease[0], identifier) === 0) { + if (isNaN(this.prerelease[1])) { + this.prerelease = prerelease; + } + } else { + this.prerelease = prerelease; + } + } + break; + } + default: + throw new Error(`invalid increment argument: ${release}`); + } + this.raw = this.format(); + if (this.build.length) { + this.raw += `+${this.build.join(".")}`; + } + return this; + } + }; + module.exports = SemVer; + } + }); + + // node_modules/semver/functions/parse.js + var require_parse = __commonJS({ + "node_modules/semver/functions/parse.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var parse3 = (version, options, throwErrors = false) => { + if (version instanceof SemVer) { + return version; + } + try { + return new SemVer(version, options); + } catch (er) { + if (!throwErrors) { + return null; + } + throw er; + } + }; + module.exports = parse3; + } + }); + + // node_modules/semver/functions/valid.js + var require_valid = __commonJS({ + "node_modules/semver/functions/valid.js"(exports, module) { + "use strict"; + var parse3 = require_parse(); + var valid = (version, options) => { + const v6 = parse3(version, options); + return v6 ? v6.version : null; + }; + module.exports = valid; + } + }); + + // node_modules/semver/functions/clean.js + var require_clean = __commonJS({ + "node_modules/semver/functions/clean.js"(exports, module) { + "use strict"; + var parse3 = require_parse(); + var clean = (version, options) => { + const s2 = parse3(version.trim().replace(/^[=v]+/, ""), options); + return s2 ? s2.version : null; + }; + module.exports = clean; + } + }); + + // node_modules/semver/functions/inc.js + var require_inc = __commonJS({ + "node_modules/semver/functions/inc.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var inc = (version, release, options, identifier, identifierBase) => { + if (typeof options === "string") { + identifierBase = identifier; + identifier = options; + options = void 0; + } + try { + return new SemVer( + version instanceof SemVer ? version.version : version, + options + ).inc(release, identifier, identifierBase).version; + } catch (er) { + return null; + } + }; + module.exports = inc; + } + }); + + // node_modules/semver/functions/diff.js + var require_diff = __commonJS({ + "node_modules/semver/functions/diff.js"(exports, module) { + "use strict"; + var parse3 = require_parse(); + var diff = (version1, version2) => { + const v1 = parse3(version1, null, true); + const v22 = parse3(version2, null, true); + const comparison = v1.compare(v22); + if (comparison === 0) { + return null; + } + const v1Higher = comparison > 0; + const highVersion = v1Higher ? v1 : v22; + const lowVersion = v1Higher ? v22 : v1; + const highHasPre = !!highVersion.prerelease.length; + const lowHasPre = !!lowVersion.prerelease.length; + if (lowHasPre && !highHasPre) { + if (!lowVersion.patch && !lowVersion.minor) { + return "major"; + } + if (lowVersion.compareMain(highVersion) === 0) { + if (lowVersion.minor && !lowVersion.patch) { + return "minor"; + } + return "patch"; + } + } + const prefix = highHasPre ? "pre" : ""; + if (v1.major !== v22.major) { + return prefix + "major"; + } + if (v1.minor !== v22.minor) { + return prefix + "minor"; + } + if (v1.patch !== v22.patch) { + return prefix + "patch"; + } + return "prerelease"; + }; + module.exports = diff; + } + }); + + // node_modules/semver/functions/major.js + var require_major = __commonJS({ + "node_modules/semver/functions/major.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var major = (a2, loose) => new SemVer(a2, loose).major; + module.exports = major; + } + }); + + // node_modules/semver/functions/minor.js + var require_minor = __commonJS({ + "node_modules/semver/functions/minor.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var minor = (a2, loose) => new SemVer(a2, loose).minor; + module.exports = minor; + } + }); + + // node_modules/semver/functions/patch.js + var require_patch = __commonJS({ + "node_modules/semver/functions/patch.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var patch = (a2, loose) => new SemVer(a2, loose).patch; + module.exports = patch; + } + }); + + // node_modules/semver/functions/prerelease.js + var require_prerelease = __commonJS({ + "node_modules/semver/functions/prerelease.js"(exports, module) { + "use strict"; + var parse3 = require_parse(); + var prerelease = (version, options) => { + const parsed = parse3(version, options); + return parsed && parsed.prerelease.length ? parsed.prerelease : null; + }; + module.exports = prerelease; + } + }); + + // node_modules/semver/functions/compare.js + var require_compare = __commonJS({ + "node_modules/semver/functions/compare.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var compare = (a2, b3, loose) => new SemVer(a2, loose).compare(new SemVer(b3, loose)); + module.exports = compare; + } + }); + + // node_modules/semver/functions/rcompare.js + var require_rcompare = __commonJS({ + "node_modules/semver/functions/rcompare.js"(exports, module) { + "use strict"; + var compare = require_compare(); + var rcompare = (a2, b3, loose) => compare(b3, a2, loose); + module.exports = rcompare; + } + }); + + // node_modules/semver/functions/compare-loose.js + var require_compare_loose = __commonJS({ + "node_modules/semver/functions/compare-loose.js"(exports, module) { + "use strict"; + var compare = require_compare(); + var compareLoose = (a2, b3) => compare(a2, b3, true); + module.exports = compareLoose; + } + }); + + // node_modules/semver/functions/compare-build.js + var require_compare_build = __commonJS({ + "node_modules/semver/functions/compare-build.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var compareBuild = (a2, b3, loose) => { + const versionA = new SemVer(a2, loose); + const versionB = new SemVer(b3, loose); + return versionA.compare(versionB) || versionA.compareBuild(versionB); + }; + module.exports = compareBuild; + } + }); + + // node_modules/semver/functions/sort.js + var require_sort = __commonJS({ + "node_modules/semver/functions/sort.js"(exports, module) { + "use strict"; + var compareBuild = require_compare_build(); + var sort = (list, loose) => list.sort((a2, b3) => compareBuild(a2, b3, loose)); + module.exports = sort; + } + }); + + // node_modules/semver/functions/rsort.js + var require_rsort = __commonJS({ + "node_modules/semver/functions/rsort.js"(exports, module) { + "use strict"; + var compareBuild = require_compare_build(); + var rsort = (list, loose) => list.sort((a2, b3) => compareBuild(b3, a2, loose)); + module.exports = rsort; + } + }); + + // node_modules/semver/functions/gt.js + var require_gt = __commonJS({ + "node_modules/semver/functions/gt.js"(exports, module) { + "use strict"; + var compare = require_compare(); + var gt = (a2, b3, loose) => compare(a2, b3, loose) > 0; + module.exports = gt; + } + }); + + // node_modules/semver/functions/lt.js + var require_lt = __commonJS({ + "node_modules/semver/functions/lt.js"(exports, module) { + "use strict"; + var compare = require_compare(); + var lt = (a2, b3, loose) => compare(a2, b3, loose) < 0; + module.exports = lt; + } + }); + + // node_modules/semver/functions/eq.js + var require_eq = __commonJS({ + "node_modules/semver/functions/eq.js"(exports, module) { + "use strict"; + var compare = require_compare(); + var eq = (a2, b3, loose) => compare(a2, b3, loose) === 0; + module.exports = eq; + } + }); + + // node_modules/semver/functions/neq.js + var require_neq = __commonJS({ + "node_modules/semver/functions/neq.js"(exports, module) { + "use strict"; + var compare = require_compare(); + var neq = (a2, b3, loose) => compare(a2, b3, loose) !== 0; + module.exports = neq; + } + }); + + // node_modules/semver/functions/gte.js + var require_gte = __commonJS({ + "node_modules/semver/functions/gte.js"(exports, module) { + "use strict"; + var compare = require_compare(); + var gte = (a2, b3, loose) => compare(a2, b3, loose) >= 0; + module.exports = gte; + } + }); + + // node_modules/semver/functions/lte.js + var require_lte = __commonJS({ + "node_modules/semver/functions/lte.js"(exports, module) { + "use strict"; + var compare = require_compare(); + var lte = (a2, b3, loose) => compare(a2, b3, loose) <= 0; + module.exports = lte; + } + }); + + // node_modules/semver/functions/cmp.js + var require_cmp = __commonJS({ + "node_modules/semver/functions/cmp.js"(exports, module) { + "use strict"; + var eq = require_eq(); + var neq = require_neq(); + var gt = require_gt(); + var gte = require_gte(); + var lt = require_lt(); + var lte = require_lte(); + var cmp = (a2, op, b3, loose) => { + switch (op) { + case "===": + if (typeof a2 === "object") { + a2 = a2.version; + } + if (typeof b3 === "object") { + b3 = b3.version; + } + return a2 === b3; + case "!==": + if (typeof a2 === "object") { + a2 = a2.version; + } + if (typeof b3 === "object") { + b3 = b3.version; + } + return a2 !== b3; + case "": + case "=": + case "==": + return eq(a2, b3, loose); + case "!=": + return neq(a2, b3, loose); + case ">": + return gt(a2, b3, loose); + case ">=": + return gte(a2, b3, loose); + case "<": + return lt(a2, b3, loose); + case "<=": + return lte(a2, b3, loose); + default: + throw new TypeError(`Invalid operator: ${op}`); + } + }; + module.exports = cmp; + } + }); + + // node_modules/semver/functions/coerce.js + var require_coerce = __commonJS({ + "node_modules/semver/functions/coerce.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var parse3 = require_parse(); + var { safeRe: re2, t: t2 } = require_re(); + var coerce = (version, options) => { + if (version instanceof SemVer) { + return version; + } + if (typeof version === "number") { + version = String(version); + } + if (typeof version !== "string") { + return null; + } + options = options || {}; + let match = null; + if (!options.rtl) { + match = version.match(options.includePrerelease ? re2[t2.COERCEFULL] : re2[t2.COERCE]); + } else { + const coerceRtlRegex = options.includePrerelease ? re2[t2.COERCERTLFULL] : re2[t2.COERCERTL]; + let next; + while ((next = coerceRtlRegex.exec(version)) && (!match || match.index + match[0].length !== version.length)) { + if (!match || next.index + next[0].length !== match.index + match[0].length) { + match = next; + } + coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length; + } + coerceRtlRegex.lastIndex = -1; + } + if (match === null) { + return null; + } + const major = match[2]; + const minor = match[3] || "0"; + const patch = match[4] || "0"; + const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ""; + const build = options.includePrerelease && match[6] ? `+${match[6]}` : ""; + return parse3(`${major}.${minor}.${patch}${prerelease}${build}`, options); + }; + module.exports = coerce; + } + }); + + // node_modules/semver/internal/lrucache.js + var require_lrucache = __commonJS({ + "node_modules/semver/internal/lrucache.js"(exports, module) { + "use strict"; + var LRUCache = class { + constructor() { + this.max = 1e3; + this.map = /* @__PURE__ */ new Map(); + } + get(key) { + const value = this.map.get(key); + if (value === void 0) { + return void 0; + } else { + this.map.delete(key); + this.map.set(key, value); + return value; + } + } + delete(key) { + return this.map.delete(key); + } + set(key, value) { + const deleted = this.delete(key); + if (!deleted && value !== void 0) { + if (this.map.size >= this.max) { + const firstKey = this.map.keys().next().value; + this.delete(firstKey); + } + this.map.set(key, value); + } + return this; + } + }; + module.exports = LRUCache; + } + }); + + // node_modules/semver/classes/range.js + var require_range = __commonJS({ + "node_modules/semver/classes/range.js"(exports, module) { + "use strict"; + var SPACE_CHARACTERS = /\s+/g; + var Range = class _Range { + constructor(range, options) { + options = parseOptions2(options); + if (range instanceof _Range) { + if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { + return range; + } else { + return new _Range(range.raw, options); + } + } + if (range instanceof Comparator) { + this.raw = range.value; + this.set = [[range]]; + this.formatted = void 0; + return this; + } + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + this.raw = range.trim().replace(SPACE_CHARACTERS, " "); + this.set = this.raw.split("||").map((r2) => this.parseRange(r2.trim())).filter((c3) => c3.length); + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${this.raw}`); + } + if (this.set.length > 1) { + const first = this.set[0]; + this.set = this.set.filter((c3) => !isNullSet(c3[0])); + if (this.set.length === 0) { + this.set = [first]; + } else if (this.set.length > 1) { + for (const c3 of this.set) { + if (c3.length === 1 && isAny(c3[0])) { + this.set = [c3]; + break; + } + } + } + } + this.formatted = void 0; + } + get range() { + if (this.formatted === void 0) { + this.formatted = ""; + for (let i2 = 0; i2 < this.set.length; i2++) { + if (i2 > 0) { + this.formatted += "||"; + } + const comps = this.set[i2]; + for (let k3 = 0; k3 < comps.length; k3++) { + if (k3 > 0) { + this.formatted += " "; + } + this.formatted += comps[k3].toString().trim(); + } + } + } + return this.formatted; + } + format() { + return this.range; + } + toString() { + return this.range; + } + parseRange(range) { + const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE); + const memoKey = memoOpts + ":" + range; + const cached = cache2.get(memoKey); + if (cached) { + return cached; + } + const loose = this.options.loose; + const hr = loose ? re2[t2.HYPHENRANGELOOSE] : re2[t2.HYPHENRANGE]; + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); + debug("hyphen replace", range); + range = range.replace(re2[t2.COMPARATORTRIM], comparatorTrimReplace); + debug("comparator trim", range); + range = range.replace(re2[t2.TILDETRIM], tildeTrimReplace); + debug("tilde trim", range); + range = range.replace(re2[t2.CARETTRIM], caretTrimReplace); + debug("caret trim", range); + let rangeList = range.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options)); + if (loose) { + rangeList = rangeList.filter((comp) => { + debug("loose invalid filter", comp, this.options); + return !!comp.match(re2[t2.COMPARATORLOOSE]); + }); + } + debug("range list", rangeList); + const rangeMap = /* @__PURE__ */ new Map(); + const comparators = rangeList.map((comp) => new Comparator(comp, this.options)); + for (const comp of comparators) { + if (isNullSet(comp)) { + return [comp]; + } + rangeMap.set(comp.value, comp); + } + if (rangeMap.size > 1 && rangeMap.has("")) { + rangeMap.delete(""); + } + const result = [...rangeMap.values()]; + cache2.set(memoKey, result); + return result; + } + intersects(range, options) { + if (!(range instanceof _Range)) { + throw new TypeError("a Range is required"); + } + return this.set.some((thisComparators) => { + return isSatisfiable(thisComparators, options) && range.set.some((rangeComparators) => { + return isSatisfiable(rangeComparators, options) && thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options); + }); + }); + }); + }); + } + // if ANY of the sets match ALL of its comparators, then pass + test(version) { + if (!version) { + return false; + } + if (typeof version === "string") { + try { + version = new SemVer(version, this.options); + } catch (er) { + return false; + } + } + for (let i2 = 0; i2 < this.set.length; i2++) { + if (testSet(this.set[i2], version, this.options)) { + return true; + } + } + return false; + } + }; + module.exports = Range; + var LRU = require_lrucache(); + var cache2 = new LRU(); + var parseOptions2 = require_parse_options(); + var Comparator = require_comparator(); + var debug = require_debug(); + var SemVer = require_semver(); + var { + safeRe: re2, + t: t2, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace + } = require_re(); + var { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require_constants(); + var isNullSet = (c3) => c3.value === "<0.0.0-0"; + var isAny = (c3) => c3.value === ""; + var isSatisfiable = (comparators, options) => { + let result = true; + const remainingComparators = comparators.slice(); + let testComparator = remainingComparators.pop(); + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options); + }); + testComparator = remainingComparators.pop(); + } + return result; + }; + var parseComparator = (comp, options) => { + comp = comp.replace(re2[t2.BUILD], ""); + debug("comp", comp, options); + comp = replaceCarets(comp, options); + debug("caret", comp); + comp = replaceTildes(comp, options); + debug("tildes", comp); + comp = replaceXRanges(comp, options); + debug("xrange", comp); + comp = replaceStars(comp, options); + debug("stars", comp); + return comp; + }; + var isX = (id) => !id || id.toLowerCase() === "x" || id === "*"; + var replaceTildes = (comp, options) => { + return comp.trim().split(/\s+/).map((c3) => replaceTilde(c3, options)).join(" "); + }; + var replaceTilde = (comp, options) => { + const r2 = options.loose ? re2[t2.TILDELOOSE] : re2[t2.TILDE]; + return comp.replace(r2, (_2, M2, m3, p2, pr) => { + debug("tilde", comp, _2, M2, m3, p2, pr); + let ret; + if (isX(M2)) { + ret = ""; + } else if (isX(m3)) { + ret = `>=${M2}.0.0 <${+M2 + 1}.0.0-0`; + } else if (isX(p2)) { + ret = `>=${M2}.${m3}.0 <${M2}.${+m3 + 1}.0-0`; + } else if (pr) { + debug("replaceTilde pr", pr); + ret = `>=${M2}.${m3}.${p2}-${pr} <${M2}.${+m3 + 1}.0-0`; + } else { + ret = `>=${M2}.${m3}.${p2} <${M2}.${+m3 + 1}.0-0`; + } + debug("tilde return", ret); + return ret; + }); + }; + var replaceCarets = (comp, options) => { + return comp.trim().split(/\s+/).map((c3) => replaceCaret(c3, options)).join(" "); + }; + var replaceCaret = (comp, options) => { + debug("caret", comp, options); + const r2 = options.loose ? re2[t2.CARETLOOSE] : re2[t2.CARET]; + const z3 = options.includePrerelease ? "-0" : ""; + return comp.replace(r2, (_2, M2, m3, p2, pr) => { + debug("caret", comp, _2, M2, m3, p2, pr); + let ret; + if (isX(M2)) { + ret = ""; + } else if (isX(m3)) { + ret = `>=${M2}.0.0${z3} <${+M2 + 1}.0.0-0`; + } else if (isX(p2)) { + if (M2 === "0") { + ret = `>=${M2}.${m3}.0${z3} <${M2}.${+m3 + 1}.0-0`; + } else { + ret = `>=${M2}.${m3}.0${z3} <${+M2 + 1}.0.0-0`; + } + } else if (pr) { + debug("replaceCaret pr", pr); + if (M2 === "0") { + if (m3 === "0") { + ret = `>=${M2}.${m3}.${p2}-${pr} <${M2}.${m3}.${+p2 + 1}-0`; + } else { + ret = `>=${M2}.${m3}.${p2}-${pr} <${M2}.${+m3 + 1}.0-0`; + } + } else { + ret = `>=${M2}.${m3}.${p2}-${pr} <${+M2 + 1}.0.0-0`; + } + } else { + debug("no pr"); + if (M2 === "0") { + if (m3 === "0") { + ret = `>=${M2}.${m3}.${p2}${z3} <${M2}.${m3}.${+p2 + 1}-0`; + } else { + ret = `>=${M2}.${m3}.${p2}${z3} <${M2}.${+m3 + 1}.0-0`; + } + } else { + ret = `>=${M2}.${m3}.${p2} <${+M2 + 1}.0.0-0`; + } + } + debug("caret return", ret); + return ret; + }); + }; + var replaceXRanges = (comp, options) => { + debug("replaceXRanges", comp, options); + return comp.split(/\s+/).map((c3) => replaceXRange(c3, options)).join(" "); + }; + var replaceXRange = (comp, options) => { + comp = comp.trim(); + const r2 = options.loose ? re2[t2.XRANGELOOSE] : re2[t2.XRANGE]; + return comp.replace(r2, (ret, gtlt, M2, m3, p2, pr) => { + debug("xRange", comp, ret, gtlt, M2, m3, p2, pr); + const xM = isX(M2); + const xm = xM || isX(m3); + const xp = xm || isX(p2); + const anyX = xp; + if (gtlt === "=" && anyX) { + gtlt = ""; + } + pr = options.includePrerelease ? "-0" : ""; + if (xM) { + if (gtlt === ">" || gtlt === "<") { + ret = "<0.0.0-0"; + } else { + ret = "*"; + } + } else if (gtlt && anyX) { + if (xm) { + m3 = 0; + } + p2 = 0; + if (gtlt === ">") { + gtlt = ">="; + if (xm) { + M2 = +M2 + 1; + m3 = 0; + p2 = 0; + } else { + m3 = +m3 + 1; + p2 = 0; + } + } else if (gtlt === "<=") { + gtlt = "<"; + if (xm) { + M2 = +M2 + 1; + } else { + m3 = +m3 + 1; + } + } + if (gtlt === "<") { + pr = "-0"; + } + ret = `${gtlt + M2}.${m3}.${p2}${pr}`; + } else if (xm) { + ret = `>=${M2}.0.0${pr} <${+M2 + 1}.0.0-0`; + } else if (xp) { + ret = `>=${M2}.${m3}.0${pr} <${M2}.${+m3 + 1}.0-0`; + } + debug("xRange return", ret); + return ret; + }); + }; + var replaceStars = (comp, options) => { + debug("replaceStars", comp, options); + return comp.trim().replace(re2[t2.STAR], ""); + }; + var replaceGTE0 = (comp, options) => { + debug("replaceGTE0", comp, options); + return comp.trim().replace(re2[options.includePrerelease ? t2.GTE0PRE : t2.GTE0], ""); + }; + var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => { + if (isX(fM)) { + from = ""; + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? "-0" : ""}`; + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? "-0" : ""}`; + } else if (fpr) { + from = `>=${from}`; + } else { + from = `>=${from}${incPr ? "-0" : ""}`; + } + if (isX(tM)) { + to = ""; + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0`; + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0`; + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}`; + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0`; + } else { + to = `<=${to}`; + } + return `${from} ${to}`.trim(); + }; + var testSet = (set2, version, options) => { + for (let i2 = 0; i2 < set2.length; i2++) { + if (!set2[i2].test(version)) { + return false; + } + } + if (version.prerelease.length && !options.includePrerelease) { + for (let i2 = 0; i2 < set2.length; i2++) { + debug(set2[i2].semver); + if (set2[i2].semver === Comparator.ANY) { + continue; + } + if (set2[i2].semver.prerelease.length > 0) { + const allowed = set2[i2].semver; + if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { + return true; + } + } + } + return false; + } + return true; + }; + } + }); + + // node_modules/semver/classes/comparator.js + var require_comparator = __commonJS({ + "node_modules/semver/classes/comparator.js"(exports, module) { + "use strict"; + var ANY = Symbol("SemVer ANY"); + var Comparator = class _Comparator { + static get ANY() { + return ANY; + } + constructor(comp, options) { + options = parseOptions2(options); + if (comp instanceof _Comparator) { + if (comp.loose === !!options.loose) { + return comp; + } else { + comp = comp.value; + } + } + comp = comp.trim().split(/\s+/).join(" "); + debug("comparator", comp, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp); + if (this.semver === ANY) { + this.value = ""; + } else { + this.value = this.operator + this.semver.version; + } + debug("comp", this); + } + parse(comp) { + const r2 = this.options.loose ? re2[t2.COMPARATORLOOSE] : re2[t2.COMPARATOR]; + const m3 = comp.match(r2); + if (!m3) { + throw new TypeError(`Invalid comparator: ${comp}`); + } + this.operator = m3[1] !== void 0 ? m3[1] : ""; + if (this.operator === "=") { + this.operator = ""; + } + if (!m3[2]) { + this.semver = ANY; + } else { + this.semver = new SemVer(m3[2], this.options.loose); + } + } + toString() { + return this.value; + } + test(version) { + debug("Comparator.test", version, this.options.loose); + if (this.semver === ANY || version === ANY) { + return true; + } + if (typeof version === "string") { + try { + version = new SemVer(version, this.options); + } catch (er) { + return false; + } + } + return cmp(version, this.operator, this.semver, this.options); + } + intersects(comp, options) { + if (!(comp instanceof _Comparator)) { + throw new TypeError("a Comparator is required"); + } + if (this.operator === "") { + if (this.value === "") { + return true; + } + return new Range(comp.value, options).test(this.value); + } else if (comp.operator === "") { + if (comp.value === "") { + return true; + } + return new Range(this.value, options).test(comp.semver); + } + options = parseOptions2(options); + if (options.includePrerelease && (this.value === "<0.0.0-0" || comp.value === "<0.0.0-0")) { + return false; + } + if (!options.includePrerelease && (this.value.startsWith("<0.0.0") || comp.value.startsWith("<0.0.0"))) { + return false; + } + if (this.operator.startsWith(">") && comp.operator.startsWith(">")) { + return true; + } + if (this.operator.startsWith("<") && comp.operator.startsWith("<")) { + return true; + } + if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) { + return true; + } + if (cmp(this.semver, "<", comp.semver, options) && this.operator.startsWith(">") && comp.operator.startsWith("<")) { + return true; + } + if (cmp(this.semver, ">", comp.semver, options) && this.operator.startsWith("<") && comp.operator.startsWith(">")) { + return true; + } + return false; + } + }; + module.exports = Comparator; + var parseOptions2 = require_parse_options(); + var { safeRe: re2, t: t2 } = require_re(); + var cmp = require_cmp(); + var debug = require_debug(); + var SemVer = require_semver(); + var Range = require_range(); + } + }); + + // node_modules/semver/functions/satisfies.js + var require_satisfies = __commonJS({ + "node_modules/semver/functions/satisfies.js"(exports, module) { + "use strict"; + var Range = require_range(); + var satisfies = (version, range, options) => { + try { + range = new Range(range, options); + } catch (er) { + return false; + } + return range.test(version); + }; + module.exports = satisfies; + } + }); + + // node_modules/semver/ranges/to-comparators.js + var require_to_comparators = __commonJS({ + "node_modules/semver/ranges/to-comparators.js"(exports, module) { + "use strict"; + var Range = require_range(); + var toComparators = (range, options) => new Range(range, options).set.map((comp) => comp.map((c3) => c3.value).join(" ").trim().split(" ")); + module.exports = toComparators; + } + }); + + // node_modules/semver/ranges/max-satisfying.js + var require_max_satisfying = __commonJS({ + "node_modules/semver/ranges/max-satisfying.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var Range = require_range(); + var maxSatisfying = (versions, range, options) => { + let max = null; + let maxSV = null; + let rangeObj = null; + try { + rangeObj = new Range(range, options); + } catch (er) { + return null; + } + versions.forEach((v6) => { + if (rangeObj.test(v6)) { + if (!max || maxSV.compare(v6) === -1) { + max = v6; + maxSV = new SemVer(max, options); + } + } + }); + return max; + }; + module.exports = maxSatisfying; + } + }); + + // node_modules/semver/ranges/min-satisfying.js + var require_min_satisfying = __commonJS({ + "node_modules/semver/ranges/min-satisfying.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var Range = require_range(); + var minSatisfying = (versions, range, options) => { + let min = null; + let minSV = null; + let rangeObj = null; + try { + rangeObj = new Range(range, options); + } catch (er) { + return null; + } + versions.forEach((v6) => { + if (rangeObj.test(v6)) { + if (!min || minSV.compare(v6) === 1) { + min = v6; + minSV = new SemVer(min, options); + } + } + }); + return min; + }; + module.exports = minSatisfying; + } + }); + + // node_modules/semver/ranges/min-version.js + var require_min_version = __commonJS({ + "node_modules/semver/ranges/min-version.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var Range = require_range(); + var gt = require_gt(); + var minVersion = (range, loose) => { + range = new Range(range, loose); + let minver = new SemVer("0.0.0"); + if (range.test(minver)) { + return minver; + } + minver = new SemVer("0.0.0-0"); + if (range.test(minver)) { + return minver; + } + minver = null; + for (let i2 = 0; i2 < range.set.length; ++i2) { + const comparators = range.set[i2]; + let setMin = null; + comparators.forEach((comparator) => { + const compver = new SemVer(comparator.semver.version); + switch (comparator.operator) { + case ">": + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } + compver.raw = compver.format(); + /* fallthrough */ + case "": + case ">=": + if (!setMin || gt(compver, setMin)) { + setMin = compver; + } + break; + case "<": + case "<=": + break; + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`); + } + }); + if (setMin && (!minver || gt(minver, setMin))) { + minver = setMin; + } + } + if (minver && range.test(minver)) { + return minver; + } + return null; + }; + module.exports = minVersion; + } + }); + + // node_modules/semver/ranges/valid.js + var require_valid2 = __commonJS({ + "node_modules/semver/ranges/valid.js"(exports, module) { + "use strict"; + var Range = require_range(); + var validRange = (range, options) => { + try { + return new Range(range, options).range || "*"; + } catch (er) { + return null; + } + }; + module.exports = validRange; + } + }); + + // node_modules/semver/ranges/outside.js + var require_outside = __commonJS({ + "node_modules/semver/ranges/outside.js"(exports, module) { + "use strict"; + var SemVer = require_semver(); + var Comparator = require_comparator(); + var { ANY } = Comparator; + var Range = require_range(); + var satisfies = require_satisfies(); + var gt = require_gt(); + var lt = require_lt(); + var lte = require_lte(); + var gte = require_gte(); + var outside = (version, range, hilo, options) => { + version = new SemVer(version, options); + range = new Range(range, options); + let gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case ">": + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = ">"; + ecomp = ">="; + break; + case "<": + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = "<"; + ecomp = "<="; + break; + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } + if (satisfies(version, range, options)) { + return false; + } + for (let i2 = 0; i2 < range.set.length; ++i2) { + const comparators = range.set[i2]; + let high = null; + let low = null; + comparators.forEach((comparator) => { + if (comparator.semver === ANY) { + comparator = new Comparator(">=0.0.0"); + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); + if (high.operator === comp || high.operator === ecomp) { + return false; + } + if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false; + } + } + return true; + }; + module.exports = outside; + } + }); + + // node_modules/semver/ranges/gtr.js + var require_gtr = __commonJS({ + "node_modules/semver/ranges/gtr.js"(exports, module) { + "use strict"; + var outside = require_outside(); + var gtr = (version, range, options) => outside(version, range, ">", options); + module.exports = gtr; + } + }); + + // node_modules/semver/ranges/ltr.js + var require_ltr = __commonJS({ + "node_modules/semver/ranges/ltr.js"(exports, module) { + "use strict"; + var outside = require_outside(); + var ltr = (version, range, options) => outside(version, range, "<", options); + module.exports = ltr; + } + }); + + // node_modules/semver/ranges/intersects.js + var require_intersects = __commonJS({ + "node_modules/semver/ranges/intersects.js"(exports, module) { + "use strict"; + var Range = require_range(); + var intersects = (r1, r2, options) => { + r1 = new Range(r1, options); + r2 = new Range(r2, options); + return r1.intersects(r2, options); + }; + module.exports = intersects; + } + }); + + // node_modules/semver/ranges/simplify.js + var require_simplify = __commonJS({ + "node_modules/semver/ranges/simplify.js"(exports, module) { + "use strict"; + var satisfies = require_satisfies(); + var compare = require_compare(); + module.exports = (versions, range, options) => { + const set2 = []; + let first = null; + let prev = null; + const v6 = versions.sort((a2, b3) => compare(a2, b3, options)); + for (const version of v6) { + const included = satisfies(version, range, options); + if (included) { + prev = version; + if (!first) { + first = version; + } + } else { + if (prev) { + set2.push([first, prev]); + } + prev = null; + first = null; + } + } + if (first) { + set2.push([first, null]); + } + const ranges = []; + for (const [min, max] of set2) { + if (min === max) { + ranges.push(min); + } else if (!max && min === v6[0]) { + ranges.push("*"); + } else if (!max) { + ranges.push(`>=${min}`); + } else if (min === v6[0]) { + ranges.push(`<=${max}`); + } else { + ranges.push(`${min} - ${max}`); + } + } + const simplified = ranges.join(" || "); + const original = typeof range.raw === "string" ? range.raw : String(range); + return simplified.length < original.length ? simplified : range; + }; + } + }); + + // node_modules/semver/ranges/subset.js + var require_subset = __commonJS({ + "node_modules/semver/ranges/subset.js"(exports, module) { + "use strict"; + var Range = require_range(); + var Comparator = require_comparator(); + var { ANY } = Comparator; + var satisfies = require_satisfies(); + var compare = require_compare(); + var subset = (sub, dom, options = {}) => { + if (sub === dom) { + return true; + } + sub = new Range(sub, options); + dom = new Range(dom, options); + let sawNonNull = false; + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options); + sawNonNull = sawNonNull || isSub !== null; + if (isSub) { + continue OUTER; + } + } + if (sawNonNull) { + return false; + } + } + return true; + }; + var minimumVersionWithPreRelease = [new Comparator(">=0.0.0-0")]; + var minimumVersion = [new Comparator(">=0.0.0")]; + var simpleSubset = (sub, dom, options) => { + if (sub === dom) { + return true; + } + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) { + return true; + } else if (options.includePrerelease) { + sub = minimumVersionWithPreRelease; + } else { + sub = minimumVersion; + } + } + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) { + return true; + } else { + dom = minimumVersion; + } + } + const eqSet = /* @__PURE__ */ new Set(); + let gt, lt; + for (const c3 of sub) { + if (c3.operator === ">" || c3.operator === ">=") { + gt = higherGT(gt, c3, options); + } else if (c3.operator === "<" || c3.operator === "<=") { + lt = lowerLT(lt, c3, options); + } else { + eqSet.add(c3.semver); + } + } + if (eqSet.size > 1) { + return null; + } + let gtltComp; + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options); + if (gtltComp > 0) { + return null; + } else if (gtltComp === 0 && (gt.operator !== ">=" || lt.operator !== "<=")) { + return null; + } + } + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) { + return null; + } + if (lt && !satisfies(eq, String(lt), options)) { + return null; + } + for (const c3 of dom) { + if (!satisfies(eq, String(c3), options)) { + return false; + } + } + return true; + } + let higher, lower; + let hasDomLT, hasDomGT; + let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false; + let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false; + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === "<" && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false; + } + for (const c3 of dom) { + hasDomGT = hasDomGT || c3.operator === ">" || c3.operator === ">="; + hasDomLT = hasDomLT || c3.operator === "<" || c3.operator === "<="; + if (gt) { + if (needDomGTPre) { + if (c3.semver.prerelease && c3.semver.prerelease.length && c3.semver.major === needDomGTPre.major && c3.semver.minor === needDomGTPre.minor && c3.semver.patch === needDomGTPre.patch) { + needDomGTPre = false; + } + } + if (c3.operator === ">" || c3.operator === ">=") { + higher = higherGT(gt, c3, options); + if (higher === c3 && higher !== gt) { + return false; + } + } else if (gt.operator === ">=" && !satisfies(gt.semver, String(c3), options)) { + return false; + } + } + if (lt) { + if (needDomLTPre) { + if (c3.semver.prerelease && c3.semver.prerelease.length && c3.semver.major === needDomLTPre.major && c3.semver.minor === needDomLTPre.minor && c3.semver.patch === needDomLTPre.patch) { + needDomLTPre = false; + } + } + if (c3.operator === "<" || c3.operator === "<=") { + lower = lowerLT(lt, c3, options); + if (lower === c3 && lower !== lt) { + return false; + } + } else if (lt.operator === "<=" && !satisfies(lt.semver, String(c3), options)) { + return false; + } + } + if (!c3.operator && (lt || gt) && gtltComp !== 0) { + return false; + } + } + if (gt && hasDomLT && !lt && gtltComp !== 0) { + return false; + } + if (lt && hasDomGT && !gt && gtltComp !== 0) { + return false; + } + if (needDomGTPre || needDomLTPre) { + return false; + } + return true; + }; + var higherGT = (a2, b3, options) => { + if (!a2) { + return b3; + } + const comp = compare(a2.semver, b3.semver, options); + return comp > 0 ? a2 : comp < 0 ? b3 : b3.operator === ">" && a2.operator === ">=" ? b3 : a2; + }; + var lowerLT = (a2, b3, options) => { + if (!a2) { + return b3; + } + const comp = compare(a2.semver, b3.semver, options); + return comp < 0 ? a2 : comp > 0 ? b3 : b3.operator === "<" && a2.operator === "<=" ? b3 : a2; + }; + module.exports = subset; + } + }); + + // node_modules/semver/index.js + var require_semver2 = __commonJS({ + "node_modules/semver/index.js"(exports, module) { + "use strict"; + var internalRe = require_re(); + var constants = require_constants(); + var SemVer = require_semver(); + var identifiers = require_identifiers(); + var parse3 = require_parse(); + var valid = require_valid(); + var clean = require_clean(); + var inc = require_inc(); + var diff = require_diff(); + var major = require_major(); + var minor = require_minor(); + var patch = require_patch(); + var prerelease = require_prerelease(); + var compare = require_compare(); + var rcompare = require_rcompare(); + var compareLoose = require_compare_loose(); + var compareBuild = require_compare_build(); + var sort = require_sort(); + var rsort = require_rsort(); + var gt = require_gt(); + var lt = require_lt(); + var eq = require_eq(); + var neq = require_neq(); + var gte = require_gte(); + var lte = require_lte(); + var cmp = require_cmp(); + var coerce = require_coerce(); + var Comparator = require_comparator(); + var Range = require_range(); + var satisfies = require_satisfies(); + var toComparators = require_to_comparators(); + var maxSatisfying = require_max_satisfying(); + var minSatisfying = require_min_satisfying(); + var minVersion = require_min_version(); + var validRange = require_valid2(); + var outside = require_outside(); + var gtr = require_gtr(); + var ltr = require_ltr(); + var intersects = require_intersects(); + var simplifyRange = require_simplify(); + var subset = require_subset(); + module.exports = { + parse: parse3, + valid, + clean, + inc, + diff, + major, + minor, + patch, + prerelease, + compare, + rcompare, + compareLoose, + compareBuild, + sort, + rsort, + gt, + lt, + eq, + neq, + gte, + lte, + cmp, + coerce, + Comparator, + Range, + satisfies, + toComparators, + maxSatisfying, + minSatisfying, + minVersion, + validRange, + outside, + gtr, + ltr, + intersects, + simplifyRange, + subset, + SemVer, + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + RELEASE_TYPES: constants.RELEASE_TYPES, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers + }; + } + }); + + // node_modules/ansi-styles/index.js + var require_ansi_styles = __commonJS({ + "node_modules/ansi-styles/index.js"(exports, module) { + "use strict"; + var ANSI_BACKGROUND_OFFSET = 10; + var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`; + var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`; + function assembleStyles() { + const codes = /* @__PURE__ */ new Map(); + const styles2 = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + overline: [53, 55], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + // Bright color + blackBright: [90, 39], + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + styles2.color.gray = styles2.color.blackBright; + styles2.bgColor.bgGray = styles2.bgColor.bgBlackBright; + styles2.color.grey = styles2.color.blackBright; + styles2.bgColor.bgGrey = styles2.bgColor.bgBlackBright; + for (const [groupName, group] of Object.entries(styles2)) { + for (const [styleName, style] of Object.entries(group)) { + styles2[styleName] = { + open: `\x1B[${style[0]}m`, + close: `\x1B[${style[1]}m` + }; + group[styleName] = styles2[styleName]; + codes.set(style[0], style[1]); + } + Object.defineProperty(styles2, groupName, { + value: group, + enumerable: false + }); + } + Object.defineProperty(styles2, "codes", { + value: codes, + enumerable: false + }); + styles2.color.close = "\x1B[39m"; + styles2.bgColor.close = "\x1B[49m"; + styles2.color.ansi256 = wrapAnsi256(); + styles2.color.ansi16m = wrapAnsi16m(); + styles2.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); + styles2.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); + Object.defineProperties(styles2, { + rgbToAnsi256: { + value: (red, green, blue) => { + if (red === green && green === blue) { + if (red < 8) { + return 16; + } + if (red > 248) { + return 231; + } + return Math.round((red - 8) / 247 * 24) + 232; + } + return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5); + }, + enumerable: false + }, + hexToRgb: { + value: (hex) => { + const matches = /(?[a-f\d]{6}|[a-f\d]{3})/i.exec(hex.toString(16)); + if (!matches) { + return [0, 0, 0]; + } + let { colorString } = matches.groups; + if (colorString.length === 3) { + colorString = colorString.split("").map((character) => character + character).join(""); + } + const integer = Number.parseInt(colorString, 16); + return [ + integer >> 16 & 255, + integer >> 8 & 255, + integer & 255 + ]; + }, + enumerable: false + }, + hexToAnsi256: { + value: (hex) => styles2.rgbToAnsi256(...styles2.hexToRgb(hex)), + enumerable: false + } + }); + return styles2; + } + Object.defineProperty(module, "exports", { + enumerable: true, + get: assembleStyles + }); + } + }); + + // node_modules/tslib/tslib.es6.mjs + var tslib_es6_exports = {}; + __export(tslib_es6_exports, { + __addDisposableResource: () => __addDisposableResource, + __assign: () => __assign, + __asyncDelegator: () => __asyncDelegator, + __asyncGenerator: () => __asyncGenerator, + __asyncValues: () => __asyncValues, + __await: () => __await, + __awaiter: () => __awaiter, + __classPrivateFieldGet: () => __classPrivateFieldGet, + __classPrivateFieldIn: () => __classPrivateFieldIn, + __classPrivateFieldSet: () => __classPrivateFieldSet, + __createBinding: () => __createBinding, + __decorate: () => __decorate, + __disposeResources: () => __disposeResources, + __esDecorate: () => __esDecorate, + __exportStar: () => __exportStar, + __extends: () => __extends, + __generator: () => __generator, + __importDefault: () => __importDefault, + __importStar: () => __importStar, + __makeTemplateObject: () => __makeTemplateObject, + __metadata: () => __metadata, + __param: () => __param, + __propKey: () => __propKey, + __read: () => __read, + __rest: () => __rest, + __rewriteRelativeImportExtension: () => __rewriteRelativeImportExtension, + __runInitializers: () => __runInitializers, + __setFunctionName: () => __setFunctionName, + __spread: () => __spread, + __spreadArray: () => __spreadArray, + __spreadArrays: () => __spreadArrays, + __values: () => __values, + default: () => tslib_es6_default + }); + function __extends(d3, b3) { + if (typeof b3 !== "function" && b3 !== null) + throw new TypeError("Class extends value " + String(b3) + " is not a constructor or null"); + extendStatics(d3, b3); + function __() { + this.constructor = d3; + } + d3.prototype = b3 === null ? Object.create(b3) : (__.prototype = b3.prototype, new __()); + } + function __rest(s2, e2) { + var t2 = {}; + for (var p2 in s2) if (Object.prototype.hasOwnProperty.call(s2, p2) && e2.indexOf(p2) < 0) + t2[p2] = s2[p2]; + if (s2 != null && typeof Object.getOwnPropertySymbols === "function") + for (var i2 = 0, p2 = Object.getOwnPropertySymbols(s2); i2 < p2.length; i2++) { + if (e2.indexOf(p2[i2]) < 0 && Object.prototype.propertyIsEnumerable.call(s2, p2[i2])) + t2[p2[i2]] = s2[p2[i2]]; + } + return t2; + } + function __decorate(decorators, target, key, desc) { + var c3 = arguments.length, r2 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d3; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r2 = Reflect.decorate(decorators, target, key, desc); + else for (var i2 = decorators.length - 1; i2 >= 0; i2--) if (d3 = decorators[i2]) r2 = (c3 < 3 ? d3(r2) : c3 > 3 ? d3(target, key, r2) : d3(target, key)) || r2; + return c3 > 3 && r2 && Object.defineProperty(target, key, r2), r2; + } + function __param(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + } + function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f3) { + if (f3 !== void 0 && typeof f3 !== "function") throw new TypeError("Function expected"); + return f3; + } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _2, done = false; + for (var i2 = decorators.length - 1; i2 >= 0; i2--) { + var context = {}; + for (var p2 in contextIn) context[p2] = p2 === "access" ? {} : contextIn[p2]; + for (var p2 in contextIn.access) context.access[p2] = contextIn.access[p2]; + context.addInitializer = function(f3) { + if (done) throw new TypeError("Cannot add initializers after decoration has completed"); + extraInitializers.push(accept(f3 || null)); + }; + var result = (0, decorators[i2])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_2 = accept(result.get)) descriptor.get = _2; + if (_2 = accept(result.set)) descriptor.set = _2; + if (_2 = accept(result.init)) initializers.unshift(_2); + } else if (_2 = accept(result)) { + if (kind === "field") initializers.unshift(_2); + else descriptor[key] = _2; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; + } + function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i2 = 0; i2 < initializers.length; i2++) { + value = useValue ? initializers[i2].call(thisArg, value) : initializers[i2].call(thisArg); + } + return useValue ? value : void 0; + } + function __propKey(x3) { + return typeof x3 === "symbol" ? x3 : "".concat(x3); + } + function __setFunctionName(f3, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f3, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); + } + function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + } + function __awaiter(thisArg, _arguments, P2, generator) { + function adopt(value) { + return value instanceof P2 ? value : new P2(function(resolve) { + resolve(value); + }); + } + return new (P2 || (P2 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e2) { + reject(e2); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e2) { + reject(e2); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + } + function __generator(thisArg, body) { + var _2 = { label: 0, sent: function() { + if (t2[0] & 1) throw t2[1]; + return t2[1]; + }, trys: [], ops: [] }, f3, y3, t2, g2 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g2.next = verb(0), g2["throw"] = verb(1), g2["return"] = verb(2), typeof Symbol === "function" && (g2[Symbol.iterator] = function() { + return this; + }), g2; + function verb(n2) { + return function(v6) { + return step([n2, v6]); + }; + } + function step(op) { + if (f3) throw new TypeError("Generator is already executing."); + while (g2 && (g2 = 0, op[0] && (_2 = 0)), _2) try { + if (f3 = 1, y3 && (t2 = op[0] & 2 ? y3["return"] : op[0] ? y3["throw"] || ((t2 = y3["return"]) && t2.call(y3), 0) : y3.next) && !(t2 = t2.call(y3, op[1])).done) return t2; + if (y3 = 0, t2) op = [op[0] & 2, t2.value]; + switch (op[0]) { + case 0: + case 1: + t2 = op; + break; + case 4: + _2.label++; + return { value: op[1], done: false }; + case 5: + _2.label++; + y3 = op[1]; + op = [0]; + continue; + case 7: + op = _2.ops.pop(); + _2.trys.pop(); + continue; + default: + if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _2 = 0; + continue; + } + if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) { + _2.label = op[1]; + break; + } + if (op[0] === 6 && _2.label < t2[1]) { + _2.label = t2[1]; + t2 = op; + break; + } + if (t2 && _2.label < t2[2]) { + _2.label = t2[2]; + _2.ops.push(op); + break; + } + if (t2[2]) _2.ops.pop(); + _2.trys.pop(); + continue; + } + op = body.call(thisArg, _2); + } catch (e2) { + op = [6, e2]; + y3 = 0; + } finally { + f3 = t2 = 0; + } + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; + } + } + function __exportStar(m3, o2) { + for (var p2 in m3) if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(o2, p2)) __createBinding(o2, m3, p2); + } + function __values(o2) { + var s2 = typeof Symbol === "function" && Symbol.iterator, m3 = s2 && o2[s2], i2 = 0; + if (m3) return m3.call(o2); + if (o2 && typeof o2.length === "number") return { + next: function() { + if (o2 && i2 >= o2.length) o2 = void 0; + return { value: o2 && o2[i2++], done: !o2 }; + } + }; + throw new TypeError(s2 ? "Object is not iterable." : "Symbol.iterator is not defined."); + } + function __read(o2, n2) { + var m3 = typeof Symbol === "function" && o2[Symbol.iterator]; + if (!m3) return o2; + var i2 = m3.call(o2), r2, ar = [], e2; + try { + while ((n2 === void 0 || n2-- > 0) && !(r2 = i2.next()).done) ar.push(r2.value); + } catch (error) { + e2 = { error }; + } finally { + try { + if (r2 && !r2.done && (m3 = i2["return"])) m3.call(i2); + } finally { + if (e2) throw e2.error; + } + } + return ar; + } + function __spread() { + for (var ar = [], i2 = 0; i2 < arguments.length; i2++) + ar = ar.concat(__read(arguments[i2])); + return ar; + } + function __spreadArrays() { + for (var s2 = 0, i2 = 0, il = arguments.length; i2 < il; i2++) s2 += arguments[i2].length; + for (var r2 = Array(s2), k3 = 0, i2 = 0; i2 < il; i2++) + for (var a2 = arguments[i2], j3 = 0, jl = a2.length; j3 < jl; j3++, k3++) + r2[k3] = a2[j3]; + return r2; + } + function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i2 = 0, l2 = from.length, ar; i2 < l2; i2++) { + if (ar || !(i2 in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i2); + ar[i2] = from[i2]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + } + function __await(v6) { + return this instanceof __await ? (this.v = v6, this) : new __await(v6); + } + function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g2 = generator.apply(thisArg, _arguments || []), i2, q3 = []; + return i2 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i2[Symbol.asyncIterator] = function() { + return this; + }, i2; + function awaitReturn(f3) { + return function(v6) { + return Promise.resolve(v6).then(f3, reject); + }; + } + function verb(n2, f3) { + if (g2[n2]) { + i2[n2] = function(v6) { + return new Promise(function(a2, b3) { + q3.push([n2, v6, a2, b3]) > 1 || resume(n2, v6); + }); + }; + if (f3) i2[n2] = f3(i2[n2]); + } + } + function resume(n2, v6) { + try { + step(g2[n2](v6)); + } catch (e2) { + settle(q3[0][3], e2); + } + } + function step(r2) { + r2.value instanceof __await ? Promise.resolve(r2.value.v).then(fulfill, reject) : settle(q3[0][2], r2); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f3, v6) { + if (f3(v6), q3.shift(), q3.length) resume(q3[0][0], q3[0][1]); + } + } + function __asyncDelegator(o2) { + var i2, p2; + return i2 = {}, verb("next"), verb("throw", function(e2) { + throw e2; + }), verb("return"), i2[Symbol.iterator] = function() { + return this; + }, i2; + function verb(n2, f3) { + i2[n2] = o2[n2] ? function(v6) { + return (p2 = !p2) ? { value: __await(o2[n2](v6)), done: false } : f3 ? f3(v6) : v6; + } : f3; + } + } + function __asyncValues(o2) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m3 = o2[Symbol.asyncIterator], i2; + return m3 ? m3.call(o2) : (o2 = typeof __values === "function" ? __values(o2) : o2[Symbol.iterator](), i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() { + return this; + }, i2); + function verb(n2) { + i2[n2] = o2[n2] && function(v6) { + return new Promise(function(resolve, reject) { + v6 = o2[n2](v6), settle(resolve, reject, v6.done, v6.value); + }); + }; + } + function settle(resolve, reject, d3, v6) { + Promise.resolve(v6).then(function(v7) { + resolve({ value: v7, done: d3 }); + }, reject); + } + } + function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { value: raw }); + } else { + cooked.raw = raw; + } + return cooked; + } + function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k3 = ownKeys(mod), i2 = 0; i2 < k3.length; i2++) if (k3[i2] !== "default") __createBinding(result, mod, k3[i2]); + } + __setModuleDefault(result, mod); + return result; + } + function __importDefault(mod) { + return mod && mod.__esModule ? mod : { default: mod }; + } + function __classPrivateFieldGet(receiver, state, kind, f3) { + if (kind === "a" && !f3) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f3 : kind === "a" ? f3.call(receiver) : f3 ? f3.value : state.get(receiver); + } + function __classPrivateFieldSet(receiver, state, value, kind, f3) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f3) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f3 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f3.call(receiver, value) : f3 ? f3.value = value : state.set(receiver, value), value; + } + function __classPrivateFieldIn(state, receiver) { + if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); + } + function __addDisposableResource(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { + try { + inner.call(this); + } catch (e2) { + return Promise.reject(e2); + } + }; + env.stack.push({ value, dispose, async }); + } else if (async) { + env.stack.push({ async: true }); + } + return value; + } + function __disposeResources(env) { + function fail(e2) { + env.error = env.hasError ? new _SuppressedError(e2, env.error, "An error was suppressed during disposal.") : e2; + env.hasError = true; + } + var r2, s2 = 0; + function next() { + while (r2 = env.stack.pop()) { + try { + if (!r2.async && s2 === 1) return s2 = 0, env.stack.push(r2), Promise.resolve().then(next); + if (r2.dispose) { + var result = r2.dispose.call(r2.value); + if (r2.async) return s2 |= 2, Promise.resolve(result).then(next, function(e2) { + fail(e2); + return next(); + }); + } else s2 |= 1; + } catch (e2) { + fail(e2); + } + } + if (s2 === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); + } + function __rewriteRelativeImportExtension(path, preserveJsx) { + if (typeof path === "string" && /^\.\.?\//.test(path)) { + return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m3, tsx, d3, ext, cm) { + return tsx ? preserveJsx ? ".jsx" : ".js" : d3 && (!ext || !cm) ? m3 : d3 + ext + "." + cm.toLowerCase() + "js"; + }); + } + return path; + } + var extendStatics, __assign, __createBinding, __setModuleDefault, ownKeys, _SuppressedError, tslib_es6_default; + var init_tslib_es6 = __esm({ + "node_modules/tslib/tslib.es6.mjs"() { + extendStatics = function(d3, b3) { + extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d4, b4) { + d4.__proto__ = b4; + } || function(d4, b4) { + for (var p2 in b4) if (Object.prototype.hasOwnProperty.call(b4, p2)) d4[p2] = b4[p2]; + }; + return extendStatics(d3, b3); + }; + __assign = function() { + __assign = Object.assign || function __assign3(t2) { + for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) { + s2 = arguments[i2]; + for (var p2 in s2) if (Object.prototype.hasOwnProperty.call(s2, p2)) t2[p2] = s2[p2]; + } + return t2; + }; + return __assign.apply(this, arguments); + }; + __createBinding = Object.create ? (function(o2, m3, k3, k22) { + if (k22 === void 0) k22 = k3; + var desc = Object.getOwnPropertyDescriptor(m3, k3); + if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m3[k3]; + } }; + } + Object.defineProperty(o2, k22, desc); + }) : (function(o2, m3, k3, k22) { + if (k22 === void 0) k22 = k3; + o2[k22] = m3[k3]; + }); + __setModuleDefault = Object.create ? (function(o2, v6) { + Object.defineProperty(o2, "default", { enumerable: true, value: v6 }); + }) : function(o2, v6) { + o2["default"] = v6; + }; + ownKeys = function(o2) { + ownKeys = Object.getOwnPropertyNames || function(o3) { + var ar = []; + for (var k3 in o3) if (Object.prototype.hasOwnProperty.call(o3, k3)) ar[ar.length] = k3; + return ar; + }; + return ownKeys(o2); + }; + _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) { + var e2 = new Error(message); + return e2.name = "SuppressedError", e2.error = error, e2.suppressed = suppressed, e2; + }; + tslib_es6_default = { + __extends, + __assign, + __rest, + __decorate, + __param, + __esDecorate, + __runInitializers, + __propKey, + __setFunctionName, + __metadata, + __awaiter, + __generator, + __createBinding, + __exportStar, + __values, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __addDisposableResource, + __disposeResources, + __rewriteRelativeImportExtension + }; + } + }); + + // node_modules/@supabase/functions-js/dist/main/helper.js + var require_helper = __commonJS({ + "node_modules/@supabase/functions-js/dist/main/helper.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolveFetch = void 0; + var resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); + }; + exports.resolveFetch = resolveFetch; + } + }); + + // node_modules/@supabase/functions-js/dist/main/types.js + var require_types = __commonJS({ + "node_modules/@supabase/functions-js/dist/main/types.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FunctionRegion = exports.FunctionsHttpError = exports.FunctionsRelayError = exports.FunctionsFetchError = exports.FunctionsError = void 0; + var FunctionsError2 = class extends Error { + constructor(message, name = "FunctionsError", context) { + super(message); + this.name = name; + this.context = context; + } + }; + exports.FunctionsError = FunctionsError2; + var FunctionsFetchError2 = class extends FunctionsError2 { + constructor(context) { + super("Failed to send a request to the Edge Function", "FunctionsFetchError", context); + } + }; + exports.FunctionsFetchError = FunctionsFetchError2; + var FunctionsRelayError2 = class extends FunctionsError2 { + constructor(context) { + super("Relay Error invoking the Edge Function", "FunctionsRelayError", context); + } + }; + exports.FunctionsRelayError = FunctionsRelayError2; + var FunctionsHttpError2 = class extends FunctionsError2 { + constructor(context) { + super("Edge Function returned a non-2xx status code", "FunctionsHttpError", context); + } + }; + exports.FunctionsHttpError = FunctionsHttpError2; + var FunctionRegion2; + (function(FunctionRegion3) { + FunctionRegion3["Any"] = "any"; + FunctionRegion3["ApNortheast1"] = "ap-northeast-1"; + FunctionRegion3["ApNortheast2"] = "ap-northeast-2"; + FunctionRegion3["ApSouth1"] = "ap-south-1"; + FunctionRegion3["ApSoutheast1"] = "ap-southeast-1"; + FunctionRegion3["ApSoutheast2"] = "ap-southeast-2"; + FunctionRegion3["CaCentral1"] = "ca-central-1"; + FunctionRegion3["EuCentral1"] = "eu-central-1"; + FunctionRegion3["EuWest1"] = "eu-west-1"; + FunctionRegion3["EuWest2"] = "eu-west-2"; + FunctionRegion3["EuWest3"] = "eu-west-3"; + FunctionRegion3["SaEast1"] = "sa-east-1"; + FunctionRegion3["UsEast1"] = "us-east-1"; + FunctionRegion3["UsWest1"] = "us-west-1"; + FunctionRegion3["UsWest2"] = "us-west-2"; + })(FunctionRegion2 || (exports.FunctionRegion = FunctionRegion2 = {})); + } + }); + + // node_modules/@supabase/functions-js/dist/main/FunctionsClient.js + var require_FunctionsClient = __commonJS({ + "node_modules/@supabase/functions-js/dist/main/FunctionsClient.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FunctionsClient = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var helper_1 = require_helper(); + var types_1 = require_types(); + var FunctionsClient = class { + /** + * Creates a new Functions client bound to an Edge Functions URL. + * + * @example + * ```ts + * import { FunctionsClient, FunctionRegion } from '@supabase/functions-js' + * + * const functions = new FunctionsClient('https://xyzcompany.supabase.co/functions/v1', { + * headers: { apikey: 'public-anon-key' }, + * region: FunctionRegion.UsEast1, + * }) + * ``` + */ + constructor(url, { headers = {}, customFetch, region: region2 = types_1.FunctionRegion.Any } = {}) { + this.url = url; + this.headers = headers; + this.region = region2; + this.fetch = (0, helper_1.resolveFetch)(customFetch); + } + /** + * Updates the authorization header + * @param token - the new jwt token sent in the authorisation header + * @example + * ```ts + * functions.setAuth(session.access_token) + * ``` + */ + setAuth(token) { + this.headers.Authorization = `Bearer ${token}`; + } + /** + * Invokes a function + * @param functionName - The name of the Function to invoke. + * @param options - Options for invoking the Function. + * @example + * ```ts + * const { data, error } = await functions.invoke('hello-world', { + * body: { name: 'Ada' }, + * }) + * ``` + */ + invoke(functionName_1) { + return tslib_1.__awaiter(this, arguments, void 0, function* (functionName, options = {}) { + var _a; + let timeoutId; + let timeoutController; + try { + const { headers, method, body: functionArgs, signal, timeout } = options; + let _headers = {}; + let { region: region2 } = options; + if (!region2) { + region2 = this.region; + } + const url = new URL(`${this.url}/${functionName}`); + if (region2 && region2 !== "any") { + _headers["x-region"] = region2; + url.searchParams.set("forceFunctionRegion", region2); + } + let body; + if (functionArgs && (headers && !Object.prototype.hasOwnProperty.call(headers, "Content-Type") || !headers)) { + if (typeof Blob !== "undefined" && functionArgs instanceof Blob || functionArgs instanceof ArrayBuffer) { + _headers["Content-Type"] = "application/octet-stream"; + body = functionArgs; + } else if (typeof functionArgs === "string") { + _headers["Content-Type"] = "text/plain"; + body = functionArgs; + } else if (typeof FormData !== "undefined" && functionArgs instanceof FormData) { + body = functionArgs; + } else { + _headers["Content-Type"] = "application/json"; + body = JSON.stringify(functionArgs); + } + } else { + body = functionArgs; + } + let effectiveSignal = signal; + if (timeout) { + timeoutController = new AbortController(); + timeoutId = setTimeout(() => timeoutController.abort(), timeout); + if (signal) { + effectiveSignal = timeoutController.signal; + signal.addEventListener("abort", () => timeoutController.abort()); + } else { + effectiveSignal = timeoutController.signal; + } + } + const response = yield this.fetch(url.toString(), { + method: method || "POST", + // headers priority is (high to low): + // 1. invoke-level headers + // 2. client-level headers + // 3. default Content-Type header + headers: Object.assign(Object.assign(Object.assign({}, _headers), this.headers), headers), + body, + signal: effectiveSignal + }).catch((fetchError) => { + throw new types_1.FunctionsFetchError(fetchError); + }); + const isRelayError = response.headers.get("x-relay-error"); + if (isRelayError && isRelayError === "true") { + throw new types_1.FunctionsRelayError(response); + } + if (!response.ok) { + throw new types_1.FunctionsHttpError(response); + } + let responseType = ((_a = response.headers.get("Content-Type")) !== null && _a !== void 0 ? _a : "text/plain").split(";")[0].trim(); + let data; + if (responseType === "application/json") { + data = yield response.json(); + } else if (responseType === "application/octet-stream" || responseType === "application/pdf") { + data = yield response.blob(); + } else if (responseType === "text/event-stream") { + data = response; + } else if (responseType === "multipart/form-data") { + data = yield response.formData(); + } else { + data = yield response.text(); + } + return { data, error: null, response }; + } catch (error) { + return { + data: null, + error, + response: error instanceof types_1.FunctionsHttpError || error instanceof types_1.FunctionsRelayError ? error.context : void 0 + }; + } finally { + if (timeoutId) { + clearTimeout(timeoutId); + } + } + }); + } + }; + exports.FunctionsClient = FunctionsClient; + } + }); + + // node_modules/@supabase/functions-js/dist/main/index.js + var require_main = __commonJS({ + "node_modules/@supabase/functions-js/dist/main/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FunctionRegion = exports.FunctionsRelayError = exports.FunctionsHttpError = exports.FunctionsFetchError = exports.FunctionsError = exports.FunctionsClient = void 0; + var FunctionsClient_1 = require_FunctionsClient(); + Object.defineProperty(exports, "FunctionsClient", { enumerable: true, get: function() { + return FunctionsClient_1.FunctionsClient; + } }); + var types_1 = require_types(); + Object.defineProperty(exports, "FunctionsError", { enumerable: true, get: function() { + return types_1.FunctionsError; + } }); + Object.defineProperty(exports, "FunctionsFetchError", { enumerable: true, get: function() { + return types_1.FunctionsFetchError; + } }); + Object.defineProperty(exports, "FunctionsHttpError", { enumerable: true, get: function() { + return types_1.FunctionsHttpError; + } }); + Object.defineProperty(exports, "FunctionsRelayError", { enumerable: true, get: function() { + return types_1.FunctionsRelayError; + } }); + Object.defineProperty(exports, "FunctionRegion", { enumerable: true, get: function() { + return types_1.FunctionRegion; + } }); + } + }); + + // node_modules/@supabase/postgrest-js/dist/cjs/PostgrestError.js + var require_PostgrestError = __commonJS({ + "node_modules/@supabase/postgrest-js/dist/cjs/PostgrestError.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var PostgrestError2 = class extends Error { + /** + * @example + * ```ts + * import PostgrestError from '@supabase/postgrest-js' + * + * throw new PostgrestError({ + * message: 'Row level security prevented the request', + * details: 'RLS denied the insert', + * hint: 'Check your policies', + * code: 'PGRST301', + * }) + * ``` + */ + constructor(context) { + super(context.message); + this.name = "PostgrestError"; + this.details = context.details; + this.hint = context.hint; + this.code = context.code; + } + }; + exports.default = PostgrestError2; + } + }); + + // node_modules/@supabase/postgrest-js/dist/cjs/PostgrestBuilder.js + var require_PostgrestBuilder = __commonJS({ + "node_modules/@supabase/postgrest-js/dist/cjs/PostgrestBuilder.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var PostgrestError_1 = tslib_1.__importDefault(require_PostgrestError()); + var PostgrestBuilder = class { + /** + * Creates a builder configured for a specific PostgREST request. + * + * @example + * ```ts + * import PostgrestQueryBuilder from '@supabase/postgrest-js' + * + * const builder = new PostgrestQueryBuilder( + * new URL('https://xyzcompany.supabase.co/rest/v1/users'), + * { headers: new Headers({ apikey: 'public-anon-key' }) } + * ) + * ``` + */ + constructor(builder) { + var _a, _b; + this.shouldThrowOnError = false; + this.method = builder.method; + this.url = builder.url; + this.headers = new Headers(builder.headers); + this.schema = builder.schema; + this.body = builder.body; + this.shouldThrowOnError = (_a = builder.shouldThrowOnError) !== null && _a !== void 0 ? _a : false; + this.signal = builder.signal; + this.isMaybeSingle = (_b = builder.isMaybeSingle) !== null && _b !== void 0 ? _b : false; + if (builder.fetch) { + this.fetch = builder.fetch; + } else { + this.fetch = fetch; + } + } + /** + * If there's an error with the query, throwOnError will reject the promise by + * throwing the error instead of returning it as part of a successful response. + * + * {@link https://github.com/supabase/supabase-js/issues/92} + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + /** + * Set an HTTP header for the request. + */ + setHeader(name, value) { + this.headers = new Headers(this.headers); + this.headers.set(name, value); + return this; + } + then(onfulfilled, onrejected) { + if (this.schema === void 0) { + } else if (["GET", "HEAD"].includes(this.method)) { + this.headers.set("Accept-Profile", this.schema); + } else { + this.headers.set("Content-Profile", this.schema); + } + if (this.method !== "GET" && this.method !== "HEAD") { + this.headers.set("Content-Type", "application/json"); + } + const _fetch = this.fetch; + let res = _fetch(this.url.toString(), { + method: this.method, + headers: this.headers, + body: JSON.stringify(this.body), + signal: this.signal + }).then(async (res2) => { + var _a, _b, _c, _d; + let error = null; + let data = null; + let count3 = null; + let status = res2.status; + let statusText = res2.statusText; + if (res2.ok) { + if (this.method !== "HEAD") { + const body = await res2.text(); + if (body === "") { + } else if (this.headers.get("Accept") === "text/csv") { + data = body; + } else if (this.headers.get("Accept") && ((_a = this.headers.get("Accept")) === null || _a === void 0 ? void 0 : _a.includes("application/vnd.pgrst.plan+text"))) { + data = body; + } else { + data = JSON.parse(body); + } + } + const countHeader = (_b = this.headers.get("Prefer")) === null || _b === void 0 ? void 0 : _b.match(/count=(exact|planned|estimated)/); + const contentRange = (_c = res2.headers.get("content-range")) === null || _c === void 0 ? void 0 : _c.split("/"); + if (countHeader && contentRange && contentRange.length > 1) { + count3 = parseInt(contentRange[1]); + } + if (this.isMaybeSingle && this.method === "GET" && Array.isArray(data)) { + if (data.length > 1) { + error = { + // https://github.com/PostgREST/postgrest/blob/a867d79c42419af16c18c3fb019eba8df992626f/src/PostgREST/Error.hs#L553 + code: "PGRST116", + details: `Results contain ${data.length} rows, application/vnd.pgrst.object+json requires 1 row`, + hint: null, + message: "JSON object requested, multiple (or no) rows returned" + }; + data = null; + count3 = null; + status = 406; + statusText = "Not Acceptable"; + } else if (data.length === 1) { + data = data[0]; + } else { + data = null; + } + } + } else { + const body = await res2.text(); + try { + error = JSON.parse(body); + if (Array.isArray(error) && res2.status === 404) { + data = []; + error = null; + status = 200; + statusText = "OK"; + } + } catch (_e2) { + if (res2.status === 404 && body === "") { + status = 204; + statusText = "No Content"; + } else { + error = { + message: body + }; + } + } + if (error && this.isMaybeSingle && ((_d = error === null || error === void 0 ? void 0 : error.details) === null || _d === void 0 ? void 0 : _d.includes("0 rows"))) { + error = null; + status = 200; + statusText = "OK"; + } + if (error && this.shouldThrowOnError) { + throw new PostgrestError_1.default(error); + } + } + const postgrestResponse = { + error, + data, + count: count3, + status, + statusText + }; + return postgrestResponse; + }); + if (!this.shouldThrowOnError) { + res = res.catch((fetchError) => { + var _a, _b, _c, _d, _e2, _f; + let errorDetails = ""; + const cause = fetchError === null || fetchError === void 0 ? void 0 : fetchError.cause; + if (cause) { + const causeMessage = (_a = cause === null || cause === void 0 ? void 0 : cause.message) !== null && _a !== void 0 ? _a : ""; + const causeCode = (_b = cause === null || cause === void 0 ? void 0 : cause.code) !== null && _b !== void 0 ? _b : ""; + errorDetails = `${(_c = fetchError === null || fetchError === void 0 ? void 0 : fetchError.name) !== null && _c !== void 0 ? _c : "FetchError"}: ${fetchError === null || fetchError === void 0 ? void 0 : fetchError.message}`; + errorDetails += ` + +Caused by: ${(_d = cause === null || cause === void 0 ? void 0 : cause.name) !== null && _d !== void 0 ? _d : "Error"}: ${causeMessage}`; + if (causeCode) { + errorDetails += ` (${causeCode})`; + } + if (cause === null || cause === void 0 ? void 0 : cause.stack) { + errorDetails += ` +${cause.stack}`; + } + } else { + errorDetails = (_e2 = fetchError === null || fetchError === void 0 ? void 0 : fetchError.stack) !== null && _e2 !== void 0 ? _e2 : ""; + } + return { + error: { + message: `${(_f = fetchError === null || fetchError === void 0 ? void 0 : fetchError.name) !== null && _f !== void 0 ? _f : "FetchError"}: ${fetchError === null || fetchError === void 0 ? void 0 : fetchError.message}`, + details: errorDetails, + hint: "", + code: "" + }, + data: null, + count: null, + status: 0, + statusText: "" + }; + }); + } + return res.then(onfulfilled, onrejected); + } + /** + * Override the type of the returned `data`. + * + * @typeParam NewResult - The new result type to override with + * @deprecated Use overrideTypes() method at the end of your call chain instead + */ + returns() { + return this; + } + /** + * Override the type of the returned `data` field in the response. + * + * @typeParam NewResult - The new type to cast the response data to + * @typeParam Options - Optional type configuration (defaults to { merge: true }) + * @typeParam Options.merge - When true, merges the new type with existing return type. When false, replaces the existing types entirely (defaults to true) + * @example + * ```typescript + * // Merge with existing types (default behavior) + * const query = supabase + * .from('users') + * .select() + * .overrideTypes<{ custom_field: string }>() + * + * // Replace existing types completely + * const replaceQuery = supabase + * .from('users') + * .select() + * .overrideTypes<{ id: number; name: string }, { merge: false }>() + * ``` + * @returns A PostgrestBuilder instance with the new type + */ + overrideTypes() { + return this; + } + }; + exports.default = PostgrestBuilder; + } + }); + + // node_modules/@supabase/postgrest-js/dist/cjs/PostgrestTransformBuilder.js + var require_PostgrestTransformBuilder = __commonJS({ + "node_modules/@supabase/postgrest-js/dist/cjs/PostgrestTransformBuilder.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var PostgrestBuilder_1 = tslib_1.__importDefault(require_PostgrestBuilder()); + var PostgrestTransformBuilder = class extends PostgrestBuilder_1.default { + /** + * Perform a SELECT on the query result. + * + * By default, `.insert()`, `.update()`, `.upsert()`, and `.delete()` do not + * return modified rows. By calling this method, modified rows are returned in + * `data`. + * + * @param columns - The columns to retrieve, separated by commas + */ + select(columns) { + let quoted = false; + const cleanedColumns = (columns !== null && columns !== void 0 ? columns : "*").split("").map((c3) => { + if (/\s/.test(c3) && !quoted) { + return ""; + } + if (c3 === '"') { + quoted = !quoted; + } + return c3; + }).join(""); + this.url.searchParams.set("select", cleanedColumns); + this.headers.append("Prefer", "return=representation"); + return this; + } + /** + * Order the query result by `column`. + * + * You can call this method multiple times to order by multiple columns. + * + * You can order referenced tables, but it only affects the ordering of the + * parent table if you use `!inner` in the query. + * + * @param column - The column to order by + * @param options - Named parameters + * @param options.ascending - If `true`, the result will be in ascending order + * @param options.nullsFirst - If `true`, `null`s appear first. If `false`, + * `null`s appear last. + * @param options.referencedTable - Set this to order a referenced table by + * its columns + * @param options.foreignTable - Deprecated, use `options.referencedTable` + * instead + */ + order(column, { ascending = true, nullsFirst, foreignTable, referencedTable = foreignTable } = {}) { + const key = referencedTable ? `${referencedTable}.order` : "order"; + const existingOrder = this.url.searchParams.get(key); + this.url.searchParams.set(key, `${existingOrder ? `${existingOrder},` : ""}${column}.${ascending ? "asc" : "desc"}${nullsFirst === void 0 ? "" : nullsFirst ? ".nullsfirst" : ".nullslast"}`); + return this; + } + /** + * Limit the query result by `count`. + * + * @param count - The maximum number of rows to return + * @param options - Named parameters + * @param options.referencedTable - Set this to limit rows of referenced + * tables instead of the parent table + * @param options.foreignTable - Deprecated, use `options.referencedTable` + * instead + */ + limit(count3, { foreignTable, referencedTable = foreignTable } = {}) { + const key = typeof referencedTable === "undefined" ? "limit" : `${referencedTable}.limit`; + this.url.searchParams.set(key, `${count3}`); + return this; + } + /** + * Limit the query result by starting at an offset `from` and ending at the offset `to`. + * Only records within this range are returned. + * This respects the query order and if there is no order clause the range could behave unexpectedly. + * The `from` and `to` values are 0-based and inclusive: `range(1, 3)` will include the second, third + * and fourth rows of the query. + * + * @param from - The starting index from which to limit the result + * @param to - The last index to which to limit the result + * @param options - Named parameters + * @param options.referencedTable - Set this to limit rows of referenced + * tables instead of the parent table + * @param options.foreignTable - Deprecated, use `options.referencedTable` + * instead + */ + range(from, to, { foreignTable, referencedTable = foreignTable } = {}) { + const keyOffset = typeof referencedTable === "undefined" ? "offset" : `${referencedTable}.offset`; + const keyLimit = typeof referencedTable === "undefined" ? "limit" : `${referencedTable}.limit`; + this.url.searchParams.set(keyOffset, `${from}`); + this.url.searchParams.set(keyLimit, `${to - from + 1}`); + return this; + } + /** + * Set the AbortSignal for the fetch request. + * + * @param signal - The AbortSignal to use for the fetch request + */ + abortSignal(signal) { + this.signal = signal; + return this; + } + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be one row (e.g. using `.limit(1)`), otherwise this + * returns an error. + */ + single() { + this.headers.set("Accept", "application/vnd.pgrst.object+json"); + return this; + } + /** + * Return `data` as a single object instead of an array of objects. + * + * Query result must be zero or one row (e.g. using `.limit(1)`), otherwise + * this returns an error. + */ + maybeSingle() { + if (this.method === "GET") { + this.headers.set("Accept", "application/json"); + } else { + this.headers.set("Accept", "application/vnd.pgrst.object+json"); + } + this.isMaybeSingle = true; + return this; + } + /** + * Return `data` as a string in CSV format. + */ + csv() { + this.headers.set("Accept", "text/csv"); + return this; + } + /** + * Return `data` as an object in [GeoJSON](https://geojson.org) format. + */ + geojson() { + this.headers.set("Accept", "application/geo+json"); + return this; + } + /** + * Return `data` as the EXPLAIN plan for the query. + * + * You need to enable the + * [db_plan_enabled](https://supabase.com/docs/guides/database/debugging-performance#enabling-explain) + * setting before using this method. + * + * @param options - Named parameters + * + * @param options.analyze - If `true`, the query will be executed and the + * actual run time will be returned + * + * @param options.verbose - If `true`, the query identifier will be returned + * and `data` will include the output columns of the query + * + * @param options.settings - If `true`, include information on configuration + * parameters that affect query planning + * + * @param options.buffers - If `true`, include information on buffer usage + * + * @param options.wal - If `true`, include information on WAL record generation + * + * @param options.format - The format of the output, can be `"text"` (default) + * or `"json"` + */ + explain({ analyze = false, verbose = false, settings = false, buffers = false, wal = false, format: format2 = "text" } = {}) { + var _a; + const options = [ + analyze ? "analyze" : null, + verbose ? "verbose" : null, + settings ? "settings" : null, + buffers ? "buffers" : null, + wal ? "wal" : null + ].filter(Boolean).join("|"); + const forMediatype = (_a = this.headers.get("Accept")) !== null && _a !== void 0 ? _a : "application/json"; + this.headers.set("Accept", `application/vnd.pgrst.plan+${format2}; for="${forMediatype}"; options=${options};`); + if (format2 === "json") { + return this; + } else { + return this; + } + } + /** + * Rollback the query. + * + * `data` will still be returned, but the query is not committed. + */ + rollback() { + this.headers.append("Prefer", "tx=rollback"); + return this; + } + /** + * Override the type of the returned `data`. + * + * @typeParam NewResult - The new result type to override with + * @deprecated Use overrideTypes() method at the end of your call chain instead + */ + returns() { + return this; + } + /** + * Set the maximum number of rows that can be affected by the query. + * Only available in PostgREST v13+ and only works with PATCH and DELETE methods. + * + * @param value - The maximum number of rows that can be affected + */ + maxAffected(value) { + this.headers.append("Prefer", "handling=strict"); + this.headers.append("Prefer", `max-affected=${value}`); + return this; + } + }; + exports.default = PostgrestTransformBuilder; + } + }); + + // node_modules/@supabase/postgrest-js/dist/cjs/PostgrestFilterBuilder.js + var require_PostgrestFilterBuilder = __commonJS({ + "node_modules/@supabase/postgrest-js/dist/cjs/PostgrestFilterBuilder.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var PostgrestTransformBuilder_1 = tslib_1.__importDefault(require_PostgrestTransformBuilder()); + var PostgrestReservedCharsRegexp = new RegExp("[,()]"); + var PostgrestFilterBuilder = class extends PostgrestTransformBuilder_1.default { + /** + * Match only rows where `column` is equal to `value`. + * + * To check if the value of `column` is NULL, you should use `.is()` instead. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + eq(column, value) { + this.url.searchParams.append(column, `eq.${value}`); + return this; + } + /** + * Match only rows where `column` is not equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + neq(column, value) { + this.url.searchParams.append(column, `neq.${value}`); + return this; + } + /** + * Match only rows where `column` is greater than `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + gt(column, value) { + this.url.searchParams.append(column, `gt.${value}`); + return this; + } + /** + * Match only rows where `column` is greater than or equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + gte(column, value) { + this.url.searchParams.append(column, `gte.${value}`); + return this; + } + /** + * Match only rows where `column` is less than `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + lt(column, value) { + this.url.searchParams.append(column, `lt.${value}`); + return this; + } + /** + * Match only rows where `column` is less than or equal to `value`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + lte(column, value) { + this.url.searchParams.append(column, `lte.${value}`); + return this; + } + /** + * Match only rows where `column` matches `pattern` case-sensitively. + * + * @param column - The column to filter on + * @param pattern - The pattern to match with + */ + like(column, pattern) { + this.url.searchParams.append(column, `like.${pattern}`); + return this; + } + /** + * Match only rows where `column` matches all of `patterns` case-sensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + likeAllOf(column, patterns) { + this.url.searchParams.append(column, `like(all).{${patterns.join(",")}}`); + return this; + } + /** + * Match only rows where `column` matches any of `patterns` case-sensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + likeAnyOf(column, patterns) { + this.url.searchParams.append(column, `like(any).{${patterns.join(",")}}`); + return this; + } + /** + * Match only rows where `column` matches `pattern` case-insensitively. + * + * @param column - The column to filter on + * @param pattern - The pattern to match with + */ + ilike(column, pattern) { + this.url.searchParams.append(column, `ilike.${pattern}`); + return this; + } + /** + * Match only rows where `column` matches all of `patterns` case-insensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + ilikeAllOf(column, patterns) { + this.url.searchParams.append(column, `ilike(all).{${patterns.join(",")}}`); + return this; + } + /** + * Match only rows where `column` matches any of `patterns` case-insensitively. + * + * @param column - The column to filter on + * @param patterns - The patterns to match with + */ + ilikeAnyOf(column, patterns) { + this.url.searchParams.append(column, `ilike(any).{${patterns.join(",")}}`); + return this; + } + /** + * Match only rows where `column` matches the PostgreSQL regex `pattern` + * case-sensitively (using the `~` operator). + * + * @param column - The column to filter on + * @param pattern - The PostgreSQL regular expression pattern to match with + */ + regexMatch(column, pattern) { + this.url.searchParams.append(column, `match.${pattern}`); + return this; + } + /** + * Match only rows where `column` matches the PostgreSQL regex `pattern` + * case-insensitively (using the `~*` operator). + * + * @param column - The column to filter on + * @param pattern - The PostgreSQL regular expression pattern to match with + */ + regexIMatch(column, pattern) { + this.url.searchParams.append(column, `imatch.${pattern}`); + return this; + } + /** + * Match only rows where `column` IS `value`. + * + * For non-boolean columns, this is only relevant for checking if the value of + * `column` is NULL by setting `value` to `null`. + * + * For boolean columns, you can also set `value` to `true` or `false` and it + * will behave the same way as `.eq()`. + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + is(column, value) { + this.url.searchParams.append(column, `is.${value}`); + return this; + } + /** + * Match only rows where `column` IS DISTINCT FROM `value`. + * + * Unlike `.neq()`, this treats `NULL` as a comparable value. Two `NULL` values + * are considered equal (not distinct), and comparing `NULL` with any non-NULL + * value returns true (distinct). + * + * @param column - The column to filter on + * @param value - The value to filter with + */ + isDistinct(column, value) { + this.url.searchParams.append(column, `isdistinct.${value}`); + return this; + } + /** + * Match only rows where `column` is included in the `values` array. + * + * @param column - The column to filter on + * @param values - The values array to filter with + */ + in(column, values) { + const cleanedValues = Array.from(new Set(values)).map((s2) => { + if (typeof s2 === "string" && PostgrestReservedCharsRegexp.test(s2)) + return `"${s2}"`; + else + return `${s2}`; + }).join(","); + this.url.searchParams.append(column, `in.(${cleanedValues})`); + return this; + } + /** + * Only relevant for jsonb, array, and range columns. Match only rows where + * `column` contains every element appearing in `value`. + * + * @param column - The jsonb, array, or range column to filter on + * @param value - The jsonb, array, or range value to filter with + */ + contains(column, value) { + if (typeof value === "string") { + this.url.searchParams.append(column, `cs.${value}`); + } else if (Array.isArray(value)) { + this.url.searchParams.append(column, `cs.{${value.join(",")}}`); + } else { + this.url.searchParams.append(column, `cs.${JSON.stringify(value)}`); + } + return this; + } + /** + * Only relevant for jsonb, array, and range columns. Match only rows where + * every element appearing in `column` is contained by `value`. + * + * @param column - The jsonb, array, or range column to filter on + * @param value - The jsonb, array, or range value to filter with + */ + containedBy(column, value) { + if (typeof value === "string") { + this.url.searchParams.append(column, `cd.${value}`); + } else if (Array.isArray(value)) { + this.url.searchParams.append(column, `cd.{${value.join(",")}}`); + } else { + this.url.searchParams.append(column, `cd.${JSON.stringify(value)}`); + } + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is greater than any element in `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeGt(column, range) { + this.url.searchParams.append(column, `sr.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is either contained in `range` or greater than any element in + * `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeGte(column, range) { + this.url.searchParams.append(column, `nxl.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is less than any element in `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeLt(column, range) { + this.url.searchParams.append(column, `sl.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where every element in + * `column` is either contained in `range` or less than any element in + * `range`. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeLte(column, range) { + this.url.searchParams.append(column, `nxr.${range}`); + return this; + } + /** + * Only relevant for range columns. Match only rows where `column` is + * mutually exclusive to `range` and there can be no element between the two + * ranges. + * + * @param column - The range column to filter on + * @param range - The range to filter with + */ + rangeAdjacent(column, range) { + this.url.searchParams.append(column, `adj.${range}`); + return this; + } + /** + * Only relevant for array and range columns. Match only rows where + * `column` and `value` have an element in common. + * + * @param column - The array or range column to filter on + * @param value - The array or range value to filter with + */ + overlaps(column, value) { + if (typeof value === "string") { + this.url.searchParams.append(column, `ov.${value}`); + } else { + this.url.searchParams.append(column, `ov.{${value.join(",")}}`); + } + return this; + } + /** + * Only relevant for text and tsvector columns. Match only rows where + * `column` matches the query string in `query`. + * + * @param column - The text or tsvector column to filter on + * @param query - The query text to match with + * @param options - Named parameters + * @param options.config - The text search configuration to use + * @param options.type - Change how the `query` text is interpreted + */ + textSearch(column, query, { config, type } = {}) { + let typePart = ""; + if (type === "plain") { + typePart = "pl"; + } else if (type === "phrase") { + typePart = "ph"; + } else if (type === "websearch") { + typePart = "w"; + } + const configPart = config === void 0 ? "" : `(${config})`; + this.url.searchParams.append(column, `${typePart}fts${configPart}.${query}`); + return this; + } + /** + * Match only rows where each column in `query` keys is equal to its + * associated value. Shorthand for multiple `.eq()`s. + * + * @param query - The object to filter with, with column names as keys mapped + * to their filter values + */ + match(query) { + Object.entries(query).forEach(([column, value]) => { + this.url.searchParams.append(column, `eq.${value}`); + }); + return this; + } + /** + * Match only rows which doesn't satisfy the filter. + * + * Unlike most filters, `opearator` and `value` are used as-is and need to + * follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure they are properly sanitized. + * + * @param column - The column to filter on + * @param operator - The operator to be negated to filter with, following + * PostgREST syntax + * @param value - The value to filter with, following PostgREST syntax + */ + not(column, operator, value) { + this.url.searchParams.append(column, `not.${operator}.${value}`); + return this; + } + /** + * Match only rows which satisfy at least one of the filters. + * + * Unlike most filters, `filters` is used as-is and needs to follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure it's properly sanitized. + * + * It's currently not possible to do an `.or()` filter across multiple tables. + * + * @param filters - The filters to use, following PostgREST syntax + * @param options - Named parameters + * @param options.referencedTable - Set this to filter on referenced tables + * instead of the parent table + * @param options.foreignTable - Deprecated, use `referencedTable` instead + */ + or(filters, { foreignTable, referencedTable = foreignTable } = {}) { + const key = referencedTable ? `${referencedTable}.or` : "or"; + this.url.searchParams.append(key, `(${filters})`); + return this; + } + /** + * Match only rows which satisfy the filter. This is an escape hatch - you + * should use the specific filter methods wherever possible. + * + * Unlike most filters, `opearator` and `value` are used as-is and need to + * follow [PostgREST + * syntax](https://postgrest.org/en/stable/api.html#operators). You also need + * to make sure they are properly sanitized. + * + * @param column - The column to filter on + * @param operator - The operator to filter with, following PostgREST syntax + * @param value - The value to filter with, following PostgREST syntax + */ + filter(column, operator, value) { + this.url.searchParams.append(column, `${operator}.${value}`); + return this; + } + }; + exports.default = PostgrestFilterBuilder; + } + }); + + // node_modules/@supabase/postgrest-js/dist/cjs/PostgrestQueryBuilder.js + var require_PostgrestQueryBuilder = __commonJS({ + "node_modules/@supabase/postgrest-js/dist/cjs/PostgrestQueryBuilder.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var PostgrestFilterBuilder_1 = tslib_1.__importDefault(require_PostgrestFilterBuilder()); + var PostgrestQueryBuilder = class { + /** + * Creates a query builder scoped to a Postgres table or view. + * + * @example + * ```ts + * import PostgrestQueryBuilder from '@supabase/postgrest-js' + * + * const query = new PostgrestQueryBuilder( + * new URL('https://xyzcompany.supabase.co/rest/v1/users'), + * { headers: { apikey: 'public-anon-key' } } + * ) + * ``` + */ + constructor(url, { headers = {}, schema: schema4, fetch: fetch2 }) { + this.url = url; + this.headers = new Headers(headers); + this.schema = schema4; + this.fetch = fetch2; + } + /** + * Perform a SELECT query on the table or view. + * + * @param columns - The columns to retrieve, separated by commas. Columns can be renamed when returned with `customName:columnName` + * + * @param options - Named parameters + * + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * + * @param options.count - Count algorithm to use to count rows in the table or view. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + select(columns, options) { + const { head = false, count: count3 } = options !== null && options !== void 0 ? options : {}; + const method = head ? "HEAD" : "GET"; + let quoted = false; + const cleanedColumns = (columns !== null && columns !== void 0 ? columns : "*").split("").map((c3) => { + if (/\s/.test(c3) && !quoted) { + return ""; + } + if (c3 === '"') { + quoted = !quoted; + } + return c3; + }).join(""); + this.url.searchParams.set("select", cleanedColumns); + if (count3) { + this.headers.append("Prefer", `count=${count3}`); + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + fetch: this.fetch + }); + } + /** + * Perform an INSERT into the table or view. + * + * By default, inserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to insert. Pass an object to insert a single row + * or an array to insert multiple rows. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count inserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. Only applies for bulk + * inserts. + */ + insert(values, { count: count3, defaultToNull = true } = {}) { + var _a; + const method = "POST"; + if (count3) { + this.headers.append("Prefer", `count=${count3}`); + } + if (!defaultToNull) { + this.headers.append("Prefer", `missing=default`); + } + if (Array.isArray(values)) { + const columns = values.reduce((acc, x3) => acc.concat(Object.keys(x3)), []); + if (columns.length > 0) { + const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`); + this.url.searchParams.set("columns", uniqueColumns.join(",")); + } + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch + }); + } + /** + * Perform an UPSERT on the table or view. Depending on the column(s) passed + * to `onConflict`, `.upsert()` allows you to perform the equivalent of + * `.insert()` if a row with the corresponding `onConflict` columns doesn't + * exist, or if it does exist, perform an alternative action depending on + * `ignoreDuplicates`. + * + * By default, upserted rows are not returned. To return it, chain the call + * with `.select()`. + * + * @param values - The values to upsert with. Pass an object to upsert a + * single row or an array to upsert multiple rows. + * + * @param options - Named parameters + * + * @param options.onConflict - Comma-separated UNIQUE column(s) to specify how + * duplicate rows are determined. Two rows are duplicates if all the + * `onConflict` columns are equal. + * + * @param options.ignoreDuplicates - If `true`, duplicate rows are ignored. If + * `false`, duplicate rows are merged with existing rows. + * + * @param options.count - Count algorithm to use to count upserted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @param options.defaultToNull - Make missing fields default to `null`. + * Otherwise, use the default value for the column. This only applies when + * inserting new rows, not when merging with existing rows under + * `ignoreDuplicates: false`. This also only applies when doing bulk upserts. + * + * @example Upsert a single row using a unique key + * ```ts + * // Upserting a single row, overwriting based on the 'username' unique column + * const { data, error } = await supabase + * .from('users') + * .upsert({ username: 'supabot' }, { onConflict: 'username' }) + * + * // Example response: + * // { + * // data: [ + * // { id: 4, message: 'bar', username: 'supabot' } + * // ], + * // error: null + * // } + * ``` + * + * @example Upsert with conflict resolution and exact row counting + * ```ts + * // Upserting and returning exact count + * const { data, error, count } = await supabase + * .from('users') + * .upsert( + * { + * id: 3, + * message: 'foo', + * username: 'supabot' + * }, + * { + * onConflict: 'username', + * count: 'exact' + * } + * ) + * + * // Example response: + * // { + * // data: [ + * // { + * // id: 42, + * // handle: "saoirse", + * // display_name: "Saoirse" + * // } + * // ], + * // count: 1, + * // error: null + * // } + * ``` + */ + upsert(values, { onConflict, ignoreDuplicates = false, count: count3, defaultToNull = true } = {}) { + var _a; + const method = "POST"; + this.headers.append("Prefer", `resolution=${ignoreDuplicates ? "ignore" : "merge"}-duplicates`); + if (onConflict !== void 0) + this.url.searchParams.set("on_conflict", onConflict); + if (count3) { + this.headers.append("Prefer", `count=${count3}`); + } + if (!defaultToNull) { + this.headers.append("Prefer", "missing=default"); + } + if (Array.isArray(values)) { + const columns = values.reduce((acc, x3) => acc.concat(Object.keys(x3)), []); + if (columns.length > 0) { + const uniqueColumns = [...new Set(columns)].map((column) => `"${column}"`); + this.url.searchParams.set("columns", uniqueColumns.join(",")); + } + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch + }); + } + /** + * Perform an UPDATE on the table or view. + * + * By default, updated rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param values - The values to update with + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count updated rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + update(values, { count: count3 } = {}) { + var _a; + const method = "PATCH"; + if (count3) { + this.headers.append("Prefer", `count=${count3}`); + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + body: values, + fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch + }); + } + /** + * Perform a DELETE on the table or view. + * + * By default, deleted rows are not returned. To return it, chain the call + * with `.select()` after filters. + * + * @param options - Named parameters + * + * @param options.count - Count algorithm to use to count deleted rows. + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + delete({ count: count3 } = {}) { + var _a; + const method = "DELETE"; + if (count3) { + this.headers.append("Prefer", `count=${count3}`); + } + return new PostgrestFilterBuilder_1.default({ + method, + url: this.url, + headers: this.headers, + schema: this.schema, + fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch + }); + } + }; + exports.default = PostgrestQueryBuilder; + } + }); + + // node_modules/@supabase/postgrest-js/dist/cjs/PostgrestClient.js + var require_PostgrestClient = __commonJS({ + "node_modules/@supabase/postgrest-js/dist/cjs/PostgrestClient.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var PostgrestQueryBuilder_1 = tslib_1.__importDefault(require_PostgrestQueryBuilder()); + var PostgrestFilterBuilder_1 = tslib_1.__importDefault(require_PostgrestFilterBuilder()); + var PostgrestClient = class _PostgrestClient { + // TODO: Add back shouldThrowOnError once we figure out the typings + /** + * Creates a PostgREST client. + * + * @param url - URL of the PostgREST endpoint + * @param options - Named parameters + * @param options.headers - Custom headers + * @param options.schema - Postgres schema to switch to + * @param options.fetch - Custom fetch + * @example + * ```ts + * import PostgrestClient from '@supabase/postgrest-js' + * + * const postgrest = new PostgrestClient('https://xyzcompany.supabase.co/rest/v1', { + * headers: { apikey: 'public-anon-key' }, + * schema: 'public', + * }) + * ``` + */ + constructor(url, { headers = {}, schema: schema4, fetch: fetch2 } = {}) { + this.url = url; + this.headers = new Headers(headers); + this.schemaName = schema4; + this.fetch = fetch2; + } + /** + * Perform a query on a table or a view. + * + * @param relation - The table or view name to query + */ + from(relation) { + if (!relation || typeof relation !== "string" || relation.trim() === "") { + throw new Error("Invalid relation name: relation must be a non-empty string."); + } + const url = new URL(`${this.url}/${relation}`); + return new PostgrestQueryBuilder_1.default(url, { + headers: new Headers(this.headers), + schema: this.schemaName, + fetch: this.fetch + }); + } + /** + * Select a schema to query or perform an function (rpc) call. + * + * The schema needs to be on the list of exposed schemas inside Supabase. + * + * @param schema - The schema to query + */ + schema(schema4) { + return new _PostgrestClient(this.url, { + headers: this.headers, + schema: schema4, + fetch: this.fetch + }); + } + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.get - When set to `true`, the function will be called with + * read-only access mode. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + * + * @example + * ```ts + * // For cross-schema functions where type inference fails, use overrideTypes: + * const { data } = await supabase + * .schema('schema_b') + * .rpc('function_a', {}) + * .overrideTypes<{ id: string; user_id: string }[]>() + * ``` + */ + rpc(fn, args = {}, { head = false, get: get3 = false, count: count3 } = {}) { + var _a; + let method; + const url = new URL(`${this.url}/rpc/${fn}`); + let body; + if (head || get3) { + method = head ? "HEAD" : "GET"; + Object.entries(args).filter(([_2, value]) => value !== void 0).map(([name, value]) => [name, Array.isArray(value) ? `{${value.join(",")}}` : `${value}`]).forEach(([name, value]) => { + url.searchParams.append(name, value); + }); + } else { + method = "POST"; + body = args; + } + const headers = new Headers(this.headers); + if (count3) { + headers.set("Prefer", `count=${count3}`); + } + return new PostgrestFilterBuilder_1.default({ + method, + url, + headers, + schema: this.schemaName, + body, + fetch: (_a = this.fetch) !== null && _a !== void 0 ? _a : fetch + }); + } + }; + exports.default = PostgrestClient; + } + }); + + // node_modules/@supabase/postgrest-js/dist/cjs/index.js + var require_cjs = __commonJS({ + "node_modules/@supabase/postgrest-js/dist/cjs/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.PostgrestError = exports.PostgrestBuilder = exports.PostgrestTransformBuilder = exports.PostgrestFilterBuilder = exports.PostgrestQueryBuilder = exports.PostgrestClient = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var PostgrestClient_1 = tslib_1.__importDefault(require_PostgrestClient()); + exports.PostgrestClient = PostgrestClient_1.default; + var PostgrestQueryBuilder_1 = tslib_1.__importDefault(require_PostgrestQueryBuilder()); + exports.PostgrestQueryBuilder = PostgrestQueryBuilder_1.default; + var PostgrestFilterBuilder_1 = tslib_1.__importDefault(require_PostgrestFilterBuilder()); + exports.PostgrestFilterBuilder = PostgrestFilterBuilder_1.default; + var PostgrestTransformBuilder_1 = tslib_1.__importDefault(require_PostgrestTransformBuilder()); + exports.PostgrestTransformBuilder = PostgrestTransformBuilder_1.default; + var PostgrestBuilder_1 = tslib_1.__importDefault(require_PostgrestBuilder()); + exports.PostgrestBuilder = PostgrestBuilder_1.default; + var PostgrestError_1 = tslib_1.__importDefault(require_PostgrestError()); + exports.PostgrestError = PostgrestError_1.default; + exports.default = { + PostgrestClient: PostgrestClient_1.default, + PostgrestQueryBuilder: PostgrestQueryBuilder_1.default, + PostgrestFilterBuilder: PostgrestFilterBuilder_1.default, + PostgrestTransformBuilder: PostgrestTransformBuilder_1.default, + PostgrestBuilder: PostgrestBuilder_1.default, + PostgrestError: PostgrestError_1.default + }; + } + }); + + // node_modules/@supabase/realtime-js/dist/main/lib/websocket-factory.js + var require_websocket_factory = __commonJS({ + "node_modules/@supabase/realtime-js/dist/main/lib/websocket-factory.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.WebSocketFactory = void 0; + var WebSocketFactory = class { + /** + * Static-only utility – prevent instantiation. + */ + constructor() { + } + static detectEnvironment() { + var _a; + if (typeof WebSocket !== "undefined") { + return { type: "native", constructor: WebSocket }; + } + if (typeof globalThis !== "undefined" && typeof globalThis.WebSocket !== "undefined") { + return { type: "native", constructor: globalThis.WebSocket }; + } + if (typeof global !== "undefined" && typeof global.WebSocket !== "undefined") { + return { type: "native", constructor: global.WebSocket }; + } + if (typeof globalThis !== "undefined" && typeof globalThis.WebSocketPair !== "undefined" && typeof globalThis.WebSocket === "undefined") { + return { + type: "cloudflare", + error: "Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.", + workaround: "Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime." + }; + } + if (typeof globalThis !== "undefined" && globalThis.EdgeRuntime || typeof navigator !== "undefined" && ((_a = navigator.userAgent) === null || _a === void 0 ? void 0 : _a.includes("Vercel-Edge"))) { + return { + type: "unsupported", + error: "Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.", + workaround: "Use serverless functions or a different deployment target for WebSocket functionality." + }; + } + if (typeof process !== "undefined") { + const processVersions = process["versions"]; + if (processVersions && processVersions["node"]) { + const versionString = processVersions["node"]; + const nodeVersion = parseInt(versionString.replace(/^v/, "").split(".")[0]); + if (nodeVersion >= 22) { + if (typeof globalThis.WebSocket !== "undefined") { + return { type: "native", constructor: globalThis.WebSocket }; + } + return { + type: "unsupported", + error: `Node.js ${nodeVersion} detected but native WebSocket not found.`, + workaround: "Provide a WebSocket implementation via the transport option." + }; + } + return { + type: "unsupported", + error: `Node.js ${nodeVersion} detected without native WebSocket support.`, + workaround: 'For Node.js < 22, install "ws" package and provide it via the transport option:\nimport ws from "ws"\nnew RealtimeClient(url, { transport: ws })' + }; + } + } + return { + type: "unsupported", + error: "Unknown JavaScript runtime without WebSocket support.", + workaround: "Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation." + }; + } + /** + * Returns the best available WebSocket constructor for the current runtime. + * + * @example + * ```ts + * const WS = WebSocketFactory.getWebSocketConstructor() + * const socket = new WS('wss://realtime.supabase.co/socket') + * ``` + */ + static getWebSocketConstructor() { + const env = this.detectEnvironment(); + if (env.constructor) { + return env.constructor; + } + let errorMessage = env.error || "WebSocket not supported in this environment."; + if (env.workaround) { + errorMessage += ` + +Suggested solution: ${env.workaround}`; + } + throw new Error(errorMessage); + } + /** + * Creates a WebSocket using the detected constructor. + * + * @example + * ```ts + * const socket = WebSocketFactory.createWebSocket('wss://realtime.supabase.co/socket') + * ``` + */ + static createWebSocket(url, protocols) { + const WS = this.getWebSocketConstructor(); + return new WS(url, protocols); + } + /** + * Detects whether the runtime can establish WebSocket connections. + * + * @example + * ```ts + * if (!WebSocketFactory.isWebSocketSupported()) { + * console.warn('Falling back to long polling') + * } + * ``` + */ + static isWebSocketSupported() { + try { + const env = this.detectEnvironment(); + return env.type === "native" || env.type === "ws"; + } catch (_a) { + return false; + } + } + }; + exports.WebSocketFactory = WebSocketFactory; + exports.default = WebSocketFactory; + } + }); + + // node_modules/@supabase/realtime-js/dist/main/lib/version.js + var require_version = __commonJS({ + "node_modules/@supabase/realtime-js/dist/main/lib/version.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.version = void 0; + exports.version = "2.87.1"; + } + }); + + // node_modules/@supabase/realtime-js/dist/main/lib/constants.js + var require_constants2 = __commonJS({ + "node_modules/@supabase/realtime-js/dist/main/lib/constants.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CONNECTION_STATE = exports.TRANSPORTS = exports.CHANNEL_EVENTS = exports.CHANNEL_STATES = exports.SOCKET_STATES = exports.MAX_PUSH_BUFFER_SIZE = exports.WS_CLOSE_NORMAL = exports.DEFAULT_TIMEOUT = exports.VERSION = exports.DEFAULT_VSN = exports.VSN_2_0_0 = exports.VSN_1_0_0 = exports.DEFAULT_VERSION = void 0; + var version_1 = require_version(); + exports.DEFAULT_VERSION = `realtime-js/${version_1.version}`; + exports.VSN_1_0_0 = "1.0.0"; + exports.VSN_2_0_0 = "2.0.0"; + exports.DEFAULT_VSN = exports.VSN_1_0_0; + exports.VERSION = version_1.version; + exports.DEFAULT_TIMEOUT = 1e4; + exports.WS_CLOSE_NORMAL = 1e3; + exports.MAX_PUSH_BUFFER_SIZE = 100; + var SOCKET_STATES; + (function(SOCKET_STATES2) { + SOCKET_STATES2[SOCKET_STATES2["connecting"] = 0] = "connecting"; + SOCKET_STATES2[SOCKET_STATES2["open"] = 1] = "open"; + SOCKET_STATES2[SOCKET_STATES2["closing"] = 2] = "closing"; + SOCKET_STATES2[SOCKET_STATES2["closed"] = 3] = "closed"; + })(SOCKET_STATES || (exports.SOCKET_STATES = SOCKET_STATES = {})); + var CHANNEL_STATES; + (function(CHANNEL_STATES2) { + CHANNEL_STATES2["closed"] = "closed"; + CHANNEL_STATES2["errored"] = "errored"; + CHANNEL_STATES2["joined"] = "joined"; + CHANNEL_STATES2["joining"] = "joining"; + CHANNEL_STATES2["leaving"] = "leaving"; + })(CHANNEL_STATES || (exports.CHANNEL_STATES = CHANNEL_STATES = {})); + var CHANNEL_EVENTS; + (function(CHANNEL_EVENTS2) { + CHANNEL_EVENTS2["close"] = "phx_close"; + CHANNEL_EVENTS2["error"] = "phx_error"; + CHANNEL_EVENTS2["join"] = "phx_join"; + CHANNEL_EVENTS2["reply"] = "phx_reply"; + CHANNEL_EVENTS2["leave"] = "phx_leave"; + CHANNEL_EVENTS2["access_token"] = "access_token"; + })(CHANNEL_EVENTS || (exports.CHANNEL_EVENTS = CHANNEL_EVENTS = {})); + var TRANSPORTS; + (function(TRANSPORTS2) { + TRANSPORTS2["websocket"] = "websocket"; + })(TRANSPORTS || (exports.TRANSPORTS = TRANSPORTS = {})); + var CONNECTION_STATE; + (function(CONNECTION_STATE2) { + CONNECTION_STATE2["Connecting"] = "connecting"; + CONNECTION_STATE2["Open"] = "open"; + CONNECTION_STATE2["Closing"] = "closing"; + CONNECTION_STATE2["Closed"] = "closed"; + })(CONNECTION_STATE || (exports.CONNECTION_STATE = CONNECTION_STATE = {})); + } + }); + + // node_modules/@supabase/realtime-js/dist/main/lib/serializer.js + var require_serializer = __commonJS({ + "node_modules/@supabase/realtime-js/dist/main/lib/serializer.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var Serializer = class { + constructor(allowedMetadataKeys) { + this.HEADER_LENGTH = 1; + this.USER_BROADCAST_PUSH_META_LENGTH = 6; + this.KINDS = { userBroadcastPush: 3, userBroadcast: 4 }; + this.BINARY_ENCODING = 0; + this.JSON_ENCODING = 1; + this.BROADCAST_EVENT = "broadcast"; + this.allowedMetadataKeys = []; + this.allowedMetadataKeys = allowedMetadataKeys !== null && allowedMetadataKeys !== void 0 ? allowedMetadataKeys : []; + } + encode(msg, callback) { + if (msg.event === this.BROADCAST_EVENT && !(msg.payload instanceof ArrayBuffer) && typeof msg.payload.event === "string") { + return callback(this._binaryEncodeUserBroadcastPush(msg)); + } + let payload = [msg.join_ref, msg.ref, msg.topic, msg.event, msg.payload]; + return callback(JSON.stringify(payload)); + } + _binaryEncodeUserBroadcastPush(message) { + var _a; + if (this._isArrayBuffer((_a = message.payload) === null || _a === void 0 ? void 0 : _a.payload)) { + return this._encodeBinaryUserBroadcastPush(message); + } else { + return this._encodeJsonUserBroadcastPush(message); + } + } + _encodeBinaryUserBroadcastPush(message) { + var _a, _b; + const userPayload = (_b = (_a = message.payload) === null || _a === void 0 ? void 0 : _a.payload) !== null && _b !== void 0 ? _b : new ArrayBuffer(0); + return this._encodeUserBroadcastPush(message, this.BINARY_ENCODING, userPayload); + } + _encodeJsonUserBroadcastPush(message) { + var _a, _b; + const userPayload = (_b = (_a = message.payload) === null || _a === void 0 ? void 0 : _a.payload) !== null && _b !== void 0 ? _b : {}; + const encoder2 = new TextEncoder(); + const encodedUserPayload = encoder2.encode(JSON.stringify(userPayload)).buffer; + return this._encodeUserBroadcastPush(message, this.JSON_ENCODING, encodedUserPayload); + } + _encodeUserBroadcastPush(message, encodingType, encodedPayload) { + var _a, _b; + const topic = message.topic; + const ref = (_a = message.ref) !== null && _a !== void 0 ? _a : ""; + const joinRef = (_b = message.join_ref) !== null && _b !== void 0 ? _b : ""; + const userEvent = message.payload.event; + const rest = this.allowedMetadataKeys ? this._pick(message.payload, this.allowedMetadataKeys) : {}; + const metadata = Object.keys(rest).length === 0 ? "" : JSON.stringify(rest); + if (joinRef.length > 255) { + throw new Error(`joinRef length ${joinRef.length} exceeds maximum of 255`); + } + if (ref.length > 255) { + throw new Error(`ref length ${ref.length} exceeds maximum of 255`); + } + if (topic.length > 255) { + throw new Error(`topic length ${topic.length} exceeds maximum of 255`); + } + if (userEvent.length > 255) { + throw new Error(`userEvent length ${userEvent.length} exceeds maximum of 255`); + } + if (metadata.length > 255) { + throw new Error(`metadata length ${metadata.length} exceeds maximum of 255`); + } + const metaLength = this.USER_BROADCAST_PUSH_META_LENGTH + joinRef.length + ref.length + topic.length + userEvent.length + metadata.length; + const header = new ArrayBuffer(this.HEADER_LENGTH + metaLength); + let view = new DataView(header); + let offset = 0; + view.setUint8(offset++, this.KINDS.userBroadcastPush); + view.setUint8(offset++, joinRef.length); + view.setUint8(offset++, ref.length); + view.setUint8(offset++, topic.length); + view.setUint8(offset++, userEvent.length); + view.setUint8(offset++, metadata.length); + view.setUint8(offset++, encodingType); + Array.from(joinRef, (char) => view.setUint8(offset++, char.charCodeAt(0))); + Array.from(ref, (char) => view.setUint8(offset++, char.charCodeAt(0))); + Array.from(topic, (char) => view.setUint8(offset++, char.charCodeAt(0))); + Array.from(userEvent, (char) => view.setUint8(offset++, char.charCodeAt(0))); + Array.from(metadata, (char) => view.setUint8(offset++, char.charCodeAt(0))); + var combined = new Uint8Array(header.byteLength + encodedPayload.byteLength); + combined.set(new Uint8Array(header), 0); + combined.set(new Uint8Array(encodedPayload), header.byteLength); + return combined.buffer; + } + decode(rawPayload, callback) { + if (this._isArrayBuffer(rawPayload)) { + let result = this._binaryDecode(rawPayload); + return callback(result); + } + if (typeof rawPayload === "string") { + const jsonPayload = JSON.parse(rawPayload); + const [join_ref, ref, topic, event, payload] = jsonPayload; + return callback({ join_ref, ref, topic, event, payload }); + } + return callback({}); + } + _binaryDecode(buffer) { + const view = new DataView(buffer); + const kind = view.getUint8(0); + const decoder = new TextDecoder(); + switch (kind) { + case this.KINDS.userBroadcast: + return this._decodeUserBroadcast(buffer, view, decoder); + } + } + _decodeUserBroadcast(buffer, view, decoder) { + const topicSize = view.getUint8(1); + const userEventSize = view.getUint8(2); + const metadataSize = view.getUint8(3); + const payloadEncoding = view.getUint8(4); + let offset = this.HEADER_LENGTH + 4; + const topic = decoder.decode(buffer.slice(offset, offset + topicSize)); + offset = offset + topicSize; + const userEvent = decoder.decode(buffer.slice(offset, offset + userEventSize)); + offset = offset + userEventSize; + const metadata = decoder.decode(buffer.slice(offset, offset + metadataSize)); + offset = offset + metadataSize; + const payload = buffer.slice(offset, buffer.byteLength); + const parsedPayload = payloadEncoding === this.JSON_ENCODING ? JSON.parse(decoder.decode(payload)) : payload; + const data = { + type: this.BROADCAST_EVENT, + event: userEvent, + payload: parsedPayload + }; + if (metadataSize > 0) { + data["meta"] = JSON.parse(metadata); + } + return { join_ref: null, ref: null, topic, event: this.BROADCAST_EVENT, payload: data }; + } + _isArrayBuffer(buffer) { + var _a; + return buffer instanceof ArrayBuffer || ((_a = buffer === null || buffer === void 0 ? void 0 : buffer.constructor) === null || _a === void 0 ? void 0 : _a.name) === "ArrayBuffer"; + } + _pick(obj, keys) { + if (!obj || typeof obj !== "object") { + return {}; + } + return Object.fromEntries(Object.entries(obj).filter(([key]) => keys.includes(key))); + } + }; + exports.default = Serializer; + } + }); + + // node_modules/@supabase/realtime-js/dist/main/lib/timer.js + var require_timer = __commonJS({ + "node_modules/@supabase/realtime-js/dist/main/lib/timer.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var Timer = class { + constructor(callback, timerCalc) { + this.callback = callback; + this.timerCalc = timerCalc; + this.timer = void 0; + this.tries = 0; + this.callback = callback; + this.timerCalc = timerCalc; + } + reset() { + this.tries = 0; + clearTimeout(this.timer); + this.timer = void 0; + } + // Cancels any previous scheduleTimeout and schedules callback + scheduleTimeout() { + clearTimeout(this.timer); + this.timer = setTimeout(() => { + this.tries = this.tries + 1; + this.callback(); + }, this.timerCalc(this.tries + 1)); + } + }; + exports.default = Timer; + } + }); + + // node_modules/@supabase/realtime-js/dist/main/lib/transformers.js + var require_transformers = __commonJS({ + "node_modules/@supabase/realtime-js/dist/main/lib/transformers.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.httpEndpointURL = exports.toTimestampString = exports.toArray = exports.toJson = exports.toNumber = exports.toBoolean = exports.convertCell = exports.convertColumn = exports.convertChangeData = exports.PostgresTypes = void 0; + var PostgresTypes; + (function(PostgresTypes2) { + PostgresTypes2["abstime"] = "abstime"; + PostgresTypes2["bool"] = "bool"; + PostgresTypes2["date"] = "date"; + PostgresTypes2["daterange"] = "daterange"; + PostgresTypes2["float4"] = "float4"; + PostgresTypes2["float8"] = "float8"; + PostgresTypes2["int2"] = "int2"; + PostgresTypes2["int4"] = "int4"; + PostgresTypes2["int4range"] = "int4range"; + PostgresTypes2["int8"] = "int8"; + PostgresTypes2["int8range"] = "int8range"; + PostgresTypes2["json"] = "json"; + PostgresTypes2["jsonb"] = "jsonb"; + PostgresTypes2["money"] = "money"; + PostgresTypes2["numeric"] = "numeric"; + PostgresTypes2["oid"] = "oid"; + PostgresTypes2["reltime"] = "reltime"; + PostgresTypes2["text"] = "text"; + PostgresTypes2["time"] = "time"; + PostgresTypes2["timestamp"] = "timestamp"; + PostgresTypes2["timestamptz"] = "timestamptz"; + PostgresTypes2["timetz"] = "timetz"; + PostgresTypes2["tsrange"] = "tsrange"; + PostgresTypes2["tstzrange"] = "tstzrange"; + })(PostgresTypes || (exports.PostgresTypes = PostgresTypes = {})); + var convertChangeData = (columns, record, options = {}) => { + var _a; + const skipTypes = (_a = options.skipTypes) !== null && _a !== void 0 ? _a : []; + if (!record) { + return {}; + } + return Object.keys(record).reduce((acc, rec_key) => { + acc[rec_key] = (0, exports.convertColumn)(rec_key, columns, record, skipTypes); + return acc; + }, {}); + }; + exports.convertChangeData = convertChangeData; + var convertColumn = (columnName, columns, record, skipTypes) => { + const column = columns.find((x3) => x3.name === columnName); + const colType = column === null || column === void 0 ? void 0 : column.type; + const value = record[columnName]; + if (colType && !skipTypes.includes(colType)) { + return (0, exports.convertCell)(colType, value); + } + return noop(value); + }; + exports.convertColumn = convertColumn; + var convertCell = (type, value) => { + if (type.charAt(0) === "_") { + const dataType = type.slice(1, type.length); + return (0, exports.toArray)(value, dataType); + } + switch (type) { + case PostgresTypes.bool: + return (0, exports.toBoolean)(value); + case PostgresTypes.float4: + case PostgresTypes.float8: + case PostgresTypes.int2: + case PostgresTypes.int4: + case PostgresTypes.int8: + case PostgresTypes.numeric: + case PostgresTypes.oid: + return (0, exports.toNumber)(value); + case PostgresTypes.json: + case PostgresTypes.jsonb: + return (0, exports.toJson)(value); + case PostgresTypes.timestamp: + return (0, exports.toTimestampString)(value); + // Format to be consistent with PostgREST + case PostgresTypes.abstime: + // To allow users to cast it based on Timezone + case PostgresTypes.date: + // To allow users to cast it based on Timezone + case PostgresTypes.daterange: + case PostgresTypes.int4range: + case PostgresTypes.int8range: + case PostgresTypes.money: + case PostgresTypes.reltime: + // To allow users to cast it based on Timezone + case PostgresTypes.text: + case PostgresTypes.time: + // To allow users to cast it based on Timezone + case PostgresTypes.timestamptz: + // To allow users to cast it based on Timezone + case PostgresTypes.timetz: + // To allow users to cast it based on Timezone + case PostgresTypes.tsrange: + case PostgresTypes.tstzrange: + return noop(value); + default: + return noop(value); + } + }; + exports.convertCell = convertCell; + var noop = (value) => { + return value; + }; + var toBoolean = (value) => { + switch (value) { + case "t": + return true; + case "f": + return false; + default: + return value; + } + }; + exports.toBoolean = toBoolean; + var toNumber = (value) => { + if (typeof value === "string") { + const parsedValue = parseFloat(value); + if (!Number.isNaN(parsedValue)) { + return parsedValue; + } + } + return value; + }; + exports.toNumber = toNumber; + var toJson = (value) => { + if (typeof value === "string") { + try { + return JSON.parse(value); + } catch (error) { + console.log(`JSON parse error: ${error}`); + return value; + } + } + return value; + }; + exports.toJson = toJson; + var toArray2 = (value, type) => { + if (typeof value !== "string") { + return value; + } + const lastIdx = value.length - 1; + const closeBrace = value[lastIdx]; + const openBrace = value[0]; + if (openBrace === "{" && closeBrace === "}") { + let arr2; + const valTrim = value.slice(1, lastIdx); + try { + arr2 = JSON.parse("[" + valTrim + "]"); + } catch (_2) { + arr2 = valTrim ? valTrim.split(",") : []; + } + return arr2.map((val) => (0, exports.convertCell)(type, val)); + } + return value; + }; + exports.toArray = toArray2; + var toTimestampString = (value) => { + if (typeof value === "string") { + return value.replace(" ", "T"); + } + return value; + }; + exports.toTimestampString = toTimestampString; + var httpEndpointURL = (socketUrl) => { + const wsUrl = new URL(socketUrl); + wsUrl.protocol = wsUrl.protocol.replace(/^ws/i, "http"); + wsUrl.pathname = wsUrl.pathname.replace(/\/+$/, "").replace(/\/socket\/websocket$/i, "").replace(/\/socket$/i, "").replace(/\/websocket$/i, ""); + if (wsUrl.pathname === "" || wsUrl.pathname === "/") { + wsUrl.pathname = "/api/broadcast"; + } else { + wsUrl.pathname = wsUrl.pathname + "/api/broadcast"; + } + return wsUrl.href; + }; + exports.httpEndpointURL = httpEndpointURL; + } + }); + + // node_modules/@supabase/realtime-js/dist/main/lib/push.js + var require_push = __commonJS({ + "node_modules/@supabase/realtime-js/dist/main/lib/push.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var constants_1 = require_constants2(); + var Push = class { + /** + * Initializes the Push + * + * @param channel The Channel + * @param event The event, for example `"phx_join"` + * @param payload The payload, for example `{user_id: 123}` + * @param timeout The push timeout in milliseconds + */ + constructor(channel, event, payload = {}, timeout = constants_1.DEFAULT_TIMEOUT) { + this.channel = channel; + this.event = event; + this.payload = payload; + this.timeout = timeout; + this.sent = false; + this.timeoutTimer = void 0; + this.ref = ""; + this.receivedResp = null; + this.recHooks = []; + this.refEvent = null; + } + resend(timeout) { + this.timeout = timeout; + this._cancelRefEvent(); + this.ref = ""; + this.refEvent = null; + this.receivedResp = null; + this.sent = false; + this.send(); + } + send() { + if (this._hasReceived("timeout")) { + return; + } + this.startTimeout(); + this.sent = true; + this.channel.socket.push({ + topic: this.channel.topic, + event: this.event, + payload: this.payload, + ref: this.ref, + join_ref: this.channel._joinRef() + }); + } + updatePayload(payload) { + this.payload = Object.assign(Object.assign({}, this.payload), payload); + } + receive(status, callback) { + var _a; + if (this._hasReceived(status)) { + callback((_a = this.receivedResp) === null || _a === void 0 ? void 0 : _a.response); + } + this.recHooks.push({ status, callback }); + return this; + } + startTimeout() { + if (this.timeoutTimer) { + return; + } + this.ref = this.channel.socket._makeRef(); + this.refEvent = this.channel._replyEventName(this.ref); + const callback = (payload) => { + this._cancelRefEvent(); + this._cancelTimeout(); + this.receivedResp = payload; + this._matchReceive(payload); + }; + this.channel._on(this.refEvent, {}, callback); + this.timeoutTimer = setTimeout(() => { + this.trigger("timeout", {}); + }, this.timeout); + } + trigger(status, response) { + if (this.refEvent) + this.channel._trigger(this.refEvent, { status, response }); + } + destroy() { + this._cancelRefEvent(); + this._cancelTimeout(); + } + _cancelRefEvent() { + if (!this.refEvent) { + return; + } + this.channel._off(this.refEvent, {}); + } + _cancelTimeout() { + clearTimeout(this.timeoutTimer); + this.timeoutTimer = void 0; + } + _matchReceive({ status, response }) { + this.recHooks.filter((h2) => h2.status === status).forEach((h2) => h2.callback(response)); + } + _hasReceived(status) { + return this.receivedResp && this.receivedResp.status === status; + } + }; + exports.default = Push; + } + }); + + // node_modules/@supabase/realtime-js/dist/main/RealtimePresence.js + var require_RealtimePresence = __commonJS({ + "node_modules/@supabase/realtime-js/dist/main/RealtimePresence.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.REALTIME_PRESENCE_LISTEN_EVENTS = void 0; + var REALTIME_PRESENCE_LISTEN_EVENTS2; + (function(REALTIME_PRESENCE_LISTEN_EVENTS3) { + REALTIME_PRESENCE_LISTEN_EVENTS3["SYNC"] = "sync"; + REALTIME_PRESENCE_LISTEN_EVENTS3["JOIN"] = "join"; + REALTIME_PRESENCE_LISTEN_EVENTS3["LEAVE"] = "leave"; + })(REALTIME_PRESENCE_LISTEN_EVENTS2 || (exports.REALTIME_PRESENCE_LISTEN_EVENTS = REALTIME_PRESENCE_LISTEN_EVENTS2 = {})); + var RealtimePresence2 = class _RealtimePresence { + /** + * Creates a Presence helper that keeps the local presence state in sync with the server. + * + * @param channel - The realtime channel to bind to. + * @param opts - Optional custom event names, e.g. `{ events: { state: 'state', diff: 'diff' } }`. + * + * @example + * ```ts + * const presence = new RealtimePresence(channel) + * + * channel.on('presence', ({ event, key }) => { + * console.log(`Presence ${event} on ${key}`) + * }) + * ``` + */ + constructor(channel, opts) { + this.channel = channel; + this.state = {}; + this.pendingDiffs = []; + this.joinRef = null; + this.enabled = false; + this.caller = { + onJoin: () => { + }, + onLeave: () => { + }, + onSync: () => { + } + }; + const events = (opts === null || opts === void 0 ? void 0 : opts.events) || { + state: "presence_state", + diff: "presence_diff" + }; + this.channel._on(events.state, {}, (newState) => { + const { onJoin, onLeave, onSync } = this.caller; + this.joinRef = this.channel._joinRef(); + this.state = _RealtimePresence.syncState(this.state, newState, onJoin, onLeave); + this.pendingDiffs.forEach((diff) => { + this.state = _RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); + }); + this.pendingDiffs = []; + onSync(); + }); + this.channel._on(events.diff, {}, (diff) => { + const { onJoin, onLeave, onSync } = this.caller; + if (this.inPendingSyncState()) { + this.pendingDiffs.push(diff); + } else { + this.state = _RealtimePresence.syncDiff(this.state, diff, onJoin, onLeave); + onSync(); + } + }); + this.onJoin((key, currentPresences, newPresences) => { + this.channel._trigger("presence", { + event: "join", + key, + currentPresences, + newPresences + }); + }); + this.onLeave((key, currentPresences, leftPresences) => { + this.channel._trigger("presence", { + event: "leave", + key, + currentPresences, + leftPresences + }); + }); + this.onSync(() => { + this.channel._trigger("presence", { event: "sync" }); + }); + } + /** + * Used to sync the list of presences on the server with the + * client's state. + * + * An optional `onJoin` and `onLeave` callback can be provided to + * react to changes in the client's local presences across + * disconnects and reconnects with the server. + * + * @internal + */ + static syncState(currentState, newState, onJoin, onLeave) { + const state = this.cloneDeep(currentState); + const transformedState = this.transformState(newState); + const joins = {}; + const leaves = {}; + this.map(state, (key, presences) => { + if (!transformedState[key]) { + leaves[key] = presences; + } + }); + this.map(transformedState, (key, newPresences) => { + const currentPresences = state[key]; + if (currentPresences) { + const newPresenceRefs = newPresences.map((m3) => m3.presence_ref); + const curPresenceRefs = currentPresences.map((m3) => m3.presence_ref); + const joinedPresences = newPresences.filter((m3) => curPresenceRefs.indexOf(m3.presence_ref) < 0); + const leftPresences = currentPresences.filter((m3) => newPresenceRefs.indexOf(m3.presence_ref) < 0); + if (joinedPresences.length > 0) { + joins[key] = joinedPresences; + } + if (leftPresences.length > 0) { + leaves[key] = leftPresences; + } + } else { + joins[key] = newPresences; + } + }); + return this.syncDiff(state, { joins, leaves }, onJoin, onLeave); + } + /** + * Used to sync a diff of presence join and leave events from the + * server, as they happen. + * + * Like `syncState`, `syncDiff` accepts optional `onJoin` and + * `onLeave` callbacks to react to a user joining or leaving from a + * device. + * + * @internal + */ + static syncDiff(state, diff, onJoin, onLeave) { + const { joins, leaves } = { + joins: this.transformState(diff.joins), + leaves: this.transformState(diff.leaves) + }; + if (!onJoin) { + onJoin = () => { + }; + } + if (!onLeave) { + onLeave = () => { + }; + } + this.map(joins, (key, newPresences) => { + var _a; + const currentPresences = (_a = state[key]) !== null && _a !== void 0 ? _a : []; + state[key] = this.cloneDeep(newPresences); + if (currentPresences.length > 0) { + const joinedPresenceRefs = state[key].map((m3) => m3.presence_ref); + const curPresences = currentPresences.filter((m3) => joinedPresenceRefs.indexOf(m3.presence_ref) < 0); + state[key].unshift(...curPresences); + } + onJoin(key, currentPresences, newPresences); + }); + this.map(leaves, (key, leftPresences) => { + let currentPresences = state[key]; + if (!currentPresences) + return; + const presenceRefsToRemove = leftPresences.map((m3) => m3.presence_ref); + currentPresences = currentPresences.filter((m3) => presenceRefsToRemove.indexOf(m3.presence_ref) < 0); + state[key] = currentPresences; + onLeave(key, currentPresences, leftPresences); + if (currentPresences.length === 0) + delete state[key]; + }); + return state; + } + /** @internal */ + static map(obj, func) { + return Object.getOwnPropertyNames(obj).map((key) => func(key, obj[key])); + } + /** + * Remove 'metas' key + * Change 'phx_ref' to 'presence_ref' + * Remove 'phx_ref' and 'phx_ref_prev' + * + * @example + * // returns { + * abc123: [ + * { presence_ref: '2', user_id: 1 }, + * { presence_ref: '3', user_id: 2 } + * ] + * } + * RealtimePresence.transformState({ + * abc123: { + * metas: [ + * { phx_ref: '2', phx_ref_prev: '1' user_id: 1 }, + * { phx_ref: '3', user_id: 2 } + * ] + * } + * }) + * + * @internal + */ + static transformState(state) { + state = this.cloneDeep(state); + return Object.getOwnPropertyNames(state).reduce((newState, key) => { + const presences = state[key]; + if ("metas" in presences) { + newState[key] = presences.metas.map((presence) => { + presence["presence_ref"] = presence["phx_ref"]; + delete presence["phx_ref"]; + delete presence["phx_ref_prev"]; + return presence; + }); + } else { + newState[key] = presences; + } + return newState; + }, {}); + } + /** @internal */ + static cloneDeep(obj) { + return JSON.parse(JSON.stringify(obj)); + } + /** @internal */ + onJoin(callback) { + this.caller.onJoin = callback; + } + /** @internal */ + onLeave(callback) { + this.caller.onLeave = callback; + } + /** @internal */ + onSync(callback) { + this.caller.onSync = callback; + } + /** @internal */ + inPendingSyncState() { + return !this.joinRef || this.joinRef !== this.channel._joinRef(); + } + }; + exports.default = RealtimePresence2; + } + }); + + // node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.js + var require_RealtimeChannel = __commonJS({ + "node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.REALTIME_CHANNEL_STATES = exports.REALTIME_SUBSCRIBE_STATES = exports.REALTIME_LISTEN_TYPES = exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var constants_1 = require_constants2(); + var push_1 = tslib_1.__importDefault(require_push()); + var timer_1 = tslib_1.__importDefault(require_timer()); + var RealtimePresence_1 = tslib_1.__importDefault(require_RealtimePresence()); + var Transformers = tslib_1.__importStar(require_transformers()); + var transformers_1 = require_transformers(); + var REALTIME_POSTGRES_CHANGES_LISTEN_EVENT2; + (function(REALTIME_POSTGRES_CHANGES_LISTEN_EVENT3) { + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT3["ALL"] = "*"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT3["INSERT"] = "INSERT"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT3["UPDATE"] = "UPDATE"; + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT3["DELETE"] = "DELETE"; + })(REALTIME_POSTGRES_CHANGES_LISTEN_EVENT2 || (exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = REALTIME_POSTGRES_CHANGES_LISTEN_EVENT2 = {})); + var REALTIME_LISTEN_TYPES2; + (function(REALTIME_LISTEN_TYPES3) { + REALTIME_LISTEN_TYPES3["BROADCAST"] = "broadcast"; + REALTIME_LISTEN_TYPES3["PRESENCE"] = "presence"; + REALTIME_LISTEN_TYPES3["POSTGRES_CHANGES"] = "postgres_changes"; + REALTIME_LISTEN_TYPES3["SYSTEM"] = "system"; + })(REALTIME_LISTEN_TYPES2 || (exports.REALTIME_LISTEN_TYPES = REALTIME_LISTEN_TYPES2 = {})); + var REALTIME_SUBSCRIBE_STATES2; + (function(REALTIME_SUBSCRIBE_STATES3) { + REALTIME_SUBSCRIBE_STATES3["SUBSCRIBED"] = "SUBSCRIBED"; + REALTIME_SUBSCRIBE_STATES3["TIMED_OUT"] = "TIMED_OUT"; + REALTIME_SUBSCRIBE_STATES3["CLOSED"] = "CLOSED"; + REALTIME_SUBSCRIBE_STATES3["CHANNEL_ERROR"] = "CHANNEL_ERROR"; + })(REALTIME_SUBSCRIBE_STATES2 || (exports.REALTIME_SUBSCRIBE_STATES = REALTIME_SUBSCRIBE_STATES2 = {})); + exports.REALTIME_CHANNEL_STATES = constants_1.CHANNEL_STATES; + var RealtimeChannel2 = class _RealtimeChannel { + /** + * Creates a channel that can broadcast messages, sync presence, and listen to Postgres changes. + * + * The topic determines which realtime stream you are subscribing to. Config options let you + * enable acknowledgement for broadcasts, presence tracking, or private channels. + * + * @example + * ```ts + * import RealtimeClient from '@supabase/realtime-js' + * + * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', { + * params: { apikey: 'public-anon-key' }, + * }) + * const channel = new RealtimeChannel('realtime:public:messages', { config: {} }, client) + * ``` + */ + constructor(topic, params = { config: {} }, socket) { + var _a, _b; + this.topic = topic; + this.params = params; + this.socket = socket; + this.bindings = {}; + this.state = constants_1.CHANNEL_STATES.closed; + this.joinedOnce = false; + this.pushBuffer = []; + this.subTopic = topic.replace(/^realtime:/i, ""); + this.params.config = Object.assign({ + broadcast: { ack: false, self: false }, + presence: { key: "", enabled: false }, + private: false + }, params.config); + this.timeout = this.socket.timeout; + this.joinPush = new push_1.default(this, constants_1.CHANNEL_EVENTS.join, this.params, this.timeout); + this.rejoinTimer = new timer_1.default(() => this._rejoinUntilConnected(), this.socket.reconnectAfterMs); + this.joinPush.receive("ok", () => { + this.state = constants_1.CHANNEL_STATES.joined; + this.rejoinTimer.reset(); + this.pushBuffer.forEach((pushEvent) => pushEvent.send()); + this.pushBuffer = []; + }); + this._onClose(() => { + this.rejoinTimer.reset(); + this.socket.log("channel", `close ${this.topic} ${this._joinRef()}`); + this.state = constants_1.CHANNEL_STATES.closed; + this.socket._remove(this); + }); + this._onError((reason) => { + if (this._isLeaving() || this._isClosed()) { + return; + } + this.socket.log("channel", `error ${this.topic}`, reason); + this.state = constants_1.CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this.joinPush.receive("timeout", () => { + if (!this._isJoining()) { + return; + } + this.socket.log("channel", `timeout ${this.topic}`, this.joinPush.timeout); + this.state = constants_1.CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this.joinPush.receive("error", (reason) => { + if (this._isLeaving() || this._isClosed()) { + return; + } + this.socket.log("channel", `error ${this.topic}`, reason); + this.state = constants_1.CHANNEL_STATES.errored; + this.rejoinTimer.scheduleTimeout(); + }); + this._on(constants_1.CHANNEL_EVENTS.reply, {}, (payload, ref) => { + this._trigger(this._replyEventName(ref), payload); + }); + this.presence = new RealtimePresence_1.default(this); + this.broadcastEndpointURL = (0, transformers_1.httpEndpointURL)(this.socket.endPoint); + this.private = this.params.config.private || false; + if (!this.private && ((_b = (_a = this.params.config) === null || _a === void 0 ? void 0 : _a.broadcast) === null || _b === void 0 ? void 0 : _b.replay)) { + throw `tried to use replay on public channel '${this.topic}'. It must be a private channel.`; + } + } + /** Subscribe registers your client with the server */ + subscribe(callback, timeout = this.timeout) { + var _a, _b, _c; + if (!this.socket.isConnected()) { + this.socket.connect(); + } + if (this.state == constants_1.CHANNEL_STATES.closed) { + const { config: { broadcast, presence, private: isPrivate } } = this.params; + const postgres_changes = (_b = (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.map((r2) => r2.filter)) !== null && _b !== void 0 ? _b : []; + const presence_enabled = !!this.bindings[REALTIME_LISTEN_TYPES2.PRESENCE] && this.bindings[REALTIME_LISTEN_TYPES2.PRESENCE].length > 0 || ((_c = this.params.config.presence) === null || _c === void 0 ? void 0 : _c.enabled) === true; + const accessTokenPayload = {}; + const config = { + broadcast, + presence: Object.assign(Object.assign({}, presence), { enabled: presence_enabled }), + postgres_changes, + private: isPrivate + }; + if (this.socket.accessTokenValue) { + accessTokenPayload.access_token = this.socket.accessTokenValue; + } + this._onError((e2) => callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES2.CHANNEL_ERROR, e2)); + this._onClose(() => callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES2.CLOSED)); + this.updateJoinPayload(Object.assign({ config }, accessTokenPayload)); + this.joinedOnce = true; + this._rejoin(timeout); + this.joinPush.receive("ok", async ({ postgres_changes: postgres_changes2 }) => { + var _a2; + if (!this.socket._isManualToken()) { + this.socket.setAuth(); + } + if (postgres_changes2 === void 0) { + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES2.SUBSCRIBED); + return; + } else { + const clientPostgresBindings = this.bindings.postgres_changes; + const bindingsLen = (_a2 = clientPostgresBindings === null || clientPostgresBindings === void 0 ? void 0 : clientPostgresBindings.length) !== null && _a2 !== void 0 ? _a2 : 0; + const newPostgresBindings = []; + for (let i2 = 0; i2 < bindingsLen; i2++) { + const clientPostgresBinding = clientPostgresBindings[i2]; + const { filter: { event, schema: schema4, table, filter } } = clientPostgresBinding; + const serverPostgresFilter = postgres_changes2 && postgres_changes2[i2]; + if (serverPostgresFilter && serverPostgresFilter.event === event && _RealtimeChannel.isFilterValueEqual(serverPostgresFilter.schema, schema4) && _RealtimeChannel.isFilterValueEqual(serverPostgresFilter.table, table) && _RealtimeChannel.isFilterValueEqual(serverPostgresFilter.filter, filter)) { + newPostgresBindings.push(Object.assign(Object.assign({}, clientPostgresBinding), { id: serverPostgresFilter.id })); + } else { + this.unsubscribe(); + this.state = constants_1.CHANNEL_STATES.errored; + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES2.CHANNEL_ERROR, new Error("mismatch between server and client bindings for postgres changes")); + return; + } + } + this.bindings.postgres_changes = newPostgresBindings; + callback && callback(REALTIME_SUBSCRIBE_STATES2.SUBSCRIBED); + return; + } + }).receive("error", (error) => { + this.state = constants_1.CHANNEL_STATES.errored; + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES2.CHANNEL_ERROR, new Error(JSON.stringify(Object.values(error).join(", ") || "error"))); + return; + }).receive("timeout", () => { + callback === null || callback === void 0 ? void 0 : callback(REALTIME_SUBSCRIBE_STATES2.TIMED_OUT); + return; + }); + } + return this; + } + /** + * Returns the current presence state for this channel. + * + * The shape is a map keyed by presence key (for example a user id) where each entry contains the + * tracked metadata for that user. + */ + presenceState() { + return this.presence.state; + } + /** + * Sends the supplied payload to the presence tracker so other subscribers can see that this + * client is online. Use `untrack` to stop broadcasting presence for the same key. + */ + async track(payload, opts = {}) { + return await this.send({ + type: "presence", + event: "track", + payload + }, opts.timeout || this.timeout); + } + /** + * Removes the current presence state for this client. + */ + async untrack(opts = {}) { + return await this.send({ + type: "presence", + event: "untrack" + }, opts); + } + on(type, filter, callback) { + if (this.state === constants_1.CHANNEL_STATES.joined && type === REALTIME_LISTEN_TYPES2.PRESENCE) { + this.socket.log("channel", `resubscribe to ${this.topic} due to change in presence callbacks on joined channel`); + this.unsubscribe().then(async () => await this.subscribe()); + } + return this._on(type, filter, callback); + } + /** + * Sends a broadcast message explicitly via REST API. + * + * This method always uses the REST API endpoint regardless of WebSocket connection state. + * Useful when you want to guarantee REST delivery or when gradually migrating from implicit REST fallback. + * + * @param event The name of the broadcast event + * @param payload Payload to be sent (required) + * @param opts Options including timeout + * @returns Promise resolving to object with success status, and error details if failed + */ + async httpSend(event, payload, opts = {}) { + var _a; + const authorization = this.socket.accessTokenValue ? `Bearer ${this.socket.accessTokenValue}` : ""; + if (payload === void 0 || payload === null) { + return Promise.reject("Payload is required for httpSend()"); + } + const options = { + method: "POST", + headers: { + Authorization: authorization, + apikey: this.socket.apiKey ? this.socket.apiKey : "", + "Content-Type": "application/json" + }, + body: JSON.stringify({ + messages: [ + { + topic: this.subTopic, + event, + payload, + private: this.private + } + ] + }) + }; + const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a = opts.timeout) !== null && _a !== void 0 ? _a : this.timeout); + if (response.status === 202) { + return { success: true }; + } + let errorMessage = response.statusText; + try { + const errorBody = await response.json(); + errorMessage = errorBody.error || errorBody.message || errorMessage; + } catch (_b) { + } + return Promise.reject(new Error(errorMessage)); + } + /** + * Sends a message into the channel. + * + * @param args Arguments to send to channel + * @param args.type The type of event to send + * @param args.event The name of the event being sent + * @param args.payload Payload to be sent + * @param opts Options to be used during the send process + */ + async send(args, opts = {}) { + var _a, _b; + if (!this._canPush() && args.type === "broadcast") { + console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery."); + const { event, payload: endpoint_payload } = args; + const authorization = this.socket.accessTokenValue ? `Bearer ${this.socket.accessTokenValue}` : ""; + const options = { + method: "POST", + headers: { + Authorization: authorization, + apikey: this.socket.apiKey ? this.socket.apiKey : "", + "Content-Type": "application/json" + }, + body: JSON.stringify({ + messages: [ + { + topic: this.subTopic, + event, + payload: endpoint_payload, + private: this.private + } + ] + }) + }; + try { + const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a = opts.timeout) !== null && _a !== void 0 ? _a : this.timeout); + await ((_b = response.body) === null || _b === void 0 ? void 0 : _b.cancel()); + return response.ok ? "ok" : "error"; + } catch (error) { + if (error.name === "AbortError") { + return "timed out"; + } else { + return "error"; + } + } + } else { + return new Promise((resolve) => { + var _a2, _b2, _c; + const push = this._push(args.type, args, opts.timeout || this.timeout); + if (args.type === "broadcast" && !((_c = (_b2 = (_a2 = this.params) === null || _a2 === void 0 ? void 0 : _a2.config) === null || _b2 === void 0 ? void 0 : _b2.broadcast) === null || _c === void 0 ? void 0 : _c.ack)) { + resolve("ok"); + } + push.receive("ok", () => resolve("ok")); + push.receive("error", () => resolve("error")); + push.receive("timeout", () => resolve("timed out")); + }); + } + } + /** + * Updates the payload that will be sent the next time the channel joins (reconnects). + * Useful for rotating access tokens or updating config without re-creating the channel. + */ + updateJoinPayload(payload) { + this.joinPush.updatePayload(payload); + } + /** + * Leaves the channel. + * + * Unsubscribes from server events, and instructs channel to terminate on server. + * Triggers onClose() hooks. + * + * To receive leave acknowledgements, use the a `receive` hook to bind to the server ack, ie: + * channel.unsubscribe().receive("ok", () => alert("left!") ) + */ + unsubscribe(timeout = this.timeout) { + this.state = constants_1.CHANNEL_STATES.leaving; + const onClose = () => { + this.socket.log("channel", `leave ${this.topic}`); + this._trigger(constants_1.CHANNEL_EVENTS.close, "leave", this._joinRef()); + }; + this.joinPush.destroy(); + let leavePush = null; + return new Promise((resolve) => { + leavePush = new push_1.default(this, constants_1.CHANNEL_EVENTS.leave, {}, timeout); + leavePush.receive("ok", () => { + onClose(); + resolve("ok"); + }).receive("timeout", () => { + onClose(); + resolve("timed out"); + }).receive("error", () => { + resolve("error"); + }); + leavePush.send(); + if (!this._canPush()) { + leavePush.trigger("ok", {}); + } + }).finally(() => { + leavePush === null || leavePush === void 0 ? void 0 : leavePush.destroy(); + }); + } + /** + * Teardown the channel. + * + * Destroys and stops related timers. + */ + teardown() { + this.pushBuffer.forEach((push) => push.destroy()); + this.pushBuffer = []; + this.rejoinTimer.reset(); + this.joinPush.destroy(); + this.state = constants_1.CHANNEL_STATES.closed; + this.bindings = {}; + } + /** @internal */ + async _fetchWithTimeout(url, options, timeout) { + const controller = new AbortController(); + const id = setTimeout(() => controller.abort(), timeout); + const response = await this.socket.fetch(url, Object.assign(Object.assign({}, options), { signal: controller.signal })); + clearTimeout(id); + return response; + } + /** @internal */ + _push(event, payload, timeout = this.timeout) { + if (!this.joinedOnce) { + throw `tried to push '${event}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`; + } + let pushEvent = new push_1.default(this, event, payload, timeout); + if (this._canPush()) { + pushEvent.send(); + } else { + this._addToPushBuffer(pushEvent); + } + return pushEvent; + } + /** @internal */ + _addToPushBuffer(pushEvent) { + pushEvent.startTimeout(); + this.pushBuffer.push(pushEvent); + if (this.pushBuffer.length > constants_1.MAX_PUSH_BUFFER_SIZE) { + const removedPush = this.pushBuffer.shift(); + if (removedPush) { + removedPush.destroy(); + this.socket.log("channel", `discarded push due to buffer overflow: ${removedPush.event}`, removedPush.payload); + } + } + } + /** + * Overridable message hook + * + * Receives all events for specialized message handling before dispatching to the channel callbacks. + * Must return the payload, modified or unmodified. + * + * @internal + */ + _onMessage(_event, payload, _ref) { + return payload; + } + /** @internal */ + _isMember(topic) { + return this.topic === topic; + } + /** @internal */ + _joinRef() { + return this.joinPush.ref; + } + /** @internal */ + _trigger(type, payload, ref) { + var _a, _b; + const typeLower = type.toLocaleLowerCase(); + const { close, error, leave, join: join2 } = constants_1.CHANNEL_EVENTS; + const events = [close, error, leave, join2]; + if (ref && events.indexOf(typeLower) >= 0 && ref !== this._joinRef()) { + return; + } + let handledPayload = this._onMessage(typeLower, payload, ref); + if (payload && !handledPayload) { + throw "channel onMessage callbacks must return the payload, modified or unmodified"; + } + if (["insert", "update", "delete"].includes(typeLower)) { + (_a = this.bindings.postgres_changes) === null || _a === void 0 ? void 0 : _a.filter((bind2) => { + var _a2, _b2, _c; + return ((_a2 = bind2.filter) === null || _a2 === void 0 ? void 0 : _a2.event) === "*" || ((_c = (_b2 = bind2.filter) === null || _b2 === void 0 ? void 0 : _b2.event) === null || _c === void 0 ? void 0 : _c.toLocaleLowerCase()) === typeLower; + }).map((bind2) => bind2.callback(handledPayload, ref)); + } else { + (_b = this.bindings[typeLower]) === null || _b === void 0 ? void 0 : _b.filter((bind2) => { + var _a2, _b2, _c, _d, _e2, _f; + if (["broadcast", "presence", "postgres_changes"].includes(typeLower)) { + if ("id" in bind2) { + const bindId = bind2.id; + const bindEvent = (_a2 = bind2.filter) === null || _a2 === void 0 ? void 0 : _a2.event; + return bindId && ((_b2 = payload.ids) === null || _b2 === void 0 ? void 0 : _b2.includes(bindId)) && (bindEvent === "*" || (bindEvent === null || bindEvent === void 0 ? void 0 : bindEvent.toLocaleLowerCase()) === ((_c = payload.data) === null || _c === void 0 ? void 0 : _c.type.toLocaleLowerCase())); + } else { + const bindEvent = (_e2 = (_d = bind2 === null || bind2 === void 0 ? void 0 : bind2.filter) === null || _d === void 0 ? void 0 : _d.event) === null || _e2 === void 0 ? void 0 : _e2.toLocaleLowerCase(); + return bindEvent === "*" || bindEvent === ((_f = payload === null || payload === void 0 ? void 0 : payload.event) === null || _f === void 0 ? void 0 : _f.toLocaleLowerCase()); + } + } else { + return bind2.type.toLocaleLowerCase() === typeLower; + } + }).map((bind2) => { + if (typeof handledPayload === "object" && "ids" in handledPayload) { + const postgresChanges = handledPayload.data; + const { schema: schema4, table, commit_timestamp, type: type2, errors: errors2 } = postgresChanges; + const enrichedPayload = { + schema: schema4, + table, + commit_timestamp, + eventType: type2, + new: {}, + old: {}, + errors: errors2 + }; + handledPayload = Object.assign(Object.assign({}, enrichedPayload), this._getPayloadRecords(postgresChanges)); + } + bind2.callback(handledPayload, ref); + }); + } + } + /** @internal */ + _isClosed() { + return this.state === constants_1.CHANNEL_STATES.closed; + } + /** @internal */ + _isJoined() { + return this.state === constants_1.CHANNEL_STATES.joined; + } + /** @internal */ + _isJoining() { + return this.state === constants_1.CHANNEL_STATES.joining; + } + /** @internal */ + _isLeaving() { + return this.state === constants_1.CHANNEL_STATES.leaving; + } + /** @internal */ + _replyEventName(ref) { + return `chan_reply_${ref}`; + } + /** @internal */ + _on(type, filter, callback) { + const typeLower = type.toLocaleLowerCase(); + const binding = { + type: typeLower, + filter, + callback + }; + if (this.bindings[typeLower]) { + this.bindings[typeLower].push(binding); + } else { + this.bindings[typeLower] = [binding]; + } + return this; + } + /** @internal */ + _off(type, filter) { + const typeLower = type.toLocaleLowerCase(); + if (this.bindings[typeLower]) { + this.bindings[typeLower] = this.bindings[typeLower].filter((bind2) => { + var _a; + return !(((_a = bind2.type) === null || _a === void 0 ? void 0 : _a.toLocaleLowerCase()) === typeLower && _RealtimeChannel.isEqual(bind2.filter, filter)); + }); + } + return this; + } + /** @internal */ + static isEqual(obj1, obj2) { + if (Object.keys(obj1).length !== Object.keys(obj2).length) { + return false; + } + for (const k3 in obj1) { + if (obj1[k3] !== obj2[k3]) { + return false; + } + } + return true; + } + /** + * Compares two optional filter values for equality. + * Treats undefined, null, and empty string as equivalent empty values. + * @internal + */ + static isFilterValueEqual(serverValue, clientValue) { + const normalizedServer = serverValue !== null && serverValue !== void 0 ? serverValue : void 0; + const normalizedClient = clientValue !== null && clientValue !== void 0 ? clientValue : void 0; + return normalizedServer === normalizedClient; + } + /** @internal */ + _rejoinUntilConnected() { + this.rejoinTimer.scheduleTimeout(); + if (this.socket.isConnected()) { + this._rejoin(); + } + } + /** + * Registers a callback that will be executed when the channel closes. + * + * @internal + */ + _onClose(callback) { + this._on(constants_1.CHANNEL_EVENTS.close, {}, callback); + } + /** + * Registers a callback that will be executed when the channel encounteres an error. + * + * @internal + */ + _onError(callback) { + this._on(constants_1.CHANNEL_EVENTS.error, {}, (reason) => callback(reason)); + } + /** + * Returns `true` if the socket is connected and the channel has been joined. + * + * @internal + */ + _canPush() { + return this.socket.isConnected() && this._isJoined(); + } + /** @internal */ + _rejoin(timeout = this.timeout) { + if (this._isLeaving()) { + return; + } + this.socket._leaveOpenTopic(this.topic); + this.state = constants_1.CHANNEL_STATES.joining; + this.joinPush.resend(timeout); + } + /** @internal */ + _getPayloadRecords(payload) { + const records = { + new: {}, + old: {} + }; + if (payload.type === "INSERT" || payload.type === "UPDATE") { + records.new = Transformers.convertChangeData(payload.columns, payload.record); + } + if (payload.type === "UPDATE" || payload.type === "DELETE") { + records.old = Transformers.convertChangeData(payload.columns, payload.old_record); + } + return records; + } + }; + exports.default = RealtimeChannel2; + } + }); + + // node_modules/@supabase/realtime-js/dist/main/RealtimeClient.js + var require_RealtimeClient = __commonJS({ + "node_modules/@supabase/realtime-js/dist/main/RealtimeClient.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var websocket_factory_1 = tslib_1.__importDefault(require_websocket_factory()); + var constants_1 = require_constants2(); + var serializer_1 = tslib_1.__importDefault(require_serializer()); + var timer_1 = tslib_1.__importDefault(require_timer()); + var transformers_1 = require_transformers(); + var RealtimeChannel_1 = tslib_1.__importDefault(require_RealtimeChannel()); + var noop = () => { + }; + var CONNECTION_TIMEOUTS = { + HEARTBEAT_INTERVAL: 25e3, + RECONNECT_DELAY: 10, + HEARTBEAT_TIMEOUT_FALLBACK: 100 + }; + var RECONNECT_INTERVALS = [1e3, 2e3, 5e3, 1e4]; + var DEFAULT_RECONNECT_FALLBACK = 1e4; + var WORKER_SCRIPT = ` + addEventListener("message", (e) => { + if (e.data.event === "start") { + setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); + } + });`; + var RealtimeClient2 = class { + /** + * Initializes the Socket. + * + * @param endPoint The string WebSocket endpoint, ie, "ws://example.com/socket", "wss://example.com", "/socket" (inherited host & protocol) + * @param httpEndpoint The string HTTP endpoint, ie, "https://example.com", "/" (inherited host & protocol) + * @param options.transport The Websocket Transport, for example WebSocket. This can be a custom implementation + * @param options.timeout The default timeout in milliseconds to trigger push timeouts. + * @param options.params The optional params to pass when connecting. + * @param options.headers Deprecated: headers cannot be set on websocket connections and this option will be removed in the future. + * @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message. + * @param options.heartbeatCallback The optional function to handle heartbeat status. + * @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) } + * @param options.logLevel Sets the log level for Realtime + * @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload)) + * @param options.decode The function to decode incoming messages. Defaults to Serializer's decode. + * @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off. + * @param options.worker Use Web Worker to set a side flow. Defaults to false. + * @param options.workerUrl The URL of the worker script. Defaults to https://realtime.supabase.com/worker.js that includes a heartbeat event call to keep the connection alive. + * @example + * ```ts + * import RealtimeClient from '@supabase/realtime-js' + * + * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', { + * params: { apikey: 'public-anon-key' }, + * }) + * client.connect() + * ``` + */ + constructor(endPoint, options) { + var _a; + this.accessTokenValue = null; + this.apiKey = null; + this._manuallySetToken = false; + this.channels = new Array(); + this.endPoint = ""; + this.httpEndpoint = ""; + this.headers = {}; + this.params = {}; + this.timeout = constants_1.DEFAULT_TIMEOUT; + this.transport = null; + this.heartbeatIntervalMs = CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL; + this.heartbeatTimer = void 0; + this.pendingHeartbeatRef = null; + this.heartbeatCallback = noop; + this.ref = 0; + this.reconnectTimer = null; + this.vsn = constants_1.DEFAULT_VSN; + this.logger = noop; + this.conn = null; + this.sendBuffer = []; + this.serializer = new serializer_1.default(); + this.stateChangeCallbacks = { + open: [], + close: [], + error: [], + message: [] + }; + this.accessToken = null; + this._connectionState = "disconnected"; + this._wasManualDisconnect = false; + this._authPromise = null; + this._resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); + }; + if (!((_a = options === null || options === void 0 ? void 0 : options.params) === null || _a === void 0 ? void 0 : _a.apikey)) { + throw new Error("API key is required to connect to Realtime"); + } + this.apiKey = options.params.apikey; + this.endPoint = `${endPoint}/${constants_1.TRANSPORTS.websocket}`; + this.httpEndpoint = (0, transformers_1.httpEndpointURL)(endPoint); + this._initializeOptions(options); + this._setupReconnectionTimer(); + this.fetch = this._resolveFetch(options === null || options === void 0 ? void 0 : options.fetch); + } + /** + * Connects the socket, unless already connected. + */ + connect() { + if (this.isConnecting() || this.isDisconnecting() || this.conn !== null && this.isConnected()) { + return; + } + this._setConnectionState("connecting"); + if (this.accessToken && !this._authPromise) { + this._setAuthSafely("connect"); + } + if (this.transport) { + this.conn = new this.transport(this.endpointURL()); + } else { + try { + this.conn = websocket_factory_1.default.createWebSocket(this.endpointURL()); + } catch (error) { + this._setConnectionState("disconnected"); + const errorMessage = error.message; + if (errorMessage.includes("Node.js")) { + throw new Error(`${errorMessage} + +To use Realtime in Node.js, you need to provide a WebSocket implementation: + +Option 1: Use Node.js 22+ which has native WebSocket support +Option 2: Install and provide the "ws" package: + + npm install ws + + import ws from "ws" + const client = new RealtimeClient(url, { + ...options, + transport: ws + })`); + } + throw new Error(`WebSocket not available: ${errorMessage}`); + } + } + this._setupConnectionHandlers(); + } + /** + * Returns the URL of the websocket. + * @returns string The URL of the websocket. + */ + endpointURL() { + return this._appendParams(this.endPoint, Object.assign({}, this.params, { vsn: this.vsn })); + } + /** + * Disconnects the socket. + * + * @param code A numeric status code to send on disconnect. + * @param reason A custom reason for the disconnect. + */ + disconnect(code, reason) { + if (this.isDisconnecting()) { + return; + } + this._setConnectionState("disconnecting", true); + if (this.conn) { + const fallbackTimer = setTimeout(() => { + this._setConnectionState("disconnected"); + }, 100); + this.conn.onclose = () => { + clearTimeout(fallbackTimer); + this._setConnectionState("disconnected"); + }; + if (typeof this.conn.close === "function") { + if (code) { + this.conn.close(code, reason !== null && reason !== void 0 ? reason : ""); + } else { + this.conn.close(); + } + } + this._teardownConnection(); + } else { + this._setConnectionState("disconnected"); + } + } + /** + * Returns all created channels + */ + getChannels() { + return this.channels; + } + /** + * Unsubscribes and removes a single channel + * @param channel A RealtimeChannel instance + */ + async removeChannel(channel) { + const status = await channel.unsubscribe(); + if (this.channels.length === 0) { + this.disconnect(); + } + return status; + } + /** + * Unsubscribes and removes all channels + */ + async removeAllChannels() { + const values_1 = await Promise.all(this.channels.map((channel) => channel.unsubscribe())); + this.channels = []; + this.disconnect(); + return values_1; + } + /** + * Logs the message. + * + * For customized logging, `this.logger` can be overridden. + */ + log(kind, msg, data) { + this.logger(kind, msg, data); + } + /** + * Returns the current state of the socket. + */ + connectionState() { + switch (this.conn && this.conn.readyState) { + case constants_1.SOCKET_STATES.connecting: + return constants_1.CONNECTION_STATE.Connecting; + case constants_1.SOCKET_STATES.open: + return constants_1.CONNECTION_STATE.Open; + case constants_1.SOCKET_STATES.closing: + return constants_1.CONNECTION_STATE.Closing; + default: + return constants_1.CONNECTION_STATE.Closed; + } + } + /** + * Returns `true` is the connection is open. + */ + isConnected() { + return this.connectionState() === constants_1.CONNECTION_STATE.Open; + } + /** + * Returns `true` if the connection is currently connecting. + */ + isConnecting() { + return this._connectionState === "connecting"; + } + /** + * Returns `true` if the connection is currently disconnecting. + */ + isDisconnecting() { + return this._connectionState === "disconnecting"; + } + /** + * Creates (or reuses) a {@link RealtimeChannel} for the provided topic. + * + * Topics are automatically prefixed with `realtime:` to match the Realtime service. + * If a channel with the same topic already exists it will be returned instead of creating + * a duplicate connection. + */ + channel(topic, params = { config: {} }) { + const realtimeTopic = `realtime:${topic}`; + const exists = this.getChannels().find((c3) => c3.topic === realtimeTopic); + if (!exists) { + const chan = new RealtimeChannel_1.default(`realtime:${topic}`, params, this); + this.channels.push(chan); + return chan; + } else { + return exists; + } + } + /** + * Push out a message if the socket is connected. + * + * If the socket is not connected, the message gets enqueued within a local buffer, and sent out when a connection is next established. + */ + push(data) { + const { topic, event, payload, ref } = data; + const callback = () => { + this.encode(data, (result) => { + var _a; + (_a = this.conn) === null || _a === void 0 ? void 0 : _a.send(result); + }); + }; + this.log("push", `${topic} ${event} (${ref})`, payload); + if (this.isConnected()) { + callback(); + } else { + this.sendBuffer.push(callback); + } + } + /** + * Sets the JWT access token used for channel subscription authorization and Realtime RLS. + * + * If param is null it will use the `accessToken` callback function or the token set on the client. + * + * On callback used, it will set the value of the token internal to the client. + * + * When a token is explicitly provided, it will be preserved across channel operations + * (including removeChannel and resubscribe). The `accessToken` callback will not be + * invoked until `setAuth()` is called without arguments. + * + * @param token A JWT string to override the token set on the client. + * + * @example + * // Use a manual token (preserved across resubscribes, ignores accessToken callback) + * client.realtime.setAuth('my-custom-jwt') + * + * // Switch back to using the accessToken callback + * client.realtime.setAuth() + */ + async setAuth(token = null) { + this._authPromise = this._performAuth(token); + try { + await this._authPromise; + } finally { + this._authPromise = null; + } + } + /** + * Returns true if the current access token was explicitly set via setAuth(token), + * false if it was obtained via the accessToken callback. + * @internal + */ + _isManualToken() { + return this._manuallySetToken; + } + /** + * Sends a heartbeat message if the socket is connected. + */ + async sendHeartbeat() { + var _a; + if (!this.isConnected()) { + try { + this.heartbeatCallback("disconnected"); + } catch (e2) { + this.log("error", "error in heartbeat callback", e2); + } + return; + } + if (this.pendingHeartbeatRef) { + this.pendingHeartbeatRef = null; + this.log("transport", "heartbeat timeout. Attempting to re-establish connection"); + try { + this.heartbeatCallback("timeout"); + } catch (e2) { + this.log("error", "error in heartbeat callback", e2); + } + this._wasManualDisconnect = false; + (_a = this.conn) === null || _a === void 0 ? void 0 : _a.close(constants_1.WS_CLOSE_NORMAL, "heartbeat timeout"); + setTimeout(() => { + var _a2; + if (!this.isConnected()) { + (_a2 = this.reconnectTimer) === null || _a2 === void 0 ? void 0 : _a2.scheduleTimeout(); + } + }, CONNECTION_TIMEOUTS.HEARTBEAT_TIMEOUT_FALLBACK); + return; + } + this.pendingHeartbeatRef = this._makeRef(); + this.push({ + topic: "phoenix", + event: "heartbeat", + payload: {}, + ref: this.pendingHeartbeatRef + }); + try { + this.heartbeatCallback("sent"); + } catch (e2) { + this.log("error", "error in heartbeat callback", e2); + } + this._setAuthSafely("heartbeat"); + } + /** + * Sets a callback that receives lifecycle events for internal heartbeat messages. + * Useful for instrumenting connection health (e.g. sent/ok/timeout/disconnected). + */ + onHeartbeat(callback) { + this.heartbeatCallback = callback; + } + /** + * Flushes send buffer + */ + flushSendBuffer() { + if (this.isConnected() && this.sendBuffer.length > 0) { + this.sendBuffer.forEach((callback) => callback()); + this.sendBuffer = []; + } + } + /** + * Return the next message ref, accounting for overflows + * + * @internal + */ + _makeRef() { + let newRef = this.ref + 1; + if (newRef === this.ref) { + this.ref = 0; + } else { + this.ref = newRef; + } + return this.ref.toString(); + } + /** + * Unsubscribe from channels with the specified topic. + * + * @internal + */ + _leaveOpenTopic(topic) { + let dupChannel = this.channels.find((c3) => c3.topic === topic && (c3._isJoined() || c3._isJoining())); + if (dupChannel) { + this.log("transport", `leaving duplicate topic "${topic}"`); + dupChannel.unsubscribe(); + } + } + /** + * Removes a subscription from the socket. + * + * @param channel An open subscription. + * + * @internal + */ + _remove(channel) { + this.channels = this.channels.filter((c3) => c3.topic !== channel.topic); + } + /** @internal */ + _onConnMessage(rawMessage) { + this.decode(rawMessage.data, (msg) => { + if (msg.topic === "phoenix" && msg.event === "phx_reply") { + try { + this.heartbeatCallback(msg.payload.status === "ok" ? "ok" : "error"); + } catch (e2) { + this.log("error", "error in heartbeat callback", e2); + } + } + if (msg.ref && msg.ref === this.pendingHeartbeatRef) { + this.pendingHeartbeatRef = null; + } + const { topic, event, payload, ref } = msg; + const refString = ref ? `(${ref})` : ""; + const status = payload.status || ""; + this.log("receive", `${status} ${topic} ${event} ${refString}`.trim(), payload); + this.channels.filter((channel) => channel._isMember(topic)).forEach((channel) => channel._trigger(event, payload, ref)); + this._triggerStateCallbacks("message", msg); + }); + } + /** + * Clear specific timer + * @internal + */ + _clearTimer(timer) { + var _a; + if (timer === "heartbeat" && this.heartbeatTimer) { + clearInterval(this.heartbeatTimer); + this.heartbeatTimer = void 0; + } else if (timer === "reconnect") { + (_a = this.reconnectTimer) === null || _a === void 0 ? void 0 : _a.reset(); + } + } + /** + * Clear all timers + * @internal + */ + _clearAllTimers() { + this._clearTimer("heartbeat"); + this._clearTimer("reconnect"); + } + /** + * Setup connection handlers for WebSocket events + * @internal + */ + _setupConnectionHandlers() { + if (!this.conn) + return; + if ("binaryType" in this.conn) { + ; + this.conn.binaryType = "arraybuffer"; + } + this.conn.onopen = () => this._onConnOpen(); + this.conn.onerror = (error) => this._onConnError(error); + this.conn.onmessage = (event) => this._onConnMessage(event); + this.conn.onclose = (event) => this._onConnClose(event); + } + /** + * Teardown connection and cleanup resources + * @internal + */ + _teardownConnection() { + if (this.conn) { + if (this.conn.readyState === constants_1.SOCKET_STATES.open || this.conn.readyState === constants_1.SOCKET_STATES.connecting) { + try { + this.conn.close(); + } catch (e2) { + this.log("error", "Error closing connection", e2); + } + } + this.conn.onopen = null; + this.conn.onerror = null; + this.conn.onmessage = null; + this.conn.onclose = null; + this.conn = null; + } + this._clearAllTimers(); + this.channels.forEach((channel) => channel.teardown()); + } + /** @internal */ + _onConnOpen() { + this._setConnectionState("connected"); + this.log("transport", `connected to ${this.endpointURL()}`); + const authPromise = this._authPromise || (this.accessToken && !this.accessTokenValue ? this.setAuth() : Promise.resolve()); + authPromise.then(() => { + this.flushSendBuffer(); + }).catch((e2) => { + this.log("error", "error waiting for auth on connect", e2); + this.flushSendBuffer(); + }); + this._clearTimer("reconnect"); + if (!this.worker) { + this._startHeartbeat(); + } else { + if (!this.workerRef) { + this._startWorkerHeartbeat(); + } + } + this._triggerStateCallbacks("open"); + } + /** @internal */ + _startHeartbeat() { + this.heartbeatTimer && clearInterval(this.heartbeatTimer); + this.heartbeatTimer = setInterval(() => this.sendHeartbeat(), this.heartbeatIntervalMs); + } + /** @internal */ + _startWorkerHeartbeat() { + if (this.workerUrl) { + this.log("worker", `starting worker for from ${this.workerUrl}`); + } else { + this.log("worker", `starting default worker`); + } + const objectUrl = this._workerObjectUrl(this.workerUrl); + this.workerRef = new Worker(objectUrl); + this.workerRef.onerror = (error) => { + this.log("worker", "worker error", error.message); + this.workerRef.terminate(); + }; + this.workerRef.onmessage = (event) => { + if (event.data.event === "keepAlive") { + this.sendHeartbeat(); + } + }; + this.workerRef.postMessage({ + event: "start", + interval: this.heartbeatIntervalMs + }); + } + /** @internal */ + _onConnClose(event) { + var _a; + this._setConnectionState("disconnected"); + this.log("transport", "close", event); + this._triggerChanError(); + this._clearTimer("heartbeat"); + if (!this._wasManualDisconnect) { + (_a = this.reconnectTimer) === null || _a === void 0 ? void 0 : _a.scheduleTimeout(); + } + this._triggerStateCallbacks("close", event); + } + /** @internal */ + _onConnError(error) { + this._setConnectionState("disconnected"); + this.log("transport", `${error}`); + this._triggerChanError(); + this._triggerStateCallbacks("error", error); + } + /** @internal */ + _triggerChanError() { + this.channels.forEach((channel) => channel._trigger(constants_1.CHANNEL_EVENTS.error)); + } + /** @internal */ + _appendParams(url, params) { + if (Object.keys(params).length === 0) { + return url; + } + const prefix = url.match(/\?/) ? "&" : "?"; + const query = new URLSearchParams(params); + return `${url}${prefix}${query}`; + } + _workerObjectUrl(url) { + let result_url; + if (url) { + result_url = url; + } else { + const blob = new Blob([WORKER_SCRIPT], { type: "application/javascript" }); + result_url = URL.createObjectURL(blob); + } + return result_url; + } + /** + * Set connection state with proper state management + * @internal + */ + _setConnectionState(state, manual = false) { + this._connectionState = state; + if (state === "connecting") { + this._wasManualDisconnect = false; + } else if (state === "disconnecting") { + this._wasManualDisconnect = manual; + } + } + /** + * Perform the actual auth operation + * @internal + */ + async _performAuth(token = null) { + let tokenToSend; + let isManualToken = false; + if (token) { + tokenToSend = token; + isManualToken = true; + } else if (this.accessToken) { + try { + tokenToSend = await this.accessToken(); + } catch (e2) { + this.log("error", "Error fetching access token from callback", e2); + tokenToSend = this.accessTokenValue; + } + } else { + tokenToSend = this.accessTokenValue; + } + if (isManualToken) { + this._manuallySetToken = true; + } else if (this.accessToken) { + this._manuallySetToken = false; + } + if (this.accessTokenValue != tokenToSend) { + this.accessTokenValue = tokenToSend; + this.channels.forEach((channel) => { + const payload = { + access_token: tokenToSend, + version: constants_1.DEFAULT_VERSION + }; + tokenToSend && channel.updateJoinPayload(payload); + if (channel.joinedOnce && channel._isJoined()) { + channel._push(constants_1.CHANNEL_EVENTS.access_token, { + access_token: tokenToSend + }); + } + }); + } + } + /** + * Wait for any in-flight auth operations to complete + * @internal + */ + async _waitForAuthIfNeeded() { + if (this._authPromise) { + await this._authPromise; + } + } + /** + * Safely call setAuth with standardized error handling + * @internal + */ + _setAuthSafely(context = "general") { + if (!this._isManualToken()) { + this.setAuth().catch((e2) => { + this.log("error", `Error setting auth in ${context}`, e2); + }); + } + } + /** + * Trigger state change callbacks with proper error handling + * @internal + */ + _triggerStateCallbacks(event, data) { + try { + this.stateChangeCallbacks[event].forEach((callback) => { + try { + callback(data); + } catch (e2) { + this.log("error", `error in ${event} callback`, e2); + } + }); + } catch (e2) { + this.log("error", `error triggering ${event} callbacks`, e2); + } + } + /** + * Setup reconnection timer with proper configuration + * @internal + */ + _setupReconnectionTimer() { + this.reconnectTimer = new timer_1.default(async () => { + setTimeout(async () => { + await this._waitForAuthIfNeeded(); + if (!this.isConnected()) { + this.connect(); + } + }, CONNECTION_TIMEOUTS.RECONNECT_DELAY); + }, this.reconnectAfterMs); + } + /** + * Initialize client options with defaults + * @internal + */ + _initializeOptions(options) { + var _a, _b, _c, _d, _e2, _f, _g, _h, _j, _k, _l, _m; + this.transport = (_a = options === null || options === void 0 ? void 0 : options.transport) !== null && _a !== void 0 ? _a : null; + this.timeout = (_b = options === null || options === void 0 ? void 0 : options.timeout) !== null && _b !== void 0 ? _b : constants_1.DEFAULT_TIMEOUT; + this.heartbeatIntervalMs = (_c = options === null || options === void 0 ? void 0 : options.heartbeatIntervalMs) !== null && _c !== void 0 ? _c : CONNECTION_TIMEOUTS.HEARTBEAT_INTERVAL; + this.worker = (_d = options === null || options === void 0 ? void 0 : options.worker) !== null && _d !== void 0 ? _d : false; + this.accessToken = (_e2 = options === null || options === void 0 ? void 0 : options.accessToken) !== null && _e2 !== void 0 ? _e2 : null; + this.heartbeatCallback = (_f = options === null || options === void 0 ? void 0 : options.heartbeatCallback) !== null && _f !== void 0 ? _f : noop; + this.vsn = (_g = options === null || options === void 0 ? void 0 : options.vsn) !== null && _g !== void 0 ? _g : constants_1.DEFAULT_VSN; + if (options === null || options === void 0 ? void 0 : options.params) + this.params = options.params; + if (options === null || options === void 0 ? void 0 : options.logger) + this.logger = options.logger; + if ((options === null || options === void 0 ? void 0 : options.logLevel) || (options === null || options === void 0 ? void 0 : options.log_level)) { + this.logLevel = options.logLevel || options.log_level; + this.params = Object.assign(Object.assign({}, this.params), { log_level: this.logLevel }); + } + this.reconnectAfterMs = (_h = options === null || options === void 0 ? void 0 : options.reconnectAfterMs) !== null && _h !== void 0 ? _h : ((tries) => { + return RECONNECT_INTERVALS[tries - 1] || DEFAULT_RECONNECT_FALLBACK; + }); + switch (this.vsn) { + case constants_1.VSN_1_0_0: + this.encode = (_j = options === null || options === void 0 ? void 0 : options.encode) !== null && _j !== void 0 ? _j : ((payload, callback) => { + return callback(JSON.stringify(payload)); + }); + this.decode = (_k = options === null || options === void 0 ? void 0 : options.decode) !== null && _k !== void 0 ? _k : ((payload, callback) => { + return callback(JSON.parse(payload)); + }); + break; + case constants_1.VSN_2_0_0: + this.encode = (_l = options === null || options === void 0 ? void 0 : options.encode) !== null && _l !== void 0 ? _l : this.serializer.encode.bind(this.serializer); + this.decode = (_m = options === null || options === void 0 ? void 0 : options.decode) !== null && _m !== void 0 ? _m : this.serializer.decode.bind(this.serializer); + break; + default: + throw new Error(`Unsupported serializer version: ${this.vsn}`); + } + if (this.worker) { + if (typeof window !== "undefined" && !window.Worker) { + throw new Error("Web Worker is not supported"); + } + this.workerUrl = options === null || options === void 0 ? void 0 : options.workerUrl; + } + } + }; + exports.default = RealtimeClient2; + } + }); + + // node_modules/@supabase/realtime-js/dist/main/index.js + var require_main2 = __commonJS({ + "node_modules/@supabase/realtime-js/dist/main/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.WebSocketFactory = exports.REALTIME_CHANNEL_STATES = exports.REALTIME_SUBSCRIBE_STATES = exports.REALTIME_PRESENCE_LISTEN_EVENTS = exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = exports.REALTIME_LISTEN_TYPES = exports.RealtimeClient = exports.RealtimeChannel = exports.RealtimePresence = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var RealtimeClient_1 = tslib_1.__importDefault(require_RealtimeClient()); + exports.RealtimeClient = RealtimeClient_1.default; + var RealtimeChannel_1 = tslib_1.__importStar(require_RealtimeChannel()); + exports.RealtimeChannel = RealtimeChannel_1.default; + Object.defineProperty(exports, "REALTIME_LISTEN_TYPES", { enumerable: true, get: function() { + return RealtimeChannel_1.REALTIME_LISTEN_TYPES; + } }); + Object.defineProperty(exports, "REALTIME_POSTGRES_CHANGES_LISTEN_EVENT", { enumerable: true, get: function() { + return RealtimeChannel_1.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT; + } }); + Object.defineProperty(exports, "REALTIME_SUBSCRIBE_STATES", { enumerable: true, get: function() { + return RealtimeChannel_1.REALTIME_SUBSCRIBE_STATES; + } }); + Object.defineProperty(exports, "REALTIME_CHANNEL_STATES", { enumerable: true, get: function() { + return RealtimeChannel_1.REALTIME_CHANNEL_STATES; + } }); + var RealtimePresence_1 = tslib_1.__importStar(require_RealtimePresence()); + exports.RealtimePresence = RealtimePresence_1.default; + Object.defineProperty(exports, "REALTIME_PRESENCE_LISTEN_EVENTS", { enumerable: true, get: function() { + return RealtimePresence_1.REALTIME_PRESENCE_LISTEN_EVENTS; + } }); + var websocket_factory_1 = tslib_1.__importDefault(require_websocket_factory()); + exports.WebSocketFactory = websocket_factory_1.default; + } + }); + + // node_modules/@supabase/storage-js/dist/main/lib/errors.js + var require_errors = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/errors.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.StorageUnknownError = exports.StorageApiError = exports.StorageError = void 0; + exports.isStorageError = isStorageError; + var StorageError = class extends Error { + constructor(message) { + super(message); + this.__isStorageError = true; + this.name = "StorageError"; + } + }; + exports.StorageError = StorageError; + function isStorageError(error) { + return typeof error === "object" && error !== null && "__isStorageError" in error; + } + var StorageApiError = class extends StorageError { + constructor(message, status, statusCode) { + super(message); + this.name = "StorageApiError"; + this.status = status; + this.statusCode = statusCode; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + statusCode: this.statusCode + }; + } + }; + exports.StorageApiError = StorageApiError; + var StorageUnknownError = class extends StorageError { + constructor(message, originalError) { + super(message); + this.name = "StorageUnknownError"; + this.originalError = originalError; + } + }; + exports.StorageUnknownError = StorageUnknownError; + } + }); + + // node_modules/@supabase/storage-js/dist/main/lib/helpers.js + var require_helpers = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/helpers.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isValidBucketName = exports.isPlainObject = exports.recursiveToCamel = exports.resolveResponse = exports.resolveFetch = void 0; + var resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); + }; + exports.resolveFetch = resolveFetch; + var resolveResponse = () => { + return Response; + }; + exports.resolveResponse = resolveResponse; + var recursiveToCamel = (item) => { + if (Array.isArray(item)) { + return item.map((el) => (0, exports.recursiveToCamel)(el)); + } else if (typeof item === "function" || item !== Object(item)) { + return item; + } + const result = {}; + Object.entries(item).forEach(([key, value]) => { + const newKey = key.replace(/([-_][a-z])/gi, (c3) => c3.toUpperCase().replace(/[-_]/g, "")); + result[newKey] = (0, exports.recursiveToCamel)(value); + }); + return result; + }; + exports.recursiveToCamel = recursiveToCamel; + var isPlainObject = (value) => { + if (typeof value !== "object" || value === null) { + return false; + } + const prototype = Object.getPrototypeOf(value); + return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value); + }; + exports.isPlainObject = isPlainObject; + var isValidBucketName = (bucketName) => { + if (!bucketName || typeof bucketName !== "string") { + return false; + } + if (bucketName.length === 0 || bucketName.length > 100) { + return false; + } + if (bucketName.trim() !== bucketName) { + return false; + } + if (bucketName.includes("/") || bucketName.includes("\\")) { + return false; + } + const bucketNameRegex = /^[\w!.\*'() &$@=;:+,?-]+$/; + return bucketNameRegex.test(bucketName); + }; + exports.isValidBucketName = isValidBucketName; + } + }); + + // node_modules/@supabase/storage-js/dist/main/lib/fetch.js + var require_fetch = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/fetch.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.get = get3; + exports.post = post; + exports.put = put; + exports.head = head; + exports.remove = remove6; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var errors_1 = require_errors(); + var helpers_1 = require_helpers(); + var _getErrorMessage = (err) => { + var _a; + return err.msg || err.message || err.error_description || (typeof err.error === "string" ? err.error : (_a = err.error) === null || _a === void 0 ? void 0 : _a.message) || JSON.stringify(err); + }; + var handleError = (error, reject, options) => tslib_1.__awaiter(void 0, void 0, void 0, function* () { + const Res = yield (0, helpers_1.resolveResponse)(); + if (error instanceof Res && !(options === null || options === void 0 ? void 0 : options.noResolveJson)) { + error.json().then((err) => { + const status = error.status || 500; + const statusCode = (err === null || err === void 0 ? void 0 : err.statusCode) || status + ""; + reject(new errors_1.StorageApiError(_getErrorMessage(err), status, statusCode)); + }).catch((err) => { + reject(new errors_1.StorageUnknownError(_getErrorMessage(err), err)); + }); + } else { + reject(new errors_1.StorageUnknownError(_getErrorMessage(error), error)); + } + }); + var _getRequestParams = (method, options, parameters, body) => { + const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; + if (method === "GET" || !body) { + return params; + } + if ((0, helpers_1.isPlainObject)(body)) { + params.headers = Object.assign({ "Content-Type": "application/json" }, options === null || options === void 0 ? void 0 : options.headers); + params.body = JSON.stringify(body); + } else { + params.body = body; + } + if (options === null || options === void 0 ? void 0 : options.duplex) { + params.duplex = options.duplex; + } + return Object.assign(Object.assign({}, params), parameters); + }; + function _handleRequest(fetcher, method, url, options, parameters, body) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + fetcher(url, _getRequestParams(method, options, parameters, body)).then((result) => { + if (!result.ok) + throw result; + if (options === null || options === void 0 ? void 0 : options.noResolveJson) + return result; + return result.json(); + }).then((data) => resolve(data)).catch((error) => handleError(error, reject, options)); + }); + }); + } + function get3(fetcher, url, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, "GET", url, options, parameters); + }); + } + function post(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, "POST", url, options, parameters, body); + }); + } + function put(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, "PUT", url, options, parameters, body); + }); + } + function head(fetcher, url, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, "HEAD", url, Object.assign(Object.assign({}, options), { noResolveJson: true }), parameters); + }); + } + function remove6(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, "DELETE", url, options, parameters, body); + }); + } + } + }); + + // node_modules/@supabase/storage-js/dist/main/packages/StreamDownloadBuilder.js + var require_StreamDownloadBuilder = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/packages/StreamDownloadBuilder.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var errors_1 = require_errors(); + var StreamDownloadBuilder = class { + constructor(downloadFn, shouldThrowOnError) { + this.downloadFn = downloadFn; + this.shouldThrowOnError = shouldThrowOnError; + } + then(onfulfilled, onrejected) { + return this.execute().then(onfulfilled, onrejected); + } + execute() { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const result = yield this.downloadFn(); + return { + data: result.body, + error: null + }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + }; + exports.default = StreamDownloadBuilder; + } + }); + + // node_modules/@supabase/storage-js/dist/main/packages/BlobDownloadBuilder.js + var require_BlobDownloadBuilder = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/packages/BlobDownloadBuilder.js"(exports) { + "use strict"; + var _a; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var errors_1 = require_errors(); + var StreamDownloadBuilder_1 = tslib_1.__importDefault(require_StreamDownloadBuilder()); + var BlobDownloadBuilder = class { + constructor(downloadFn, shouldThrowOnError) { + this.downloadFn = downloadFn; + this.shouldThrowOnError = shouldThrowOnError; + this[_a] = "BlobDownloadBuilder"; + this.promise = null; + } + asStream() { + return new StreamDownloadBuilder_1.default(this.downloadFn, this.shouldThrowOnError); + } + then(onfulfilled, onrejected) { + return this.getPromise().then(onfulfilled, onrejected); + } + catch(onrejected) { + return this.getPromise().catch(onrejected); + } + finally(onfinally) { + return this.getPromise().finally(onfinally); + } + getPromise() { + if (!this.promise) { + this.promise = this.execute(); + } + return this.promise; + } + execute() { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const result = yield this.downloadFn(); + return { + data: yield result.blob(), + error: null + }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + }; + _a = Symbol.toStringTag; + exports.default = BlobDownloadBuilder; + } + }); + + // node_modules/@supabase/storage-js/dist/main/packages/StorageFileApi.js + var require_StorageFileApi = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/packages/StorageFileApi.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var errors_1 = require_errors(); + var fetch_1 = require_fetch(); + var helpers_1 = require_helpers(); + var BlobDownloadBuilder_1 = tslib_1.__importDefault(require_BlobDownloadBuilder()); + var DEFAULT_SEARCH_OPTIONS = { + limit: 100, + offset: 0, + sortBy: { + column: "name", + order: "asc" + } + }; + var DEFAULT_FILE_OPTIONS = { + cacheControl: "3600", + contentType: "text/plain;charset=UTF-8", + upsert: false + }; + var StorageFileApi = class { + constructor(url, headers = {}, bucketId, fetch2) { + this.shouldThrowOnError = false; + this.url = url; + this.headers = headers; + this.bucketId = bucketId; + this.fetch = (0, helpers_1.resolveFetch)(fetch2); + } + /** + * Enable throwing errors instead of returning them. + * + * @category File Buckets + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + /** + * Uploads a file to an existing bucket or replaces an existing file at the specified path with a new one. + * + * @param method HTTP method. + * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param fileBody The body of the file to be stored in the bucket. + */ + uploadOrUpdate(method, path, fileBody, fileOptions) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + let body; + const options = Object.assign(Object.assign({}, DEFAULT_FILE_OPTIONS), fileOptions); + let headers = Object.assign(Object.assign({}, this.headers), method === "POST" && { "x-upsert": String(options.upsert) }); + const metadata = options.metadata; + if (typeof Blob !== "undefined" && fileBody instanceof Blob) { + body = new FormData(); + body.append("cacheControl", options.cacheControl); + if (metadata) { + body.append("metadata", this.encodeMetadata(metadata)); + } + body.append("", fileBody); + } else if (typeof FormData !== "undefined" && fileBody instanceof FormData) { + body = fileBody; + if (!body.has("cacheControl")) { + body.append("cacheControl", options.cacheControl); + } + if (metadata && !body.has("metadata")) { + body.append("metadata", this.encodeMetadata(metadata)); + } + } else { + body = fileBody; + headers["cache-control"] = `max-age=${options.cacheControl}`; + headers["content-type"] = options.contentType; + if (metadata) { + headers["x-metadata"] = this.toBase64(this.encodeMetadata(metadata)); + } + const isStream = typeof ReadableStream !== "undefined" && body instanceof ReadableStream || body && typeof body === "object" && "pipe" in body && typeof body.pipe === "function"; + if (isStream && !options.duplex) { + options.duplex = "half"; + } + } + if (fileOptions === null || fileOptions === void 0 ? void 0 : fileOptions.headers) { + headers = Object.assign(Object.assign({}, headers), fileOptions.headers); + } + const cleanPath = this._removeEmptyFolders(path); + const _path = this._getFinalPath(cleanPath); + const data = yield (method == "PUT" ? fetch_1.put : fetch_1.post)(this.fetch, `${this.url}/object/${_path}`, body, Object.assign({ headers }, (options === null || options === void 0 ? void 0 : options.duplex) ? { duplex: options.duplex } : {})); + return { + data: { path: cleanPath, id: data.Id, fullPath: data.Key }, + error: null + }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Uploads a file to an existing bucket. + * + * @category File Buckets + * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param fileBody The body of the file to be stored in the bucket. + * @param fileOptions Optional file upload options including cacheControl, contentType, upsert, and metadata. + * @returns Promise with response containing file path, id, and fullPath or error + * + * @example Upload file + * ```js + * const avatarFile = event.target.files[0] + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .upload('public/avatar1.png', avatarFile, { + * cacheControl: '3600', + * upsert: false + * }) + * ``` + * + * Response: + * ```json + * { + * "data": { + * "path": "public/avatar1.png", + * "fullPath": "avatars/public/avatar1.png" + * }, + * "error": null + * } + * ``` + * + * @example Upload file using `ArrayBuffer` from base64 file data + * ```js + * import { decode } from 'base64-arraybuffer' + * + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .upload('public/avatar1.png', decode('base64FileData'), { + * contentType: 'image/png' + * }) + * ``` + */ + upload(path, fileBody, fileOptions) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return this.uploadOrUpdate("POST", path, fileBody, fileOptions); + }); + } + /** + * Upload a file with a token generated from `createSignedUploadUrl`. + * + * @category File Buckets + * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. + * @param token The token generated from `createSignedUploadUrl` + * @param fileBody The body of the file to be stored in the bucket. + * @param fileOptions HTTP headers (cacheControl, contentType, etc.). + * **Note:** The `upsert` option has no effect here. To enable upsert behavior, + * pass `{ upsert: true }` when calling `createSignedUploadUrl()` instead. + * @returns Promise with response containing file path and fullPath or error + * + * @example Upload to a signed URL + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .uploadToSignedUrl('folder/cat.jpg', 'token-from-createSignedUploadUrl', file) + * ``` + * + * Response: + * ```json + * { + * "data": { + * "path": "folder/cat.jpg", + * "fullPath": "avatars/folder/cat.jpg" + * }, + * "error": null + * } + * ``` + */ + uploadToSignedUrl(path, token, fileBody, fileOptions) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + const cleanPath = this._removeEmptyFolders(path); + const _path = this._getFinalPath(cleanPath); + const url = new URL(this.url + `/object/upload/sign/${_path}`); + url.searchParams.set("token", token); + try { + let body; + const options = Object.assign({ upsert: DEFAULT_FILE_OPTIONS.upsert }, fileOptions); + const headers = Object.assign(Object.assign({}, this.headers), { "x-upsert": String(options.upsert) }); + if (typeof Blob !== "undefined" && fileBody instanceof Blob) { + body = new FormData(); + body.append("cacheControl", options.cacheControl); + body.append("", fileBody); + } else if (typeof FormData !== "undefined" && fileBody instanceof FormData) { + body = fileBody; + body.append("cacheControl", options.cacheControl); + } else { + body = fileBody; + headers["cache-control"] = `max-age=${options.cacheControl}`; + headers["content-type"] = options.contentType; + } + const data = yield (0, fetch_1.put)(this.fetch, url.toString(), body, { headers }); + return { + data: { path: cleanPath, fullPath: data.Key }, + error: null + }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Creates a signed upload URL. + * Signed upload URLs can be used to upload files to the bucket without further authentication. + * They are valid for 2 hours. + * + * @category File Buckets + * @param path The file path, including the current file name. For example `folder/image.png`. + * @param options.upsert If set to true, allows the file to be overwritten if it already exists. + * @returns Promise with response containing signed upload URL, token, and path or error + * + * @example Create Signed Upload URL + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .createSignedUploadUrl('folder/cat.jpg') + * ``` + * + * Response: + * ```json + * { + * "data": { + * "signedUrl": "https://example.supabase.co/storage/v1/object/upload/sign/avatars/folder/cat.jpg?token=", + * "path": "folder/cat.jpg", + * "token": "" + * }, + * "error": null + * } + * ``` + */ + createSignedUploadUrl(path, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + let _path = this._getFinalPath(path); + const headers = Object.assign({}, this.headers); + if (options === null || options === void 0 ? void 0 : options.upsert) { + headers["x-upsert"] = "true"; + } + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/upload/sign/${_path}`, {}, { headers }); + const url = new URL(this.url + data.url); + const token = url.searchParams.get("token"); + if (!token) { + throw new errors_1.StorageError("No token returned by API"); + } + return { data: { signedUrl: url.toString(), path, token }, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Replaces an existing file at the specified path with a new one. + * + * @category File Buckets + * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to update. + * @param fileBody The body of the file to be stored in the bucket. + * @param fileOptions Optional file upload options including cacheControl, contentType, upsert, and metadata. + * @returns Promise with response containing file path, id, and fullPath or error + * + * @example Update file + * ```js + * const avatarFile = event.target.files[0] + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .update('public/avatar1.png', avatarFile, { + * cacheControl: '3600', + * upsert: true + * }) + * ``` + * + * Response: + * ```json + * { + * "data": { + * "path": "public/avatar1.png", + * "fullPath": "avatars/public/avatar1.png" + * }, + * "error": null + * } + * ``` + * + * @example Update file using `ArrayBuffer` from base64 file data + * ```js + * import {decode} from 'base64-arraybuffer' + * + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .update('public/avatar1.png', decode('base64FileData'), { + * contentType: 'image/png' + * }) + * ``` + */ + update(path, fileBody, fileOptions) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return this.uploadOrUpdate("PUT", path, fileBody, fileOptions); + }); + } + /** + * Moves an existing file to a new path in the same bucket. + * + * @category File Buckets + * @param fromPath The original file path, including the current file name. For example `folder/image.png`. + * @param toPath The new file path, including the new file name. For example `folder/image-new.png`. + * @param options The destination options. + * @returns Promise with response containing success message or error + * + * @example Move file + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .move('public/avatar1.png', 'private/avatar2.png') + * ``` + * + * Response: + * ```json + * { + * "data": { + * "message": "Successfully moved" + * }, + * "error": null + * } + * ``` + */ + move(fromPath, toPath, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/move`, { + bucketId: this.bucketId, + sourceKey: fromPath, + destinationKey: toPath, + destinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket + }, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Copies an existing file to a new path in the same bucket. + * + * @category File Buckets + * @param fromPath The original file path, including the current file name. For example `folder/image.png`. + * @param toPath The new file path, including the new file name. For example `folder/image-copy.png`. + * @param options The destination options. + * @returns Promise with response containing copied file path or error + * + * @example Copy file + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .copy('public/avatar1.png', 'private/avatar2.png') + * ``` + * + * Response: + * ```json + * { + * "data": { + * "path": "avatars/private/avatar2.png" + * }, + * "error": null + * } + * ``` + */ + copy(fromPath, toPath, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/copy`, { + bucketId: this.bucketId, + sourceKey: fromPath, + destinationKey: toPath, + destinationBucket: options === null || options === void 0 ? void 0 : options.destinationBucket + }, { headers: this.headers }); + return { data: { path: data.Key }, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Creates a signed URL. Use a signed URL to share a file for a fixed amount of time. + * + * @category File Buckets + * @param path The file path, including the current file name. For example `folder/image.png`. + * @param expiresIn The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute. + * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + * @param options.transform Transform the asset before serving it to the client. + * @returns Promise with response containing signed URL or error + * + * @example Create Signed URL + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .createSignedUrl('folder/avatar1.png', 60) + * ``` + * + * Response: + * ```json + * { + * "data": { + * "signedUrl": "https://example.supabase.co/storage/v1/object/sign/avatars/folder/avatar1.png?token=" + * }, + * "error": null + * } + * ``` + * + * @example Create a signed URL for an asset with transformations + * ```js + * const { data } = await supabase + * .storage + * .from('avatars') + * .createSignedUrl('folder/avatar1.png', 60, { + * transform: { + * width: 100, + * height: 100, + * } + * }) + * ``` + * + * @example Create a signed URL which triggers the download of the asset + * ```js + * const { data } = await supabase + * .storage + * .from('avatars') + * .createSignedUrl('folder/avatar1.png', 60, { + * download: true, + * }) + * ``` + */ + createSignedUrl(path, expiresIn, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + let _path = this._getFinalPath(path); + let data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/sign/${_path}`, Object.assign({ expiresIn }, (options === null || options === void 0 ? void 0 : options.transform) ? { transform: options.transform } : {}), { headers: this.headers }); + const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) ? `&download=${options.download === true ? "" : options.download}` : ""; + const signedUrl = encodeURI(`${this.url}${data.signedURL}${downloadQueryParam}`); + data = { signedUrl }; + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Creates multiple signed URLs. Use a signed URL to share a file for a fixed amount of time. + * + * @category File Buckets + * @param paths The file paths to be downloaded, including the current file names. For example `['folder/image.png', 'folder2/image2.png']`. + * @param expiresIn The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute. + * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + * @returns Promise with response containing array of objects with signedUrl, path, and error or error + * + * @example Create Signed URLs + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .createSignedUrls(['folder/avatar1.png', 'folder/avatar2.png'], 60) + * ``` + * + * Response: + * ```json + * { + * "data": [ + * { + * "error": null, + * "path": "folder/avatar1.png", + * "signedURL": "/object/sign/avatars/folder/avatar1.png?token=", + * "signedUrl": "https://example.supabase.co/storage/v1/object/sign/avatars/folder/avatar1.png?token=" + * }, + * { + * "error": null, + * "path": "folder/avatar2.png", + * "signedURL": "/object/sign/avatars/folder/avatar2.png?token=", + * "signedUrl": "https://example.supabase.co/storage/v1/object/sign/avatars/folder/avatar2.png?token=" + * } + * ], + * "error": null + * } + * ``` + */ + createSignedUrls(paths, expiresIn, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/sign/${this.bucketId}`, { expiresIn, paths }, { headers: this.headers }); + const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) ? `&download=${options.download === true ? "" : options.download}` : ""; + return { + data: data.map((datum) => Object.assign(Object.assign({}, datum), { signedUrl: datum.signedURL ? encodeURI(`${this.url}${datum.signedURL}${downloadQueryParam}`) : null })), + error: null + }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Downloads a file from a private bucket. For public buckets, make a request to the URL returned from `getPublicUrl` instead. + * + * @category File Buckets + * @param path The full path and file name of the file to be downloaded. For example `folder/image.png`. + * @param options.transform Transform the asset before serving it to the client. + * @returns BlobDownloadBuilder instance for downloading the file + * + * @example Download file + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .download('folder/avatar1.png') + * ``` + * + * Response: + * ```json + * { + * "data": , + * "error": null + * } + * ``` + * + * @example Download file with transformations + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .download('folder/avatar1.png', { + * transform: { + * width: 100, + * height: 100, + * quality: 80 + * } + * }) + * ``` + */ + download(path, options) { + const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== "undefined"; + const renderPath = wantsTransformation ? "render/image/authenticated" : "object"; + const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {}); + const queryString = transformationQuery ? `?${transformationQuery}` : ""; + const _path = this._getFinalPath(path); + const downloadFn = () => (0, fetch_1.get)(this.fetch, `${this.url}/${renderPath}/${_path}${queryString}`, { + headers: this.headers, + noResolveJson: true + }); + return new BlobDownloadBuilder_1.default(downloadFn, this.shouldThrowOnError); + } + /** + * Retrieves the details of an existing file. + * + * @category File Buckets + * @param path The file path, including the file name. For example `folder/image.png`. + * @returns Promise with response containing file metadata or error + * + * @example Get file info + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .info('folder/avatar1.png') + * ``` + */ + info(path) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + const _path = this._getFinalPath(path); + try { + const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/object/info/${_path}`, { + headers: this.headers + }); + return { data: (0, helpers_1.recursiveToCamel)(data), error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Checks the existence of a file. + * + * @category File Buckets + * @param path The file path, including the file name. For example `folder/image.png`. + * @returns Promise with response containing boolean indicating file existence or error + * + * @example Check file existence + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .exists('folder/avatar1.png') + * ``` + */ + exists(path) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + const _path = this._getFinalPath(path); + try { + yield (0, fetch_1.head)(this.fetch, `${this.url}/object/${_path}`, { + headers: this.headers + }); + return { data: true, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error) && error instanceof errors_1.StorageUnknownError) { + const originalError = error.originalError; + if ([400, 404].includes(originalError === null || originalError === void 0 ? void 0 : originalError.status)) { + return { data: false, error }; + } + } + throw error; + } + }); + } + /** + * A simple convenience function to get the URL for an asset in a public bucket. If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset. + * This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset. + * + * @category File Buckets + * @param path The path and name of the file to generate the public URL for. For example `folder/image.png`. + * @param options.download Triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. + * @param options.transform Transform the asset before serving it to the client. + * @returns Object with public URL + * + * @example Returns the URL for an asset in a public bucket + * ```js + * const { data } = supabase + * .storage + * .from('public-bucket') + * .getPublicUrl('folder/avatar1.png') + * ``` + * + * Response: + * ```json + * { + * "data": { + * "publicUrl": "https://example.supabase.co/storage/v1/object/public/public-bucket/folder/avatar1.png" + * } + * } + * ``` + * + * @example Returns the URL for an asset in a public bucket with transformations + * ```js + * const { data } = supabase + * .storage + * .from('public-bucket') + * .getPublicUrl('folder/avatar1.png', { + * transform: { + * width: 100, + * height: 100, + * } + * }) + * ``` + * + * @example Returns the URL which triggers the download of an asset in a public bucket + * ```js + * const { data } = supabase + * .storage + * .from('public-bucket') + * .getPublicUrl('folder/avatar1.png', { + * download: true, + * }) + * ``` + */ + getPublicUrl(path, options) { + const _path = this._getFinalPath(path); + const _queryString = []; + const downloadQueryParam = (options === null || options === void 0 ? void 0 : options.download) ? `download=${options.download === true ? "" : options.download}` : ""; + if (downloadQueryParam !== "") { + _queryString.push(downloadQueryParam); + } + const wantsTransformation = typeof (options === null || options === void 0 ? void 0 : options.transform) !== "undefined"; + const renderPath = wantsTransformation ? "render/image" : "object"; + const transformationQuery = this.transformOptsToQueryString((options === null || options === void 0 ? void 0 : options.transform) || {}); + if (transformationQuery !== "") { + _queryString.push(transformationQuery); + } + let queryString = _queryString.join("&"); + if (queryString !== "") { + queryString = `?${queryString}`; + } + return { + data: { publicUrl: encodeURI(`${this.url}/${renderPath}/public/${_path}${queryString}`) } + }; + } + /** + * Deletes files within the same bucket + * + * @category File Buckets + * @param paths An array of files to delete, including the path and file name. For example [`'folder/image.png'`]. + * @returns Promise with response containing array of deleted file objects or error + * + * @example Delete file + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .remove(['folder/avatar1.png']) + * ``` + * + * Response: + * ```json + * { + * "data": [], + * "error": null + * } + * ``` + */ + remove(paths) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/object/${this.bucketId}`, { prefixes: paths }, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Get file metadata + * @param id the file id to retrieve metadata + */ + // async getMetadata( + // id: string + // ): Promise< + // | { + // data: Metadata + // error: null + // } + // | { + // data: null + // error: StorageError + // } + // > { + // try { + // const data = await get(this.fetch, `${this.url}/metadata/${id}`, { headers: this.headers }) + // return { data, error: null } + // } catch (error) { + // if (isStorageError(error)) { + // return { data: null, error } + // } + // throw error + // } + // } + /** + * Update file metadata + * @param id the file id to update metadata + * @param meta the new file metadata + */ + // async updateMetadata( + // id: string, + // meta: Metadata + // ): Promise< + // | { + // data: Metadata + // error: null + // } + // | { + // data: null + // error: StorageError + // } + // > { + // try { + // const data = await post( + // this.fetch, + // `${this.url}/metadata/${id}`, + // { ...meta }, + // { headers: this.headers } + // ) + // return { data, error: null } + // } catch (error) { + // if (isStorageError(error)) { + // return { data: null, error } + // } + // throw error + // } + // } + /** + * Lists all the files and folders within a path of the bucket. + * + * @category File Buckets + * @param path The folder path. + * @param options Search options including limit (defaults to 100), offset, sortBy, and search + * @param parameters Optional fetch parameters including signal for cancellation + * @returns Promise with response containing array of files or error + * + * @example List files in a bucket + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .list('folder', { + * limit: 100, + * offset: 0, + * sortBy: { column: 'name', order: 'asc' }, + * }) + * ``` + * + * Response: + * ```json + * { + * "data": [ + * { + * "name": "avatar1.png", + * "id": "e668cf7f-821b-4a2f-9dce-7dfa5dd1cfd2", + * "updated_at": "2024-05-22T23:06:05.580Z", + * "created_at": "2024-05-22T23:04:34.443Z", + * "last_accessed_at": "2024-05-22T23:04:34.443Z", + * "metadata": { + * "eTag": "\"c5e8c553235d9af30ef4f6e280790b92\"", + * "size": 32175, + * "mimetype": "image/png", + * "cacheControl": "max-age=3600", + * "lastModified": "2024-05-22T23:06:05.574Z", + * "contentLength": 32175, + * "httpStatusCode": 200 + * } + * } + * ], + * "error": null + * } + * ``` + * + * @example Search files in a bucket + * ```js + * const { data, error } = await supabase + * .storage + * .from('avatars') + * .list('folder', { + * limit: 100, + * offset: 0, + * sortBy: { column: 'name', order: 'asc' }, + * search: 'jon' + * }) + * ``` + */ + list(path, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const body = Object.assign(Object.assign(Object.assign({}, DEFAULT_SEARCH_OPTIONS), options), { prefix: path || "" }); + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/list/${this.bucketId}`, body, { headers: this.headers }, parameters); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * @experimental this method signature might change in the future + * + * @category File Buckets + * @param options search options + * @param parameters + */ + listV2(options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const body = Object.assign({}, options); + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/object/list-v2/${this.bucketId}`, body, { headers: this.headers }, parameters); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + encodeMetadata(metadata) { + return JSON.stringify(metadata); + } + toBase64(data) { + if (typeof Buffer !== "undefined") { + return Buffer.from(data).toString("base64"); + } + return btoa(data); + } + _getFinalPath(path) { + return `${this.bucketId}/${path.replace(/^\/+/, "")}`; + } + _removeEmptyFolders(path) { + return path.replace(/^\/|\/$/g, "").replace(/\/+/g, "/"); + } + transformOptsToQueryString(transform) { + const params = []; + if (transform.width) { + params.push(`width=${transform.width}`); + } + if (transform.height) { + params.push(`height=${transform.height}`); + } + if (transform.resize) { + params.push(`resize=${transform.resize}`); + } + if (transform.format) { + params.push(`format=${transform.format}`); + } + if (transform.quality) { + params.push(`quality=${transform.quality}`); + } + return params.join("&"); + } + }; + exports.default = StorageFileApi; + } + }); + + // node_modules/@supabase/storage-js/dist/main/lib/version.js + var require_version2 = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/version.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.version = void 0; + exports.version = "2.87.1"; + } + }); + + // node_modules/@supabase/storage-js/dist/main/lib/constants.js + var require_constants3 = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/constants.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DEFAULT_HEADERS = void 0; + var version_1 = require_version2(); + exports.DEFAULT_HEADERS = { + "X-Client-Info": `storage-js/${version_1.version}` + }; + } + }); + + // node_modules/@supabase/storage-js/dist/main/packages/StorageBucketApi.js + var require_StorageBucketApi = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/packages/StorageBucketApi.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var constants_1 = require_constants3(); + var errors_1 = require_errors(); + var fetch_1 = require_fetch(); + var helpers_1 = require_helpers(); + var StorageBucketApi = class { + constructor(url, headers = {}, fetch2, opts) { + this.shouldThrowOnError = false; + const baseUrl = new URL(url); + if (opts === null || opts === void 0 ? void 0 : opts.useNewHostname) { + const isSupabaseHost = /supabase\.(co|in|red)$/.test(baseUrl.hostname); + if (isSupabaseHost && !baseUrl.hostname.includes("storage.supabase.")) { + baseUrl.hostname = baseUrl.hostname.replace("supabase.", "storage.supabase."); + } + } + this.url = baseUrl.href.replace(/\/$/, ""); + this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); + this.fetch = (0, helpers_1.resolveFetch)(fetch2); + } + /** + * Enable throwing errors instead of returning them. + * + * @category File Buckets + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + /** + * Retrieves the details of all Storage buckets within an existing project. + * + * @category File Buckets + * @param options Query parameters for listing buckets + * @param options.limit Maximum number of buckets to return + * @param options.offset Number of buckets to skip + * @param options.sortColumn Column to sort by ('id', 'name', 'created_at', 'updated_at') + * @param options.sortOrder Sort order ('asc' or 'desc') + * @param options.search Search term to filter bucket names + * @returns Promise with response containing array of buckets or error + * + * @example List buckets + * ```js + * const { data, error } = await supabase + * .storage + * .listBuckets() + * ``` + * + * @example List buckets with options + * ```js + * const { data, error } = await supabase + * .storage + * .listBuckets({ + * limit: 10, + * offset: 0, + * sortColumn: 'created_at', + * sortOrder: 'desc', + * search: 'prod' + * }) + * ``` + */ + listBuckets(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const queryString = this.listBucketOptionsToQueryString(options); + const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/bucket${queryString}`, { + headers: this.headers + }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Retrieves the details of an existing Storage bucket. + * + * @category File Buckets + * @param id The unique identifier of the bucket you would like to retrieve. + * @returns Promise with response containing bucket details or error + * + * @example Get bucket + * ```js + * const { data, error } = await supabase + * .storage + * .getBucket('avatars') + * ``` + * + * Response: + * ```json + * { + * "data": { + * "id": "avatars", + * "name": "avatars", + * "owner": "", + * "public": false, + * "file_size_limit": 1024, + * "allowed_mime_types": [ + * "image/png" + * ], + * "created_at": "2024-05-22T22:26:05.100Z", + * "updated_at": "2024-05-22T22:26:05.100Z" + * }, + * "error": null + * } + * ``` + */ + getBucket(id) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.get)(this.fetch, `${this.url}/bucket/${id}`, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Creates a new Storage bucket + * + * @category File Buckets + * @param id A unique identifier for the bucket you are creating. + * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. By default, buckets are private. + * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. + * The global file size limit takes precedence over this value. + * The default value is null, which doesn't set a per bucket file size limit. + * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. + * The default value is null, which allows files with all mime types to be uploaded. + * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. + * @param options.type (private-beta) specifies the bucket type. see `BucketType` for more details. + * - default bucket type is `STANDARD` + * @returns Promise with response containing newly created bucket name or error + * + * @example Create bucket + * ```js + * const { data, error } = await supabase + * .storage + * .createBucket('avatars', { + * public: false, + * allowedMimeTypes: ['image/png'], + * fileSizeLimit: 1024 + * }) + * ``` + * + * Response: + * ```json + * { + * "data": { + * "name": "avatars" + * }, + * "error": null + * } + * ``` + */ + createBucket(id_1) { + return tslib_1.__awaiter(this, arguments, void 0, function* (id, options = { + public: false + }) { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket`, { + id, + name: id, + type: options.type, + public: options.public, + file_size_limit: options.fileSizeLimit, + allowed_mime_types: options.allowedMimeTypes + }, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Updates a Storage bucket + * + * @category File Buckets + * @param id A unique identifier for the bucket you are updating. + * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. + * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. + * The global file size limit takes precedence over this value. + * The default value is null, which doesn't set a per bucket file size limit. + * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. + * The default value is null, which allows files with all mime types to be uploaded. + * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. + * @returns Promise with response containing success message or error + * + * @example Update bucket + * ```js + * const { data, error } = await supabase + * .storage + * .updateBucket('avatars', { + * public: false, + * allowedMimeTypes: ['image/png'], + * fileSizeLimit: 1024 + * }) + * ``` + * + * Response: + * ```json + * { + * "data": { + * "message": "Successfully updated" + * }, + * "error": null + * } + * ``` + */ + updateBucket(id, options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.put)(this.fetch, `${this.url}/bucket/${id}`, { + id, + name: id, + public: options.public, + file_size_limit: options.fileSizeLimit, + allowed_mime_types: options.allowedMimeTypes + }, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Removes all objects inside a single bucket. + * + * @category File Buckets + * @param id The unique identifier of the bucket you would like to empty. + * @returns Promise with success message or error + * + * @example Empty bucket + * ```js + * const { data, error } = await supabase + * .storage + * .emptyBucket('avatars') + * ``` + * + * Response: + * ```json + * { + * "data": { + * "message": "Successfully emptied" + * }, + * "error": null + * } + * ``` + */ + emptyBucket(id) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket/${id}/empty`, {}, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * Deletes an existing bucket. A bucket can't be deleted with existing objects inside it. + * You must first `empty()` the bucket. + * + * @category File Buckets + * @param id The unique identifier of the bucket you would like to delete. + * @returns Promise with success message or error + * + * @example Delete bucket + * ```js + * const { data, error } = await supabase + * .storage + * .deleteBucket('avatars') + * ``` + * + * Response: + * ```json + * { + * "data": { + * "message": "Successfully deleted" + * }, + * "error": null + * } + * ``` + */ + deleteBucket(id) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/bucket/${id}`, {}, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + listBucketOptionsToQueryString(options) { + const params = {}; + if (options) { + if ("limit" in options) { + params.limit = String(options.limit); + } + if ("offset" in options) { + params.offset = String(options.offset); + } + if (options.search) { + params.search = options.search; + } + if (options.sortColumn) { + params.sortColumn = options.sortColumn; + } + if (options.sortOrder) { + params.sortOrder = options.sortOrder; + } + } + return Object.keys(params).length > 0 ? "?" + new URLSearchParams(params).toString() : ""; + } + }; + exports.default = StorageBucketApi; + } + }); + + // node_modules/iceberg-js/dist/index.cjs + var require_dist2 = __commonJS({ + "node_modules/iceberg-js/dist/index.cjs"(exports) { + "use strict"; + var IcebergError = class extends Error { + constructor(message, opts) { + super(message); + this.name = "IcebergError"; + this.status = opts.status; + this.icebergType = opts.icebergType; + this.icebergCode = opts.icebergCode; + this.details = opts.details; + this.isCommitStateUnknown = opts.icebergType === "CommitStateUnknownException" || [500, 502, 504].includes(opts.status) && opts.icebergType?.includes("CommitState") === true; + } + /** + * Returns true if the error is a 404 Not Found error. + */ + isNotFound() { + return this.status === 404; + } + /** + * Returns true if the error is a 409 Conflict error. + */ + isConflict() { + return this.status === 409; + } + /** + * Returns true if the error is a 419 Authentication Timeout error. + */ + isAuthenticationTimeout() { + return this.status === 419; + } + }; + function buildUrl(baseUrl, path, query) { + const url = new URL(path, baseUrl); + if (query) { + for (const [key, value] of Object.entries(query)) { + if (value !== void 0) { + url.searchParams.set(key, value); + } + } + } + return url.toString(); + } + async function buildAuthHeaders(auth) { + if (!auth || auth.type === "none") { + return {}; + } + if (auth.type === "bearer") { + return { Authorization: `Bearer ${auth.token}` }; + } + if (auth.type === "header") { + return { [auth.name]: auth.value }; + } + if (auth.type === "custom") { + return await auth.getHeaders(); + } + return {}; + } + function createFetchClient(options) { + const fetchFn = options.fetchImpl ?? globalThis.fetch; + return { + async request({ + method, + path, + query, + body, + headers + }) { + const url = buildUrl(options.baseUrl, path, query); + const authHeaders = await buildAuthHeaders(options.auth); + const res = await fetchFn(url, { + method, + headers: { + ...body ? { "Content-Type": "application/json" } : {}, + ...authHeaders, + ...headers + }, + body: body ? JSON.stringify(body) : void 0 + }); + const text2 = await res.text(); + const isJson = (res.headers.get("content-type") || "").includes("application/json"); + const data = isJson && text2 ? JSON.parse(text2) : text2; + if (!res.ok) { + const errBody = isJson ? data : void 0; + const errorDetail = errBody?.error; + throw new IcebergError( + errorDetail?.message ?? `Request failed with status ${res.status}`, + { + status: res.status, + icebergType: errorDetail?.type, + icebergCode: errorDetail?.code, + details: errBody + } + ); + } + return { status: res.status, headers: res.headers, data }; + } + }; + } + function namespaceToPath(namespace) { + return namespace.join(""); + } + var NamespaceOperations = class { + constructor(client2, prefix = "") { + this.client = client2; + this.prefix = prefix; + } + async listNamespaces(parent) { + const query = parent ? { parent: namespaceToPath(parent.namespace) } : void 0; + const response = await this.client.request({ + method: "GET", + path: `${this.prefix}/namespaces`, + query + }); + return response.data.namespaces.map((ns) => ({ namespace: ns })); + } + async createNamespace(id, metadata) { + const request = { + namespace: id.namespace, + properties: metadata?.properties + }; + const response = await this.client.request({ + method: "POST", + path: `${this.prefix}/namespaces`, + body: request + }); + return response.data; + } + async dropNamespace(id) { + await this.client.request({ + method: "DELETE", + path: `${this.prefix}/namespaces/${namespaceToPath(id.namespace)}` + }); + } + async loadNamespaceMetadata(id) { + const response = await this.client.request({ + method: "GET", + path: `${this.prefix}/namespaces/${namespaceToPath(id.namespace)}` + }); + return { + properties: response.data.properties + }; + } + async namespaceExists(id) { + try { + await this.client.request({ + method: "HEAD", + path: `${this.prefix}/namespaces/${namespaceToPath(id.namespace)}` + }); + return true; + } catch (error) { + if (error instanceof IcebergError && error.status === 404) { + return false; + } + throw error; + } + } + async createNamespaceIfNotExists(id, metadata) { + try { + return await this.createNamespace(id, metadata); + } catch (error) { + if (error instanceof IcebergError && error.status === 409) { + return; + } + throw error; + } + } + }; + function namespaceToPath2(namespace) { + return namespace.join(""); + } + var TableOperations = class { + constructor(client2, prefix = "", accessDelegation) { + this.client = client2; + this.prefix = prefix; + this.accessDelegation = accessDelegation; + } + async listTables(namespace) { + const response = await this.client.request({ + method: "GET", + path: `${this.prefix}/namespaces/${namespaceToPath2(namespace.namespace)}/tables` + }); + return response.data.identifiers; + } + async createTable(namespace, request) { + const headers = {}; + if (this.accessDelegation) { + headers["X-Iceberg-Access-Delegation"] = this.accessDelegation; + } + const response = await this.client.request({ + method: "POST", + path: `${this.prefix}/namespaces/${namespaceToPath2(namespace.namespace)}/tables`, + body: request, + headers + }); + return response.data.metadata; + } + async updateTable(id, request) { + const response = await this.client.request({ + method: "POST", + path: `${this.prefix}/namespaces/${namespaceToPath2(id.namespace)}/tables/${id.name}`, + body: request + }); + return { + "metadata-location": response.data["metadata-location"], + metadata: response.data.metadata + }; + } + async dropTable(id, options) { + await this.client.request({ + method: "DELETE", + path: `${this.prefix}/namespaces/${namespaceToPath2(id.namespace)}/tables/${id.name}`, + query: { purgeRequested: String(options?.purge ?? false) } + }); + } + async loadTable(id) { + const headers = {}; + if (this.accessDelegation) { + headers["X-Iceberg-Access-Delegation"] = this.accessDelegation; + } + const response = await this.client.request({ + method: "GET", + path: `${this.prefix}/namespaces/${namespaceToPath2(id.namespace)}/tables/${id.name}`, + headers + }); + return response.data.metadata; + } + async tableExists(id) { + const headers = {}; + if (this.accessDelegation) { + headers["X-Iceberg-Access-Delegation"] = this.accessDelegation; + } + try { + await this.client.request({ + method: "HEAD", + path: `${this.prefix}/namespaces/${namespaceToPath2(id.namespace)}/tables/${id.name}`, + headers + }); + return true; + } catch (error) { + if (error instanceof IcebergError && error.status === 404) { + return false; + } + throw error; + } + } + async createTableIfNotExists(namespace, request) { + try { + return await this.createTable(namespace, request); + } catch (error) { + if (error instanceof IcebergError && error.status === 409) { + return await this.loadTable({ namespace: namespace.namespace, name: request.name }); + } + throw error; + } + } + }; + var IcebergRestCatalog = class { + /** + * Creates a new Iceberg REST Catalog client. + * + * @param options - Configuration options for the catalog client + */ + constructor(options) { + let prefix = "v1"; + if (options.catalogName) { + prefix += `/${options.catalogName}`; + } + const baseUrl = options.baseUrl.endsWith("/") ? options.baseUrl : `${options.baseUrl}/`; + this.client = createFetchClient({ + baseUrl, + auth: options.auth, + fetchImpl: options.fetch + }); + this.accessDelegation = options.accessDelegation?.join(","); + this.namespaceOps = new NamespaceOperations(this.client, prefix); + this.tableOps = new TableOperations(this.client, prefix, this.accessDelegation); + } + /** + * Lists all namespaces in the catalog. + * + * @param parent - Optional parent namespace to list children under + * @returns Array of namespace identifiers + * + * @example + * ```typescript + * // List all top-level namespaces + * const namespaces = await catalog.listNamespaces(); + * + * // List namespaces under a parent + * const children = await catalog.listNamespaces({ namespace: ['analytics'] }); + * ``` + */ + async listNamespaces(parent) { + return this.namespaceOps.listNamespaces(parent); + } + /** + * Creates a new namespace in the catalog. + * + * @param id - Namespace identifier to create + * @param metadata - Optional metadata properties for the namespace + * @returns Response containing the created namespace and its properties + * + * @example + * ```typescript + * const response = await catalog.createNamespace( + * { namespace: ['analytics'] }, + * { properties: { owner: 'data-team' } } + * ); + * console.log(response.namespace); // ['analytics'] + * console.log(response.properties); // { owner: 'data-team', ... } + * ``` + */ + async createNamespace(id, metadata) { + return this.namespaceOps.createNamespace(id, metadata); + } + /** + * Drops a namespace from the catalog. + * + * The namespace must be empty (contain no tables) before it can be dropped. + * + * @param id - Namespace identifier to drop + * + * @example + * ```typescript + * await catalog.dropNamespace({ namespace: ['analytics'] }); + * ``` + */ + async dropNamespace(id) { + await this.namespaceOps.dropNamespace(id); + } + /** + * Loads metadata for a namespace. + * + * @param id - Namespace identifier to load + * @returns Namespace metadata including properties + * + * @example + * ```typescript + * const metadata = await catalog.loadNamespaceMetadata({ namespace: ['analytics'] }); + * console.log(metadata.properties); + * ``` + */ + async loadNamespaceMetadata(id) { + return this.namespaceOps.loadNamespaceMetadata(id); + } + /** + * Lists all tables in a namespace. + * + * @param namespace - Namespace identifier to list tables from + * @returns Array of table identifiers + * + * @example + * ```typescript + * const tables = await catalog.listTables({ namespace: ['analytics'] }); + * console.log(tables); // [{ namespace: ['analytics'], name: 'events' }, ...] + * ``` + */ + async listTables(namespace) { + return this.tableOps.listTables(namespace); + } + /** + * Creates a new table in the catalog. + * + * @param namespace - Namespace to create the table in + * @param request - Table creation request including name, schema, partition spec, etc. + * @returns Table metadata for the created table + * + * @example + * ```typescript + * const metadata = await catalog.createTable( + * { namespace: ['analytics'] }, + * { + * name: 'events', + * schema: { + * type: 'struct', + * fields: [ + * { id: 1, name: 'id', type: 'long', required: true }, + * { id: 2, name: 'timestamp', type: 'timestamp', required: true } + * ], + * 'schema-id': 0 + * }, + * 'partition-spec': { + * 'spec-id': 0, + * fields: [ + * { source_id: 2, field_id: 1000, name: 'ts_day', transform: 'day' } + * ] + * } + * } + * ); + * ``` + */ + async createTable(namespace, request) { + return this.tableOps.createTable(namespace, request); + } + /** + * Updates an existing table's metadata. + * + * Can update the schema, partition spec, or properties of a table. + * + * @param id - Table identifier to update + * @param request - Update request with fields to modify + * @returns Response containing the metadata location and updated table metadata + * + * @example + * ```typescript + * const response = await catalog.updateTable( + * { namespace: ['analytics'], name: 'events' }, + * { + * properties: { 'read.split.target-size': '134217728' } + * } + * ); + * console.log(response['metadata-location']); // s3://... + * console.log(response.metadata); // TableMetadata object + * ``` + */ + async updateTable(id, request) { + return this.tableOps.updateTable(id, request); + } + /** + * Drops a table from the catalog. + * + * @param id - Table identifier to drop + * + * @example + * ```typescript + * await catalog.dropTable({ namespace: ['analytics'], name: 'events' }); + * ``` + */ + async dropTable(id, options) { + await this.tableOps.dropTable(id, options); + } + /** + * Loads metadata for a table. + * + * @param id - Table identifier to load + * @returns Table metadata including schema, partition spec, location, etc. + * + * @example + * ```typescript + * const metadata = await catalog.loadTable({ namespace: ['analytics'], name: 'events' }); + * console.log(metadata.schema); + * console.log(metadata.location); + * ``` + */ + async loadTable(id) { + return this.tableOps.loadTable(id); + } + /** + * Checks if a namespace exists in the catalog. + * + * @param id - Namespace identifier to check + * @returns True if the namespace exists, false otherwise + * + * @example + * ```typescript + * const exists = await catalog.namespaceExists({ namespace: ['analytics'] }); + * console.log(exists); // true or false + * ``` + */ + async namespaceExists(id) { + return this.namespaceOps.namespaceExists(id); + } + /** + * Checks if a table exists in the catalog. + * + * @param id - Table identifier to check + * @returns True if the table exists, false otherwise + * + * @example + * ```typescript + * const exists = await catalog.tableExists({ namespace: ['analytics'], name: 'events' }); + * console.log(exists); // true or false + * ``` + */ + async tableExists(id) { + return this.tableOps.tableExists(id); + } + /** + * Creates a namespace if it does not exist. + * + * If the namespace already exists, returns void. If created, returns the response. + * + * @param id - Namespace identifier to create + * @param metadata - Optional metadata properties for the namespace + * @returns Response containing the created namespace and its properties, or void if it already exists + * + * @example + * ```typescript + * const response = await catalog.createNamespaceIfNotExists( + * { namespace: ['analytics'] }, + * { properties: { owner: 'data-team' } } + * ); + * if (response) { + * console.log('Created:', response.namespace); + * } else { + * console.log('Already exists'); + * } + * ``` + */ + async createNamespaceIfNotExists(id, metadata) { + return this.namespaceOps.createNamespaceIfNotExists(id, metadata); + } + /** + * Creates a table if it does not exist. + * + * If the table already exists, returns its metadata instead. + * + * @param namespace - Namespace to create the table in + * @param request - Table creation request including name, schema, partition spec, etc. + * @returns Table metadata for the created or existing table + * + * @example + * ```typescript + * const metadata = await catalog.createTableIfNotExists( + * { namespace: ['analytics'] }, + * { + * name: 'events', + * schema: { + * type: 'struct', + * fields: [ + * { id: 1, name: 'id', type: 'long', required: true }, + * { id: 2, name: 'timestamp', type: 'timestamp', required: true } + * ], + * 'schema-id': 0 + * } + * } + * ); + * ``` + */ + async createTableIfNotExists(namespace, request) { + return this.tableOps.createTableIfNotExists(namespace, request); + } + }; + var DECIMAL_REGEX = /^decimal\s*\(\s*(\d+)\s*,\s*(\d+)\s*\)$/; + var FIXED_REGEX = /^fixed\s*\[\s*(\d+)\s*\]$/; + function parseDecimalType(type) { + const match = type.match(DECIMAL_REGEX); + if (!match) return null; + return { + precision: parseInt(match[1], 10), + scale: parseInt(match[2], 10) + }; + } + function parseFixedType(type) { + const match = type.match(FIXED_REGEX); + if (!match) return null; + return { + length: parseInt(match[1], 10) + }; + } + function isDecimalType(type) { + return DECIMAL_REGEX.test(type); + } + function isFixedType(type) { + return FIXED_REGEX.test(type); + } + function typesEqual(a2, b3) { + const decimalA = parseDecimalType(a2); + const decimalB = parseDecimalType(b3); + if (decimalA && decimalB) { + return decimalA.precision === decimalB.precision && decimalA.scale === decimalB.scale; + } + const fixedA = parseFixedType(a2); + const fixedB = parseFixedType(b3); + if (fixedA && fixedB) { + return fixedA.length === fixedB.length; + } + return a2 === b3; + } + function getCurrentSchema(metadata) { + return metadata.schemas.find((s2) => s2["schema-id"] === metadata["current-schema-id"]); + } + exports.IcebergError = IcebergError; + exports.IcebergRestCatalog = IcebergRestCatalog; + exports.getCurrentSchema = getCurrentSchema; + exports.isDecimalType = isDecimalType; + exports.isFixedType = isFixedType; + exports.parseDecimalType = parseDecimalType; + exports.parseFixedType = parseFixedType; + exports.typesEqual = typesEqual; + } + }); + + // node_modules/@supabase/storage-js/dist/main/packages/StorageAnalyticsClient.js + var require_StorageAnalyticsClient = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/packages/StorageAnalyticsClient.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var iceberg_js_1 = require_dist2(); + var constants_1 = require_constants3(); + var errors_1 = require_errors(); + var fetch_1 = require_fetch(); + var helpers_1 = require_helpers(); + var StorageAnalyticsClient = class { + /** + * @alpha + * + * Creates a new StorageAnalyticsClient instance + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Analytics Buckets + * @param url - The base URL for the storage API + * @param headers - HTTP headers to include in requests + * @param fetch - Optional custom fetch implementation + * + * @example + * ```typescript + * const client = new StorageAnalyticsClient(url, headers) + * ``` + */ + constructor(url, headers = {}, fetch2) { + this.shouldThrowOnError = false; + this.url = url.replace(/\/$/, ""); + this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); + this.fetch = (0, helpers_1.resolveFetch)(fetch2); + } + /** + * @alpha + * + * Enable throwing errors instead of returning them in the response + * When enabled, failed operations will throw instead of returning { data: null, error } + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Analytics Buckets + * @returns This instance for method chaining + */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + /** + * @alpha + * + * Creates a new analytics bucket using Iceberg tables + * Analytics buckets are optimized for analytical queries and data processing + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Analytics Buckets + * @param name A unique name for the bucket you are creating + * @returns Promise with response containing newly created analytics bucket or error + * + * @example Create analytics bucket + * ```js + * const { data, error } = await supabase + * .storage + * .analytics + * .createBucket('analytics-data') + * ``` + * + * Response: + * ```json + * { + * "data": { + * "name": "analytics-data", + * "type": "ANALYTICS", + * "format": "iceberg", + * "created_at": "2024-05-22T22:26:05.100Z", + * "updated_at": "2024-05-22T22:26:05.100Z" + * }, + * "error": null + * } + * ``` + */ + createBucket(name) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/bucket`, { name }, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * @alpha + * + * Retrieves the details of all Analytics Storage buckets within an existing project + * Only returns buckets of type 'ANALYTICS' + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Analytics Buckets + * @param options Query parameters for listing buckets + * @param options.limit Maximum number of buckets to return + * @param options.offset Number of buckets to skip + * @param options.sortColumn Column to sort by ('name', 'created_at', 'updated_at') + * @param options.sortOrder Sort order ('asc' or 'desc') + * @param options.search Search term to filter bucket names + * @returns Promise with response containing array of analytics buckets or error + * + * @example List analytics buckets + * ```js + * const { data, error } = await supabase + * .storage + * .analytics + * .listBuckets({ + * limit: 10, + * offset: 0, + * sortColumn: 'created_at', + * sortOrder: 'desc' + * }) + * ``` + * + * Response: + * ```json + * { + * "data": [ + * { + * "name": "analytics-data", + * "type": "ANALYTICS", + * "format": "iceberg", + * "created_at": "2024-05-22T22:26:05.100Z", + * "updated_at": "2024-05-22T22:26:05.100Z" + * } + * ], + * "error": null + * } + * ``` + */ + listBuckets(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const queryParams = new URLSearchParams(); + if ((options === null || options === void 0 ? void 0 : options.limit) !== void 0) + queryParams.set("limit", options.limit.toString()); + if ((options === null || options === void 0 ? void 0 : options.offset) !== void 0) + queryParams.set("offset", options.offset.toString()); + if (options === null || options === void 0 ? void 0 : options.sortColumn) + queryParams.set("sortColumn", options.sortColumn); + if (options === null || options === void 0 ? void 0 : options.sortOrder) + queryParams.set("sortOrder", options.sortOrder); + if (options === null || options === void 0 ? void 0 : options.search) + queryParams.set("search", options.search); + const queryString = queryParams.toString(); + const url = queryString ? `${this.url}/bucket?${queryString}` : `${this.url}/bucket`; + const data = yield (0, fetch_1.get)(this.fetch, url, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * @alpha + * + * Deletes an existing analytics bucket + * A bucket can't be deleted with existing objects inside it + * You must first empty the bucket before deletion + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Analytics Buckets + * @param bucketName The unique identifier of the bucket you would like to delete + * @returns Promise with response containing success message or error + * + * @example Delete analytics bucket + * ```js + * const { data, error } = await supabase + * .storage + * .analytics + * .deleteBucket('analytics-data') + * ``` + * + * Response: + * ```json + * { + * "data": { + * "message": "Successfully deleted" + * }, + * "error": null + * } + * ``` + */ + deleteBucket(bucketName) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.remove)(this.fetch, `${this.url}/bucket/${bucketName}`, {}, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** + * @alpha + * + * Get an Iceberg REST Catalog client configured for a specific analytics bucket + * Use this to perform advanced table and namespace operations within the bucket + * The returned client provides full access to the Apache Iceberg REST Catalog API + * with the Supabase `{ data, error }` pattern for consistent error handling on all operations. + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Analytics Buckets + * @param bucketName - The name of the analytics bucket (warehouse) to connect to + * @returns The wrapped Iceberg catalog client + * @throws {StorageError} If the bucket name is invalid + * + * @example Get catalog and create table + * ```js + * // First, create an analytics bucket + * const { data: bucket, error: bucketError } = await supabase + * .storage + * .analytics + * .createBucket('analytics-data') + * + * // Get the Iceberg catalog for that bucket + * const catalog = supabase.storage.analytics.from('analytics-data') + * + * // Create a namespace + * const { error: nsError } = await catalog.createNamespace({ namespace: ['default'] }) + * + * // Create a table with schema + * const { data: tableMetadata, error: tableError } = await catalog.createTable( + * { namespace: ['default'] }, + * { + * name: 'events', + * schema: { + * type: 'struct', + * fields: [ + * { id: 1, name: 'id', type: 'long', required: true }, + * { id: 2, name: 'timestamp', type: 'timestamp', required: true }, + * { id: 3, name: 'user_id', type: 'string', required: false } + * ], + * 'schema-id': 0, + * 'identifier-field-ids': [1] + * }, + * 'partition-spec': { + * 'spec-id': 0, + * fields: [] + * }, + * 'write-order': { + * 'order-id': 0, + * fields: [] + * }, + * properties: { + * 'write.format.default': 'parquet' + * } + * } + * ) + * ``` + * + * @example List tables in namespace + * ```js + * const catalog = supabase.storage.analytics.from('analytics-data') + * + * // List all tables in the default namespace + * const { data: tables, error: listError } = await catalog.listTables({ namespace: ['default'] }) + * if (listError) { + * if (listError.isNotFound()) { + * console.log('Namespace not found') + * } + * return + * } + * console.log(tables) // [{ namespace: ['default'], name: 'events' }] + * ``` + * + * @example Working with namespaces + * ```js + * const catalog = supabase.storage.analytics.from('analytics-data') + * + * // List all namespaces + * const { data: namespaces } = await catalog.listNamespaces() + * + * // Create namespace with properties + * await catalog.createNamespace( + * { namespace: ['production'] }, + * { properties: { owner: 'data-team', env: 'prod' } } + * ) + * ``` + * + * @example Cleanup operations + * ```js + * const catalog = supabase.storage.analytics.from('analytics-data') + * + * // Drop table with purge option (removes all data) + * const { error: dropError } = await catalog.dropTable( + * { namespace: ['default'], name: 'events' }, + * { purge: true } + * ) + * + * if (dropError?.isNotFound()) { + * console.log('Table does not exist') + * } + * + * // Drop namespace (must be empty) + * await catalog.dropNamespace({ namespace: ['default'] }) + * ``` + * + * @remarks + * This method provides a bridge between Supabase's bucket management and the standard + * Apache Iceberg REST Catalog API. The bucket name maps to the Iceberg warehouse parameter. + * All authentication and configuration is handled automatically using your Supabase credentials. + * + * **Error Handling**: Invalid bucket names throw immediately. All catalog + * operations return `{ data, error }` where errors are `IcebergError` instances from iceberg-js. + * Use helper methods like `error.isNotFound()` or check `error.status` for specific error handling. + * Use `.throwOnError()` on the analytics client if you prefer exceptions for catalog operations. + * + * **Cleanup Operations**: When using `dropTable`, the `purge: true` option permanently + * deletes all table data. Without it, the table is marked as deleted but data remains. + * + * **Library Dependency**: The returned catalog wraps `IcebergRestCatalog` from iceberg-js. + * For complete API documentation and advanced usage, refer to the + * [iceberg-js documentation](https://supabase.github.io/iceberg-js/). + */ + from(bucketName) { + if (!(0, helpers_1.isValidBucketName)(bucketName)) { + throw new errors_1.StorageError("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters."); + } + const catalog = new iceberg_js_1.IcebergRestCatalog({ + baseUrl: this.url, + catalogName: bucketName, + // Maps to the warehouse parameter in Supabase's implementation + auth: { + type: "custom", + getHeaders: () => tslib_1.__awaiter(this, void 0, void 0, function* () { + return this.headers; + }) + }, + fetch: this.fetch + }); + const shouldThrowOnError = this.shouldThrowOnError; + const wrappedCatalog = new Proxy(catalog, { + get(target, prop) { + const value = target[prop]; + if (typeof value !== "function") { + return value; + } + return (...args) => tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield value.apply(target, args); + return { data, error: null }; + } catch (error) { + if (shouldThrowOnError) { + throw error; + } + return { data: null, error }; + } + }); + } + }); + return wrappedCatalog; + } + }; + exports.default = StorageAnalyticsClient; + } + }); + + // node_modules/@supabase/storage-js/dist/main/lib/vectors/constants.js + var require_constants4 = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/vectors/constants.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DEFAULT_HEADERS = void 0; + var version_1 = require_version2(); + exports.DEFAULT_HEADERS = { + "X-Client-Info": `storage-js/${version_1.version}`, + "Content-Type": "application/json" + }; + } + }); + + // node_modules/@supabase/storage-js/dist/main/lib/vectors/errors.js + var require_errors2 = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/vectors/errors.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.StorageVectorsErrorCode = exports.StorageVectorsUnknownError = exports.StorageVectorsApiError = exports.StorageVectorsError = void 0; + exports.isStorageVectorsError = isStorageVectorsError; + var StorageVectorsError = class extends Error { + constructor(message) { + super(message); + this.__isStorageVectorsError = true; + this.name = "StorageVectorsError"; + } + }; + exports.StorageVectorsError = StorageVectorsError; + function isStorageVectorsError(error) { + return typeof error === "object" && error !== null && "__isStorageVectorsError" in error; + } + var StorageVectorsApiError = class extends StorageVectorsError { + constructor(message, status, statusCode) { + super(message); + this.name = "StorageVectorsApiError"; + this.status = status; + this.statusCode = statusCode; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + statusCode: this.statusCode + }; + } + }; + exports.StorageVectorsApiError = StorageVectorsApiError; + var StorageVectorsUnknownError = class extends StorageVectorsError { + constructor(message, originalError) { + super(message); + this.name = "StorageVectorsUnknownError"; + this.originalError = originalError; + } + }; + exports.StorageVectorsUnknownError = StorageVectorsUnknownError; + var StorageVectorsErrorCode; + (function(StorageVectorsErrorCode2) { + StorageVectorsErrorCode2["InternalError"] = "InternalError"; + StorageVectorsErrorCode2["S3VectorConflictException"] = "S3VectorConflictException"; + StorageVectorsErrorCode2["S3VectorNotFoundException"] = "S3VectorNotFoundException"; + StorageVectorsErrorCode2["S3VectorBucketNotEmpty"] = "S3VectorBucketNotEmpty"; + StorageVectorsErrorCode2["S3VectorMaxBucketsExceeded"] = "S3VectorMaxBucketsExceeded"; + StorageVectorsErrorCode2["S3VectorMaxIndexesExceeded"] = "S3VectorMaxIndexesExceeded"; + })(StorageVectorsErrorCode || (exports.StorageVectorsErrorCode = StorageVectorsErrorCode = {})); + } + }); + + // node_modules/@supabase/storage-js/dist/main/lib/vectors/helpers.js + var require_helpers2 = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/vectors/helpers.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateVectorDimension = exports.normalizeToFloat32 = exports.isPlainObject = exports.resolveResponse = exports.resolveFetch = void 0; + var resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); + }; + exports.resolveFetch = resolveFetch; + var resolveResponse = () => { + return Response; + }; + exports.resolveResponse = resolveResponse; + var isPlainObject = (value) => { + if (typeof value !== "object" || value === null) { + return false; + } + const prototype = Object.getPrototypeOf(value); + return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value); + }; + exports.isPlainObject = isPlainObject; + var normalizeToFloat32 = (values) => { + return Array.from(new Float32Array(values)); + }; + exports.normalizeToFloat32 = normalizeToFloat32; + var validateVectorDimension = (vector, expectedDimension) => { + if (expectedDimension !== void 0 && vector.float32.length !== expectedDimension) { + throw new Error(`Vector dimension mismatch: expected ${expectedDimension}, got ${vector.float32.length}`); + } + }; + exports.validateVectorDimension = validateVectorDimension; + } + }); + + // node_modules/@supabase/storage-js/dist/main/lib/vectors/fetch.js + var require_fetch2 = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/vectors/fetch.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.get = get3; + exports.post = post; + exports.put = put; + exports.remove = remove6; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var errors_1 = require_errors2(); + var helpers_1 = require_helpers2(); + var _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err); + var handleError = (error, reject, options) => tslib_1.__awaiter(void 0, void 0, void 0, function* () { + const isResponseLike = error && typeof error === "object" && "status" in error && "ok" in error && typeof error.status === "number"; + if (isResponseLike && !(options === null || options === void 0 ? void 0 : options.noResolveJson)) { + const status = error.status || 500; + const responseError = error; + if (typeof responseError.json === "function") { + responseError.json().then((err) => { + const statusCode = (err === null || err === void 0 ? void 0 : err.statusCode) || (err === null || err === void 0 ? void 0 : err.code) || status + ""; + reject(new errors_1.StorageVectorsApiError(_getErrorMessage(err), status, statusCode)); + }).catch(() => { + const statusCode = status + ""; + const message = responseError.statusText || `HTTP ${status} error`; + reject(new errors_1.StorageVectorsApiError(message, status, statusCode)); + }); + } else { + const statusCode = status + ""; + const message = responseError.statusText || `HTTP ${status} error`; + reject(new errors_1.StorageVectorsApiError(message, status, statusCode)); + } + } else { + reject(new errors_1.StorageVectorsUnknownError(_getErrorMessage(error), error)); + } + }); + var _getRequestParams = (method, options, parameters, body) => { + const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; + if (method === "GET" || !body) { + return params; + } + if ((0, helpers_1.isPlainObject)(body)) { + params.headers = Object.assign({ "Content-Type": "application/json" }, options === null || options === void 0 ? void 0 : options.headers); + params.body = JSON.stringify(body); + } else { + params.body = body; + } + return Object.assign(Object.assign({}, params), parameters); + }; + function _handleRequest(fetcher, method, url, options, parameters, body) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + fetcher(url, _getRequestParams(method, options, parameters, body)).then((result) => { + if (!result.ok) + throw result; + if (options === null || options === void 0 ? void 0 : options.noResolveJson) + return result; + const contentType = result.headers.get("content-type"); + if (!contentType || !contentType.includes("application/json")) { + return {}; + } + return result.json(); + }).then((data) => resolve(data)).catch((error) => handleError(error, reject, options)); + }); + }); + } + function get3(fetcher, url, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, "GET", url, options, parameters); + }); + } + function post(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, "POST", url, options, parameters, body); + }); + } + function put(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, "PUT", url, options, parameters, body); + }); + } + function remove6(fetcher, url, body, options, parameters) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _handleRequest(fetcher, "DELETE", url, options, parameters, body); + }); + } + } + }); + + // node_modules/@supabase/storage-js/dist/main/lib/vectors/VectorIndexApi.js + var require_VectorIndexApi = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/vectors/VectorIndexApi.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var constants_1 = require_constants4(); + var errors_1 = require_errors2(); + var fetch_1 = require_fetch2(); + var helpers_1 = require_helpers2(); + var VectorIndexApi = class { + /** Creates a new VectorIndexApi instance */ + constructor(url, headers = {}, fetch2) { + this.shouldThrowOnError = false; + this.url = url.replace(/\/$/, ""); + this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); + this.fetch = (0, helpers_1.resolveFetch)(fetch2); + } + /** Enable throwing errors instead of returning them in the response */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + /** Creates a new vector index within a bucket */ + createIndex(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/CreateIndex`, options, { + headers: this.headers + }); + return { data: data || {}, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** Retrieves metadata for a specific vector index */ + getIndex(vectorBucketName, indexName) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/GetIndex`, { vectorBucketName, indexName }, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** Lists vector indexes within a bucket with optional filtering and pagination */ + listIndexes(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/ListIndexes`, options, { + headers: this.headers + }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** Deletes a vector index and all its data */ + deleteIndex(vectorBucketName, indexName) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/DeleteIndex`, { vectorBucketName, indexName }, { headers: this.headers }); + return { data: data || {}, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + }; + exports.default = VectorIndexApi; + } + }); + + // node_modules/@supabase/storage-js/dist/main/lib/vectors/VectorDataApi.js + var require_VectorDataApi = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/vectors/VectorDataApi.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var constants_1 = require_constants4(); + var errors_1 = require_errors2(); + var fetch_1 = require_fetch2(); + var helpers_1 = require_helpers2(); + var VectorDataApi = class { + /** Creates a new VectorDataApi instance */ + constructor(url, headers = {}, fetch2) { + this.shouldThrowOnError = false; + this.url = url.replace(/\/$/, ""); + this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); + this.fetch = (0, helpers_1.resolveFetch)(fetch2); + } + /** Enable throwing errors instead of returning them in the response */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + /** Inserts or updates vectors in batch (1-500 per request) */ + putVectors(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + if (options.vectors.length < 1 || options.vectors.length > 500) { + throw new Error("Vector batch size must be between 1 and 500 items"); + } + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/PutVectors`, options, { + headers: this.headers + }); + return { data: data || {}, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** Retrieves vectors by their keys in batch */ + getVectors(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/GetVectors`, options, { + headers: this.headers + }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** Lists vectors in an index with pagination */ + listVectors(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + if (options.segmentCount !== void 0) { + if (options.segmentCount < 1 || options.segmentCount > 16) { + throw new Error("segmentCount must be between 1 and 16"); + } + if (options.segmentIndex !== void 0) { + if (options.segmentIndex < 0 || options.segmentIndex >= options.segmentCount) { + throw new Error(`segmentIndex must be between 0 and ${options.segmentCount - 1}`); + } + } + } + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/ListVectors`, options, { + headers: this.headers + }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** Queries for similar vectors using approximate nearest neighbor search */ + queryVectors(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/QueryVectors`, options, { + headers: this.headers + }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** Deletes vectors by their keys in batch (1-500 per request) */ + deleteVectors(options) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + if (options.keys.length < 1 || options.keys.length > 500) { + throw new Error("Keys batch size must be between 1 and 500 items"); + } + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/DeleteVectors`, options, { + headers: this.headers + }); + return { data: data || {}, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + }; + exports.default = VectorDataApi; + } + }); + + // node_modules/@supabase/storage-js/dist/main/lib/vectors/VectorBucketApi.js + var require_VectorBucketApi = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/vectors/VectorBucketApi.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var constants_1 = require_constants4(); + var errors_1 = require_errors2(); + var fetch_1 = require_fetch2(); + var helpers_1 = require_helpers2(); + var VectorBucketApi = class { + /** Creates a new VectorBucketApi instance */ + constructor(url, headers = {}, fetch2) { + this.shouldThrowOnError = false; + this.url = url.replace(/\/$/, ""); + this.headers = Object.assign(Object.assign({}, constants_1.DEFAULT_HEADERS), headers); + this.fetch = (0, helpers_1.resolveFetch)(fetch2); + } + /** Enable throwing errors instead of returning them in the response */ + throwOnError() { + this.shouldThrowOnError = true; + return this; + } + /** Creates a new vector bucket */ + createBucket(vectorBucketName) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/CreateVectorBucket`, { vectorBucketName }, { headers: this.headers }); + return { data: data || {}, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** Retrieves metadata for a specific vector bucket */ + getBucket(vectorBucketName) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/GetVectorBucket`, { vectorBucketName }, { headers: this.headers }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** Lists vector buckets with optional filtering and pagination */ + listBuckets() { + return tslib_1.__awaiter(this, arguments, void 0, function* (options = {}) { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/ListVectorBuckets`, options, { + headers: this.headers + }); + return { data, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + /** Deletes a vector bucket (must be empty first) */ + deleteBucket(vectorBucketName) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + const data = yield (0, fetch_1.post)(this.fetch, `${this.url}/DeleteVectorBucket`, { vectorBucketName }, { headers: this.headers }); + return { data: data || {}, error: null }; + } catch (error) { + if (this.shouldThrowOnError) { + throw error; + } + if ((0, errors_1.isStorageVectorsError)(error)) { + return { data: null, error }; + } + throw error; + } + }); + } + }; + exports.default = VectorBucketApi; + } + }); + + // node_modules/@supabase/storage-js/dist/main/lib/vectors/StorageVectorsClient.js + var require_StorageVectorsClient = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/vectors/StorageVectorsClient.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.VectorIndexScope = exports.VectorBucketScope = exports.StorageVectorsClient = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var VectorIndexApi_1 = tslib_1.__importDefault(require_VectorIndexApi()); + var VectorDataApi_1 = tslib_1.__importDefault(require_VectorDataApi()); + var VectorBucketApi_1 = tslib_1.__importDefault(require_VectorBucketApi()); + var StorageVectorsClient = class extends VectorBucketApi_1.default { + /** + * @alpha + * + * Creates a StorageVectorsClient that can manage buckets, indexes, and vectors. + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param url - Base URL of the Storage Vectors REST API. + * @param options.headers - Optional headers (for example `Authorization`) applied to every request. + * @param options.fetch - Optional custom `fetch` implementation for non-browser runtimes. + * + * @example + * ```typescript + * const client = new StorageVectorsClient(url, options) + * ``` + */ + constructor(url, options = {}) { + super(url, options.headers || {}, options.fetch); + } + /** + * + * @alpha + * + * Access operations for a specific vector bucket + * Returns a scoped client for index and vector operations within the bucket + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param vectorBucketName - Name of the vector bucket + * @returns Bucket-scoped client with index and vector operations + * + * @example + * ```typescript + * const bucket = supabase.storage.vectors.from('embeddings-prod') + * ``` + */ + from(vectorBucketName) { + return new VectorBucketScope(this.url, this.headers, vectorBucketName, this.fetch); + } + /** + * + * @alpha + * + * Creates a new vector bucket + * Vector buckets are containers for vector indexes and their data + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param vectorBucketName - Unique name for the vector bucket + * @returns Promise with empty response on success or error + * + * @example + * ```typescript + * const { data, error } = await supabase + * .storage + * .vectors + * .createBucket('embeddings-prod') + * ``` + */ + createBucket(vectorBucketName) { + const _super = Object.create(null, { + createBucket: { get: () => super.createBucket } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.createBucket.call(this, vectorBucketName); + }); + } + /** + * + * @alpha + * + * Retrieves metadata for a specific vector bucket + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param vectorBucketName - Name of the vector bucket + * @returns Promise with bucket metadata or error + * + * @example + * ```typescript + * const { data, error } = await supabase + * .storage + * .vectors + * .getBucket('embeddings-prod') + * + * console.log('Bucket created:', data?.vectorBucket.creationTime) + * ``` + */ + getBucket(vectorBucketName) { + const _super = Object.create(null, { + getBucket: { get: () => super.getBucket } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.getBucket.call(this, vectorBucketName); + }); + } + /** + * + * @alpha + * + * Lists all vector buckets with optional filtering and pagination + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param options - Optional filters (prefix, maxResults, nextToken) + * @returns Promise with list of buckets or error + * + * @example + * ```typescript + * const { data, error } = await supabase + * .storage + * .vectors + * .listBuckets({ prefix: 'embeddings-' }) + * + * data?.vectorBuckets.forEach(bucket => { + * console.log(bucket.vectorBucketName) + * }) + * ``` + */ + listBuckets() { + const _super = Object.create(null, { + listBuckets: { get: () => super.listBuckets } + }); + return tslib_1.__awaiter(this, arguments, void 0, function* (options = {}) { + return _super.listBuckets.call(this, options); + }); + } + /** + * + * @alpha + * + * Deletes a vector bucket (bucket must be empty) + * All indexes must be deleted before deleting the bucket + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param vectorBucketName - Name of the vector bucket to delete + * @returns Promise with empty response on success or error + * + * @example + * ```typescript + * const { data, error } = await supabase + * .storage + * .vectors + * .deleteBucket('embeddings-old') + * ``` + */ + deleteBucket(vectorBucketName) { + const _super = Object.create(null, { + deleteBucket: { get: () => super.deleteBucket } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.deleteBucket.call(this, vectorBucketName); + }); + } + }; + exports.StorageVectorsClient = StorageVectorsClient; + var VectorBucketScope = class extends VectorIndexApi_1.default { + /** + * @alpha + * + * Creates a helper that automatically scopes all index operations to the provided bucket. + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @example + * ```typescript + * const bucket = supabase.storage.vectors.from('embeddings-prod') + * ``` + */ + constructor(url, headers, vectorBucketName, fetch2) { + super(url, headers, fetch2); + this.vectorBucketName = vectorBucketName; + } + /** + * + * @alpha + * + * Creates a new vector index in this bucket + * Convenience method that automatically includes the bucket name + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param options - Index configuration (vectorBucketName is automatically set) + * @returns Promise with empty response on success or error + * + * @example + * ```typescript + * const bucket = supabase.storage.vectors.from('embeddings-prod') + * await bucket.createIndex({ + * indexName: 'documents-openai', + * dataType: 'float32', + * dimension: 1536, + * distanceMetric: 'cosine', + * metadataConfiguration: { + * nonFilterableMetadataKeys: ['raw_text'] + * } + * }) + * ``` + */ + createIndex(options) { + const _super = Object.create(null, { + createIndex: { get: () => super.createIndex } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.createIndex.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName })); + }); + } + /** + * + * @alpha + * + * Lists indexes in this bucket + * Convenience method that automatically includes the bucket name + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param options - Listing options (vectorBucketName is automatically set) + * @returns Promise with response containing indexes array and pagination token or error + * + * @example + * ```typescript + * const bucket = supabase.storage.vectors.from('embeddings-prod') + * const { data } = await bucket.listIndexes({ prefix: 'documents-' }) + * ``` + */ + listIndexes() { + const _super = Object.create(null, { + listIndexes: { get: () => super.listIndexes } + }); + return tslib_1.__awaiter(this, arguments, void 0, function* (options = {}) { + return _super.listIndexes.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName })); + }); + } + /** + * + * @alpha + * + * Retrieves metadata for a specific index in this bucket + * Convenience method that automatically includes the bucket name + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param indexName - Name of the index to retrieve + * @returns Promise with index metadata or error + * + * @example + * ```typescript + * const bucket = supabase.storage.vectors.from('embeddings-prod') + * const { data } = await bucket.getIndex('documents-openai') + * console.log('Dimension:', data?.index.dimension) + * ``` + */ + getIndex(indexName) { + const _super = Object.create(null, { + getIndex: { get: () => super.getIndex } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.getIndex.call(this, this.vectorBucketName, indexName); + }); + } + /** + * + * @alpha + * + * Deletes an index from this bucket + * Convenience method that automatically includes the bucket name + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param indexName - Name of the index to delete + * @returns Promise with empty response on success or error + * + * @example + * ```typescript + * const bucket = supabase.storage.vectors.from('embeddings-prod') + * await bucket.deleteIndex('old-index') + * ``` + */ + deleteIndex(indexName) { + const _super = Object.create(null, { + deleteIndex: { get: () => super.deleteIndex } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.deleteIndex.call(this, this.vectorBucketName, indexName); + }); + } + /** + * + * @alpha + * + * Access operations for a specific index within this bucket + * Returns a scoped client for vector data operations + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param indexName - Name of the index + * @returns Index-scoped client with vector data operations + * + * @example + * ```typescript + * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai') + * + * // Insert vectors + * await index.putVectors({ + * vectors: [ + * { key: 'doc-1', data: { float32: [...] }, metadata: { title: 'Intro' } } + * ] + * }) + * + * // Query similar vectors + * const { data } = await index.queryVectors({ + * queryVector: { float32: [...] }, + * topK: 5 + * }) + * ``` + */ + index(indexName) { + return new VectorIndexScope(this.url, this.headers, this.vectorBucketName, indexName, this.fetch); + } + }; + exports.VectorBucketScope = VectorBucketScope; + var VectorIndexScope = class extends VectorDataApi_1.default { + /** + * + * @alpha + * + * Creates a helper that automatically scopes all vector operations to the provided bucket/index names. + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @example + * ```typescript + * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai') + * ``` + */ + constructor(url, headers, vectorBucketName, indexName, fetch2) { + super(url, headers, fetch2); + this.vectorBucketName = vectorBucketName; + this.indexName = indexName; + } + /** + * + * @alpha + * + * Inserts or updates vectors in this index + * Convenience method that automatically includes bucket and index names + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param options - Vector insertion options (bucket and index names automatically set) + * @returns Promise with empty response on success or error + * + * @example + * ```typescript + * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai') + * await index.putVectors({ + * vectors: [ + * { + * key: 'doc-1', + * data: { float32: [0.1, 0.2, ...] }, + * metadata: { title: 'Introduction', page: 1 } + * } + * ] + * }) + * ``` + */ + putVectors(options) { + const _super = Object.create(null, { + putVectors: { get: () => super.putVectors } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.putVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); + }); + } + /** + * + * @alpha + * + * Retrieves vectors by keys from this index + * Convenience method that automatically includes bucket and index names + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param options - Vector retrieval options (bucket and index names automatically set) + * @returns Promise with response containing vectors array or error + * + * @example + * ```typescript + * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai') + * const { data } = await index.getVectors({ + * keys: ['doc-1', 'doc-2'], + * returnMetadata: true + * }) + * ``` + */ + getVectors(options) { + const _super = Object.create(null, { + getVectors: { get: () => super.getVectors } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.getVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); + }); + } + /** + * + * @alpha + * + * Lists vectors in this index with pagination + * Convenience method that automatically includes bucket and index names + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param options - Listing options (bucket and index names automatically set) + * @returns Promise with response containing vectors array and pagination token or error + * + * @example + * ```typescript + * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai') + * const { data } = await index.listVectors({ + * maxResults: 500, + * returnMetadata: true + * }) + * ``` + */ + listVectors() { + const _super = Object.create(null, { + listVectors: { get: () => super.listVectors } + }); + return tslib_1.__awaiter(this, arguments, void 0, function* (options = {}) { + return _super.listVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); + }); + } + /** + * + * @alpha + * + * Queries for similar vectors in this index + * Convenience method that automatically includes bucket and index names + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param options - Query options (bucket and index names automatically set) + * @returns Promise with response containing matches array of similar vectors ordered by distance or error + * + * @example + * ```typescript + * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai') + * const { data } = await index.queryVectors({ + * queryVector: { float32: [0.1, 0.2, ...] }, + * topK: 5, + * filter: { category: 'technical' }, + * returnDistance: true, + * returnMetadata: true + * }) + * ``` + */ + queryVectors(options) { + const _super = Object.create(null, { + queryVectors: { get: () => super.queryVectors } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.queryVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); + }); + } + /** + * + * @alpha + * + * Deletes vectors by keys from this index + * Convenience method that automatically includes bucket and index names + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @param options - Deletion options (bucket and index names automatically set) + * @returns Promise with empty response on success or error + * + * @example + * ```typescript + * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai') + * await index.deleteVectors({ + * keys: ['doc-1', 'doc-2', 'doc-3'] + * }) + * ``` + */ + deleteVectors(options) { + const _super = Object.create(null, { + deleteVectors: { get: () => super.deleteVectors } + }); + return tslib_1.__awaiter(this, void 0, void 0, function* () { + return _super.deleteVectors.call(this, Object.assign(Object.assign({}, options), { vectorBucketName: this.vectorBucketName, indexName: this.indexName })); + }); + } + }; + exports.VectorIndexScope = VectorIndexScope; + } + }); + + // node_modules/@supabase/storage-js/dist/main/lib/vectors/index.js + var require_vectors = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/vectors/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateVectorDimension = exports.normalizeToFloat32 = exports.isPlainObject = exports.resolveResponse = exports.resolveFetch = exports.isStorageVectorsError = exports.StorageVectorsErrorCode = exports.StorageVectorsUnknownError = exports.StorageVectorsApiError = exports.StorageVectorsError = exports.VectorDataApi = exports.VectorIndexApi = exports.VectorBucketApi = exports.VectorIndexScope = exports.VectorBucketScope = exports.StorageVectorsClient = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var StorageVectorsClient_1 = require_StorageVectorsClient(); + Object.defineProperty(exports, "StorageVectorsClient", { enumerable: true, get: function() { + return StorageVectorsClient_1.StorageVectorsClient; + } }); + Object.defineProperty(exports, "VectorBucketScope", { enumerable: true, get: function() { + return StorageVectorsClient_1.VectorBucketScope; + } }); + Object.defineProperty(exports, "VectorIndexScope", { enumerable: true, get: function() { + return StorageVectorsClient_1.VectorIndexScope; + } }); + var VectorBucketApi_1 = require_VectorBucketApi(); + Object.defineProperty(exports, "VectorBucketApi", { enumerable: true, get: function() { + return tslib_1.__importDefault(VectorBucketApi_1).default; + } }); + var VectorIndexApi_1 = require_VectorIndexApi(); + Object.defineProperty(exports, "VectorIndexApi", { enumerable: true, get: function() { + return tslib_1.__importDefault(VectorIndexApi_1).default; + } }); + var VectorDataApi_1 = require_VectorDataApi(); + Object.defineProperty(exports, "VectorDataApi", { enumerable: true, get: function() { + return tslib_1.__importDefault(VectorDataApi_1).default; + } }); + var errors_1 = require_errors2(); + Object.defineProperty(exports, "StorageVectorsError", { enumerable: true, get: function() { + return errors_1.StorageVectorsError; + } }); + Object.defineProperty(exports, "StorageVectorsApiError", { enumerable: true, get: function() { + return errors_1.StorageVectorsApiError; + } }); + Object.defineProperty(exports, "StorageVectorsUnknownError", { enumerable: true, get: function() { + return errors_1.StorageVectorsUnknownError; + } }); + Object.defineProperty(exports, "StorageVectorsErrorCode", { enumerable: true, get: function() { + return errors_1.StorageVectorsErrorCode; + } }); + Object.defineProperty(exports, "isStorageVectorsError", { enumerable: true, get: function() { + return errors_1.isStorageVectorsError; + } }); + var helpers_1 = require_helpers2(); + Object.defineProperty(exports, "resolveFetch", { enumerable: true, get: function() { + return helpers_1.resolveFetch; + } }); + Object.defineProperty(exports, "resolveResponse", { enumerable: true, get: function() { + return helpers_1.resolveResponse; + } }); + Object.defineProperty(exports, "isPlainObject", { enumerable: true, get: function() { + return helpers_1.isPlainObject; + } }); + Object.defineProperty(exports, "normalizeToFloat32", { enumerable: true, get: function() { + return helpers_1.normalizeToFloat32; + } }); + Object.defineProperty(exports, "validateVectorDimension", { enumerable: true, get: function() { + return helpers_1.validateVectorDimension; + } }); + } + }); + + // node_modules/@supabase/storage-js/dist/main/StorageClient.js + var require_StorageClient = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/StorageClient.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.StorageClient = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var StorageFileApi_1 = tslib_1.__importDefault(require_StorageFileApi()); + var StorageBucketApi_1 = tslib_1.__importDefault(require_StorageBucketApi()); + var StorageAnalyticsClient_1 = tslib_1.__importDefault(require_StorageAnalyticsClient()); + var vectors_1 = require_vectors(); + var StorageClient = class extends StorageBucketApi_1.default { + /** + * Creates a client for Storage buckets, files, analytics, and vectors. + * + * @category File Buckets + * @example + * ```ts + * import { StorageClient } from '@supabase/storage-js' + * + * const storage = new StorageClient('https://xyzcompany.supabase.co/storage/v1', { + * apikey: 'public-anon-key', + * }) + * const avatars = storage.from('avatars') + * ``` + */ + constructor(url, headers = {}, fetch2, opts) { + super(url, headers, fetch2, opts); + } + /** + * Perform file operation in a bucket. + * + * @category File Buckets + * @param id The bucket id to operate on. + * + * @example + * ```typescript + * const avatars = supabase.storage.from('avatars') + * ``` + */ + from(id) { + return new StorageFileApi_1.default(this.url, this.headers, id, this.fetch); + } + /** + * + * @alpha + * + * Access vector storage operations. + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Vector Buckets + * @returns A StorageVectorsClient instance configured with the current storage settings. + */ + get vectors() { + return new vectors_1.StorageVectorsClient(this.url + "/vector", { + headers: this.headers, + fetch: this.fetch + }); + } + /** + * + * @alpha + * + * Access analytics storage operations using Iceberg tables. + * + * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. + * + * @category Analytics Buckets + * @returns A StorageAnalyticsClient instance configured with the current storage settings. + */ + get analytics() { + return new StorageAnalyticsClient_1.default(this.url + "/iceberg", this.headers, this.fetch); + } + }; + exports.StorageClient = StorageClient; + } + }); + + // node_modules/@supabase/storage-js/dist/main/lib/types.js + var require_types2 = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/lib/types.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + } + }); + + // node_modules/@supabase/storage-js/dist/main/index.js + var require_main3 = __commonJS({ + "node_modules/@supabase/storage-js/dist/main/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.StorageAnalyticsClient = exports.StorageClient = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var StorageClient_1 = require_StorageClient(); + Object.defineProperty(exports, "StorageClient", { enumerable: true, get: function() { + return StorageClient_1.StorageClient; + } }); + var StorageAnalyticsClient_1 = require_StorageAnalyticsClient(); + Object.defineProperty(exports, "StorageAnalyticsClient", { enumerable: true, get: function() { + return tslib_1.__importDefault(StorageAnalyticsClient_1).default; + } }); + tslib_1.__exportStar(require_types2(), exports); + tslib_1.__exportStar(require_errors(), exports); + tslib_1.__exportStar(require_vectors(), exports); + } + }); + + // node_modules/@supabase/supabase-js/dist/main/lib/version.js + var require_version3 = __commonJS({ + "node_modules/@supabase/supabase-js/dist/main/lib/version.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.version = void 0; + exports.version = "2.87.1"; + } + }); + + // node_modules/@supabase/supabase-js/dist/main/lib/constants.js + var require_constants5 = __commonJS({ + "node_modules/@supabase/supabase-js/dist/main/lib/constants.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DEFAULT_REALTIME_OPTIONS = exports.DEFAULT_AUTH_OPTIONS = exports.DEFAULT_DB_OPTIONS = exports.DEFAULT_GLOBAL_OPTIONS = exports.DEFAULT_HEADERS = void 0; + var version_1 = require_version3(); + var JS_ENV = ""; + if (typeof Deno !== "undefined") { + JS_ENV = "deno"; + } else if (typeof document !== "undefined") { + JS_ENV = "web"; + } else if (typeof navigator !== "undefined" && navigator.product === "ReactNative") { + JS_ENV = "react-native"; + } else { + JS_ENV = "node"; + } + exports.DEFAULT_HEADERS = { "X-Client-Info": `supabase-js-${JS_ENV}/${version_1.version}` }; + exports.DEFAULT_GLOBAL_OPTIONS = { + headers: exports.DEFAULT_HEADERS + }; + exports.DEFAULT_DB_OPTIONS = { + schema: "public" + }; + exports.DEFAULT_AUTH_OPTIONS = { + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true, + flowType: "implicit" + }; + exports.DEFAULT_REALTIME_OPTIONS = {}; + } + }); + + // node_modules/@supabase/supabase-js/dist/main/lib/fetch.js + var require_fetch3 = __commonJS({ + "node_modules/@supabase/supabase-js/dist/main/lib/fetch.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fetchWithAuth = exports.resolveHeadersConstructor = exports.resolveFetch = void 0; + var resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); + }; + exports.resolveFetch = resolveFetch; + var resolveHeadersConstructor = () => { + return Headers; + }; + exports.resolveHeadersConstructor = resolveHeadersConstructor; + var fetchWithAuth = (supabaseKey, getAccessToken, customFetch) => { + const fetch2 = (0, exports.resolveFetch)(customFetch); + const HeadersConstructor = (0, exports.resolveHeadersConstructor)(); + return async (input, init) => { + var _a; + const accessToken = (_a = await getAccessToken()) !== null && _a !== void 0 ? _a : supabaseKey; + let headers = new HeadersConstructor(init === null || init === void 0 ? void 0 : init.headers); + if (!headers.has("apikey")) { + headers.set("apikey", supabaseKey); + } + if (!headers.has("Authorization")) { + headers.set("Authorization", `Bearer ${accessToken}`); + } + return fetch2(input, Object.assign(Object.assign({}, init), { headers })); + }; + }; + exports.fetchWithAuth = fetchWithAuth; + } + }); + + // node_modules/@supabase/supabase-js/dist/main/lib/helpers.js + var require_helpers3 = __commonJS({ + "node_modules/@supabase/supabase-js/dist/main/lib/helpers.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isBrowser = void 0; + exports.uuid = uuid; + exports.ensureTrailingSlash = ensureTrailingSlash; + exports.applySettingDefaults = applySettingDefaults; + exports.validateSupabaseUrl = validateSupabaseUrl; + function uuid() { + return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c3) { + var r2 = Math.random() * 16 | 0, v6 = c3 == "x" ? r2 : r2 & 3 | 8; + return v6.toString(16); + }); + } + function ensureTrailingSlash(url) { + return url.endsWith("/") ? url : url + "/"; + } + var isBrowser3 = () => typeof window !== "undefined"; + exports.isBrowser = isBrowser3; + function applySettingDefaults(options, defaults) { + var _a, _b; + const { db: dbOptions, auth: authOptions, realtime: realtimeOptions, global: globalOptions } = options; + const { db: DEFAULT_DB_OPTIONS, auth: DEFAULT_AUTH_OPTIONS, realtime: DEFAULT_REALTIME_OPTIONS, global: DEFAULT_GLOBAL_OPTIONS } = defaults; + const result = { + db: Object.assign(Object.assign({}, DEFAULT_DB_OPTIONS), dbOptions), + auth: Object.assign(Object.assign({}, DEFAULT_AUTH_OPTIONS), authOptions), + realtime: Object.assign(Object.assign({}, DEFAULT_REALTIME_OPTIONS), realtimeOptions), + storage: {}, + global: Object.assign(Object.assign(Object.assign({}, DEFAULT_GLOBAL_OPTIONS), globalOptions), { headers: Object.assign(Object.assign({}, (_a = DEFAULT_GLOBAL_OPTIONS === null || DEFAULT_GLOBAL_OPTIONS === void 0 ? void 0 : DEFAULT_GLOBAL_OPTIONS.headers) !== null && _a !== void 0 ? _a : {}), (_b = globalOptions === null || globalOptions === void 0 ? void 0 : globalOptions.headers) !== null && _b !== void 0 ? _b : {}) }), + accessToken: async () => "" + }; + if (options.accessToken) { + result.accessToken = options.accessToken; + } else { + delete result.accessToken; + } + return result; + } + function validateSupabaseUrl(supabaseUrl) { + const trimmedUrl = supabaseUrl === null || supabaseUrl === void 0 ? void 0 : supabaseUrl.trim(); + if (!trimmedUrl) { + throw new Error("supabaseUrl is required."); + } + if (!trimmedUrl.match(/^https?:\/\//i)) { + throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL."); + } + try { + return new URL(ensureTrailingSlash(trimmedUrl)); + } catch (_a) { + throw Error("Invalid supabaseUrl: Provided URL is malformed."); + } + } + } + }); + + // node_modules/@supabase/auth-js/dist/main/lib/version.js + var require_version4 = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/version.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.version = void 0; + exports.version = "2.87.1"; + } + }); + + // node_modules/@supabase/auth-js/dist/main/lib/constants.js + var require_constants6 = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/constants.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JWKS_TTL = exports.BASE64URL_REGEX = exports.API_VERSIONS = exports.API_VERSION_HEADER_NAME = exports.NETWORK_FAILURE = exports.DEFAULT_HEADERS = exports.AUDIENCE = exports.STORAGE_KEY = exports.GOTRUE_URL = exports.EXPIRY_MARGIN_MS = exports.AUTO_REFRESH_TICK_THRESHOLD = exports.AUTO_REFRESH_TICK_DURATION_MS = void 0; + var version_1 = require_version4(); + exports.AUTO_REFRESH_TICK_DURATION_MS = 30 * 1e3; + exports.AUTO_REFRESH_TICK_THRESHOLD = 3; + exports.EXPIRY_MARGIN_MS = exports.AUTO_REFRESH_TICK_THRESHOLD * exports.AUTO_REFRESH_TICK_DURATION_MS; + exports.GOTRUE_URL = "http://localhost:9999"; + exports.STORAGE_KEY = "supabase.auth.token"; + exports.AUDIENCE = ""; + exports.DEFAULT_HEADERS = { "X-Client-Info": `gotrue-js/${version_1.version}` }; + exports.NETWORK_FAILURE = { + MAX_RETRIES: 10, + RETRY_INTERVAL: 2 + // in deciseconds + }; + exports.API_VERSION_HEADER_NAME = "X-Supabase-Api-Version"; + exports.API_VERSIONS = { + "2024-01-01": { + timestamp: Date.parse("2024-01-01T00:00:00.0Z"), + name: "2024-01-01" + } + }; + exports.BASE64URL_REGEX = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i; + exports.JWKS_TTL = 10 * 60 * 1e3; + } + }); + + // node_modules/@supabase/auth-js/dist/main/lib/errors.js + var require_errors3 = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/errors.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AuthInvalidJwtError = exports.AuthWeakPasswordError = exports.AuthRetryableFetchError = exports.AuthPKCEGrantCodeExchangeError = exports.AuthImplicitGrantRedirectError = exports.AuthInvalidCredentialsError = exports.AuthInvalidTokenResponseError = exports.AuthSessionMissingError = exports.CustomAuthError = exports.AuthUnknownError = exports.AuthApiError = exports.AuthError = void 0; + exports.isAuthError = isAuthError2; + exports.isAuthApiError = isAuthApiError2; + exports.isAuthSessionMissingError = isAuthSessionMissingError2; + exports.isAuthImplicitGrantRedirectError = isAuthImplicitGrantRedirectError2; + exports.isAuthRetryableFetchError = isAuthRetryableFetchError2; + exports.isAuthWeakPasswordError = isAuthWeakPasswordError2; + var AuthError3 = class extends Error { + constructor(message, status, code) { + super(message); + this.__isAuthError = true; + this.name = "AuthError"; + this.status = status; + this.code = code; + } + }; + exports.AuthError = AuthError3; + function isAuthError2(error) { + return typeof error === "object" && error !== null && "__isAuthError" in error; + } + var AuthApiError2 = class extends AuthError3 { + constructor(message, status, code) { + super(message, status, code); + this.name = "AuthApiError"; + this.status = status; + this.code = code; + } + }; + exports.AuthApiError = AuthApiError2; + function isAuthApiError2(error) { + return isAuthError2(error) && error.name === "AuthApiError"; + } + var AuthUnknownError2 = class extends AuthError3 { + constructor(message, originalError) { + super(message); + this.name = "AuthUnknownError"; + this.originalError = originalError; + } + }; + exports.AuthUnknownError = AuthUnknownError2; + var CustomAuthError2 = class extends AuthError3 { + constructor(message, name, status, code) { + super(message, status, code); + this.name = name; + this.status = status; + } + }; + exports.CustomAuthError = CustomAuthError2; + var AuthSessionMissingError2 = class extends CustomAuthError2 { + constructor() { + super("Auth session missing!", "AuthSessionMissingError", 400, void 0); + } + }; + exports.AuthSessionMissingError = AuthSessionMissingError2; + function isAuthSessionMissingError2(error) { + return isAuthError2(error) && error.name === "AuthSessionMissingError"; + } + var AuthInvalidTokenResponseError2 = class extends CustomAuthError2 { + constructor() { + super("Auth session or user missing", "AuthInvalidTokenResponseError", 500, void 0); + } + }; + exports.AuthInvalidTokenResponseError = AuthInvalidTokenResponseError2; + var AuthInvalidCredentialsError2 = class extends CustomAuthError2 { + constructor(message) { + super(message, "AuthInvalidCredentialsError", 400, void 0); + } + }; + exports.AuthInvalidCredentialsError = AuthInvalidCredentialsError2; + var AuthImplicitGrantRedirectError2 = class extends CustomAuthError2 { + constructor(message, details = null) { + super(message, "AuthImplicitGrantRedirectError", 500, void 0); + this.details = null; + this.details = details; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + details: this.details + }; + } + }; + exports.AuthImplicitGrantRedirectError = AuthImplicitGrantRedirectError2; + function isAuthImplicitGrantRedirectError2(error) { + return isAuthError2(error) && error.name === "AuthImplicitGrantRedirectError"; + } + var AuthPKCEGrantCodeExchangeError2 = class extends CustomAuthError2 { + constructor(message, details = null) { + super(message, "AuthPKCEGrantCodeExchangeError", 500, void 0); + this.details = null; + this.details = details; + } + toJSON() { + return { + name: this.name, + message: this.message, + status: this.status, + details: this.details + }; + } + }; + exports.AuthPKCEGrantCodeExchangeError = AuthPKCEGrantCodeExchangeError2; + var AuthRetryableFetchError2 = class extends CustomAuthError2 { + constructor(message, status) { + super(message, "AuthRetryableFetchError", status, void 0); + } + }; + exports.AuthRetryableFetchError = AuthRetryableFetchError2; + function isAuthRetryableFetchError2(error) { + return isAuthError2(error) && error.name === "AuthRetryableFetchError"; + } + var AuthWeakPasswordError2 = class extends CustomAuthError2 { + constructor(message, status, reasons) { + super(message, "AuthWeakPasswordError", status, "weak_password"); + this.reasons = reasons; + } + }; + exports.AuthWeakPasswordError = AuthWeakPasswordError2; + function isAuthWeakPasswordError2(error) { + return isAuthError2(error) && error.name === "AuthWeakPasswordError"; + } + var AuthInvalidJwtError2 = class extends CustomAuthError2 { + constructor(message) { + super(message, "AuthInvalidJwtError", 400, "invalid_jwt"); + } + }; + exports.AuthInvalidJwtError = AuthInvalidJwtError2; + } + }); + + // node_modules/@supabase/auth-js/dist/main/lib/base64url.js + var require_base64url = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/base64url.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.byteToBase64URL = byteToBase64URL; + exports.byteFromBase64URL = byteFromBase64URL; + exports.stringToBase64URL = stringToBase64URL; + exports.stringFromBase64URL = stringFromBase64URL; + exports.codepointToUTF8 = codepointToUTF8; + exports.stringToUTF8 = stringToUTF8; + exports.stringFromUTF8 = stringFromUTF8; + exports.base64UrlToUint8Array = base64UrlToUint8Array; + exports.stringToUint8Array = stringToUint8Array; + exports.bytesToBase64URL = bytesToBase64URL; + var TO_BASE64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""); + var IGNORE_BASE64URL = " \n\r=".split(""); + var FROM_BASE64URL = (() => { + const charMap = new Array(128); + for (let i2 = 0; i2 < charMap.length; i2 += 1) { + charMap[i2] = -1; + } + for (let i2 = 0; i2 < IGNORE_BASE64URL.length; i2 += 1) { + charMap[IGNORE_BASE64URL[i2].charCodeAt(0)] = -2; + } + for (let i2 = 0; i2 < TO_BASE64URL.length; i2 += 1) { + charMap[TO_BASE64URL[i2].charCodeAt(0)] = i2; + } + return charMap; + })(); + function byteToBase64URL(byte, state, emit) { + if (byte !== null) { + state.queue = state.queue << 8 | byte; + state.queuedBits += 8; + while (state.queuedBits >= 6) { + const pos = state.queue >> state.queuedBits - 6 & 63; + emit(TO_BASE64URL[pos]); + state.queuedBits -= 6; + } + } else if (state.queuedBits > 0) { + state.queue = state.queue << 6 - state.queuedBits; + state.queuedBits = 6; + while (state.queuedBits >= 6) { + const pos = state.queue >> state.queuedBits - 6 & 63; + emit(TO_BASE64URL[pos]); + state.queuedBits -= 6; + } + } + } + function byteFromBase64URL(charCode, state, emit) { + const bits = FROM_BASE64URL[charCode]; + if (bits > -1) { + state.queue = state.queue << 6 | bits; + state.queuedBits += 6; + while (state.queuedBits >= 8) { + emit(state.queue >> state.queuedBits - 8 & 255); + state.queuedBits -= 8; + } + } else if (bits === -2) { + return; + } else { + throw new Error(`Invalid Base64-URL character "${String.fromCharCode(charCode)}"`); + } + } + function stringToBase64URL(str) { + const base64 = []; + const emitter = (char) => { + base64.push(char); + }; + const state = { queue: 0, queuedBits: 0 }; + stringToUTF8(str, (byte) => { + byteToBase64URL(byte, state, emitter); + }); + byteToBase64URL(null, state, emitter); + return base64.join(""); + } + function stringFromBase64URL(str) { + const conv = []; + const utf8Emit = (codepoint) => { + conv.push(String.fromCodePoint(codepoint)); + }; + const utf8State = { + utf8seq: 0, + codepoint: 0 + }; + const b64State = { queue: 0, queuedBits: 0 }; + const byteEmit = (byte) => { + stringFromUTF8(byte, utf8State, utf8Emit); + }; + for (let i2 = 0; i2 < str.length; i2 += 1) { + byteFromBase64URL(str.charCodeAt(i2), b64State, byteEmit); + } + return conv.join(""); + } + function codepointToUTF8(codepoint, emit) { + if (codepoint <= 127) { + emit(codepoint); + return; + } else if (codepoint <= 2047) { + emit(192 | codepoint >> 6); + emit(128 | codepoint & 63); + return; + } else if (codepoint <= 65535) { + emit(224 | codepoint >> 12); + emit(128 | codepoint >> 6 & 63); + emit(128 | codepoint & 63); + return; + } else if (codepoint <= 1114111) { + emit(240 | codepoint >> 18); + emit(128 | codepoint >> 12 & 63); + emit(128 | codepoint >> 6 & 63); + emit(128 | codepoint & 63); + return; + } + throw new Error(`Unrecognized Unicode codepoint: ${codepoint.toString(16)}`); + } + function stringToUTF8(str, emit) { + for (let i2 = 0; i2 < str.length; i2 += 1) { + let codepoint = str.charCodeAt(i2); + if (codepoint > 55295 && codepoint <= 56319) { + const highSurrogate = (codepoint - 55296) * 1024 & 65535; + const lowSurrogate = str.charCodeAt(i2 + 1) - 56320 & 65535; + codepoint = (lowSurrogate | highSurrogate) + 65536; + i2 += 1; + } + codepointToUTF8(codepoint, emit); + } + } + function stringFromUTF8(byte, state, emit) { + if (state.utf8seq === 0) { + if (byte <= 127) { + emit(byte); + return; + } + for (let leadingBit = 1; leadingBit < 6; leadingBit += 1) { + if ((byte >> 7 - leadingBit & 1) === 0) { + state.utf8seq = leadingBit; + break; + } + } + if (state.utf8seq === 2) { + state.codepoint = byte & 31; + } else if (state.utf8seq === 3) { + state.codepoint = byte & 15; + } else if (state.utf8seq === 4) { + state.codepoint = byte & 7; + } else { + throw new Error("Invalid UTF-8 sequence"); + } + state.utf8seq -= 1; + } else if (state.utf8seq > 0) { + if (byte <= 127) { + throw new Error("Invalid UTF-8 sequence"); + } + state.codepoint = state.codepoint << 6 | byte & 63; + state.utf8seq -= 1; + if (state.utf8seq === 0) { + emit(state.codepoint); + } + } + } + function base64UrlToUint8Array(str) { + const result = []; + const state = { queue: 0, queuedBits: 0 }; + const onByte = (byte) => { + result.push(byte); + }; + for (let i2 = 0; i2 < str.length; i2 += 1) { + byteFromBase64URL(str.charCodeAt(i2), state, onByte); + } + return new Uint8Array(result); + } + function stringToUint8Array(str) { + const result = []; + stringToUTF8(str, (byte) => result.push(byte)); + return new Uint8Array(result); + } + function bytesToBase64URL(bytes) { + const result = []; + const state = { queue: 0, queuedBits: 0 }; + const onChar = (char) => { + result.push(char); + }; + bytes.forEach((byte) => byteToBase64URL(byte, state, onChar)); + byteToBase64URL(null, state, onChar); + return result.join(""); + } + } + }); + + // node_modules/@supabase/auth-js/dist/main/lib/helpers.js + var require_helpers4 = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/helpers.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Deferred = exports.removeItemAsync = exports.getItemAsync = exports.setItemAsync = exports.looksLikeFetchResponse = exports.resolveFetch = exports.supportsLocalStorage = exports.isBrowser = void 0; + exports.expiresAt = expiresAt; + exports.generateCallbackId = generateCallbackId; + exports.parseParametersFromURL = parseParametersFromURL; + exports.decodeJWT = decodeJWT; + exports.sleep = sleep2; + exports.retryable = retryable; + exports.generatePKCEVerifier = generatePKCEVerifier; + exports.generatePKCEChallenge = generatePKCEChallenge; + exports.getCodeChallengeAndMethod = getCodeChallengeAndMethod; + exports.parseResponseAPIVersion = parseResponseAPIVersion; + exports.validateExp = validateExp; + exports.getAlgorithm = getAlgorithm; + exports.validateUUID = validateUUID; + exports.userNotAvailableProxy = userNotAvailableProxy; + exports.insecureUserWarningProxy = insecureUserWarningProxy; + exports.deepClone = deepClone2; + var constants_1 = require_constants6(); + var errors_1 = require_errors3(); + var base64url_1 = require_base64url(); + function expiresAt(expiresIn) { + const timeNow = Math.round(Date.now() / 1e3); + return timeNow + expiresIn; + } + function generateCallbackId() { + return Symbol("auth-callback"); + } + var isBrowser3 = () => typeof window !== "undefined" && typeof document !== "undefined"; + exports.isBrowser = isBrowser3; + var localStorageWriteTests = { + tested: false, + writable: false + }; + var supportsLocalStorage = () => { + if (!(0, exports.isBrowser)()) { + return false; + } + try { + if (typeof globalThis.localStorage !== "object") { + return false; + } + } catch (e2) { + return false; + } + if (localStorageWriteTests.tested) { + return localStorageWriteTests.writable; + } + const randomKey = `lswt-${Math.random()}${Math.random()}`; + try { + globalThis.localStorage.setItem(randomKey, randomKey); + globalThis.localStorage.removeItem(randomKey); + localStorageWriteTests.tested = true; + localStorageWriteTests.writable = true; + } catch (e2) { + localStorageWriteTests.tested = true; + localStorageWriteTests.writable = false; + } + return localStorageWriteTests.writable; + }; + exports.supportsLocalStorage = supportsLocalStorage; + function parseParametersFromURL(href) { + const result = {}; + const url = new URL(href); + if (url.hash && url.hash[0] === "#") { + try { + const hashSearchParams = new URLSearchParams(url.hash.substring(1)); + hashSearchParams.forEach((value, key) => { + result[key] = value; + }); + } catch (e2) { + } + } + url.searchParams.forEach((value, key) => { + result[key] = value; + }); + return result; + } + var resolveFetch = (customFetch) => { + if (customFetch) { + return (...args) => customFetch(...args); + } + return (...args) => fetch(...args); + }; + exports.resolveFetch = resolveFetch; + var looksLikeFetchResponse = (maybeResponse) => { + return typeof maybeResponse === "object" && maybeResponse !== null && "status" in maybeResponse && "ok" in maybeResponse && "json" in maybeResponse && typeof maybeResponse.json === "function"; + }; + exports.looksLikeFetchResponse = looksLikeFetchResponse; + var setItemAsync = async (storage, key, data) => { + await storage.setItem(key, JSON.stringify(data)); + }; + exports.setItemAsync = setItemAsync; + var getItemAsync = async (storage, key) => { + const value = await storage.getItem(key); + if (!value) { + return null; + } + try { + return JSON.parse(value); + } catch (_a) { + return value; + } + }; + exports.getItemAsync = getItemAsync; + var removeItemAsync = async (storage, key) => { + await storage.removeItem(key); + }; + exports.removeItemAsync = removeItemAsync; + var Deferred = class _Deferred { + constructor() { + ; + this.promise = new _Deferred.promiseConstructor((res, rej) => { + ; + this.resolve = res; + this.reject = rej; + }); + } + }; + exports.Deferred = Deferred; + Deferred.promiseConstructor = Promise; + function decodeJWT(token) { + const parts = token.split("."); + if (parts.length !== 3) { + throw new errors_1.AuthInvalidJwtError("Invalid JWT structure"); + } + for (let i2 = 0; i2 < parts.length; i2++) { + if (!constants_1.BASE64URL_REGEX.test(parts[i2])) { + throw new errors_1.AuthInvalidJwtError("JWT not in base64url format"); + } + } + const data = { + // using base64url lib + header: JSON.parse((0, base64url_1.stringFromBase64URL)(parts[0])), + payload: JSON.parse((0, base64url_1.stringFromBase64URL)(parts[1])), + signature: (0, base64url_1.base64UrlToUint8Array)(parts[2]), + raw: { + header: parts[0], + payload: parts[1] + } + }; + return data; + } + async function sleep2(time2) { + return await new Promise((accept) => { + setTimeout(() => accept(null), time2); + }); + } + function retryable(fn, isRetryable) { + const promise = new Promise((accept, reject) => { + ; + (async () => { + for (let attempt = 0; attempt < Infinity; attempt++) { + try { + const result = await fn(attempt); + if (!isRetryable(attempt, null, result)) { + accept(result); + return; + } + } catch (e2) { + if (!isRetryable(attempt, e2)) { + reject(e2); + return; + } + } + } + })(); + }); + return promise; + } + function dec2hex(dec) { + return ("0" + dec.toString(16)).substr(-2); + } + function generatePKCEVerifier() { + const verifierLength = 56; + const array = new Uint32Array(verifierLength); + if (typeof crypto === "undefined") { + const charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"; + const charSetLen = charSet.length; + let verifier = ""; + for (let i2 = 0; i2 < verifierLength; i2++) { + verifier += charSet.charAt(Math.floor(Math.random() * charSetLen)); + } + return verifier; + } + crypto.getRandomValues(array); + return Array.from(array, dec2hex).join(""); + } + async function sha256(randomString) { + const encoder2 = new TextEncoder(); + const encodedData = encoder2.encode(randomString); + const hash = await crypto.subtle.digest("SHA-256", encodedData); + const bytes = new Uint8Array(hash); + return Array.from(bytes).map((c3) => String.fromCharCode(c3)).join(""); + } + async function generatePKCEChallenge(verifier) { + const hasCryptoSupport = typeof crypto !== "undefined" && typeof crypto.subtle !== "undefined" && typeof TextEncoder !== "undefined"; + if (!hasCryptoSupport) { + console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."); + return verifier; + } + const hashed = await sha256(verifier); + return btoa(hashed).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); + } + async function getCodeChallengeAndMethod(storage, storageKey, isPasswordRecovery = false) { + const codeVerifier = generatePKCEVerifier(); + let storedCodeVerifier = codeVerifier; + if (isPasswordRecovery) { + storedCodeVerifier += "/PASSWORD_RECOVERY"; + } + await (0, exports.setItemAsync)(storage, `${storageKey}-code-verifier`, storedCodeVerifier); + const codeChallenge = await generatePKCEChallenge(codeVerifier); + const codeChallengeMethod = codeVerifier === codeChallenge ? "plain" : "s256"; + return [codeChallenge, codeChallengeMethod]; + } + var API_VERSION_REGEX = /^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i; + function parseResponseAPIVersion(response) { + const apiVersion = response.headers.get(constants_1.API_VERSION_HEADER_NAME); + if (!apiVersion) { + return null; + } + if (!apiVersion.match(API_VERSION_REGEX)) { + return null; + } + try { + const date2 = /* @__PURE__ */ new Date(`${apiVersion}T00:00:00.0Z`); + return date2; + } catch (e2) { + return null; + } + } + function validateExp(exp) { + if (!exp) { + throw new Error("Missing exp claim"); + } + const timeNow = Math.floor(Date.now() / 1e3); + if (exp <= timeNow) { + throw new Error("JWT has expired"); + } + } + function getAlgorithm(alg) { + switch (alg) { + case "RS256": + return { + name: "RSASSA-PKCS1-v1_5", + hash: { name: "SHA-256" } + }; + case "ES256": + return { + name: "ECDSA", + namedCurve: "P-256", + hash: { name: "SHA-256" } + }; + default: + throw new Error("Invalid alg claim"); + } + } + var UUID_REGEX2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; + function validateUUID(str) { + if (!UUID_REGEX2.test(str)) { + throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not"); + } + } + function userNotAvailableProxy() { + const proxyTarget = {}; + return new Proxy(proxyTarget, { + get: (target, prop) => { + if (prop === "__isUserNotAvailableProxy") { + return true; + } + if (typeof prop === "symbol") { + const sProp = prop.toString(); + if (sProp === "Symbol(Symbol.toPrimitive)" || sProp === "Symbol(Symbol.toStringTag)" || sProp === "Symbol(util.inspect.custom)") { + return void 0; + } + } + throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${prop}" property of the session object is not supported. Please use getUser() instead.`); + }, + set: (_target, prop) => { + throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`); + }, + deleteProperty: (_target, prop) => { + throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${prop}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`); + } + }); + } + function insecureUserWarningProxy(user, suppressWarningRef) { + return new Proxy(user, { + get: (target, prop, receiver) => { + if (prop === "__isInsecureUserWarningProxy") { + return true; + } + if (typeof prop === "symbol") { + const sProp = prop.toString(); + if (sProp === "Symbol(Symbol.toPrimitive)" || sProp === "Symbol(Symbol.toStringTag)" || sProp === "Symbol(util.inspect.custom)" || sProp === "Symbol(nodejs.util.inspect.custom)") { + return Reflect.get(target, prop, receiver); + } + } + if (!suppressWarningRef.value && typeof prop === "string") { + console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."); + suppressWarningRef.value = true; + } + return Reflect.get(target, prop, receiver); + } + }); + } + function deepClone2(obj) { + return JSON.parse(JSON.stringify(obj)); + } + } + }); + + // node_modules/@supabase/auth-js/dist/main/lib/fetch.js + var require_fetch4 = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/fetch.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.handleError = handleError; + exports._request = _request; + exports._sessionResponse = _sessionResponse; + exports._sessionResponsePassword = _sessionResponsePassword; + exports._userResponse = _userResponse; + exports._ssoResponse = _ssoResponse; + exports._generateLinkResponse = _generateLinkResponse; + exports._noResolveJsonResponse = _noResolveJsonResponse; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var constants_1 = require_constants6(); + var helpers_1 = require_helpers4(); + var errors_1 = require_errors3(); + var _getErrorMessage = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err); + var NETWORK_ERROR_CODES = [502, 503, 504]; + async function handleError(error) { + var _a; + if (!(0, helpers_1.looksLikeFetchResponse)(error)) { + throw new errors_1.AuthRetryableFetchError(_getErrorMessage(error), 0); + } + if (NETWORK_ERROR_CODES.includes(error.status)) { + throw new errors_1.AuthRetryableFetchError(_getErrorMessage(error), error.status); + } + let data; + try { + data = await error.json(); + } catch (e2) { + throw new errors_1.AuthUnknownError(_getErrorMessage(e2), e2); + } + let errorCode = void 0; + const responseAPIVersion = (0, helpers_1.parseResponseAPIVersion)(error); + if (responseAPIVersion && responseAPIVersion.getTime() >= constants_1.API_VERSIONS["2024-01-01"].timestamp && typeof data === "object" && data && typeof data.code === "string") { + errorCode = data.code; + } else if (typeof data === "object" && data && typeof data.error_code === "string") { + errorCode = data.error_code; + } + if (!errorCode) { + if (typeof data === "object" && data && typeof data.weak_password === "object" && data.weak_password && Array.isArray(data.weak_password.reasons) && data.weak_password.reasons.length && data.weak_password.reasons.reduce((a2, i2) => a2 && typeof i2 === "string", true)) { + throw new errors_1.AuthWeakPasswordError(_getErrorMessage(data), error.status, data.weak_password.reasons); + } + } else if (errorCode === "weak_password") { + throw new errors_1.AuthWeakPasswordError(_getErrorMessage(data), error.status, ((_a = data.weak_password) === null || _a === void 0 ? void 0 : _a.reasons) || []); + } else if (errorCode === "session_not_found") { + throw new errors_1.AuthSessionMissingError(); + } + throw new errors_1.AuthApiError(_getErrorMessage(data), error.status || 500, errorCode); + } + var _getRequestParams = (method, options, parameters, body) => { + const params = { method, headers: (options === null || options === void 0 ? void 0 : options.headers) || {} }; + if (method === "GET") { + return params; + } + params.headers = Object.assign({ "Content-Type": "application/json;charset=UTF-8" }, options === null || options === void 0 ? void 0 : options.headers); + params.body = JSON.stringify(body); + return Object.assign(Object.assign({}, params), parameters); + }; + async function _request(fetcher, method, url, options) { + var _a; + const headers = Object.assign({}, options === null || options === void 0 ? void 0 : options.headers); + if (!headers[constants_1.API_VERSION_HEADER_NAME]) { + headers[constants_1.API_VERSION_HEADER_NAME] = constants_1.API_VERSIONS["2024-01-01"].name; + } + if (options === null || options === void 0 ? void 0 : options.jwt) { + headers["Authorization"] = `Bearer ${options.jwt}`; + } + const qs = (_a = options === null || options === void 0 ? void 0 : options.query) !== null && _a !== void 0 ? _a : {}; + if (options === null || options === void 0 ? void 0 : options.redirectTo) { + qs["redirect_to"] = options.redirectTo; + } + const queryString = Object.keys(qs).length ? "?" + new URLSearchParams(qs).toString() : ""; + const data = await _handleRequest(fetcher, method, url + queryString, { + headers, + noResolveJson: options === null || options === void 0 ? void 0 : options.noResolveJson + }, {}, options === null || options === void 0 ? void 0 : options.body); + return (options === null || options === void 0 ? void 0 : options.xform) ? options === null || options === void 0 ? void 0 : options.xform(data) : { data: Object.assign({}, data), error: null }; + } + async function _handleRequest(fetcher, method, url, options, parameters, body) { + const requestParams = _getRequestParams(method, options, parameters, body); + let result; + try { + result = await fetcher(url, Object.assign({}, requestParams)); + } catch (e2) { + console.error(e2); + throw new errors_1.AuthRetryableFetchError(_getErrorMessage(e2), 0); + } + if (!result.ok) { + await handleError(result); + } + if (options === null || options === void 0 ? void 0 : options.noResolveJson) { + return result; + } + try { + return await result.json(); + } catch (e2) { + await handleError(e2); + } + } + function _sessionResponse(data) { + var _a; + let session = null; + if (hasSession(data)) { + session = Object.assign({}, data); + if (!data.expires_at) { + session.expires_at = (0, helpers_1.expiresAt)(data.expires_in); + } + } + const user = (_a = data.user) !== null && _a !== void 0 ? _a : data; + return { data: { session, user }, error: null }; + } + function _sessionResponsePassword(data) { + const response = _sessionResponse(data); + if (!response.error && data.weak_password && typeof data.weak_password === "object" && Array.isArray(data.weak_password.reasons) && data.weak_password.reasons.length && data.weak_password.message && typeof data.weak_password.message === "string" && data.weak_password.reasons.reduce((a2, i2) => a2 && typeof i2 === "string", true)) { + response.data.weak_password = data.weak_password; + } + return response; + } + function _userResponse(data) { + var _a; + const user = (_a = data.user) !== null && _a !== void 0 ? _a : data; + return { data: { user }, error: null }; + } + function _ssoResponse(data) { + return { data, error: null }; + } + function _generateLinkResponse(data) { + const { action_link, email_otp, hashed_token, redirect_to, verification_type } = data, rest = tslib_1.__rest(data, ["action_link", "email_otp", "hashed_token", "redirect_to", "verification_type"]); + const properties = { + action_link, + email_otp, + hashed_token, + redirect_to, + verification_type + }; + const user = Object.assign({}, rest); + return { + data: { + properties, + user + }, + error: null + }; + } + function _noResolveJsonResponse(data) { + return data; + } + function hasSession(data) { + return data.access_token && data.refresh_token && data.expires_in; + } + } + }); + + // node_modules/@supabase/auth-js/dist/main/lib/types.js + var require_types3 = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/types.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SIGN_OUT_SCOPES = void 0; + exports.SIGN_OUT_SCOPES = ["global", "local", "others"]; + } + }); + + // node_modules/@supabase/auth-js/dist/main/GoTrueAdminApi.js + var require_GoTrueAdminApi = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/GoTrueAdminApi.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var fetch_1 = require_fetch4(); + var helpers_1 = require_helpers4(); + var types_1 = require_types3(); + var errors_1 = require_errors3(); + var GoTrueAdminApi2 = class { + /** + * Creates an admin API client that can be used to manage users and OAuth clients. + * + * @example + * ```ts + * import { GoTrueAdminApi } from '@supabase/auth-js' + * + * const admin = new GoTrueAdminApi({ + * url: 'https://xyzcompany.supabase.co/auth/v1', + * headers: { Authorization: `Bearer ${process.env.SUPABASE_SERVICE_ROLE_KEY}` }, + * }) + * ``` + */ + constructor({ url = "", headers = {}, fetch: fetch2 }) { + this.url = url; + this.headers = headers; + this.fetch = (0, helpers_1.resolveFetch)(fetch2); + this.mfa = { + listFactors: this._listFactors.bind(this), + deleteFactor: this._deleteFactor.bind(this) + }; + this.oauth = { + listClients: this._listOAuthClients.bind(this), + createClient: this._createOAuthClient.bind(this), + getClient: this._getOAuthClient.bind(this), + updateClient: this._updateOAuthClient.bind(this), + deleteClient: this._deleteOAuthClient.bind(this), + regenerateClientSecret: this._regenerateOAuthClientSecret.bind(this) + }; + } + /** + * Removes a logged-in session. + * @param jwt A valid, logged-in JWT. + * @param scope The logout sope. + */ + async signOut(jwt, scope = types_1.SIGN_OUT_SCOPES[0]) { + if (types_1.SIGN_OUT_SCOPES.indexOf(scope) < 0) { + throw new Error(`@supabase/auth-js: Parameter scope must be one of ${types_1.SIGN_OUT_SCOPES.join(", ")}`); + } + try { + await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/logout?scope=${scope}`, { + headers: this.headers, + jwt, + noResolveJson: true + }); + return { data: null, error: null }; + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Sends an invite link to an email address. + * @param email The email address of the user. + * @param options Additional options to be included when inviting. + */ + async inviteUserByEmail(email, options = {}) { + try { + return await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/invite`, { + body: { email, data: options.data }, + headers: this.headers, + redirectTo: options.redirectTo, + xform: fetch_1._userResponse + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Generates email links and OTPs to be sent via a custom email provider. + * @param email The user's email. + * @param options.password User password. For signup only. + * @param options.data Optional user metadata. For signup only. + * @param options.redirectTo The redirect url which should be appended to the generated link + */ + async generateLink(params) { + try { + const { options } = params, rest = tslib_1.__rest(params, ["options"]); + const body = Object.assign(Object.assign({}, rest), options); + if ("newEmail" in rest) { + body.new_email = rest === null || rest === void 0 ? void 0 : rest.newEmail; + delete body["newEmail"]; + } + return await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/admin/generate_link`, { + body, + headers: this.headers, + xform: fetch_1._generateLinkResponse, + redirectTo: options === null || options === void 0 ? void 0 : options.redirectTo + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { + data: { + properties: null, + user: null + }, + error + }; + } + throw error; + } + } + // User Admin API + /** + * Creates a new user. + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async createUser(attributes) { + try { + return await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/admin/users`, { + body: attributes, + headers: this.headers, + xform: fetch_1._userResponse + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Get a list of users. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results. + */ + async listUsers(params) { + var _a, _b, _c, _d, _e2, _f, _g; + try { + const pagination = { nextPage: null, lastPage: 0, total: 0 }; + const response = await (0, fetch_1._request)(this.fetch, "GET", `${this.url}/admin/users`, { + headers: this.headers, + noResolveJson: true, + query: { + page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : "", + per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : "" + }, + xform: fetch_1._noResolveJsonResponse + }); + if (response.error) + throw response.error; + const users = await response.json(); + const total = (_e2 = response.headers.get("x-total-count")) !== null && _e2 !== void 0 ? _e2 : 0; + const links = (_g = (_f = response.headers.get("link")) === null || _f === void 0 ? void 0 : _f.split(",")) !== null && _g !== void 0 ? _g : []; + if (links.length > 0) { + links.forEach((link) => { + const page = parseInt(link.split(";")[0].split("=")[1].substring(0, 1)); + const rel = JSON.parse(link.split(";")[1].split("=")[1]); + pagination[`${rel}Page`] = page; + }); + pagination.total = parseInt(total); + } + return { data: Object.assign(Object.assign({}, users), pagination), error: null }; + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { users: [] }, error }; + } + throw error; + } + } + /** + * Get user by id. + * + * @param uid The user's unique identifier + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async getUserById(uid) { + (0, helpers_1.validateUUID)(uid); + try { + return await (0, fetch_1._request)(this.fetch, "GET", `${this.url}/admin/users/${uid}`, { + headers: this.headers, + xform: fetch_1._userResponse + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Updates the user data. + * + * @param attributes The data you want to update. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async updateUserById(uid, attributes) { + (0, helpers_1.validateUUID)(uid); + try { + return await (0, fetch_1._request)(this.fetch, "PUT", `${this.url}/admin/users/${uid}`, { + body: attributes, + headers: this.headers, + xform: fetch_1._userResponse + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + /** + * Delete a user. Requires a `service_role` key. + * + * @param id The user id you want to remove. + * @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. Soft deletion allows user identification from the hashed user ID but is not reversible. + * Defaults to false for backward compatibility. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async deleteUser(id, shouldSoftDelete = false) { + (0, helpers_1.validateUUID)(id); + try { + return await (0, fetch_1._request)(this.fetch, "DELETE", `${this.url}/admin/users/${id}`, { + headers: this.headers, + body: { + should_soft_delete: shouldSoftDelete + }, + xform: fetch_1._userResponse + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { user: null }, error }; + } + throw error; + } + } + async _listFactors(params) { + (0, helpers_1.validateUUID)(params.userId); + try { + const { data, error } = await (0, fetch_1._request)(this.fetch, "GET", `${this.url}/admin/users/${params.userId}/factors`, { + headers: this.headers, + xform: (factors) => { + return { data: { factors }, error: null }; + } + }); + return { data, error }; + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + async _deleteFactor(params) { + (0, helpers_1.validateUUID)(params.userId); + (0, helpers_1.validateUUID)(params.id); + try { + const data = await (0, fetch_1._request)(this.fetch, "DELETE", `${this.url}/admin/users/${params.userId}/factors/${params.id}`, { + headers: this.headers + }); + return { data, error: null }; + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Lists all OAuth clients with optional pagination. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _listOAuthClients(params) { + var _a, _b, _c, _d, _e2, _f, _g; + try { + const pagination = { nextPage: null, lastPage: 0, total: 0 }; + const response = await (0, fetch_1._request)(this.fetch, "GET", `${this.url}/admin/oauth/clients`, { + headers: this.headers, + noResolveJson: true, + query: { + page: (_b = (_a = params === null || params === void 0 ? void 0 : params.page) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : "", + per_page: (_d = (_c = params === null || params === void 0 ? void 0 : params.perPage) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : "" + }, + xform: fetch_1._noResolveJsonResponse + }); + if (response.error) + throw response.error; + const clients = await response.json(); + const total = (_e2 = response.headers.get("x-total-count")) !== null && _e2 !== void 0 ? _e2 : 0; + const links = (_g = (_f = response.headers.get("link")) === null || _f === void 0 ? void 0 : _f.split(",")) !== null && _g !== void 0 ? _g : []; + if (links.length > 0) { + links.forEach((link) => { + const page = parseInt(link.split(";")[0].split("=")[1].substring(0, 1)); + const rel = JSON.parse(link.split(";")[1].split("=")[1]); + pagination[`${rel}Page`] = page; + }); + pagination.total = parseInt(total); + } + return { data: Object.assign(Object.assign({}, clients), pagination), error: null }; + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: { clients: [] }, error }; + } + throw error; + } + } + /** + * Creates a new OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _createOAuthClient(params) { + try { + return await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/admin/oauth/clients`, { + body: params, + headers: this.headers, + xform: (client2) => { + return { data: client2, error: null }; + } + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Gets details of a specific OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _getOAuthClient(clientId) { + try { + return await (0, fetch_1._request)(this.fetch, "GET", `${this.url}/admin/oauth/clients/${clientId}`, { + headers: this.headers, + xform: (client2) => { + return { data: client2, error: null }; + } + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Updates an existing OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _updateOAuthClient(clientId, params) { + try { + return await (0, fetch_1._request)(this.fetch, "PUT", `${this.url}/admin/oauth/clients/${clientId}`, { + body: params, + headers: this.headers, + xform: (client2) => { + return { data: client2, error: null }; + } + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Deletes an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _deleteOAuthClient(clientId) { + try { + await (0, fetch_1._request)(this.fetch, "DELETE", `${this.url}/admin/oauth/clients/${clientId}`, { + headers: this.headers, + noResolveJson: true + }); + return { data: null, error: null }; + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + /** + * Regenerates the secret for an OAuth client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * This function should only be called on a server. Never expose your `service_role` key in the browser. + */ + async _regenerateOAuthClientSecret(clientId) { + try { + return await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/admin/oauth/clients/${clientId}/regenerate_secret`, { + headers: this.headers, + xform: (client2) => { + return { data: client2, error: null }; + } + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + throw error; + } + } + }; + exports.default = GoTrueAdminApi2; + } + }); + + // node_modules/@supabase/auth-js/dist/main/lib/local-storage.js + var require_local_storage = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/local-storage.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.memoryLocalStorageAdapter = memoryLocalStorageAdapter; + function memoryLocalStorageAdapter(store2 = {}) { + return { + getItem: (key) => { + return store2[key] || null; + }, + setItem: (key, value) => { + store2[key] = value; + }, + removeItem: (key) => { + delete store2[key]; + } + }; + } + } + }); + + // node_modules/@supabase/auth-js/dist/main/lib/locks.js + var require_locks = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/locks.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProcessLockAcquireTimeoutError = exports.NavigatorLockAcquireTimeoutError = exports.LockAcquireTimeoutError = exports.internals = void 0; + exports.navigatorLock = navigatorLock2; + exports.processLock = processLock2; + var helpers_1 = require_helpers4(); + exports.internals = { + /** + * @experimental + */ + debug: !!(globalThis && (0, helpers_1.supportsLocalStorage)() && globalThis.localStorage && globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug") === "true") + }; + var LockAcquireTimeoutError = class extends Error { + constructor(message) { + super(message); + this.isAcquireTimeout = true; + } + }; + exports.LockAcquireTimeoutError = LockAcquireTimeoutError; + var NavigatorLockAcquireTimeoutError2 = class extends LockAcquireTimeoutError { + }; + exports.NavigatorLockAcquireTimeoutError = NavigatorLockAcquireTimeoutError2; + var ProcessLockAcquireTimeoutError = class extends LockAcquireTimeoutError { + }; + exports.ProcessLockAcquireTimeoutError = ProcessLockAcquireTimeoutError; + async function navigatorLock2(name, acquireTimeout, fn) { + if (exports.internals.debug) { + console.log("@supabase/gotrue-js: navigatorLock: acquire lock", name, acquireTimeout); + } + const abortController = new globalThis.AbortController(); + if (acquireTimeout > 0) { + setTimeout(() => { + abortController.abort(); + if (exports.internals.debug) { + console.log("@supabase/gotrue-js: navigatorLock acquire timed out", name); + } + }, acquireTimeout); + } + return await Promise.resolve().then(() => globalThis.navigator.locks.request(name, acquireTimeout === 0 ? { + mode: "exclusive", + ifAvailable: true + } : { + mode: "exclusive", + signal: abortController.signal + }, async (lock) => { + if (lock) { + if (exports.internals.debug) { + console.log("@supabase/gotrue-js: navigatorLock: acquired", name, lock.name); + } + try { + return await fn(); + } finally { + if (exports.internals.debug) { + console.log("@supabase/gotrue-js: navigatorLock: released", name, lock.name); + } + } + } else { + if (acquireTimeout === 0) { + if (exports.internals.debug) { + console.log("@supabase/gotrue-js: navigatorLock: not immediately available", name); + } + throw new NavigatorLockAcquireTimeoutError2(`Acquiring an exclusive Navigator LockManager lock "${name}" immediately failed`); + } else { + if (exports.internals.debug) { + try { + const result = await globalThis.navigator.locks.query(); + console.log("@supabase/gotrue-js: Navigator LockManager state", JSON.stringify(result, null, " ")); + } catch (e2) { + console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state", e2); + } + } + console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"); + return await fn(); + } + } + })); + } + var PROCESS_LOCKS = {}; + async function processLock2(name, acquireTimeout, fn) { + var _a; + const previousOperation = (_a = PROCESS_LOCKS[name]) !== null && _a !== void 0 ? _a : Promise.resolve(); + const currentOperation = Promise.race([ + previousOperation.catch(() => { + return null; + }), + acquireTimeout >= 0 ? new Promise((_2, reject) => { + setTimeout(() => { + reject(new ProcessLockAcquireTimeoutError(`Acquring process lock with name "${name}" timed out`)); + }, acquireTimeout); + }) : null + ].filter((x3) => x3)).catch((e2) => { + if (e2 && e2.isAcquireTimeout) { + throw e2; + } + return null; + }).then(async () => { + return await fn(); + }); + PROCESS_LOCKS[name] = currentOperation.catch(async (e2) => { + if (e2 && e2.isAcquireTimeout) { + await previousOperation; + return null; + } + throw e2; + }); + return await currentOperation; + } + } + }); + + // node_modules/@supabase/auth-js/dist/main/lib/polyfills.js + var require_polyfills = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/polyfills.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.polyfillGlobalThis = polyfillGlobalThis; + function polyfillGlobalThis() { + if (typeof globalThis === "object") + return; + try { + Object.defineProperty(Object.prototype, "__magic__", { + get: function() { + return this; + }, + configurable: true + }); + __magic__.globalThis = __magic__; + delete Object.prototype.__magic__; + } catch (e2) { + if (typeof self !== "undefined") { + self.globalThis = self; + } + } + } + } + }); + + // node_modules/@supabase/auth-js/dist/main/lib/web3/ethereum.js + var require_ethereum = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/web3/ethereum.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getAddress = getAddress; + exports.fromHex = fromHex3; + exports.toHex = toHex3; + exports.createSiweMessage = createSiweMessage; + function getAddress(address) { + if (!/^0x[a-fA-F0-9]{40}$/.test(address)) { + throw new Error(`@supabase/auth-js: Address "${address}" is invalid.`); + } + return address.toLowerCase(); + } + function fromHex3(hex) { + return parseInt(hex, 16); + } + function toHex3(value) { + const bytes = new TextEncoder().encode(value); + const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(""); + return "0x" + hex; + } + function createSiweMessage(parameters) { + var _a; + const { chainId, domain, expirationTime, issuedAt = /* @__PURE__ */ new Date(), nonce, notBefore, requestId, resources, scheme, uri: uri2, version } = parameters; + { + if (!Number.isInteger(chainId)) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${chainId}`); + if (!domain) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.`); + if (nonce && nonce.length < 8) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${nonce}`); + if (!uri2) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.`); + if (version !== "1") + throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${version}`); + if ((_a = parameters.statement) === null || _a === void 0 ? void 0 : _a.includes("\n")) + throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${parameters.statement}`); + } + const address = getAddress(parameters.address); + const origin = scheme ? `${scheme}://${domain}` : domain; + const statement = parameters.statement ? `${parameters.statement} +` : ""; + const prefix = `${origin} wants you to sign in with your Ethereum account: +${address} + +${statement}`; + let suffix = `URI: ${uri2} +Version: ${version} +Chain ID: ${chainId}${nonce ? ` +Nonce: ${nonce}` : ""} +Issued At: ${issuedAt.toISOString()}`; + if (expirationTime) + suffix += ` +Expiration Time: ${expirationTime.toISOString()}`; + if (notBefore) + suffix += ` +Not Before: ${notBefore.toISOString()}`; + if (requestId) + suffix += ` +Request ID: ${requestId}`; + if (resources) { + let content = "\nResources:"; + for (const resource of resources) { + if (!resource || typeof resource !== "string") + throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${resource}`); + content += ` +- ${resource}`; + } + suffix += content; + } + return `${prefix} +${suffix}`; + } + } + }); + + // node_modules/@supabase/auth-js/dist/main/lib/webauthn.errors.js + var require_webauthn_errors = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/webauthn.errors.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.WebAuthnUnknownError = exports.WebAuthnError = void 0; + exports.isWebAuthnError = isWebAuthnError; + exports.identifyRegistrationError = identifyRegistrationError; + exports.identifyAuthenticationError = identifyAuthenticationError; + var webauthn_1 = require_webauthn(); + var WebAuthnError = class extends Error { + constructor({ message, code, cause, name }) { + var _a; + super(message, { cause }); + this.__isWebAuthnError = true; + this.name = (_a = name !== null && name !== void 0 ? name : cause instanceof Error ? cause.name : void 0) !== null && _a !== void 0 ? _a : "Unknown Error"; + this.code = code; + } + }; + exports.WebAuthnError = WebAuthnError; + var WebAuthnUnknownError = class extends WebAuthnError { + constructor(message, originalError) { + super({ + code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY", + cause: originalError, + message + }); + this.name = "WebAuthnUnknownError"; + this.originalError = originalError; + } + }; + exports.WebAuthnUnknownError = WebAuthnUnknownError; + function isWebAuthnError(error) { + return typeof error === "object" && error !== null && "__isWebAuthnError" in error; + } + function identifyRegistrationError({ error, options }) { + var _a, _b, _c; + const { publicKey } = options; + if (!publicKey) { + throw Error("options was missing required publicKey property"); + } + if (error.name === "AbortError") { + if (options.signal instanceof AbortSignal) { + return new WebAuthnError({ + message: "Registration ceremony was sent an abort signal", + code: "ERROR_CEREMONY_ABORTED", + cause: error + }); + } + } else if (error.name === "ConstraintError") { + if (((_a = publicKey.authenticatorSelection) === null || _a === void 0 ? void 0 : _a.requireResidentKey) === true) { + return new WebAuthnError({ + message: "Discoverable credentials were required but no available authenticator supported it", + code: "ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT", + cause: error + }); + } else if ( + // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024 + options.mediation === "conditional" && ((_b = publicKey.authenticatorSelection) === null || _b === void 0 ? void 0 : _b.userVerification) === "required" + ) { + return new WebAuthnError({ + message: "User verification was required during automatic registration but it could not be performed", + code: "ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE", + cause: error + }); + } else if (((_c = publicKey.authenticatorSelection) === null || _c === void 0 ? void 0 : _c.userVerification) === "required") { + return new WebAuthnError({ + message: "User verification was required but no available authenticator supported it", + code: "ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT", + cause: error + }); + } + } else if (error.name === "InvalidStateError") { + return new WebAuthnError({ + message: "The authenticator was previously registered", + code: "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED", + cause: error + }); + } else if (error.name === "NotAllowedError") { + return new WebAuthnError({ + message: error.message, + code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY", + cause: error + }); + } else if (error.name === "NotSupportedError") { + const validPubKeyCredParams = publicKey.pubKeyCredParams.filter((param) => param.type === "public-key"); + if (validPubKeyCredParams.length === 0) { + return new WebAuthnError({ + message: 'No entry in pubKeyCredParams was of type "public-key"', + code: "ERROR_MALFORMED_PUBKEYCREDPARAMS", + cause: error + }); + } + return new WebAuthnError({ + message: "No available authenticator supported any of the specified pubKeyCredParams algorithms", + code: "ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG", + cause: error + }); + } else if (error.name === "SecurityError") { + const effectiveDomain = window.location.hostname; + if (!(0, webauthn_1.isValidDomain)(effectiveDomain)) { + return new WebAuthnError({ + message: `${window.location.hostname} is an invalid domain`, + code: "ERROR_INVALID_DOMAIN", + cause: error + }); + } else if (publicKey.rp.id !== effectiveDomain) { + return new WebAuthnError({ + message: `The RP ID "${publicKey.rp.id}" is invalid for this domain`, + code: "ERROR_INVALID_RP_ID", + cause: error + }); + } + } else if (error.name === "TypeError") { + if (publicKey.user.id.byteLength < 1 || publicKey.user.id.byteLength > 64) { + return new WebAuthnError({ + message: "User ID was not between 1 and 64 characters", + code: "ERROR_INVALID_USER_ID_LENGTH", + cause: error + }); + } + } else if (error.name === "UnknownError") { + return new WebAuthnError({ + message: "The authenticator was unable to process the specified options, or could not create a new credential", + code: "ERROR_AUTHENTICATOR_GENERAL_ERROR", + cause: error + }); + } + return new WebAuthnError({ + message: "a Non-Webauthn related error has occurred", + code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY", + cause: error + }); + } + function identifyAuthenticationError({ error, options }) { + const { publicKey } = options; + if (!publicKey) { + throw Error("options was missing required publicKey property"); + } + if (error.name === "AbortError") { + if (options.signal instanceof AbortSignal) { + return new WebAuthnError({ + message: "Authentication ceremony was sent an abort signal", + code: "ERROR_CEREMONY_ABORTED", + cause: error + }); + } + } else if (error.name === "NotAllowedError") { + return new WebAuthnError({ + message: error.message, + code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY", + cause: error + }); + } else if (error.name === "SecurityError") { + const effectiveDomain = window.location.hostname; + if (!(0, webauthn_1.isValidDomain)(effectiveDomain)) { + return new WebAuthnError({ + message: `${window.location.hostname} is an invalid domain`, + code: "ERROR_INVALID_DOMAIN", + cause: error + }); + } else if (publicKey.rpId !== effectiveDomain) { + return new WebAuthnError({ + message: `The RP ID "${publicKey.rpId}" is invalid for this domain`, + code: "ERROR_INVALID_RP_ID", + cause: error + }); + } + } else if (error.name === "UnknownError") { + return new WebAuthnError({ + message: "The authenticator was unable to process the specified options, or could not create a new assertion signature", + code: "ERROR_AUTHENTICATOR_GENERAL_ERROR", + cause: error + }); + } + return new WebAuthnError({ + message: "a Non-Webauthn related error has occurred", + code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY", + cause: error + }); + } + } + }); + + // node_modules/@supabase/auth-js/dist/main/lib/webauthn.js + var require_webauthn = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/lib/webauthn.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.WebAuthnApi = exports.DEFAULT_REQUEST_OPTIONS = exports.DEFAULT_CREATION_OPTIONS = exports.webAuthnAbortService = exports.WebAuthnAbortService = exports.identifyAuthenticationError = exports.identifyRegistrationError = exports.isWebAuthnError = exports.WebAuthnError = void 0; + exports.deserializeCredentialCreationOptions = deserializeCredentialCreationOptions; + exports.deserializeCredentialRequestOptions = deserializeCredentialRequestOptions; + exports.serializeCredentialCreationResponse = serializeCredentialCreationResponse; + exports.serializeCredentialRequestResponse = serializeCredentialRequestResponse; + exports.isValidDomain = isValidDomain; + exports.createCredential = createCredential; + exports.getCredential = getCredential; + exports.mergeCredentialCreationOptions = mergeCredentialCreationOptions; + exports.mergeCredentialRequestOptions = mergeCredentialRequestOptions; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var base64url_1 = require_base64url(); + var errors_1 = require_errors3(); + var helpers_1 = require_helpers4(); + var webauthn_errors_1 = require_webauthn_errors(); + Object.defineProperty(exports, "identifyAuthenticationError", { enumerable: true, get: function() { + return webauthn_errors_1.identifyAuthenticationError; + } }); + Object.defineProperty(exports, "identifyRegistrationError", { enumerable: true, get: function() { + return webauthn_errors_1.identifyRegistrationError; + } }); + Object.defineProperty(exports, "isWebAuthnError", { enumerable: true, get: function() { + return webauthn_errors_1.isWebAuthnError; + } }); + Object.defineProperty(exports, "WebAuthnError", { enumerable: true, get: function() { + return webauthn_errors_1.WebAuthnError; + } }); + var WebAuthnAbortService = class { + /** + * Create an abort signal for a new WebAuthn operation. + * Automatically cancels any existing operation. + * + * @returns {AbortSignal} Signal to pass to navigator.credentials.create() or .get() + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal MDN - AbortSignal} + */ + createNewAbortSignal() { + if (this.controller) { + const abortError = new Error("Cancelling existing WebAuthn API call for new one"); + abortError.name = "AbortError"; + this.controller.abort(abortError); + } + const newController = new AbortController(); + this.controller = newController; + return newController.signal; + } + /** + * Manually cancel the current WebAuthn operation. + * Useful for cleaning up when user cancels or navigates away. + * + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort MDN - AbortController.abort} + */ + cancelCeremony() { + if (this.controller) { + const abortError = new Error("Manually cancelling existing WebAuthn API call"); + abortError.name = "AbortError"; + this.controller.abort(abortError); + this.controller = void 0; + } + } + }; + exports.WebAuthnAbortService = WebAuthnAbortService; + exports.webAuthnAbortService = new WebAuthnAbortService(); + function deserializeCredentialCreationOptions(options) { + if (!options) { + throw new Error("Credential creation options are required"); + } + if (typeof PublicKeyCredential !== "undefined" && "parseCreationOptionsFromJSON" in PublicKeyCredential && typeof PublicKeyCredential.parseCreationOptionsFromJSON === "function") { + return PublicKeyCredential.parseCreationOptionsFromJSON( + /** we assert the options here as typescript still doesn't know about future webauthn types */ + options + ); + } + const { challenge: challengeStr, user: userOpts, excludeCredentials } = options, restOptions = tslib_1.__rest( + options, + ["challenge", "user", "excludeCredentials"] + ); + const challenge = (0, base64url_1.base64UrlToUint8Array)(challengeStr).buffer; + const user = Object.assign(Object.assign({}, userOpts), { id: (0, base64url_1.base64UrlToUint8Array)(userOpts.id).buffer }); + const result = Object.assign(Object.assign({}, restOptions), { + challenge, + user + }); + if (excludeCredentials && excludeCredentials.length > 0) { + result.excludeCredentials = new Array(excludeCredentials.length); + for (let i2 = 0; i2 < excludeCredentials.length; i2++) { + const cred = excludeCredentials[i2]; + result.excludeCredentials[i2] = Object.assign(Object.assign({}, cred), { + id: (0, base64url_1.base64UrlToUint8Array)(cred.id).buffer, + type: cred.type || "public-key", + // Cast transports to handle future transport types like "cable" + transports: cred.transports + }); + } + } + return result; + } + function deserializeCredentialRequestOptions(options) { + if (!options) { + throw new Error("Credential request options are required"); + } + if (typeof PublicKeyCredential !== "undefined" && "parseRequestOptionsFromJSON" in PublicKeyCredential && typeof PublicKeyCredential.parseRequestOptionsFromJSON === "function") { + return PublicKeyCredential.parseRequestOptionsFromJSON(options); + } + const { challenge: challengeStr, allowCredentials } = options, restOptions = tslib_1.__rest( + options, + ["challenge", "allowCredentials"] + ); + const challenge = (0, base64url_1.base64UrlToUint8Array)(challengeStr).buffer; + const result = Object.assign(Object.assign({}, restOptions), { challenge }); + if (allowCredentials && allowCredentials.length > 0) { + result.allowCredentials = new Array(allowCredentials.length); + for (let i2 = 0; i2 < allowCredentials.length; i2++) { + const cred = allowCredentials[i2]; + result.allowCredentials[i2] = Object.assign(Object.assign({}, cred), { + id: (0, base64url_1.base64UrlToUint8Array)(cred.id).buffer, + type: cred.type || "public-key", + // Cast transports to handle future transport types like "cable" + transports: cred.transports + }); + } + } + return result; + } + function serializeCredentialCreationResponse(credential) { + var _a; + if ("toJSON" in credential && typeof credential.toJSON === "function") { + return credential.toJSON(); + } + const credentialWithAttachment = credential; + return { + id: credential.id, + rawId: credential.id, + response: { + attestationObject: (0, base64url_1.bytesToBase64URL)(new Uint8Array(credential.response.attestationObject)), + clientDataJSON: (0, base64url_1.bytesToBase64URL)(new Uint8Array(credential.response.clientDataJSON)) + }, + type: "public-key", + clientExtensionResults: credential.getClientExtensionResults(), + // Convert null to undefined and cast to AuthenticatorAttachment type + authenticatorAttachment: (_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : void 0 + }; + } + function serializeCredentialRequestResponse(credential) { + var _a; + if ("toJSON" in credential && typeof credential.toJSON === "function") { + return credential.toJSON(); + } + const credentialWithAttachment = credential; + const clientExtensionResults = credential.getClientExtensionResults(); + const assertionResponse = credential.response; + return { + id: credential.id, + rawId: credential.id, + // W3C spec expects rawId to match id for JSON format + response: { + authenticatorData: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.authenticatorData)), + clientDataJSON: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.clientDataJSON)), + signature: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.signature)), + userHandle: assertionResponse.userHandle ? (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.userHandle)) : void 0 + }, + type: "public-key", + clientExtensionResults, + // Convert null to undefined and cast to AuthenticatorAttachment type + authenticatorAttachment: (_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : void 0 + }; + } + function isValidDomain(hostname) { + return ( + // Consider localhost valid as well since it's okay wrt Secure Contexts + hostname === "localhost" || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname) + ); + } + function browserSupportsWebAuthn() { + var _a, _b; + return !!((0, helpers_1.isBrowser)() && "PublicKeyCredential" in window && window.PublicKeyCredential && "credentials" in navigator && typeof ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _a === void 0 ? void 0 : _a.create) === "function" && typeof ((_b = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _b === void 0 ? void 0 : _b.get) === "function"); + } + async function createCredential(options) { + try { + const response = await navigator.credentials.create( + /** we assert the type here until typescript types are updated */ + options + ); + if (!response) { + return { + data: null, + error: new webauthn_errors_1.WebAuthnUnknownError("Empty credential response", response) + }; + } + if (!(response instanceof PublicKeyCredential)) { + return { + data: null, + error: new webauthn_errors_1.WebAuthnUnknownError("Browser returned unexpected credential type", response) + }; + } + return { data: response, error: null }; + } catch (err) { + return { + data: null, + error: (0, webauthn_errors_1.identifyRegistrationError)({ + error: err, + options + }) + }; + } + } + async function getCredential(options) { + try { + const response = await navigator.credentials.get( + /** we assert the type here until typescript types are updated */ + options + ); + if (!response) { + return { + data: null, + error: new webauthn_errors_1.WebAuthnUnknownError("Empty credential response", response) + }; + } + if (!(response instanceof PublicKeyCredential)) { + return { + data: null, + error: new webauthn_errors_1.WebAuthnUnknownError("Browser returned unexpected credential type", response) + }; + } + return { data: response, error: null }; + } catch (err) { + return { + data: null, + error: (0, webauthn_errors_1.identifyAuthenticationError)({ + error: err, + options + }) + }; + } + } + exports.DEFAULT_CREATION_OPTIONS = { + hints: ["security-key"], + authenticatorSelection: { + authenticatorAttachment: "cross-platform", + requireResidentKey: false, + /** set to preferred because older yubikeys don't have PIN/Biometric */ + userVerification: "preferred", + residentKey: "discouraged" + }, + attestation: "direct" + }; + exports.DEFAULT_REQUEST_OPTIONS = { + /** set to preferred because older yubikeys don't have PIN/Biometric */ + userVerification: "preferred", + hints: ["security-key"], + attestation: "direct" + }; + function deepMerge(...sources) { + const isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val); + const isArrayBufferLike = (val) => val instanceof ArrayBuffer || ArrayBuffer.isView(val); + const result = {}; + for (const source of sources) { + if (!source) + continue; + for (const key in source) { + const value = source[key]; + if (value === void 0) + continue; + if (Array.isArray(value)) { + result[key] = value; + } else if (isArrayBufferLike(value)) { + result[key] = value; + } else if (isObject(value)) { + const existing = result[key]; + if (isObject(existing)) { + result[key] = deepMerge(existing, value); + } else { + result[key] = deepMerge(value); + } + } else { + result[key] = value; + } + } + } + return result; + } + function mergeCredentialCreationOptions(baseOptions, overrides) { + return deepMerge(exports.DEFAULT_CREATION_OPTIONS, baseOptions, overrides || {}); + } + function mergeCredentialRequestOptions(baseOptions, overrides) { + return deepMerge(exports.DEFAULT_REQUEST_OPTIONS, baseOptions, overrides || {}); + } + var WebAuthnApi = class { + constructor(client2) { + this.client = client2; + this.enroll = this._enroll.bind(this); + this.challenge = this._challenge.bind(this); + this.verify = this._verify.bind(this); + this.authenticate = this._authenticate.bind(this); + this.register = this._register.bind(this); + } + /** + * Enroll a new WebAuthn factor. + * Creates an unverified WebAuthn factor that must be verified with a credential. + * + * @experimental This method is experimental and may change in future releases + * @param {Omit} params - Enrollment parameters (friendlyName required) + * @returns {Promise} Enrolled factor details or error + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential} + */ + async _enroll(params) { + return this.client.mfa.enroll(Object.assign(Object.assign({}, params), { factorType: "webauthn" })); + } + /** + * Challenge for WebAuthn credential creation or authentication. + * Combines server challenge with browser credential operations. + * Handles both registration (create) and authentication (request) flows. + * + * @experimental This method is experimental and may change in future releases + * @param {MFAChallengeWebauthnParams & { friendlyName?: string; signal?: AbortSignal }} params - Challenge parameters including factorId + * @param {Object} overrides - Allows you to override the parameters passed to navigator.credentials + * @param {PublicKeyCredentialCreationOptionsFuture} overrides.create - Override options for credential creation + * @param {PublicKeyCredentialRequestOptionsFuture} overrides.request - Override options for credential request + * @returns {Promise} Challenge response with credential or error + * @see {@link https://w3c.github.io/webauthn/#sctn-credential-creation W3C WebAuthn Spec - Credential Creation} + * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying Assertion} + */ + async _challenge({ factorId, webauthn, friendlyName, signal }, overrides) { + try { + const { data: challengeResponse, error: challengeError } = await this.client.mfa.challenge({ + factorId, + webauthn + }); + if (!challengeResponse) { + return { data: null, error: challengeError }; + } + const abortSignal = signal !== null && signal !== void 0 ? signal : exports.webAuthnAbortService.createNewAbortSignal(); + if (challengeResponse.webauthn.type === "create") { + const { user } = challengeResponse.webauthn.credential_options.publicKey; + if (!user.name) { + user.name = `${user.id}:${friendlyName}`; + } + if (!user.displayName) { + user.displayName = user.name; + } + } + switch (challengeResponse.webauthn.type) { + case "create": { + const options = mergeCredentialCreationOptions(challengeResponse.webauthn.credential_options.publicKey, overrides === null || overrides === void 0 ? void 0 : overrides.create); + const { data, error } = await createCredential({ + publicKey: options, + signal: abortSignal + }); + if (data) { + return { + data: { + factorId, + challengeId: challengeResponse.id, + webauthn: { + type: challengeResponse.webauthn.type, + credential_response: data + } + }, + error: null + }; + } + return { data: null, error }; + } + case "request": { + const options = mergeCredentialRequestOptions(challengeResponse.webauthn.credential_options.publicKey, overrides === null || overrides === void 0 ? void 0 : overrides.request); + const { data, error } = await getCredential(Object.assign(Object.assign({}, challengeResponse.webauthn.credential_options), { publicKey: options, signal: abortSignal })); + if (data) { + return { + data: { + factorId, + challengeId: challengeResponse.id, + webauthn: { + type: challengeResponse.webauthn.type, + credential_response: data + } + }, + error: null + }; + } + return { data: null, error }; + } + } + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + return { + data: null, + error: new errors_1.AuthUnknownError("Unexpected error in challenge", error) + }; + } + } + /** + * Verify a WebAuthn credential with the server. + * Completes the WebAuthn ceremony by sending the credential to the server for verification. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Verification parameters + * @param {string} params.challengeId - ID of the challenge being verified + * @param {string} params.factorId - ID of the WebAuthn factor + * @param {MFAVerifyWebauthnParams['webauthn']} params.webauthn - WebAuthn credential response + * @returns {Promise} Verification result with session or error + * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying an Authentication Assertion} + * */ + async _verify({ challengeId, factorId, webauthn }) { + return this.client.mfa.verify({ + factorId, + challengeId, + webauthn + }); + } + /** + * Complete WebAuthn authentication flow. + * Performs challenge and verification in a single operation for existing credentials. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Authentication parameters + * @param {string} params.factorId - ID of the WebAuthn factor to authenticate with + * @param {Object} params.webauthn - WebAuthn configuration + * @param {string} params.webauthn.rpId - Relying Party ID (defaults to current hostname) + * @param {string[]} params.webauthn.rpOrigins - Allowed origins (defaults to current origin) + * @param {AbortSignal} params.webauthn.signal - Optional abort signal + * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Override options for navigator.credentials.get + * @returns {Promise>} Authentication result + * @see {@link https://w3c.github.io/webauthn/#sctn-authentication W3C WebAuthn Spec - Authentication Ceremony} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions MDN - PublicKeyCredentialRequestOptions} + */ + async _authenticate({ factorId, webauthn: { rpId = typeof window !== "undefined" ? window.location.hostname : void 0, rpOrigins = typeof window !== "undefined" ? [window.location.origin] : void 0, signal } = {} }, overrides) { + if (!rpId) { + return { + data: null, + error: new errors_1.AuthError("rpId is required for WebAuthn authentication") + }; + } + try { + if (!browserSupportsWebAuthn()) { + return { + data: null, + error: new errors_1.AuthUnknownError("Browser does not support WebAuthn", null) + }; + } + const { data: challengeResponse, error: challengeError } = await this.challenge({ + factorId, + webauthn: { rpId, rpOrigins }, + signal + }, { request: overrides }); + if (!challengeResponse) { + return { data: null, error: challengeError }; + } + const { webauthn } = challengeResponse; + return this._verify({ + factorId, + challengeId: challengeResponse.challengeId, + webauthn: { + type: webauthn.type, + rpId, + rpOrigins, + credential_response: webauthn.credential_response + } + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + return { + data: null, + error: new errors_1.AuthUnknownError("Unexpected error in authenticate", error) + }; + } + } + /** + * Complete WebAuthn registration flow. + * Performs enrollment, challenge, and verification in a single operation for new credentials. + * + * @experimental This method is experimental and may change in future releases + * @param {Object} params - Registration parameters + * @param {string} params.friendlyName - User-friendly name for the credential + * @param {string} params.rpId - Relying Party ID (defaults to current hostname) + * @param {string[]} params.rpOrigins - Allowed origins (defaults to current origin) + * @param {AbortSignal} params.signal - Optional abort signal + * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Override options for navigator.credentials.create + * @returns {Promise>} Registration result + * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registration Ceremony} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions MDN - PublicKeyCredentialCreationOptions} + */ + async _register({ friendlyName, webauthn: { rpId = typeof window !== "undefined" ? window.location.hostname : void 0, rpOrigins = typeof window !== "undefined" ? [window.location.origin] : void 0, signal } = {} }, overrides) { + if (!rpId) { + return { + data: null, + error: new errors_1.AuthError("rpId is required for WebAuthn registration") + }; + } + try { + if (!browserSupportsWebAuthn()) { + return { + data: null, + error: new errors_1.AuthUnknownError("Browser does not support WebAuthn", null) + }; + } + const { data: factor, error: enrollError } = await this._enroll({ + friendlyName + }); + if (!factor) { + await this.client.mfa.listFactors().then((factors) => { + var _a; + return (_a = factors.data) === null || _a === void 0 ? void 0 : _a.all.find((v6) => v6.factor_type === "webauthn" && v6.friendly_name === friendlyName && v6.status !== "unverified"); + }).then((factor2) => factor2 ? this.client.mfa.unenroll({ factorId: factor2 === null || factor2 === void 0 ? void 0 : factor2.id }) : void 0); + return { data: null, error: enrollError }; + } + const { data: challengeResponse, error: challengeError } = await this._challenge({ + factorId: factor.id, + friendlyName: factor.friendly_name, + webauthn: { rpId, rpOrigins }, + signal + }, { + create: overrides + }); + if (!challengeResponse) { + return { data: null, error: challengeError }; + } + return this._verify({ + factorId: factor.id, + challengeId: challengeResponse.challengeId, + webauthn: { + rpId, + rpOrigins, + type: challengeResponse.webauthn.type, + credential_response: challengeResponse.webauthn.credential_response + } + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return { data: null, error }; + } + return { + data: null, + error: new errors_1.AuthUnknownError("Unexpected error in register", error) + }; + } + } + }; + exports.WebAuthnApi = WebAuthnApi; + } + }); + + // node_modules/@supabase/auth-js/dist/main/GoTrueClient.js + var require_GoTrueClient = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/GoTrueClient.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var GoTrueAdminApi_1 = tslib_1.__importDefault(require_GoTrueAdminApi()); + var constants_1 = require_constants6(); + var errors_1 = require_errors3(); + var fetch_1 = require_fetch4(); + var helpers_1 = require_helpers4(); + var local_storage_1 = require_local_storage(); + var locks_1 = require_locks(); + var polyfills_1 = require_polyfills(); + var version_1 = require_version4(); + var base64url_1 = require_base64url(); + var ethereum_1 = require_ethereum(); + var webauthn_1 = require_webauthn(); + (0, polyfills_1.polyfillGlobalThis)(); + var DEFAULT_OPTIONS = { + url: constants_1.GOTRUE_URL, + storageKey: constants_1.STORAGE_KEY, + autoRefreshToken: true, + persistSession: true, + detectSessionInUrl: true, + headers: constants_1.DEFAULT_HEADERS, + flowType: "implicit", + debug: false, + hasCustomAuthorizationHeader: false, + throwOnError: false + }; + async function lockNoOp(name, acquireTimeout, fn) { + return await fn(); + } + var GLOBAL_JWKS = {}; + var GoTrueClient2 = class _GoTrueClient { + /** + * The JWKS used for verifying asymmetric JWTs + */ + get jwks() { + var _a, _b; + return (_b = (_a = GLOBAL_JWKS[this.storageKey]) === null || _a === void 0 ? void 0 : _a.jwks) !== null && _b !== void 0 ? _b : { keys: [] }; + } + set jwks(value) { + GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { jwks: value }); + } + get jwks_cached_at() { + var _a, _b; + return (_b = (_a = GLOBAL_JWKS[this.storageKey]) === null || _a === void 0 ? void 0 : _a.cachedAt) !== null && _b !== void 0 ? _b : Number.MIN_SAFE_INTEGER; + } + set jwks_cached_at(value) { + GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { cachedAt: value }); + } + /** + * Create a new client for use in the browser. + * + * @example + * ```ts + * import { GoTrueClient } from '@supabase/auth-js' + * + * const auth = new GoTrueClient({ + * url: 'https://xyzcompany.supabase.co/auth/v1', + * headers: { apikey: 'public-anon-key' }, + * storageKey: 'supabase-auth', + * }) + * ``` + */ + constructor(options) { + var _a, _b, _c; + this.userStorage = null; + this.memoryStorage = null; + this.stateChangeEmitters = /* @__PURE__ */ new Map(); + this.autoRefreshTicker = null; + this.visibilityChangedCallback = null; + this.refreshingDeferred = null; + this.initializePromise = null; + this.detectSessionInUrl = true; + this.hasCustomAuthorizationHeader = false; + this.suppressGetSessionWarning = false; + this.lockAcquired = false; + this.pendingInLock = []; + this.broadcastChannel = null; + this.logger = console.log; + const settings = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options); + this.storageKey = settings.storageKey; + this.instanceID = (_a = _GoTrueClient.nextInstanceID[this.storageKey]) !== null && _a !== void 0 ? _a : 0; + _GoTrueClient.nextInstanceID[this.storageKey] = this.instanceID + 1; + this.logDebugMessages = !!settings.debug; + if (typeof settings.debug === "function") { + this.logger = settings.debug; + } + if (this.instanceID > 0 && (0, helpers_1.isBrowser)()) { + const message = `${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`; + console.warn(message); + if (this.logDebugMessages) { + console.trace(message); + } + } + this.persistSession = settings.persistSession; + this.autoRefreshToken = settings.autoRefreshToken; + this.admin = new GoTrueAdminApi_1.default({ + url: settings.url, + headers: settings.headers, + fetch: settings.fetch + }); + this.url = settings.url; + this.headers = settings.headers; + this.fetch = (0, helpers_1.resolveFetch)(settings.fetch); + this.lock = settings.lock || lockNoOp; + this.detectSessionInUrl = settings.detectSessionInUrl; + this.flowType = settings.flowType; + this.hasCustomAuthorizationHeader = settings.hasCustomAuthorizationHeader; + this.throwOnError = settings.throwOnError; + if (settings.lock) { + this.lock = settings.lock; + } else if (this.persistSession && (0, helpers_1.isBrowser)() && ((_b = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _b === void 0 ? void 0 : _b.locks)) { + this.lock = locks_1.navigatorLock; + } else { + this.lock = lockNoOp; + } + if (!this.jwks) { + this.jwks = { keys: [] }; + this.jwks_cached_at = Number.MIN_SAFE_INTEGER; + } + this.mfa = { + verify: this._verify.bind(this), + enroll: this._enroll.bind(this), + unenroll: this._unenroll.bind(this), + challenge: this._challenge.bind(this), + listFactors: this._listFactors.bind(this), + challengeAndVerify: this._challengeAndVerify.bind(this), + getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this), + webauthn: new webauthn_1.WebAuthnApi(this) + }; + this.oauth = { + getAuthorizationDetails: this._getAuthorizationDetails.bind(this), + approveAuthorization: this._approveAuthorization.bind(this), + denyAuthorization: this._denyAuthorization.bind(this), + listGrants: this._listOAuthGrants.bind(this), + revokeGrant: this._revokeOAuthGrant.bind(this) + }; + if (this.persistSession) { + if (settings.storage) { + this.storage = settings.storage; + } else { + if ((0, helpers_1.supportsLocalStorage)()) { + this.storage = globalThis.localStorage; + } else { + this.memoryStorage = {}; + this.storage = (0, local_storage_1.memoryLocalStorageAdapter)(this.memoryStorage); + } + } + if (settings.userStorage) { + this.userStorage = settings.userStorage; + } + } else { + this.memoryStorage = {}; + this.storage = (0, local_storage_1.memoryLocalStorageAdapter)(this.memoryStorage); + } + if ((0, helpers_1.isBrowser)() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) { + try { + this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey); + } catch (e2) { + console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available", e2); + } + (_c = this.broadcastChannel) === null || _c === void 0 ? void 0 : _c.addEventListener("message", async (event) => { + this._debug("received broadcast notification from other tab or client", event); + await this._notifyAllSubscribers(event.data.event, event.data.session, false); + }); + } + this.initialize(); + } + /** + * Returns whether error throwing mode is enabled for this client. + */ + isThrowOnErrorEnabled() { + return this.throwOnError; + } + /** + * Centralizes return handling with optional error throwing. When `throwOnError` is enabled + * and the provided result contains a non-nullish error, the error is thrown instead of + * being returned. This ensures consistent behavior across all public API methods. + */ + _returnResult(result) { + if (this.throwOnError && result && result.error) { + throw result.error; + } + return result; + } + _logPrefix() { + return `GoTrueClient@${this.storageKey}:${this.instanceID} (${version_1.version}) ${(/* @__PURE__ */ new Date()).toISOString()}`; + } + _debug(...args) { + if (this.logDebugMessages) { + this.logger(this._logPrefix(), ...args); + } + return this; + } + /** + * Initializes the client session either from the url or from storage. + * This method is automatically called when instantiating the client, but should also be called + * manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc). + */ + async initialize() { + if (this.initializePromise) { + return await this.initializePromise; + } + this.initializePromise = (async () => { + return await this._acquireLock(-1, async () => { + return await this._initialize(); + }); + })(); + return await this.initializePromise; + } + /** + * IMPORTANT: + * 1. Never throw in this method, as it is called from the constructor + * 2. Never return a session from this method as it would be cached over + * the whole lifetime of the client + */ + async _initialize() { + var _a; + try { + let params = {}; + let callbackUrlType = "none"; + if ((0, helpers_1.isBrowser)()) { + params = (0, helpers_1.parseParametersFromURL)(window.location.href); + if (this._isImplicitGrantCallback(params)) { + callbackUrlType = "implicit"; + } else if (await this._isPKCECallback(params)) { + callbackUrlType = "pkce"; + } + } + if ((0, helpers_1.isBrowser)() && this.detectSessionInUrl && callbackUrlType !== "none") { + const { data, error } = await this._getSessionFromURL(params, callbackUrlType); + if (error) { + this._debug("#_initialize()", "error detecting session from URL", error); + if ((0, errors_1.isAuthImplicitGrantRedirectError)(error)) { + const errorCode = (_a = error.details) === null || _a === void 0 ? void 0 : _a.code; + if (errorCode === "identity_already_exists" || errorCode === "identity_not_found" || errorCode === "single_identity_not_deletable") { + return { error }; + } + } + await this._removeSession(); + return { error }; + } + const { session, redirectType } = data; + this._debug("#_initialize()", "detected session in URL", session, "redirect type", redirectType); + await this._saveSession(session); + setTimeout(async () => { + if (redirectType === "recovery") { + await this._notifyAllSubscribers("PASSWORD_RECOVERY", session); + } else { + await this._notifyAllSubscribers("SIGNED_IN", session); + } + }, 0); + return { error: null }; + } + await this._recoverAndRefresh(); + return { error: null }; + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ error }); + } + return this._returnResult({ + error: new errors_1.AuthUnknownError("Unexpected error during initialization", error) + }); + } finally { + await this._handleVisibilityChange(); + this._debug("#_initialize()", "end"); + } + } + /** + * Creates a new anonymous user. + * + * @returns A session where the is_anonymous claim in the access token JWT set to true + */ + async signInAnonymously(credentials) { + var _a, _b, _c; + try { + const res = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/signup`, { + headers: this.headers, + body: { + data: (_b = (_a = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : {}, + gotrue_meta_security: { captcha_token: (_c = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _c === void 0 ? void 0 : _c.captchaToken } + }, + xform: fetch_1._sessionResponse + }); + const { data, error } = res; + if (error || !data) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + const session = data.session; + const user = data.user; + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers("SIGNED_IN", session); + } + return this._returnResult({ data: { user, session }, error: null }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Creates a new user. + * + * Be aware that if a user account exists in the system you may get back an + * error message that attempts to hide this information from the user. + * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled. + * + * @returns A logged-in session if the server has "autoconfirm" ON + * @returns A user if the server has "autoconfirm" OFF + */ + async signUp(credentials) { + var _a, _b, _c; + try { + let res; + if ("email" in credentials) { + const { email, password, options } = credentials; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === "pkce") { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + } + res = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/signup`, { + headers: this.headers, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + body: { + email, + password, + data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod + }, + xform: fetch_1._sessionResponse + }); + } else if ("phone" in credentials) { + const { phone, password, options } = credentials; + res = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/signup`, { + headers: this.headers, + body: { + phone, + password, + data: (_b = options === null || options === void 0 ? void 0 : options.data) !== null && _b !== void 0 ? _b : {}, + channel: (_c = options === null || options === void 0 ? void 0 : options.channel) !== null && _c !== void 0 ? _c : "sms", + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken } + }, + xform: fetch_1._sessionResponse + }); + } else { + throw new errors_1.AuthInvalidCredentialsError("You must provide either an email or phone number and a password"); + } + const { data, error } = res; + if (error || !data) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + return this._returnResult({ data: { user: null, session: null }, error }); + } + const session = data.session; + const user = data.user; + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers("SIGNED_IN", session); + } + return this._returnResult({ data: { user, session }, error: null }); + } catch (error) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Log in an existing user with an email and password or phone and password. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or that the + * email/phone and password combination is wrong or that the account can only + * be accessed via social login. + */ + async signInWithPassword(credentials) { + try { + let res; + if ("email" in credentials) { + const { email, password, options } = credentials; + res = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/token?grant_type=password`, { + headers: this.headers, + body: { + email, + password, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken } + }, + xform: fetch_1._sessionResponsePassword + }); + } else if ("phone" in credentials) { + const { phone, password, options } = credentials; + res = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/token?grant_type=password`, { + headers: this.headers, + body: { + phone, + password, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken } + }, + xform: fetch_1._sessionResponsePassword + }); + } else { + throw new errors_1.AuthInvalidCredentialsError("You must provide either an email or phone number and a password"); + } + const { data, error } = res; + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }); + } else if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers("SIGNED_IN", data.session); + } + return this._returnResult({ + data: Object.assign({ user: data.user, session: data.session }, data.weak_password ? { weakPassword: data.weak_password } : null), + error + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Log in an existing user via a third-party provider. + * This method supports the PKCE flow. + */ + async signInWithOAuth(credentials) { + var _a, _b, _c, _d; + return await this._handleProviderSignIn(credentials.provider, { + redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo, + scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes, + queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams, + skipBrowserRedirect: (_d = credentials.options) === null || _d === void 0 ? void 0 : _d.skipBrowserRedirect + }); + } + /** + * Log in an existing user by exchanging an Auth Code issued during the PKCE flow. + */ + async exchangeCodeForSession(authCode) { + await this.initializePromise; + return this._acquireLock(-1, async () => { + return this._exchangeCodeForSession(authCode); + }); + } + /** + * Signs in a user by verifying a message signed by the user's private key. + * Supports Ethereum (via Sign-In-With-Ethereum) & Solana (Sign-In-With-Solana) standards, + * both of which derive from the EIP-4361 standard + * With slight variation on Solana's side. + * @reference https://eips.ethereum.org/EIPS/eip-4361 + */ + async signInWithWeb3(credentials) { + const { chain } = credentials; + switch (chain) { + case "ethereum": + return await this.signInWithEthereum(credentials); + case "solana": + return await this.signInWithSolana(credentials); + default: + throw new Error(`@supabase/auth-js: Unsupported chain "${chain}"`); + } + } + async signInWithEthereum(credentials) { + var _a, _b, _c, _d, _e2, _f, _g, _h, _j, _k, _l; + let message; + let signature; + if ("message" in credentials) { + message = credentials.message; + signature = credentials.signature; + } else { + const { chain, wallet, statement, options } = credentials; + let resolvedWallet; + if (!(0, helpers_1.isBrowser)()) { + if (typeof wallet !== "object" || !(options === null || options === void 0 ? void 0 : options.url)) { + throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments."); + } + resolvedWallet = wallet; + } else if (typeof wallet === "object") { + resolvedWallet = wallet; + } else { + const windowAny = window; + if ("ethereum" in windowAny && typeof windowAny.ethereum === "object" && "request" in windowAny.ethereum && typeof windowAny.ethereum.request === "function") { + resolvedWallet = windowAny.ethereum; + } else { + throw new Error(`@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.`); + } + } + const url = new URL((_a = options === null || options === void 0 ? void 0 : options.url) !== null && _a !== void 0 ? _a : window.location.href); + const accounts = await resolvedWallet.request({ + method: "eth_requestAccounts" + }).then((accs) => accs).catch(() => { + throw new Error(`@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid`); + }); + if (!accounts || accounts.length === 0) { + throw new Error(`@supabase/auth-js: No accounts available. Please ensure the wallet is connected.`); + } + const address = (0, ethereum_1.getAddress)(accounts[0]); + let chainId = (_b = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _b === void 0 ? void 0 : _b.chainId; + if (!chainId) { + const chainIdHex = await resolvedWallet.request({ + method: "eth_chainId" + }); + chainId = (0, ethereum_1.fromHex)(chainIdHex); + } + const siweMessage = { + domain: url.host, + address, + statement, + uri: url.href, + version: "1", + chainId, + nonce: (_c = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _c === void 0 ? void 0 : _c.nonce, + issuedAt: (_e2 = (_d = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _d === void 0 ? void 0 : _d.issuedAt) !== null && _e2 !== void 0 ? _e2 : /* @__PURE__ */ new Date(), + expirationTime: (_f = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _f === void 0 ? void 0 : _f.expirationTime, + notBefore: (_g = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _g === void 0 ? void 0 : _g.notBefore, + requestId: (_h = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _h === void 0 ? void 0 : _h.requestId, + resources: (_j = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _j === void 0 ? void 0 : _j.resources + }; + message = (0, ethereum_1.createSiweMessage)(siweMessage); + signature = await resolvedWallet.request({ + method: "personal_sign", + params: [(0, ethereum_1.toHex)(message), address] + }); + } + try { + const { data, error } = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/token?grant_type=web3`, { + headers: this.headers, + body: Object.assign({ + chain: "ethereum", + message, + signature + }, ((_k = credentials.options) === null || _k === void 0 ? void 0 : _k.captchaToken) ? { gotrue_meta_security: { captcha_token: (_l = credentials.options) === null || _l === void 0 ? void 0 : _l.captchaToken } } : null), + xform: fetch_1._sessionResponse + }); + if (error) { + throw error; + } + if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers("SIGNED_IN", data.session); + } + return this._returnResult({ data: Object.assign({}, data), error }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + async signInWithSolana(credentials) { + var _a, _b, _c, _d, _e2, _f, _g, _h, _j, _k, _l, _m; + let message; + let signature; + if ("message" in credentials) { + message = credentials.message; + signature = credentials.signature; + } else { + const { chain, wallet, statement, options } = credentials; + let resolvedWallet; + if (!(0, helpers_1.isBrowser)()) { + if (typeof wallet !== "object" || !(options === null || options === void 0 ? void 0 : options.url)) { + throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments."); + } + resolvedWallet = wallet; + } else if (typeof wallet === "object") { + resolvedWallet = wallet; + } else { + const windowAny = window; + if ("solana" in windowAny && typeof windowAny.solana === "object" && ("signIn" in windowAny.solana && typeof windowAny.solana.signIn === "function" || "signMessage" in windowAny.solana && typeof windowAny.solana.signMessage === "function")) { + resolvedWallet = windowAny.solana; + } else { + throw new Error(`@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.`); + } + } + const url = new URL((_a = options === null || options === void 0 ? void 0 : options.url) !== null && _a !== void 0 ? _a : window.location.href); + if ("signIn" in resolvedWallet && resolvedWallet.signIn) { + const output = await resolvedWallet.signIn(Object.assign(Object.assign(Object.assign({ issuedAt: (/* @__PURE__ */ new Date()).toISOString() }, options === null || options === void 0 ? void 0 : options.signInWithSolana), { + // non-overridable properties + version: "1", + domain: url.host, + uri: url.href + }), statement ? { statement } : null)); + let outputToProcess; + if (Array.isArray(output) && output[0] && typeof output[0] === "object") { + outputToProcess = output[0]; + } else if (output && typeof output === "object" && "signedMessage" in output && "signature" in output) { + outputToProcess = output; + } else { + throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value"); + } + if ("signedMessage" in outputToProcess && "signature" in outputToProcess && (typeof outputToProcess.signedMessage === "string" || outputToProcess.signedMessage instanceof Uint8Array) && outputToProcess.signature instanceof Uint8Array) { + message = typeof outputToProcess.signedMessage === "string" ? outputToProcess.signedMessage : new TextDecoder().decode(outputToProcess.signedMessage); + signature = outputToProcess.signature; + } else { + throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields"); + } + } else { + if (!("signMessage" in resolvedWallet) || typeof resolvedWallet.signMessage !== "function" || !("publicKey" in resolvedWallet) || typeof resolvedWallet !== "object" || !resolvedWallet.publicKey || !("toBase58" in resolvedWallet.publicKey) || typeof resolvedWallet.publicKey.toBase58 !== "function") { + throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API"); + } + message = [ + `${url.host} wants you to sign in with your Solana account:`, + resolvedWallet.publicKey.toBase58(), + ...statement ? ["", statement, ""] : [""], + "Version: 1", + `URI: ${url.href}`, + `Issued At: ${(_c = (_b = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _b === void 0 ? void 0 : _b.issuedAt) !== null && _c !== void 0 ? _c : (/* @__PURE__ */ new Date()).toISOString()}`, + ...((_d = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _d === void 0 ? void 0 : _d.notBefore) ? [`Not Before: ${options.signInWithSolana.notBefore}`] : [], + ...((_e2 = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _e2 === void 0 ? void 0 : _e2.expirationTime) ? [`Expiration Time: ${options.signInWithSolana.expirationTime}`] : [], + ...((_f = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _f === void 0 ? void 0 : _f.chainId) ? [`Chain ID: ${options.signInWithSolana.chainId}`] : [], + ...((_g = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _g === void 0 ? void 0 : _g.nonce) ? [`Nonce: ${options.signInWithSolana.nonce}`] : [], + ...((_h = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _h === void 0 ? void 0 : _h.requestId) ? [`Request ID: ${options.signInWithSolana.requestId}`] : [], + ...((_k = (_j = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _j === void 0 ? void 0 : _j.resources) === null || _k === void 0 ? void 0 : _k.length) ? [ + "Resources", + ...options.signInWithSolana.resources.map((resource) => `- ${resource}`) + ] : [] + ].join("\n"); + const maybeSignature = await resolvedWallet.signMessage(new TextEncoder().encode(message), "utf8"); + if (!maybeSignature || !(maybeSignature instanceof Uint8Array)) { + throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value"); + } + signature = maybeSignature; + } + } + try { + const { data, error } = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/token?grant_type=web3`, { + headers: this.headers, + body: Object.assign({ chain: "solana", message, signature: (0, base64url_1.bytesToBase64URL)(signature) }, ((_l = credentials.options) === null || _l === void 0 ? void 0 : _l.captchaToken) ? { gotrue_meta_security: { captcha_token: (_m = credentials.options) === null || _m === void 0 ? void 0 : _m.captchaToken } } : null), + xform: fetch_1._sessionResponse + }); + if (error) { + throw error; + } + if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers("SIGNED_IN", data.session); + } + return this._returnResult({ data: Object.assign({}, data), error }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + async _exchangeCodeForSession(authCode) { + const storageItem = await (0, helpers_1.getItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + const [codeVerifier, redirectType] = (storageItem !== null && storageItem !== void 0 ? storageItem : "").split("/"); + try { + const { data, error } = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/token?grant_type=pkce`, { + headers: this.headers, + body: { + auth_code: authCode, + code_verifier: codeVerifier + }, + xform: fetch_1._sessionResponse + }); + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if (error) { + throw error; + } + if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ + data: { user: null, session: null, redirectType: null }, + error: invalidTokenError + }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers("SIGNED_IN", data.session); + } + return this._returnResult({ data: Object.assign(Object.assign({}, data), { redirectType: redirectType !== null && redirectType !== void 0 ? redirectType : null }), error }); + } catch (error) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ + data: { user: null, session: null, redirectType: null }, + error + }); + } + throw error; + } + } + /** + * Allows signing in with an OIDC ID token. The authentication provider used + * should be enabled and configured. + */ + async signInWithIdToken(credentials) { + try { + const { options, provider, token, access_token, nonce } = credentials; + const res = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/token?grant_type=id_token`, { + headers: this.headers, + body: { + provider, + id_token: token, + access_token, + nonce, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken } + }, + xform: fetch_1._sessionResponse + }); + const { data, error } = res; + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }); + } else if (!data || !data.session || !data.user) { + const invalidTokenError = new errors_1.AuthInvalidTokenResponseError(); + return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers("SIGNED_IN", data.session); + } + return this._returnResult({ data, error }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Log in a user using magiclink or a one-time password (OTP). + * + * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent. + * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent. + * If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins. + * + * Be aware that you may get back an error message that will not distinguish + * between the cases where the account does not exist or, that the account + * can only be accessed via social login. + * + * Do note that you will need to configure a Whatsapp sender on Twilio + * if you are using phone sign in with the 'whatsapp' channel. The whatsapp + * channel is not supported on other providers + * at this time. + * This method supports PKCE when an email is passed. + */ + async signInWithOtp(credentials) { + var _a, _b, _c, _d, _e2; + try { + if ("email" in credentials) { + const { email, options } = credentials; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === "pkce") { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + } + const { error } = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/otp`, { + headers: this.headers, + body: { + email, + data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {}, + create_user: (_b = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _b !== void 0 ? _b : true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod + }, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo + }); + return this._returnResult({ data: { user: null, session: null }, error }); + } + if ("phone" in credentials) { + const { phone, options } = credentials; + const { data, error } = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/otp`, { + headers: this.headers, + body: { + phone, + data: (_c = options === null || options === void 0 ? void 0 : options.data) !== null && _c !== void 0 ? _c : {}, + create_user: (_d = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _d !== void 0 ? _d : true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken }, + channel: (_e2 = options === null || options === void 0 ? void 0 : options.channel) !== null && _e2 !== void 0 ? _e2 : "sms" + } + }); + return this._returnResult({ + data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, + error + }); + } + throw new errors_1.AuthInvalidCredentialsError("You must provide either an email or phone number."); + } catch (error) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Log in a user given a User supplied OTP or TokenHash received through mobile or email. + */ + async verifyOtp(params) { + var _a, _b; + try { + let redirectTo = void 0; + let captchaToken = void 0; + if ("options" in params) { + redirectTo = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo; + captchaToken = (_b = params.options) === null || _b === void 0 ? void 0 : _b.captchaToken; + } + const { data, error } = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/verify`, { + headers: this.headers, + body: Object.assign(Object.assign({}, params), { gotrue_meta_security: { captcha_token: captchaToken } }), + redirectTo, + xform: fetch_1._sessionResponse + }); + if (error) { + throw error; + } + if (!data) { + const tokenVerificationError = new Error("An error occurred on token verification."); + throw tokenVerificationError; + } + const session = data.session; + const user = data.user; + if (session === null || session === void 0 ? void 0 : session.access_token) { + await this._saveSession(session); + await this._notifyAllSubscribers(params.type == "recovery" ? "PASSWORD_RECOVERY" : "SIGNED_IN", session); + } + return this._returnResult({ data: { user, session }, error: null }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Attempts a single-sign on using an enterprise Identity Provider. A + * successful SSO attempt will redirect the current page to the identity + * provider authorization page. The redirect URL is implementation and SSO + * protocol specific. + * + * You can use it by providing a SSO domain. Typically you can extract this + * domain by asking users for their email address. If this domain is + * registered on the Auth instance the redirect will use that organization's + * currently active SSO Identity Provider for the login. + * + * If you have built an organization-specific login page, you can use the + * organization's SSO Identity Provider UUID directly instead. + */ + async signInWithSSO(params) { + var _a, _b, _c, _d, _e2; + try { + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === "pkce") { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + } + const result = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/sso`, { + body: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, "providerId" in params ? { provider_id: params.providerId } : null), "domain" in params ? { domain: params.domain } : null), { redirect_to: (_b = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo) !== null && _b !== void 0 ? _b : void 0 }), ((_c = params === null || params === void 0 ? void 0 : params.options) === null || _c === void 0 ? void 0 : _c.captchaToken) ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } } : null), { skip_http_redirect: true, code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }), + headers: this.headers, + xform: fetch_1._ssoResponse + }); + if (((_d = result.data) === null || _d === void 0 ? void 0 : _d.url) && (0, helpers_1.isBrowser)() && !((_e2 = params.options) === null || _e2 === void 0 ? void 0 : _e2.skipBrowserRedirect)) { + window.location.assign(result.data.url); + } + return this._returnResult(result); + } catch (error) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Sends a reauthentication OTP to the user's email or phone number. + * Requires the user to be signed-in. + */ + async reauthenticate() { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._reauthenticate(); + }); + } + async _reauthenticate() { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError } = result; + if (sessionError) + throw sessionError; + if (!session) + throw new errors_1.AuthSessionMissingError(); + const { error } = await (0, fetch_1._request)(this.fetch, "GET", `${this.url}/reauthenticate`, { + headers: this.headers, + jwt: session.access_token + }); + return this._returnResult({ data: { user: null, session: null }, error }); + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP. + */ + async resend(credentials) { + try { + const endpoint = `${this.url}/resend`; + if ("email" in credentials) { + const { email, type, options } = credentials; + const { error } = await (0, fetch_1._request)(this.fetch, "POST", endpoint, { + headers: this.headers, + body: { + email, + type, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken } + }, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo + }); + return this._returnResult({ data: { user: null, session: null }, error }); + } else if ("phone" in credentials) { + const { phone, type, options } = credentials; + const { data, error } = await (0, fetch_1._request)(this.fetch, "POST", endpoint, { + headers: this.headers, + body: { + phone, + type, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken } + } + }); + return this._returnResult({ + data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id }, + error + }); + } + throw new errors_1.AuthInvalidCredentialsError("You must provide either an email or phone number and a type"); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Returns the session, refreshing it if necessary. + * + * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out. + * + * **IMPORTANT:** This method loads values directly from the storage attached + * to the client. If that storage is based on request cookies for example, + * the values in it may not be authentic and therefore it's strongly advised + * against using this method and its results in such circumstances. A warning + * will be emitted if this is detected. Use {@link #getUser()} instead. + */ + async getSession() { + await this.initializePromise; + const result = await this._acquireLock(-1, async () => { + return this._useSession(async (result2) => { + return result2; + }); + }); + return result; + } + /** + * Acquires a global lock based on the storage key. + */ + async _acquireLock(acquireTimeout, fn) { + this._debug("#_acquireLock", "begin", acquireTimeout); + try { + if (this.lockAcquired) { + const last2 = this.pendingInLock.length ? this.pendingInLock[this.pendingInLock.length - 1] : Promise.resolve(); + const result = (async () => { + await last2; + return await fn(); + })(); + this.pendingInLock.push((async () => { + try { + await result; + } catch (e2) { + } + })()); + return result; + } + return await this.lock(`lock:${this.storageKey}`, acquireTimeout, async () => { + this._debug("#_acquireLock", "lock acquired for storage key", this.storageKey); + try { + this.lockAcquired = true; + const result = fn(); + this.pendingInLock.push((async () => { + try { + await result; + } catch (e2) { + } + })()); + await result; + while (this.pendingInLock.length) { + const waitOn = [...this.pendingInLock]; + await Promise.all(waitOn); + this.pendingInLock.splice(0, waitOn.length); + } + return await result; + } finally { + this._debug("#_acquireLock", "lock released for storage key", this.storageKey); + this.lockAcquired = false; + } + }); + } finally { + this._debug("#_acquireLock", "end"); + } + } + /** + * Use instead of {@link #getSession} inside the library. It is + * semantically usually what you want, as getting a session involves some + * processing afterwards that requires only one client operating on the + * session at once across multiple tabs or processes. + */ + async _useSession(fn) { + this._debug("#_useSession", "begin"); + try { + const result = await this.__loadSession(); + return await fn(result); + } finally { + this._debug("#_useSession", "end"); + } + } + /** + * NEVER USE DIRECTLY! + * + * Always use {@link #_useSession}. + */ + async __loadSession() { + this._debug("#__loadSession()", "begin"); + if (!this.lockAcquired) { + this._debug("#__loadSession()", "used outside of an acquired lock!", new Error().stack); + } + try { + let currentSession = null; + const maybeSession = await (0, helpers_1.getItemAsync)(this.storage, this.storageKey); + this._debug("#getSession()", "session from storage", maybeSession); + if (maybeSession !== null) { + if (this._isValidSession(maybeSession)) { + currentSession = maybeSession; + } else { + this._debug("#getSession()", "session from storage is not valid"); + await this._removeSession(); + } + } + if (!currentSession) { + return { data: { session: null }, error: null }; + } + const hasExpired = currentSession.expires_at ? currentSession.expires_at * 1e3 - Date.now() < constants_1.EXPIRY_MARGIN_MS : false; + this._debug("#__loadSession()", `session has${hasExpired ? "" : " not"} expired`, "expires_at", currentSession.expires_at); + if (!hasExpired) { + if (this.userStorage) { + const maybeUser = await (0, helpers_1.getItemAsync)(this.userStorage, this.storageKey + "-user"); + if (maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) { + currentSession.user = maybeUser.user; + } else { + currentSession.user = (0, helpers_1.userNotAvailableProxy)(); + } + } + if (this.storage.isServer && currentSession.user && !currentSession.user.__isUserNotAvailableProxy) { + const suppressWarningRef = { value: this.suppressGetSessionWarning }; + currentSession.user = (0, helpers_1.insecureUserWarningProxy)(currentSession.user, suppressWarningRef); + if (suppressWarningRef.value) { + this.suppressGetSessionWarning = true; + } + } + return { data: { session: currentSession }, error: null }; + } + const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return this._returnResult({ data: { session: null }, error }); + } + return this._returnResult({ data: { session }, error: null }); + } finally { + this._debug("#__loadSession()", "end"); + } + } + /** + * Gets the current user details if there is an existing session. This method + * performs a network request to the Supabase Auth server, so the returned + * value is authentic and can be used to base authorization rules on. + * + * @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used. + */ + async getUser(jwt) { + if (jwt) { + return await this._getUser(jwt); + } + await this.initializePromise; + const result = await this._acquireLock(-1, async () => { + return await this._getUser(); + }); + if (result.data.user) { + this.suppressGetSessionWarning = true; + } + return result; + } + async _getUser(jwt) { + try { + if (jwt) { + return await (0, fetch_1._request)(this.fetch, "GET", `${this.url}/user`, { + headers: this.headers, + jwt, + xform: fetch_1._userResponse + }); + } + return await this._useSession(async (result) => { + var _a, _b, _c; + const { data, error } = result; + if (error) { + throw error; + } + if (!((_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) && !this.hasCustomAuthorizationHeader) { + return { data: { user: null }, error: new errors_1.AuthSessionMissingError() }; + } + return await (0, fetch_1._request)(this.fetch, "GET", `${this.url}/user`, { + headers: this.headers, + jwt: (_c = (_b = data.session) === null || _b === void 0 ? void 0 : _b.access_token) !== null && _c !== void 0 ? _c : void 0, + xform: fetch_1._userResponse + }); + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + if ((0, errors_1.isAuthSessionMissingError)(error)) { + await this._removeSession(); + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + } + return this._returnResult({ data: { user: null }, error }); + } + throw error; + } + } + /** + * Updates user data for a logged in user. + */ + async updateUser(attributes, options = {}) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._updateUser(attributes, options); + }); + } + async _updateUser(attributes, options = {}) { + try { + return await this._useSession(async (result) => { + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + throw sessionError; + } + if (!sessionData.session) { + throw new errors_1.AuthSessionMissingError(); + } + const session = sessionData.session; + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === "pkce" && attributes.email != null) { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + } + const { data, error: userError } = await (0, fetch_1._request)(this.fetch, "PUT", `${this.url}/user`, { + headers: this.headers, + redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo, + body: Object.assign(Object.assign({}, attributes), { code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }), + jwt: session.access_token, + xform: fetch_1._userResponse + }); + if (userError) { + throw userError; + } + session.user = data.user; + await this._saveSession(session); + await this._notifyAllSubscribers("USER_UPDATED", session); + return this._returnResult({ data: { user: session.user }, error: null }); + }); + } catch (error) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null }, error }); + } + throw error; + } + } + /** + * Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session. + * If the refresh token or access token in the current session is invalid, an error will be thrown. + * @param currentSession The current session that minimally contains an access token and refresh token. + */ + async setSession(currentSession) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._setSession(currentSession); + }); + } + async _setSession(currentSession) { + try { + if (!currentSession.access_token || !currentSession.refresh_token) { + throw new errors_1.AuthSessionMissingError(); + } + const timeNow = Date.now() / 1e3; + let expiresAt = timeNow; + let hasExpired = true; + let session = null; + const { payload } = (0, helpers_1.decodeJWT)(currentSession.access_token); + if (payload.exp) { + expiresAt = payload.exp; + hasExpired = expiresAt <= timeNow; + } + if (hasExpired) { + const { data: refreshedSession, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + if (!refreshedSession) { + return { data: { user: null, session: null }, error: null }; + } + session = refreshedSession; + } else { + const { data, error } = await this._getUser(currentSession.access_token); + if (error) { + throw error; + } + session = { + access_token: currentSession.access_token, + refresh_token: currentSession.refresh_token, + user: data.user, + token_type: "bearer", + expires_in: expiresAt - timeNow, + expires_at: expiresAt + }; + await this._saveSession(session); + await this._notifyAllSubscribers("SIGNED_IN", session); + } + return this._returnResult({ data: { user: session.user, session }, error: null }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { session: null, user: null }, error }); + } + throw error; + } + } + /** + * Returns a new session, regardless of expiry status. + * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession(). + * If the current session's refresh token is invalid, an error will be thrown. + * @param currentSession The current session. If passed in, it must contain a refresh token. + */ + async refreshSession(currentSession) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._refreshSession(currentSession); + }); + } + async _refreshSession(currentSession) { + try { + return await this._useSession(async (result) => { + var _a; + if (!currentSession) { + const { data, error: error2 } = result; + if (error2) { + throw error2; + } + currentSession = (_a = data.session) !== null && _a !== void 0 ? _a : void 0; + } + if (!(currentSession === null || currentSession === void 0 ? void 0 : currentSession.refresh_token)) { + throw new errors_1.AuthSessionMissingError(); + } + const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + if (!session) { + return this._returnResult({ data: { user: null, session: null }, error: null }); + } + return this._returnResult({ data: { user: session.user, session }, error: null }); + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + } + /** + * Gets the session data from a URL string + */ + async _getSessionFromURL(params, callbackUrlType) { + try { + if (!(0, helpers_1.isBrowser)()) + throw new errors_1.AuthImplicitGrantRedirectError("No browser detected."); + if (params.error || params.error_description || params.error_code) { + throw new errors_1.AuthImplicitGrantRedirectError(params.error_description || "Error in URL with unspecified error_description", { + error: params.error || "unspecified_error", + code: params.error_code || "unspecified_code" + }); + } + switch (callbackUrlType) { + case "implicit": + if (this.flowType === "pkce") { + throw new errors_1.AuthPKCEGrantCodeExchangeError("Not a valid PKCE flow url."); + } + break; + case "pkce": + if (this.flowType === "implicit") { + throw new errors_1.AuthImplicitGrantRedirectError("Not a valid implicit grant flow url."); + } + break; + default: + } + if (callbackUrlType === "pkce") { + this._debug("#_initialize()", "begin", "is PKCE flow", true); + if (!params.code) + throw new errors_1.AuthPKCEGrantCodeExchangeError("No code detected."); + const { data: data2, error: error2 } = await this._exchangeCodeForSession(params.code); + if (error2) + throw error2; + const url = new URL(window.location.href); + url.searchParams.delete("code"); + window.history.replaceState(window.history.state, "", url.toString()); + return { data: { session: data2.session, redirectType: null }, error: null }; + } + const { provider_token, provider_refresh_token, access_token, refresh_token, expires_in, expires_at, token_type } = params; + if (!access_token || !expires_in || !refresh_token || !token_type) { + throw new errors_1.AuthImplicitGrantRedirectError("No session defined in URL"); + } + const timeNow = Math.round(Date.now() / 1e3); + const expiresIn = parseInt(expires_in); + let expiresAt = timeNow + expiresIn; + if (expires_at) { + expiresAt = parseInt(expires_at); + } + const actuallyExpiresIn = expiresAt - timeNow; + if (actuallyExpiresIn * 1e3 <= constants_1.AUTO_REFRESH_TICK_DURATION_MS) { + console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${actuallyExpiresIn}s, should have been closer to ${expiresIn}s`); + } + const issuedAt = expiresAt - expiresIn; + if (timeNow - issuedAt >= 120) { + console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale", issuedAt, expiresAt, timeNow); + } else if (timeNow - issuedAt < 0) { + console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew", issuedAt, expiresAt, timeNow); + } + const { data, error } = await this._getUser(access_token); + if (error) + throw error; + const session = { + provider_token, + provider_refresh_token, + access_token, + expires_in: expiresIn, + expires_at: expiresAt, + refresh_token, + token_type, + user: data.user + }; + window.location.hash = ""; + this._debug("#_getSessionFromURL()", "clearing window.location.hash"); + return this._returnResult({ data: { session, redirectType: params.type }, error: null }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { session: null, redirectType: null }, error }); + } + throw error; + } + } + /** + * Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2) + */ + _isImplicitGrantCallback(params) { + return Boolean(params.access_token || params.error_description); + } + /** + * Checks if the current URL and backing storage contain parameters given by a PKCE flow + */ + async _isPKCECallback(params) { + const currentStorageContent = await (0, helpers_1.getItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + return !!(params.code && currentStorageContent); + } + /** + * Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event. + * + * For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`. + * There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason. + * + * If using `others` scope, no `SIGNED_OUT` event is fired! + */ + async signOut(options = { scope: "global" }) { + await this.initializePromise; + return await this._acquireLock(-1, async () => { + return await this._signOut(options); + }); + } + async _signOut({ scope } = { scope: "global" }) { + return await this._useSession(async (result) => { + var _a; + const { data, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ error: sessionError }); + } + const accessToken = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token; + if (accessToken) { + const { error } = await this.admin.signOut(accessToken, scope); + if (error) { + if (!((0, errors_1.isAuthApiError)(error) && (error.status === 404 || error.status === 401 || error.status === 403))) { + return this._returnResult({ error }); + } + } + } + if (scope !== "others") { + await this._removeSession(); + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + } + return this._returnResult({ error: null }); + }); + } + onAuthStateChange(callback) { + const id = (0, helpers_1.generateCallbackId)(); + const subscription = { + id, + callback, + unsubscribe: () => { + this._debug("#unsubscribe()", "state change callback with id removed", id); + this.stateChangeEmitters.delete(id); + } + }; + this._debug("#onAuthStateChange()", "registered callback with id", id); + this.stateChangeEmitters.set(id, subscription); + (async () => { + await this.initializePromise; + await this._acquireLock(-1, async () => { + this._emitInitialSession(id); + }); + })(); + return { data: { subscription } }; + } + async _emitInitialSession(id) { + return await this._useSession(async (result) => { + var _a, _b; + try { + const { data: { session }, error } = result; + if (error) + throw error; + await ((_a = this.stateChangeEmitters.get(id)) === null || _a === void 0 ? void 0 : _a.callback("INITIAL_SESSION", session)); + this._debug("INITIAL_SESSION", "callback id", id, "session", session); + } catch (err) { + await ((_b = this.stateChangeEmitters.get(id)) === null || _b === void 0 ? void 0 : _b.callback("INITIAL_SESSION", null)); + this._debug("INITIAL_SESSION", "callback id", id, "error", err); + console.error(err); + } + }); + } + /** + * Sends a password reset request to an email address. This method supports the PKCE flow. + * + * @param email The email address of the user. + * @param options.redirectTo The URL to send the user to after they click the password reset link. + * @param options.captchaToken Verification token received when the user completes the captcha on the site. + */ + async resetPasswordForEmail(email, options = {}) { + let codeChallenge = null; + let codeChallengeMethod = null; + if (this.flowType === "pkce") { + ; + [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)( + this.storage, + this.storageKey, + true + // isPasswordRecovery + ); + } + try { + return await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/recover`, { + body: { + email, + code_challenge: codeChallenge, + code_challenge_method: codeChallengeMethod, + gotrue_meta_security: { captcha_token: options.captchaToken } + }, + headers: this.headers, + redirectTo: options.redirectTo + }); + } catch (error) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Gets all the identities linked to a user. + */ + async getUserIdentities() { + var _a; + try { + const { data, error } = await this.getUser(); + if (error) + throw error; + return this._returnResult({ data: { identities: (_a = data.user.identities) !== null && _a !== void 0 ? _a : [] }, error: null }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + async linkIdentity(credentials) { + if ("token" in credentials) { + return this.linkIdentityIdToken(credentials); + } + return this.linkIdentityOAuth(credentials); + } + async linkIdentityOAuth(credentials) { + var _a; + try { + const { data, error } = await this._useSession(async (result) => { + var _a2, _b, _c, _d, _e2; + const { data: data2, error: error2 } = result; + if (error2) + throw error2; + const url = await this._getUrlForProvider(`${this.url}/user/identities/authorize`, credentials.provider, { + redirectTo: (_a2 = credentials.options) === null || _a2 === void 0 ? void 0 : _a2.redirectTo, + scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes, + queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams, + skipBrowserRedirect: true + }); + return await (0, fetch_1._request)(this.fetch, "GET", url, { + headers: this.headers, + jwt: (_e2 = (_d = data2.session) === null || _d === void 0 ? void 0 : _d.access_token) !== null && _e2 !== void 0 ? _e2 : void 0 + }); + }); + if (error) + throw error; + if ((0, helpers_1.isBrowser)() && !((_a = credentials.options) === null || _a === void 0 ? void 0 : _a.skipBrowserRedirect)) { + window.location.assign(data === null || data === void 0 ? void 0 : data.url); + } + return this._returnResult({ + data: { provider: credentials.provider, url: data === null || data === void 0 ? void 0 : data.url }, + error: null + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { provider: credentials.provider, url: null }, error }); + } + throw error; + } + } + async linkIdentityIdToken(credentials) { + return await this._useSession(async (result) => { + var _a; + try { + const { error: sessionError, data: { session } } = result; + if (sessionError) + throw sessionError; + const { options, provider, token, access_token, nonce } = credentials; + const res = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/token?grant_type=id_token`, { + headers: this.headers, + jwt: (_a = session === null || session === void 0 ? void 0 : session.access_token) !== null && _a !== void 0 ? _a : void 0, + body: { + provider, + id_token: token, + access_token, + nonce, + link_identity: true, + gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken } + }, + xform: fetch_1._sessionResponse + }); + const { data, error } = res; + if (error) { + return this._returnResult({ data: { user: null, session: null }, error }); + } else if (!data || !data.session || !data.user) { + return this._returnResult({ + data: { user: null, session: null }, + error: new errors_1.AuthInvalidTokenResponseError() + }); + } + if (data.session) { + await this._saveSession(data.session); + await this._notifyAllSubscribers("USER_UPDATED", data.session); + } + return this._returnResult({ data, error }); + } catch (error) { + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { user: null, session: null }, error }); + } + throw error; + } + }); + } + /** + * Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked. + */ + async unlinkIdentity(identity) { + try { + return await this._useSession(async (result) => { + var _a, _b; + const { data, error } = result; + if (error) { + throw error; + } + return await (0, fetch_1._request)(this.fetch, "DELETE", `${this.url}/user/identities/${identity.identity_id}`, { + headers: this.headers, + jwt: (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : void 0 + }); + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Generates a new JWT. + * @param refreshToken A valid refresh token that was returned on login. + */ + async _refreshAccessToken(refreshToken) { + const debugName = `#_refreshAccessToken(${refreshToken.substring(0, 5)}...)`; + this._debug(debugName, "begin"); + try { + const startedAt = Date.now(); + return await (0, helpers_1.retryable)(async (attempt) => { + if (attempt > 0) { + await (0, helpers_1.sleep)(200 * Math.pow(2, attempt - 1)); + } + this._debug(debugName, "refreshing attempt", attempt); + return await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/token?grant_type=refresh_token`, { + body: { refresh_token: refreshToken }, + headers: this.headers, + xform: fetch_1._sessionResponse + }); + }, (attempt, error) => { + const nextBackOffInterval = 200 * Math.pow(2, attempt); + return error && (0, errors_1.isAuthRetryableFetchError)(error) && // retryable only if the request can be sent before the backoff overflows the tick duration + Date.now() + nextBackOffInterval - startedAt < constants_1.AUTO_REFRESH_TICK_DURATION_MS; + }); + } catch (error) { + this._debug(debugName, "error", error); + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: { session: null, user: null }, error }); + } + throw error; + } finally { + this._debug(debugName, "end"); + } + } + _isValidSession(maybeSession) { + const isValidSession = typeof maybeSession === "object" && maybeSession !== null && "access_token" in maybeSession && "refresh_token" in maybeSession && "expires_at" in maybeSession; + return isValidSession; + } + async _handleProviderSignIn(provider, options) { + const url = await this._getUrlForProvider(`${this.url}/authorize`, provider, { + redirectTo: options.redirectTo, + scopes: options.scopes, + queryParams: options.queryParams + }); + this._debug("#_handleProviderSignIn()", "provider", provider, "options", options, "url", url); + if ((0, helpers_1.isBrowser)() && !options.skipBrowserRedirect) { + window.location.assign(url); + } + return { data: { provider, url }, error: null }; + } + /** + * Recovers the session from LocalStorage and refreshes the token + * Note: this method is async to accommodate for AsyncStorage e.g. in React native. + */ + async _recoverAndRefresh() { + var _a, _b; + const debugName = "#_recoverAndRefresh()"; + this._debug(debugName, "begin"); + try { + const currentSession = await (0, helpers_1.getItemAsync)(this.storage, this.storageKey); + if (currentSession && this.userStorage) { + let maybeUser = await (0, helpers_1.getItemAsync)(this.userStorage, this.storageKey + "-user"); + if (!this.storage.isServer && Object.is(this.storage, this.userStorage) && !maybeUser) { + maybeUser = { user: currentSession.user }; + await (0, helpers_1.setItemAsync)(this.userStorage, this.storageKey + "-user", maybeUser); + } + currentSession.user = (_a = maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) !== null && _a !== void 0 ? _a : (0, helpers_1.userNotAvailableProxy)(); + } else if (currentSession && !currentSession.user) { + if (!currentSession.user) { + const separateUser = await (0, helpers_1.getItemAsync)(this.storage, this.storageKey + "-user"); + if (separateUser && (separateUser === null || separateUser === void 0 ? void 0 : separateUser.user)) { + currentSession.user = separateUser.user; + await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey + "-user"); + await (0, helpers_1.setItemAsync)(this.storage, this.storageKey, currentSession); + } else { + currentSession.user = (0, helpers_1.userNotAvailableProxy)(); + } + } + } + this._debug(debugName, "session from storage", currentSession); + if (!this._isValidSession(currentSession)) { + this._debug(debugName, "session is not valid"); + if (currentSession !== null) { + await this._removeSession(); + } + return; + } + const expiresWithMargin = ((_b = currentSession.expires_at) !== null && _b !== void 0 ? _b : Infinity) * 1e3 - Date.now() < constants_1.EXPIRY_MARGIN_MS; + this._debug(debugName, `session has${expiresWithMargin ? "" : " not"} expired with margin of ${constants_1.EXPIRY_MARGIN_MS}s`); + if (expiresWithMargin) { + if (this.autoRefreshToken && currentSession.refresh_token) { + const { error } = await this._callRefreshToken(currentSession.refresh_token); + if (error) { + console.error(error); + if (!(0, errors_1.isAuthRetryableFetchError)(error)) { + this._debug(debugName, "refresh failed with a non-retryable error, removing the session", error); + await this._removeSession(); + } + } + } + } else if (currentSession.user && currentSession.user.__isUserNotAvailableProxy === true) { + try { + const { data, error: userError } = await this._getUser(currentSession.access_token); + if (!userError && (data === null || data === void 0 ? void 0 : data.user)) { + currentSession.user = data.user; + await this._saveSession(currentSession); + await this._notifyAllSubscribers("SIGNED_IN", currentSession); + } else { + this._debug(debugName, "could not get user data, skipping SIGNED_IN notification"); + } + } catch (getUserError) { + console.error("Error getting user data:", getUserError); + this._debug(debugName, "error getting user data, skipping SIGNED_IN notification", getUserError); + } + } else { + await this._notifyAllSubscribers("SIGNED_IN", currentSession); + } + } catch (err) { + this._debug(debugName, "error", err); + console.error(err); + return; + } finally { + this._debug(debugName, "end"); + } + } + async _callRefreshToken(refreshToken) { + var _a, _b; + if (!refreshToken) { + throw new errors_1.AuthSessionMissingError(); + } + if (this.refreshingDeferred) { + return this.refreshingDeferred.promise; + } + const debugName = `#_callRefreshToken(${refreshToken.substring(0, 5)}...)`; + this._debug(debugName, "begin"); + try { + this.refreshingDeferred = new helpers_1.Deferred(); + const { data, error } = await this._refreshAccessToken(refreshToken); + if (error) + throw error; + if (!data.session) + throw new errors_1.AuthSessionMissingError(); + await this._saveSession(data.session); + await this._notifyAllSubscribers("TOKEN_REFRESHED", data.session); + const result = { data: data.session, error: null }; + this.refreshingDeferred.resolve(result); + return result; + } catch (error) { + this._debug(debugName, "error", error); + if ((0, errors_1.isAuthError)(error)) { + const result = { data: null, error }; + if (!(0, errors_1.isAuthRetryableFetchError)(error)) { + await this._removeSession(); + } + (_a = this.refreshingDeferred) === null || _a === void 0 ? void 0 : _a.resolve(result); + return result; + } + (_b = this.refreshingDeferred) === null || _b === void 0 ? void 0 : _b.reject(error); + throw error; + } finally { + this.refreshingDeferred = null; + this._debug(debugName, "end"); + } + } + async _notifyAllSubscribers(event, session, broadcast = true) { + const debugName = `#_notifyAllSubscribers(${event})`; + this._debug(debugName, "begin", session, `broadcast = ${broadcast}`); + try { + if (this.broadcastChannel && broadcast) { + this.broadcastChannel.postMessage({ event, session }); + } + const errors2 = []; + const promises = Array.from(this.stateChangeEmitters.values()).map(async (x3) => { + try { + await x3.callback(event, session); + } catch (e2) { + errors2.push(e2); + } + }); + await Promise.all(promises); + if (errors2.length > 0) { + for (let i2 = 0; i2 < errors2.length; i2 += 1) { + console.error(errors2[i2]); + } + throw errors2[0]; + } + } finally { + this._debug(debugName, "end"); + } + } + /** + * set currentSession and currentUser + * process to _startAutoRefreshToken if possible + */ + async _saveSession(session) { + this._debug("#_saveSession()", session); + this.suppressGetSessionWarning = true; + await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`); + const sessionToProcess = Object.assign({}, session); + const userIsProxy = sessionToProcess.user && sessionToProcess.user.__isUserNotAvailableProxy === true; + if (this.userStorage) { + if (!userIsProxy && sessionToProcess.user) { + await (0, helpers_1.setItemAsync)(this.userStorage, this.storageKey + "-user", { + user: sessionToProcess.user + }); + } else if (userIsProxy) { + } + const mainSessionData = Object.assign({}, sessionToProcess); + delete mainSessionData.user; + const clonedMainSessionData = (0, helpers_1.deepClone)(mainSessionData); + await (0, helpers_1.setItemAsync)(this.storage, this.storageKey, clonedMainSessionData); + } else { + const clonedSession = (0, helpers_1.deepClone)(sessionToProcess); + await (0, helpers_1.setItemAsync)(this.storage, this.storageKey, clonedSession); + } + } + async _removeSession() { + this._debug("#_removeSession()"); + this.suppressGetSessionWarning = false; + await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey); + await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey + "-code-verifier"); + await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey + "-user"); + if (this.userStorage) { + await (0, helpers_1.removeItemAsync)(this.userStorage, this.storageKey + "-user"); + } + await this._notifyAllSubscribers("SIGNED_OUT", null); + } + /** + * Removes any registered visibilitychange callback. + * + * {@see #startAutoRefresh} + * {@see #stopAutoRefresh} + */ + _removeVisibilityChangedCallback() { + this._debug("#_removeVisibilityChangedCallback()"); + const callback = this.visibilityChangedCallback; + this.visibilityChangedCallback = null; + try { + if (callback && (0, helpers_1.isBrowser)() && (window === null || window === void 0 ? void 0 : window.removeEventListener)) { + window.removeEventListener("visibilitychange", callback); + } + } catch (e2) { + console.error("removing visibilitychange callback failed", e2); + } + } + /** + * This is the private implementation of {@link #startAutoRefresh}. Use this + * within the library. + */ + async _startAutoRefresh() { + await this._stopAutoRefresh(); + this._debug("#_startAutoRefresh()"); + const ticker = setInterval(() => this._autoRefreshTokenTick(), constants_1.AUTO_REFRESH_TICK_DURATION_MS); + this.autoRefreshTicker = ticker; + if (ticker && typeof ticker === "object" && typeof ticker.unref === "function") { + ticker.unref(); + } else if (typeof Deno !== "undefined" && typeof Deno.unrefTimer === "function") { + Deno.unrefTimer(ticker); + } + setTimeout(async () => { + await this.initializePromise; + await this._autoRefreshTokenTick(); + }, 0); + } + /** + * This is the private implementation of {@link #stopAutoRefresh}. Use this + * within the library. + */ + async _stopAutoRefresh() { + this._debug("#_stopAutoRefresh()"); + const ticker = this.autoRefreshTicker; + this.autoRefreshTicker = null; + if (ticker) { + clearInterval(ticker); + } + } + /** + * Starts an auto-refresh process in the background. The session is checked + * every few seconds. Close to the time of expiration a process is started to + * refresh the session. If refreshing fails it will be retried for as long as + * necessary. + * + * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need + * to call this function, it will be called for you. + * + * On browsers the refresh process works only when the tab/window is in the + * foreground to conserve resources as well as prevent race conditions and + * flooding auth with requests. If you call this method any managed + * visibility change callback will be removed and you must manage visibility + * changes on your own. + * + * On non-browser platforms the refresh process works *continuously* in the + * background, which may not be desirable. You should hook into your + * platform's foreground indication mechanism and call these methods + * appropriately to conserve resources. + * + * {@see #stopAutoRefresh} + */ + async startAutoRefresh() { + this._removeVisibilityChangedCallback(); + await this._startAutoRefresh(); + } + /** + * Stops an active auto refresh process running in the background (if any). + * + * If you call this method any managed visibility change callback will be + * removed and you must manage visibility changes on your own. + * + * See {@link #startAutoRefresh} for more details. + */ + async stopAutoRefresh() { + this._removeVisibilityChangedCallback(); + await this._stopAutoRefresh(); + } + /** + * Runs the auto refresh token tick. + */ + async _autoRefreshTokenTick() { + this._debug("#_autoRefreshTokenTick()", "begin"); + try { + await this._acquireLock(0, async () => { + try { + const now2 = Date.now(); + try { + return await this._useSession(async (result) => { + const { data: { session } } = result; + if (!session || !session.refresh_token || !session.expires_at) { + this._debug("#_autoRefreshTokenTick()", "no session"); + return; + } + const expiresInTicks = Math.floor((session.expires_at * 1e3 - now2) / constants_1.AUTO_REFRESH_TICK_DURATION_MS); + this._debug("#_autoRefreshTokenTick()", `access token expires in ${expiresInTicks} ticks, a tick lasts ${constants_1.AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${constants_1.AUTO_REFRESH_TICK_THRESHOLD} ticks`); + if (expiresInTicks <= constants_1.AUTO_REFRESH_TICK_THRESHOLD) { + await this._callRefreshToken(session.refresh_token); + } + }); + } catch (e2) { + console.error("Auto refresh tick failed with error. This is likely a transient error.", e2); + } + } finally { + this._debug("#_autoRefreshTokenTick()", "end"); + } + }); + } catch (e2) { + if (e2.isAcquireTimeout || e2 instanceof locks_1.LockAcquireTimeoutError) { + this._debug("auto refresh token tick lock not available"); + } else { + throw e2; + } + } + } + /** + * Registers callbacks on the browser / platform, which in-turn run + * algorithms when the browser window/tab are in foreground. On non-browser + * platforms it assumes always foreground. + */ + async _handleVisibilityChange() { + this._debug("#_handleVisibilityChange()"); + if (!(0, helpers_1.isBrowser)() || !(window === null || window === void 0 ? void 0 : window.addEventListener)) { + if (this.autoRefreshToken) { + this.startAutoRefresh(); + } + return false; + } + try { + this.visibilityChangedCallback = async () => await this._onVisibilityChanged(false); + window === null || window === void 0 ? void 0 : window.addEventListener("visibilitychange", this.visibilityChangedCallback); + await this._onVisibilityChanged(true); + } catch (error) { + console.error("_handleVisibilityChange", error); + } + } + /** + * Callback registered with `window.addEventListener('visibilitychange')`. + */ + async _onVisibilityChanged(calledFromInitialize) { + const methodName = `#_onVisibilityChanged(${calledFromInitialize})`; + this._debug(methodName, "visibilityState", document.visibilityState); + if (document.visibilityState === "visible") { + if (this.autoRefreshToken) { + this._startAutoRefresh(); + } + if (!calledFromInitialize) { + await this.initializePromise; + await this._acquireLock(-1, async () => { + if (document.visibilityState !== "visible") { + this._debug(methodName, "acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting"); + return; + } + await this._recoverAndRefresh(); + }); + } + } else if (document.visibilityState === "hidden") { + if (this.autoRefreshToken) { + this._stopAutoRefresh(); + } + } + } + /** + * Generates the relevant login URL for a third-party provider. + * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed. + * @param options.scopes A space-separated list of scopes granted to the OAuth application. + * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application. + */ + async _getUrlForProvider(url, provider, options) { + const urlParams = [`provider=${encodeURIComponent(provider)}`]; + if (options === null || options === void 0 ? void 0 : options.redirectTo) { + urlParams.push(`redirect_to=${encodeURIComponent(options.redirectTo)}`); + } + if (options === null || options === void 0 ? void 0 : options.scopes) { + urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`); + } + if (this.flowType === "pkce") { + const [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey); + const flowParams = new URLSearchParams({ + code_challenge: `${encodeURIComponent(codeChallenge)}`, + code_challenge_method: `${encodeURIComponent(codeChallengeMethod)}` + }); + urlParams.push(flowParams.toString()); + } + if (options === null || options === void 0 ? void 0 : options.queryParams) { + const query = new URLSearchParams(options.queryParams); + urlParams.push(query.toString()); + } + if (options === null || options === void 0 ? void 0 : options.skipBrowserRedirect) { + urlParams.push(`skip_http_redirect=${options.skipBrowserRedirect}`); + } + return `${url}?${urlParams.join("&")}`; + } + async _unenroll(params) { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + return await (0, fetch_1._request)(this.fetch, "DELETE", `${this.url}/factors/${params.factorId}`, { + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token + }); + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + async _enroll(params) { + try { + return await this._useSession(async (result) => { + var _a, _b; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + const body = Object.assign({ friendly_name: params.friendlyName, factor_type: params.factorType }, params.factorType === "phone" ? { phone: params.phone } : params.factorType === "totp" ? { issuer: params.issuer } : {}); + const { data, error } = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/factors`, { + body, + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token + }); + if (error) { + return this._returnResult({ data: null, error }); + } + if (params.factorType === "totp" && data.type === "totp" && ((_b = data === null || data === void 0 ? void 0 : data.totp) === null || _b === void 0 ? void 0 : _b.qr_code)) { + data.totp.qr_code = `data:image/svg+xml;utf-8,${data.totp.qr_code}`; + } + return this._returnResult({ data, error: null }); + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + async _verify(params) { + return this._acquireLock(-1, async () => { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + const body = Object.assign({ challenge_id: params.challengeId }, "webauthn" in params ? { + webauthn: Object.assign(Object.assign({}, params.webauthn), { credential_response: params.webauthn.type === "create" ? (0, webauthn_1.serializeCredentialCreationResponse)(params.webauthn.credential_response) : (0, webauthn_1.serializeCredentialRequestResponse)(params.webauthn.credential_response) }) + } : { code: params.code }); + const { data, error } = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/factors/${params.factorId}/verify`, { + body, + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token + }); + if (error) { + return this._returnResult({ data: null, error }); + } + await this._saveSession(Object.assign({ expires_at: Math.round(Date.now() / 1e3) + data.expires_in }, data)); + await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED", data); + return this._returnResult({ data, error }); + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + }); + } + async _challenge(params) { + return this._acquireLock(-1, async () => { + try { + return await this._useSession(async (result) => { + var _a; + const { data: sessionData, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + const response = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/factors/${params.factorId}/challenge`, { + body: params, + headers: this.headers, + jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token + }); + if (response.error) { + return response; + } + const { data } = response; + if (data.type !== "webauthn") { + return { data, error: null }; + } + switch (data.webauthn.type) { + case "create": + return { + data: Object.assign(Object.assign({}, data), { webauthn: Object.assign(Object.assign({}, data.webauthn), { credential_options: Object.assign(Object.assign({}, data.webauthn.credential_options), { publicKey: (0, webauthn_1.deserializeCredentialCreationOptions)(data.webauthn.credential_options.publicKey) }) }) }), + error: null + }; + case "request": + return { + data: Object.assign(Object.assign({}, data), { webauthn: Object.assign(Object.assign({}, data.webauthn), { credential_options: Object.assign(Object.assign({}, data.webauthn.credential_options), { publicKey: (0, webauthn_1.deserializeCredentialRequestOptions)(data.webauthn.credential_options.publicKey) }) }) }), + error: null + }; + } + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + }); + } + /** + * {@see GoTrueMFAApi#challengeAndVerify} + */ + async _challengeAndVerify(params) { + const { data: challengeData, error: challengeError } = await this._challenge({ + factorId: params.factorId + }); + if (challengeError) { + return this._returnResult({ data: null, error: challengeError }); + } + return await this._verify({ + factorId: params.factorId, + challengeId: challengeData.id, + code: params.code + }); + } + /** + * {@see GoTrueMFAApi#listFactors} + */ + async _listFactors() { + var _a; + const { data: { user }, error: userError } = await this.getUser(); + if (userError) { + return { data: null, error: userError }; + } + const data = { + all: [], + phone: [], + totp: [], + webauthn: [] + }; + for (const factor of (_a = user === null || user === void 0 ? void 0 : user.factors) !== null && _a !== void 0 ? _a : []) { + data.all.push(factor); + if (factor.status === "verified") { + ; + data[factor.factor_type].push(factor); + } + } + return { + data, + error: null + }; + } + /** + * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel} + */ + async _getAuthenticatorAssuranceLevel() { + var _a, _b; + const { data: { session }, error: sessionError } = await this.getSession(); + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return { + data: { currentLevel: null, nextLevel: null, currentAuthenticationMethods: [] }, + error: null + }; + } + const { payload } = (0, helpers_1.decodeJWT)(session.access_token); + let currentLevel = null; + if (payload.aal) { + currentLevel = payload.aal; + } + let nextLevel = currentLevel; + const verifiedFactors = (_b = (_a = session.user.factors) === null || _a === void 0 ? void 0 : _a.filter((factor) => factor.status === "verified")) !== null && _b !== void 0 ? _b : []; + if (verifiedFactors.length > 0) { + nextLevel = "aal2"; + } + const currentAuthenticationMethods = payload.amr || []; + return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null }; + } + /** + * Retrieves details about an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + * + * Returns authorization details including client info, scopes, and user information. + * If the API returns a redirect_uri, it means consent was already given - the caller + * should handle the redirect manually if needed. + */ + async _getAuthorizationDetails(authorizationId) { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new errors_1.AuthSessionMissingError() }); + } + return await (0, fetch_1._request)(this.fetch, "GET", `${this.url}/oauth/authorizations/${authorizationId}`, { + headers: this.headers, + jwt: session.access_token, + xform: (data) => ({ data, error: null }) + }); + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Approves an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + async _approveAuthorization(authorizationId, options) { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new errors_1.AuthSessionMissingError() }); + } + const response = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/oauth/authorizations/${authorizationId}/consent`, { + headers: this.headers, + jwt: session.access_token, + body: { action: "approve" }, + xform: (data) => ({ data, error: null }) + }); + if (response.data && response.data.redirect_url) { + if ((0, helpers_1.isBrowser)() && !(options === null || options === void 0 ? void 0 : options.skipBrowserRedirect)) { + window.location.assign(response.data.redirect_url); + } + } + return response; + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Denies an OAuth authorization request. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + async _denyAuthorization(authorizationId, options) { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new errors_1.AuthSessionMissingError() }); + } + const response = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/oauth/authorizations/${authorizationId}/consent`, { + headers: this.headers, + jwt: session.access_token, + body: { action: "deny" }, + xform: (data) => ({ data, error: null }) + }); + if (response.data && response.data.redirect_url) { + if ((0, helpers_1.isBrowser)() && !(options === null || options === void 0 ? void 0 : options.skipBrowserRedirect)) { + window.location.assign(response.data.redirect_url); + } + } + return response; + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Lists all OAuth grants that the authenticated user has authorized. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + async _listOAuthGrants() { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new errors_1.AuthSessionMissingError() }); + } + return await (0, fetch_1._request)(this.fetch, "GET", `${this.url}/user/oauth/grants`, { + headers: this.headers, + jwt: session.access_token, + xform: (data) => ({ data, error: null }) + }); + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + /** + * Revokes a user's OAuth grant for a specific client. + * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. + */ + async _revokeOAuthGrant(options) { + try { + return await this._useSession(async (result) => { + const { data: { session }, error: sessionError } = result; + if (sessionError) { + return this._returnResult({ data: null, error: sessionError }); + } + if (!session) { + return this._returnResult({ data: null, error: new errors_1.AuthSessionMissingError() }); + } + await (0, fetch_1._request)(this.fetch, "DELETE", `${this.url}/user/oauth/grants`, { + headers: this.headers, + jwt: session.access_token, + query: { client_id: options.clientId }, + noResolveJson: true + }); + return { data: {}, error: null }; + }); + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + async fetchJwk(kid, jwks = { keys: [] }) { + let jwk = jwks.keys.find((key) => key.kid === kid); + if (jwk) { + return jwk; + } + const now2 = Date.now(); + jwk = this.jwks.keys.find((key) => key.kid === kid); + if (jwk && this.jwks_cached_at + constants_1.JWKS_TTL > now2) { + return jwk; + } + const { data, error } = await (0, fetch_1._request)(this.fetch, "GET", `${this.url}/.well-known/jwks.json`, { + headers: this.headers + }); + if (error) { + throw error; + } + if (!data.keys || data.keys.length === 0) { + return null; + } + this.jwks = data; + this.jwks_cached_at = now2; + jwk = data.keys.find((key) => key.kid === kid); + if (!jwk) { + return null; + } + return jwk; + } + /** + * Extracts the JWT claims present in the access token by first verifying the + * JWT against the server's JSON Web Key Set endpoint + * `/.well-known/jwks.json` which is often cached, resulting in significantly + * faster responses. Prefer this method over {@link #getUser} which always + * sends a request to the Auth server for each JWT. + * + * If the project is not using an asymmetric JWT signing key (like ECC or + * RSA) it always sends a request to the Auth server (similar to {@link + * #getUser}) to verify the JWT. + * + * @param jwt An optional specific JWT you wish to verify, not the one you + * can obtain from {@link #getSession}. + * @param options Various additional options that allow you to customize the + * behavior of this method. + */ + async getClaims(jwt, options = {}) { + try { + let token = jwt; + if (!token) { + const { data, error } = await this.getSession(); + if (error || !data.session) { + return this._returnResult({ data: null, error }); + } + token = data.session.access_token; + } + const { header, payload, signature, raw: { header: rawHeader, payload: rawPayload } } = (0, helpers_1.decodeJWT)(token); + if (!(options === null || options === void 0 ? void 0 : options.allowExpired)) { + (0, helpers_1.validateExp)(payload.exp); + } + const signingKey = !header.alg || header.alg.startsWith("HS") || !header.kid || !("crypto" in globalThis && "subtle" in globalThis.crypto) ? null : await this.fetchJwk(header.kid, (options === null || options === void 0 ? void 0 : options.keys) ? { keys: options.keys } : options === null || options === void 0 ? void 0 : options.jwks); + if (!signingKey) { + const { error } = await this.getUser(token); + if (error) { + throw error; + } + return { + data: { + claims: payload, + header, + signature + }, + error: null + }; + } + const algorithm = (0, helpers_1.getAlgorithm)(header.alg); + const publicKey = await crypto.subtle.importKey("jwk", signingKey, algorithm, true, [ + "verify" + ]); + const isValid = await crypto.subtle.verify(algorithm, publicKey, signature, (0, base64url_1.stringToUint8Array)(`${rawHeader}.${rawPayload}`)); + if (!isValid) { + throw new errors_1.AuthInvalidJwtError("Invalid JWT signature"); + } + return { + data: { + claims: payload, + header, + signature + }, + error: null + }; + } catch (error) { + if ((0, errors_1.isAuthError)(error)) { + return this._returnResult({ data: null, error }); + } + throw error; + } + } + }; + GoTrueClient2.nextInstanceID = {}; + exports.default = GoTrueClient2; + } + }); + + // node_modules/@supabase/auth-js/dist/main/AuthAdminApi.js + var require_AuthAdminApi = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/AuthAdminApi.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var GoTrueAdminApi_1 = tslib_1.__importDefault(require_GoTrueAdminApi()); + var AuthAdminApi2 = GoTrueAdminApi_1.default; + exports.default = AuthAdminApi2; + } + }); + + // node_modules/@supabase/auth-js/dist/main/AuthClient.js + var require_AuthClient = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/AuthClient.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var GoTrueClient_1 = tslib_1.__importDefault(require_GoTrueClient()); + var AuthClient2 = GoTrueClient_1.default; + exports.default = AuthClient2; + } + }); + + // node_modules/@supabase/auth-js/dist/main/index.js + var require_main4 = __commonJS({ + "node_modules/@supabase/auth-js/dist/main/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.processLock = exports.lockInternals = exports.NavigatorLockAcquireTimeoutError = exports.navigatorLock = exports.AuthClient = exports.AuthAdminApi = exports.GoTrueClient = exports.GoTrueAdminApi = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var GoTrueAdminApi_1 = tslib_1.__importDefault(require_GoTrueAdminApi()); + exports.GoTrueAdminApi = GoTrueAdminApi_1.default; + var GoTrueClient_1 = tslib_1.__importDefault(require_GoTrueClient()); + exports.GoTrueClient = GoTrueClient_1.default; + var AuthAdminApi_1 = tslib_1.__importDefault(require_AuthAdminApi()); + exports.AuthAdminApi = AuthAdminApi_1.default; + var AuthClient_1 = tslib_1.__importDefault(require_AuthClient()); + exports.AuthClient = AuthClient_1.default; + tslib_1.__exportStar(require_types3(), exports); + tslib_1.__exportStar(require_errors3(), exports); + var locks_1 = require_locks(); + Object.defineProperty(exports, "navigatorLock", { enumerable: true, get: function() { + return locks_1.navigatorLock; + } }); + Object.defineProperty(exports, "NavigatorLockAcquireTimeoutError", { enumerable: true, get: function() { + return locks_1.NavigatorLockAcquireTimeoutError; + } }); + Object.defineProperty(exports, "lockInternals", { enumerable: true, get: function() { + return locks_1.internals; + } }); + Object.defineProperty(exports, "processLock", { enumerable: true, get: function() { + return locks_1.processLock; + } }); + } + }); + + // node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.js + var require_SupabaseAuthClient = __commonJS({ + "node_modules/@supabase/supabase-js/dist/main/lib/SupabaseAuthClient.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SupabaseAuthClient = void 0; + var auth_js_1 = require_main4(); + var SupabaseAuthClient = class extends auth_js_1.AuthClient { + constructor(options) { + super(options); + } + }; + exports.SupabaseAuthClient = SupabaseAuthClient; + } + }); + + // node_modules/@supabase/supabase-js/dist/main/SupabaseClient.js + var require_SupabaseClient = __commonJS({ + "node_modules/@supabase/supabase-js/dist/main/SupabaseClient.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var functions_js_1 = require_main(); + var postgrest_js_1 = require_cjs(); + var realtime_js_1 = require_main2(); + var storage_js_1 = require_main3(); + var constants_1 = require_constants5(); + var fetch_1 = require_fetch3(); + var helpers_1 = require_helpers3(); + var SupabaseAuthClient_1 = require_SupabaseAuthClient(); + var SupabaseClient3 = class { + /** + * Create a new client for use in the browser. + * @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard. + * @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard. + * @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase. + * @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring. + * @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage. + * @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user. + * @param options.realtime Options passed along to realtime-js constructor. + * @param options.storage Options passed along to the storage-js constructor. + * @param options.global.fetch A custom fetch implementation. + * @param options.global.headers Any additional headers to send with each network request. + * @example + * ```ts + * import { createClient } from '@supabase/supabase-js' + * + * const supabase = createClient('https://xyzcompany.supabase.co', 'public-anon-key') + * const { data } = await supabase.from('profiles').select('*') + * ``` + */ + constructor(supabaseUrl, supabaseKey, options) { + var _a, _b, _c; + this.supabaseUrl = supabaseUrl; + this.supabaseKey = supabaseKey; + const baseUrl = (0, helpers_1.validateSupabaseUrl)(supabaseUrl); + if (!supabaseKey) + throw new Error("supabaseKey is required."); + this.realtimeUrl = new URL("realtime/v1", baseUrl); + this.realtimeUrl.protocol = this.realtimeUrl.protocol.replace("http", "ws"); + this.authUrl = new URL("auth/v1", baseUrl); + this.storageUrl = new URL("storage/v1", baseUrl); + this.functionsUrl = new URL("functions/v1", baseUrl); + const defaultStorageKey = `sb-${baseUrl.hostname.split(".")[0]}-auth-token`; + const DEFAULTS = { + db: constants_1.DEFAULT_DB_OPTIONS, + realtime: constants_1.DEFAULT_REALTIME_OPTIONS, + auth: Object.assign(Object.assign({}, constants_1.DEFAULT_AUTH_OPTIONS), { storageKey: defaultStorageKey }), + global: constants_1.DEFAULT_GLOBAL_OPTIONS + }; + const settings = (0, helpers_1.applySettingDefaults)(options !== null && options !== void 0 ? options : {}, DEFAULTS); + this.storageKey = (_a = settings.auth.storageKey) !== null && _a !== void 0 ? _a : ""; + this.headers = (_b = settings.global.headers) !== null && _b !== void 0 ? _b : {}; + if (!settings.accessToken) { + this.auth = this._initSupabaseAuthClient((_c = settings.auth) !== null && _c !== void 0 ? _c : {}, this.headers, settings.global.fetch); + } else { + this.accessToken = settings.accessToken; + this.auth = new Proxy({}, { + get: (_2, prop) => { + throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(prop)} is not possible`); + } + }); + } + this.fetch = (0, fetch_1.fetchWithAuth)(supabaseKey, this._getAccessToken.bind(this), settings.global.fetch); + this.realtime = this._initRealtimeClient(Object.assign({ headers: this.headers, accessToken: this._getAccessToken.bind(this) }, settings.realtime)); + if (this.accessToken) { + this.accessToken().then((token) => this.realtime.setAuth(token)).catch((e2) => console.warn("Failed to set initial Realtime auth token:", e2)); + } + this.rest = new postgrest_js_1.PostgrestClient(new URL("rest/v1", baseUrl).href, { + headers: this.headers, + schema: settings.db.schema, + fetch: this.fetch + }); + this.storage = new storage_js_1.StorageClient(this.storageUrl.href, this.headers, this.fetch, options === null || options === void 0 ? void 0 : options.storage); + if (!settings.accessToken) { + this._listenForAuthEvents(); + } + } + /** + * Supabase Functions allows you to deploy and invoke edge functions. + */ + get functions() { + return new functions_js_1.FunctionsClient(this.functionsUrl.href, { + headers: this.headers, + customFetch: this.fetch + }); + } + /** + * Perform a query on a table or a view. + * + * @param relation - The table or view name to query + */ + from(relation) { + return this.rest.from(relation); + } + // NOTE: signatures must be kept in sync with PostgrestClient.schema + /** + * Select a schema to query or perform an function (rpc) call. + * + * The schema needs to be on the list of exposed schemas inside Supabase. + * + * @param schema - The schema to query + */ + schema(schema4) { + return this.rest.schema(schema4); + } + // NOTE: signatures must be kept in sync with PostgrestClient.rpc + /** + * Perform a function call. + * + * @param fn - The function name to call + * @param args - The arguments to pass to the function call + * @param options - Named parameters + * @param options.head - When set to `true`, `data` will not be returned. + * Useful if you only need the count. + * @param options.get - When set to `true`, the function will be called with + * read-only access mode. + * @param options.count - Count algorithm to use to count rows returned by the + * function. Only applicable for [set-returning + * functions](https://www.postgresql.org/docs/current/functions-srf.html). + * + * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the + * hood. + * + * `"planned"`: Approximated but fast count algorithm. Uses the Postgres + * statistics under the hood. + * + * `"estimated"`: Uses exact count for low numbers and planned count for high + * numbers. + */ + rpc(fn, args = {}, options = { + head: false, + get: false, + count: void 0 + }) { + return this.rest.rpc(fn, args, options); + } + /** + * Creates a Realtime channel with Broadcast, Presence, and Postgres Changes. + * + * @param {string} name - The name of the Realtime channel. + * @param {Object} opts - The options to pass to the Realtime channel. + * + */ + channel(name, opts = { config: {} }) { + return this.realtime.channel(name, opts); + } + /** + * Returns all Realtime channels. + */ + getChannels() { + return this.realtime.getChannels(); + } + /** + * Unsubscribes and removes Realtime channel from Realtime client. + * + * @param {RealtimeChannel} channel - The name of the Realtime channel. + * + */ + removeChannel(channel) { + return this.realtime.removeChannel(channel); + } + /** + * Unsubscribes and removes all Realtime channels from Realtime client. + */ + removeAllChannels() { + return this.realtime.removeAllChannels(); + } + async _getAccessToken() { + var _a, _b; + if (this.accessToken) { + return await this.accessToken(); + } + const { data } = await this.auth.getSession(); + return (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : this.supabaseKey; + } + _initSupabaseAuthClient({ autoRefreshToken, persistSession, detectSessionInUrl, storage, userStorage, storageKey, flowType, lock, debug, throwOnError }, headers, fetch2) { + const authHeaders = { + Authorization: `Bearer ${this.supabaseKey}`, + apikey: `${this.supabaseKey}` + }; + return new SupabaseAuthClient_1.SupabaseAuthClient({ + url: this.authUrl.href, + headers: Object.assign(Object.assign({}, authHeaders), headers), + storageKey, + autoRefreshToken, + persistSession, + detectSessionInUrl, + storage, + userStorage, + flowType, + lock, + debug, + throwOnError, + fetch: fetch2, + // auth checks if there is a custom authorizaiton header using this flag + // so it knows whether to return an error when getUser is called with no session + hasCustomAuthorizationHeader: Object.keys(this.headers).some((key) => key.toLowerCase() === "authorization") + }); + } + _initRealtimeClient(options) { + return new realtime_js_1.RealtimeClient(this.realtimeUrl.href, Object.assign(Object.assign({}, options), { params: Object.assign({ apikey: this.supabaseKey }, options === null || options === void 0 ? void 0 : options.params) })); + } + _listenForAuthEvents() { + const data = this.auth.onAuthStateChange((event, session) => { + this._handleTokenChanged(event, "CLIENT", session === null || session === void 0 ? void 0 : session.access_token); + }); + return data; + } + _handleTokenChanged(event, source, token) { + if ((event === "TOKEN_REFRESHED" || event === "SIGNED_IN") && this.changedAccessToken !== token) { + this.changedAccessToken = token; + this.realtime.setAuth(token); + } else if (event === "SIGNED_OUT") { + this.realtime.setAuth(); + if (source == "STORAGE") + this.auth.signOut(); + this.changedAccessToken = void 0; + } + } + }; + exports.default = SupabaseClient3; + } + }); + + // node_modules/@supabase/supabase-js/dist/main/index.js + var require_main5 = __commonJS({ + "node_modules/@supabase/supabase-js/dist/main/index.js"(exports) { + "use strict"; + var __createBinding3 = exports && exports.__createBinding || (Object.create ? (function(o2, m3, k3, k22) { + if (k22 === void 0) k22 = k3; + var desc = Object.getOwnPropertyDescriptor(m3, k3); + if (!desc || ("get" in desc ? !m3.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m3[k3]; + } }; + } + Object.defineProperty(o2, k22, desc); + }) : (function(o2, m3, k3, k22) { + if (k22 === void 0) k22 = k3; + o2[k22] = m3[k3]; + })); + var __exportStar3 = exports && exports.__exportStar || function(m3, exports2) { + for (var p2 in m3) if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p2)) __createBinding3(exports2, m3, p2); + }; + var __importDefault3 = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createClient = exports.SupabaseClient = exports.FunctionRegion = exports.FunctionsError = exports.FunctionsRelayError = exports.FunctionsFetchError = exports.FunctionsHttpError = exports.PostgrestError = void 0; + var SupabaseClient_1 = __importDefault3(require_SupabaseClient()); + __exportStar3(require_main4(), exports); + var postgrest_js_1 = require_cjs(); + Object.defineProperty(exports, "PostgrestError", { enumerable: true, get: function() { + return postgrest_js_1.PostgrestError; + } }); + var functions_js_1 = require_main(); + Object.defineProperty(exports, "FunctionsHttpError", { enumerable: true, get: function() { + return functions_js_1.FunctionsHttpError; + } }); + Object.defineProperty(exports, "FunctionsFetchError", { enumerable: true, get: function() { + return functions_js_1.FunctionsFetchError; + } }); + Object.defineProperty(exports, "FunctionsRelayError", { enumerable: true, get: function() { + return functions_js_1.FunctionsRelayError; + } }); + Object.defineProperty(exports, "FunctionsError", { enumerable: true, get: function() { + return functions_js_1.FunctionsError; + } }); + Object.defineProperty(exports, "FunctionRegion", { enumerable: true, get: function() { + return functions_js_1.FunctionRegion; + } }); + __exportStar3(require_main2(), exports); + var SupabaseClient_2 = require_SupabaseClient(); + Object.defineProperty(exports, "SupabaseClient", { enumerable: true, get: function() { + return __importDefault3(SupabaseClient_2).default; + } }); + var createClient2 = (supabaseUrl, supabaseKey, options) => { + return new SupabaseClient_1.default(supabaseUrl, supabaseKey, options); + }; + exports.createClient = createClient2; + function shouldShowDeprecationWarning() { + if (typeof window !== "undefined") { + return false; + } + if (typeof process === "undefined") { + return false; + } + const processVersion = process["version"]; + if (processVersion === void 0 || processVersion === null) { + return false; + } + const versionMatch = processVersion.match(/^v(\d+)\./); + if (!versionMatch) { + return false; + } + const majorVersion = parseInt(versionMatch[1], 10); + return majorVersion <= 18; + } + if (shouldShowDeprecationWarning()) { + console.warn(`\u26A0\uFE0F Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217`); + } + } + }); + + // node_modules/@aws-crypto/sha256-js/build/module/constants.js + var BLOCK_SIZE, DIGEST_LENGTH, KEY, INIT, MAX_HASHABLE_LENGTH; + var init_constants = __esm({ + "node_modules/@aws-crypto/sha256-js/build/module/constants.js"() { + BLOCK_SIZE = 64; + DIGEST_LENGTH = 32; + KEY = new Uint32Array([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 + ]); + INIT = [ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 + ]; + MAX_HASHABLE_LENGTH = Math.pow(2, 53) - 1; + } + }); + + // node_modules/@aws-crypto/sha256-js/build/module/RawSha256.js + var RawSha256; + var init_RawSha256 = __esm({ + "node_modules/@aws-crypto/sha256-js/build/module/RawSha256.js"() { + init_constants(); + RawSha256 = /** @class */ + (function() { + function RawSha2562() { + this.state = Int32Array.from(INIT); + this.temp = new Int32Array(64); + this.buffer = new Uint8Array(64); + this.bufferLength = 0; + this.bytesHashed = 0; + this.finished = false; + } + RawSha2562.prototype.update = function(data) { + if (this.finished) { + throw new Error("Attempted to update an already finished hash."); + } + var position = 0; + var byteLength = data.byteLength; + this.bytesHashed += byteLength; + if (this.bytesHashed * 8 > MAX_HASHABLE_LENGTH) { + throw new Error("Cannot hash more than 2^53 - 1 bits"); + } + while (byteLength > 0) { + this.buffer[this.bufferLength++] = data[position++]; + byteLength--; + if (this.bufferLength === BLOCK_SIZE) { + this.hashBuffer(); + this.bufferLength = 0; + } + } + }; + RawSha2562.prototype.digest = function() { + if (!this.finished) { + var bitsHashed = this.bytesHashed * 8; + var bufferView = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength); + var undecoratedLength = this.bufferLength; + bufferView.setUint8(this.bufferLength++, 128); + if (undecoratedLength % BLOCK_SIZE >= BLOCK_SIZE - 8) { + for (var i2 = this.bufferLength; i2 < BLOCK_SIZE; i2++) { + bufferView.setUint8(i2, 0); + } + this.hashBuffer(); + this.bufferLength = 0; + } + for (var i2 = this.bufferLength; i2 < BLOCK_SIZE - 8; i2++) { + bufferView.setUint8(i2, 0); + } + bufferView.setUint32(BLOCK_SIZE - 8, Math.floor(bitsHashed / 4294967296), true); + bufferView.setUint32(BLOCK_SIZE - 4, bitsHashed); + this.hashBuffer(); + this.finished = true; + } + var out = new Uint8Array(DIGEST_LENGTH); + for (var i2 = 0; i2 < 8; i2++) { + out[i2 * 4] = this.state[i2] >>> 24 & 255; + out[i2 * 4 + 1] = this.state[i2] >>> 16 & 255; + out[i2 * 4 + 2] = this.state[i2] >>> 8 & 255; + out[i2 * 4 + 3] = this.state[i2] >>> 0 & 255; + } + return out; + }; + RawSha2562.prototype.hashBuffer = function() { + var _a = this, buffer = _a.buffer, state = _a.state; + var state0 = state[0], state1 = state[1], state2 = state[2], state3 = state[3], state4 = state[4], state5 = state[5], state6 = state[6], state7 = state[7]; + for (var i2 = 0; i2 < BLOCK_SIZE; i2++) { + if (i2 < 16) { + this.temp[i2] = (buffer[i2 * 4] & 255) << 24 | (buffer[i2 * 4 + 1] & 255) << 16 | (buffer[i2 * 4 + 2] & 255) << 8 | buffer[i2 * 4 + 3] & 255; + } else { + var u4 = this.temp[i2 - 2]; + var t1_1 = (u4 >>> 17 | u4 << 15) ^ (u4 >>> 19 | u4 << 13) ^ u4 >>> 10; + u4 = this.temp[i2 - 15]; + var t2_1 = (u4 >>> 7 | u4 << 25) ^ (u4 >>> 18 | u4 << 14) ^ u4 >>> 3; + this.temp[i2] = (t1_1 + this.temp[i2 - 7] | 0) + (t2_1 + this.temp[i2 - 16] | 0); + } + var t1 = (((state4 >>> 6 | state4 << 26) ^ (state4 >>> 11 | state4 << 21) ^ (state4 >>> 25 | state4 << 7)) + (state4 & state5 ^ ~state4 & state6) | 0) + (state7 + (KEY[i2] + this.temp[i2] | 0) | 0) | 0; + var t2 = ((state0 >>> 2 | state0 << 30) ^ (state0 >>> 13 | state0 << 19) ^ (state0 >>> 22 | state0 << 10)) + (state0 & state1 ^ state0 & state2 ^ state1 & state2) | 0; + state7 = state6; + state6 = state5; + state5 = state4; + state4 = state3 + t1 | 0; + state3 = state2; + state2 = state1; + state1 = state0; + state0 = t1 + t2 | 0; + } + state[0] += state0; + state[1] += state1; + state[2] += state2; + state[3] += state3; + state[4] += state4; + state[5] += state5; + state[6] += state6; + state[7] += state7; + }; + return RawSha2562; + })(); + } + }); + + // node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-es/fromUtf8.browser.js + var fromUtf8; + var init_fromUtf8_browser = __esm({ + "node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-es/fromUtf8.browser.js"() { + fromUtf8 = (input) => new TextEncoder().encode(input); + } + }); + + // node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js + var init_toUint8Array = __esm({ + "node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js"() { + init_fromUtf8_browser(); + } + }); + + // node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-es/toUtf8.browser.js + var init_toUtf8_browser = __esm({ + "node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-es/toUtf8.browser.js"() { + } + }); + + // node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-es/index.js + var init_dist_es = __esm({ + "node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-es/index.js"() { + init_fromUtf8_browser(); + init_toUint8Array(); + init_toUtf8_browser(); + } + }); + + // node_modules/@aws-crypto/util/build/module/convertToBuffer.js + function convertToBuffer(data) { + if (data instanceof Uint8Array) + return data; + if (typeof data === "string") { + return fromUtf82(data); + } + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); + } + return new Uint8Array(data); + } + var fromUtf82; + var init_convertToBuffer = __esm({ + "node_modules/@aws-crypto/util/build/module/convertToBuffer.js"() { + init_dist_es(); + fromUtf82 = typeof Buffer !== "undefined" && Buffer.from ? function(input) { + return Buffer.from(input, "utf8"); + } : fromUtf8; + } + }); + + // node_modules/@aws-crypto/util/build/module/isEmptyData.js + function isEmptyData(data) { + if (typeof data === "string") { + return data.length === 0; + } + return data.byteLength === 0; + } + var init_isEmptyData = __esm({ + "node_modules/@aws-crypto/util/build/module/isEmptyData.js"() { + } + }); + + // node_modules/@aws-crypto/util/build/module/numToUint8.js + var init_numToUint8 = __esm({ + "node_modules/@aws-crypto/util/build/module/numToUint8.js"() { + } + }); + + // node_modules/@aws-crypto/util/build/module/uint32ArrayFrom.js + var init_uint32ArrayFrom = __esm({ + "node_modules/@aws-crypto/util/build/module/uint32ArrayFrom.js"() { + } + }); + + // node_modules/@aws-crypto/util/build/module/index.js + var init_module = __esm({ + "node_modules/@aws-crypto/util/build/module/index.js"() { + init_convertToBuffer(); + init_isEmptyData(); + init_numToUint8(); + init_uint32ArrayFrom(); + } + }); + + // node_modules/@aws-crypto/sha256-js/build/module/jsSha256.js + function bufferFromSecret(secret) { + var input = convertToBuffer(secret); + if (input.byteLength > BLOCK_SIZE) { + var bufferHash = new RawSha256(); + bufferHash.update(input); + input = bufferHash.digest(); + } + var buffer = new Uint8Array(BLOCK_SIZE); + buffer.set(input); + return buffer; + } + var Sha256; + var init_jsSha256 = __esm({ + "node_modules/@aws-crypto/sha256-js/build/module/jsSha256.js"() { + init_tslib_es6(); + init_constants(); + init_RawSha256(); + init_module(); + Sha256 = /** @class */ + (function() { + function Sha2564(secret) { + this.secret = secret; + this.hash = new RawSha256(); + this.reset(); + } + Sha2564.prototype.update = function(toHash) { + if (isEmptyData(toHash) || this.error) { + return; + } + try { + this.hash.update(convertToBuffer(toHash)); + } catch (e2) { + this.error = e2; + } + }; + Sha2564.prototype.digestSync = function() { + if (this.error) { + throw this.error; + } + if (this.outer) { + if (!this.outer.finished) { + this.outer.update(this.hash.digest()); + } + return this.outer.digest(); + } + return this.hash.digest(); + }; + Sha2564.prototype.digest = function() { + return __awaiter(this, void 0, void 0, function() { + return __generator(this, function(_a) { + return [2, this.digestSync()]; + }); + }); + }; + Sha2564.prototype.reset = function() { + this.hash = new RawSha256(); + if (this.secret) { + this.outer = new RawSha256(); + var inner = bufferFromSecret(this.secret); + var outer = new Uint8Array(BLOCK_SIZE); + outer.set(inner); + for (var i2 = 0; i2 < BLOCK_SIZE; i2++) { + inner[i2] ^= 54; + outer[i2] ^= 92; + } + this.hash.update(inner); + this.outer.update(outer); + for (var i2 = 0; i2 < inner.byteLength; i2++) { + inner[i2] = 0; + } + } + }; + return Sha2564; + })(); + } + }); + + // node_modules/@aws-crypto/sha256-js/build/module/index.js + var init_module2 = __esm({ + "node_modules/@aws-crypto/sha256-js/build/module/index.js"() { + init_jsSha256(); + } + }); + + // node_modules/@smithy/property-provider/dist-es/ProviderError.js + var ProviderError; + var init_ProviderError = __esm({ + "node_modules/@smithy/property-provider/dist-es/ProviderError.js"() { + ProviderError = class _ProviderError extends Error { + name = "ProviderError"; + tryNextLink; + constructor(message, options = true) { + let logger2; + let tryNextLink = true; + if (typeof options === "boolean") { + logger2 = void 0; + tryNextLink = options; + } else if (options != null && typeof options === "object") { + logger2 = options.logger; + tryNextLink = options.tryNextLink ?? true; + } + super(message); + this.tryNextLink = tryNextLink; + Object.setPrototypeOf(this, _ProviderError.prototype); + logger2?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); + } + static from(error, options = true) { + return Object.assign(new this(error.message, options), error); + } + }; + } + }); + + // node_modules/@smithy/property-provider/dist-es/CredentialsProviderError.js + var CredentialsProviderError; + var init_CredentialsProviderError = __esm({ + "node_modules/@smithy/property-provider/dist-es/CredentialsProviderError.js"() { + init_ProviderError(); + CredentialsProviderError = class _CredentialsProviderError extends ProviderError { + name = "CredentialsProviderError"; + constructor(message, options = true) { + super(message, options); + Object.setPrototypeOf(this, _CredentialsProviderError.prototype); + } + }; + } + }); + + // node_modules/@smithy/property-provider/dist-es/TokenProviderError.js + var init_TokenProviderError = __esm({ + "node_modules/@smithy/property-provider/dist-es/TokenProviderError.js"() { + } + }); + + // node_modules/@smithy/property-provider/dist-es/chain.js + var init_chain = __esm({ + "node_modules/@smithy/property-provider/dist-es/chain.js"() { + } + }); + + // node_modules/@smithy/property-provider/dist-es/fromStatic.js + var init_fromStatic = __esm({ + "node_modules/@smithy/property-provider/dist-es/fromStatic.js"() { + } + }); + + // node_modules/@smithy/property-provider/dist-es/memoize.js + var memoize; + var init_memoize = __esm({ + "node_modules/@smithy/property-provider/dist-es/memoize.js"() { + memoize = (provider, isExpired, requiresRefresh) => { + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = async () => { + if (!pending) { + pending = provider(); + } + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } finally { + pending = void 0; + } + return resolved; + }; + if (isExpired === void 0) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + return resolved; + }; + } + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(); + } + if (isConstant) { + return resolved; + } + if (requiresRefresh && !requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(); + return resolved; + } + return resolved; + }; + }; + } + }); + + // node_modules/@smithy/property-provider/dist-es/index.js + var init_dist_es2 = __esm({ + "node_modules/@smithy/property-provider/dist-es/index.js"() { + init_CredentialsProviderError(); + init_ProviderError(); + init_TokenProviderError(); + init_chain(); + init_fromStatic(); + init_memoize(); + } + }); + + // node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js + var getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig; + var init_httpExtensionConfiguration = __esm({ + "node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js"() { + getHttpHandlerExtensionConfiguration = (runtimeConfig) => { + return { + setHttpHandler(handler) { + runtimeConfig.httpHandler = handler; + }, + httpHandler() { + return runtimeConfig.httpHandler; + }, + updateHttpClientConfig(key, value) { + runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); + }, + httpHandlerConfigs() { + return runtimeConfig.httpHandler.httpHandlerConfigs(); + } + }; + }; + resolveHttpHandlerRuntimeConfig = (httpHandlerExtensionConfiguration) => { + return { + httpHandler: httpHandlerExtensionConfiguration.httpHandler() + }; + }; + } + }); + + // node_modules/@smithy/protocol-http/dist-es/extensions/index.js + var init_extensions = __esm({ + "node_modules/@smithy/protocol-http/dist-es/extensions/index.js"() { + init_httpExtensionConfiguration(); + } + }); + + // node_modules/@smithy/types/dist-es/abort.js + var init_abort = __esm({ + "node_modules/@smithy/types/dist-es/abort.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/auth/auth.js + var HttpAuthLocation; + var init_auth = __esm({ + "node_modules/@smithy/types/dist-es/auth/auth.js"() { + (function(HttpAuthLocation2) { + HttpAuthLocation2["HEADER"] = "header"; + HttpAuthLocation2["QUERY"] = "query"; + })(HttpAuthLocation || (HttpAuthLocation = {})); + } + }); + + // node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js + var HttpApiKeyAuthLocation; + var init_HttpApiKeyAuth = __esm({ + "node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js"() { + (function(HttpApiKeyAuthLocation2) { + HttpApiKeyAuthLocation2["HEADER"] = "header"; + HttpApiKeyAuthLocation2["QUERY"] = "query"; + })(HttpApiKeyAuthLocation || (HttpApiKeyAuthLocation = {})); + } + }); + + // node_modules/@smithy/types/dist-es/auth/HttpAuthScheme.js + var init_HttpAuthScheme = __esm({ + "node_modules/@smithy/types/dist-es/auth/HttpAuthScheme.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/auth/HttpAuthSchemeProvider.js + var init_HttpAuthSchemeProvider = __esm({ + "node_modules/@smithy/types/dist-es/auth/HttpAuthSchemeProvider.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/auth/HttpSigner.js + var init_HttpSigner = __esm({ + "node_modules/@smithy/types/dist-es/auth/HttpSigner.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/auth/IdentityProviderConfig.js + var init_IdentityProviderConfig = __esm({ + "node_modules/@smithy/types/dist-es/auth/IdentityProviderConfig.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/auth/index.js + var init_auth2 = __esm({ + "node_modules/@smithy/types/dist-es/auth/index.js"() { + init_auth(); + init_HttpApiKeyAuth(); + init_HttpAuthScheme(); + init_HttpAuthSchemeProvider(); + init_HttpSigner(); + init_IdentityProviderConfig(); + } + }); + + // node_modules/@smithy/types/dist-es/blob/blob-payload-input-types.js + var init_blob_payload_input_types = __esm({ + "node_modules/@smithy/types/dist-es/blob/blob-payload-input-types.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/checksum.js + var init_checksum = __esm({ + "node_modules/@smithy/types/dist-es/checksum.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/client.js + var init_client = __esm({ + "node_modules/@smithy/types/dist-es/client.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/command.js + var init_command = __esm({ + "node_modules/@smithy/types/dist-es/command.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/connection/config.js + var init_config = __esm({ + "node_modules/@smithy/types/dist-es/connection/config.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/connection/manager.js + var init_manager = __esm({ + "node_modules/@smithy/types/dist-es/connection/manager.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/connection/pool.js + var init_pool = __esm({ + "node_modules/@smithy/types/dist-es/connection/pool.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/connection/index.js + var init_connection = __esm({ + "node_modules/@smithy/types/dist-es/connection/index.js"() { + init_config(); + init_manager(); + init_pool(); + } + }); + + // node_modules/@smithy/types/dist-es/crypto.js + var init_crypto = __esm({ + "node_modules/@smithy/types/dist-es/crypto.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/encode.js + var init_encode = __esm({ + "node_modules/@smithy/types/dist-es/encode.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/endpoint.js + var EndpointURLScheme; + var init_endpoint = __esm({ + "node_modules/@smithy/types/dist-es/endpoint.js"() { + (function(EndpointURLScheme2) { + EndpointURLScheme2["HTTP"] = "http"; + EndpointURLScheme2["HTTPS"] = "https"; + })(EndpointURLScheme || (EndpointURLScheme = {})); + } + }); + + // node_modules/@smithy/types/dist-es/endpoints/EndpointRuleObject.js + var init_EndpointRuleObject = __esm({ + "node_modules/@smithy/types/dist-es/endpoints/EndpointRuleObject.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/endpoints/ErrorRuleObject.js + var init_ErrorRuleObject = __esm({ + "node_modules/@smithy/types/dist-es/endpoints/ErrorRuleObject.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/endpoints/RuleSetObject.js + var init_RuleSetObject = __esm({ + "node_modules/@smithy/types/dist-es/endpoints/RuleSetObject.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/endpoints/shared.js + var init_shared = __esm({ + "node_modules/@smithy/types/dist-es/endpoints/shared.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/endpoints/TreeRuleObject.js + var init_TreeRuleObject = __esm({ + "node_modules/@smithy/types/dist-es/endpoints/TreeRuleObject.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/endpoints/index.js + var init_endpoints = __esm({ + "node_modules/@smithy/types/dist-es/endpoints/index.js"() { + init_EndpointRuleObject(); + init_ErrorRuleObject(); + init_RuleSetObject(); + init_shared(); + init_TreeRuleObject(); + } + }); + + // node_modules/@smithy/types/dist-es/eventStream.js + var init_eventStream = __esm({ + "node_modules/@smithy/types/dist-es/eventStream.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/extensions/checksum.js + var AlgorithmId; + var init_checksum2 = __esm({ + "node_modules/@smithy/types/dist-es/extensions/checksum.js"() { + (function(AlgorithmId2) { + AlgorithmId2["MD5"] = "md5"; + AlgorithmId2["CRC32"] = "crc32"; + AlgorithmId2["CRC32C"] = "crc32c"; + AlgorithmId2["SHA1"] = "sha1"; + AlgorithmId2["SHA256"] = "sha256"; + })(AlgorithmId || (AlgorithmId = {})); + } + }); + + // node_modules/@smithy/types/dist-es/extensions/defaultClientConfiguration.js + var init_defaultClientConfiguration = __esm({ + "node_modules/@smithy/types/dist-es/extensions/defaultClientConfiguration.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/extensions/defaultExtensionConfiguration.js + var init_defaultExtensionConfiguration = __esm({ + "node_modules/@smithy/types/dist-es/extensions/defaultExtensionConfiguration.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/extensions/index.js + var init_extensions2 = __esm({ + "node_modules/@smithy/types/dist-es/extensions/index.js"() { + init_defaultClientConfiguration(); + init_defaultExtensionConfiguration(); + init_checksum2(); + } + }); + + // node_modules/@smithy/types/dist-es/feature-ids.js + var init_feature_ids = __esm({ + "node_modules/@smithy/types/dist-es/feature-ids.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/http.js + var FieldPosition; + var init_http = __esm({ + "node_modules/@smithy/types/dist-es/http.js"() { + (function(FieldPosition3) { + FieldPosition3[FieldPosition3["HEADER"] = 0] = "HEADER"; + FieldPosition3[FieldPosition3["TRAILER"] = 1] = "TRAILER"; + })(FieldPosition || (FieldPosition = {})); + } + }); + + // node_modules/@smithy/types/dist-es/http/httpHandlerInitialization.js + var init_httpHandlerInitialization = __esm({ + "node_modules/@smithy/types/dist-es/http/httpHandlerInitialization.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/identity/apiKeyIdentity.js + var init_apiKeyIdentity = __esm({ + "node_modules/@smithy/types/dist-es/identity/apiKeyIdentity.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/identity/awsCredentialIdentity.js + var init_awsCredentialIdentity = __esm({ + "node_modules/@smithy/types/dist-es/identity/awsCredentialIdentity.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/identity/identity.js + var init_identity = __esm({ + "node_modules/@smithy/types/dist-es/identity/identity.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/identity/tokenIdentity.js + var init_tokenIdentity = __esm({ + "node_modules/@smithy/types/dist-es/identity/tokenIdentity.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/identity/index.js + var init_identity2 = __esm({ + "node_modules/@smithy/types/dist-es/identity/index.js"() { + init_apiKeyIdentity(); + init_awsCredentialIdentity(); + init_identity(); + init_tokenIdentity(); + } + }); + + // node_modules/@smithy/types/dist-es/logger.js + var init_logger = __esm({ + "node_modules/@smithy/types/dist-es/logger.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/middleware.js + var SMITHY_CONTEXT_KEY; + var init_middleware = __esm({ + "node_modules/@smithy/types/dist-es/middleware.js"() { + SMITHY_CONTEXT_KEY = "__smithy_context"; + } + }); + + // node_modules/@smithy/types/dist-es/pagination.js + var init_pagination = __esm({ + "node_modules/@smithy/types/dist-es/pagination.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/profile.js + var IniSectionType; + var init_profile = __esm({ + "node_modules/@smithy/types/dist-es/profile.js"() { + (function(IniSectionType2) { + IniSectionType2["PROFILE"] = "profile"; + IniSectionType2["SSO_SESSION"] = "sso-session"; + IniSectionType2["SERVICES"] = "services"; + })(IniSectionType || (IniSectionType = {})); + } + }); + + // node_modules/@smithy/types/dist-es/response.js + var init_response = __esm({ + "node_modules/@smithy/types/dist-es/response.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/retry.js + var init_retry = __esm({ + "node_modules/@smithy/types/dist-es/retry.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/schema/schema.js + var init_schema = __esm({ + "node_modules/@smithy/types/dist-es/schema/schema.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/schema/sentinels.js + var init_sentinels = __esm({ + "node_modules/@smithy/types/dist-es/schema/sentinels.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/serde.js + var init_serde = __esm({ + "node_modules/@smithy/types/dist-es/serde.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/shapes.js + var init_shapes = __esm({ + "node_modules/@smithy/types/dist-es/shapes.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/signature.js + var init_signature = __esm({ + "node_modules/@smithy/types/dist-es/signature.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/stream.js + var init_stream = __esm({ + "node_modules/@smithy/types/dist-es/stream.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-common-types.js + var init_streaming_blob_common_types = __esm({ + "node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-common-types.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-input-types.js + var init_streaming_blob_payload_input_types = __esm({ + "node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-input-types.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-output-types.js + var init_streaming_blob_payload_output_types = __esm({ + "node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-output-types.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/transfer.js + var RequestHandlerProtocol; + var init_transfer = __esm({ + "node_modules/@smithy/types/dist-es/transfer.js"() { + (function(RequestHandlerProtocol2) { + RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; + RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; + RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; + })(RequestHandlerProtocol || (RequestHandlerProtocol = {})); + } + }); + + // node_modules/@smithy/types/dist-es/transform/client-payload-blob-type-narrow.js + var init_client_payload_blob_type_narrow = __esm({ + "node_modules/@smithy/types/dist-es/transform/client-payload-blob-type-narrow.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/transform/mutable.js + var init_mutable = __esm({ + "node_modules/@smithy/types/dist-es/transform/mutable.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/transform/no-undefined.js + var init_no_undefined = __esm({ + "node_modules/@smithy/types/dist-es/transform/no-undefined.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/transform/type-transform.js + var init_type_transform = __esm({ + "node_modules/@smithy/types/dist-es/transform/type-transform.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/uri.js + var init_uri = __esm({ + "node_modules/@smithy/types/dist-es/uri.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/util.js + var init_util = __esm({ + "node_modules/@smithy/types/dist-es/util.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/waiter.js + var init_waiter = __esm({ + "node_modules/@smithy/types/dist-es/waiter.js"() { + } + }); + + // node_modules/@smithy/types/dist-es/index.js + var init_dist_es3 = __esm({ + "node_modules/@smithy/types/dist-es/index.js"() { + init_abort(); + init_auth2(); + init_blob_payload_input_types(); + init_checksum(); + init_client(); + init_command(); + init_connection(); + init_crypto(); + init_encode(); + init_endpoint(); + init_endpoints(); + init_eventStream(); + init_extensions2(); + init_feature_ids(); + init_http(); + init_httpHandlerInitialization(); + init_identity2(); + init_logger(); + init_middleware(); + init_pagination(); + init_profile(); + init_response(); + init_retry(); + init_schema(); + init_sentinels(); + init_serde(); + init_shapes(); + init_signature(); + init_stream(); + init_streaming_blob_common_types(); + init_streaming_blob_payload_input_types(); + init_streaming_blob_payload_output_types(); + init_transfer(); + init_client_payload_blob_type_narrow(); + init_mutable(); + init_no_undefined(); + init_type_transform(); + init_uri(); + init_util(); + init_waiter(); + } + }); + + // node_modules/@smithy/protocol-http/dist-es/Field.js + var init_Field = __esm({ + "node_modules/@smithy/protocol-http/dist-es/Field.js"() { + } + }); + + // node_modules/@smithy/protocol-http/dist-es/Fields.js + var init_Fields = __esm({ + "node_modules/@smithy/protocol-http/dist-es/Fields.js"() { + } + }); + + // node_modules/@smithy/protocol-http/dist-es/httpHandler.js + var init_httpHandler = __esm({ + "node_modules/@smithy/protocol-http/dist-es/httpHandler.js"() { + } + }); + + // node_modules/@smithy/protocol-http/dist-es/httpRequest.js + function cloneQuery(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param + }; + }, {}); + } + var HttpRequest; + var init_httpRequest = __esm({ + "node_modules/@smithy/protocol-http/dist-es/httpRequest.js"() { + HttpRequest = class _HttpRequest { + method; + protocol; + hostname; + port; + path; + query; + headers; + username; + password; + fragment; + body; + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; + this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static clone(request) { + const cloned = new _HttpRequest({ + ...request, + headers: { ...request.headers } + }); + if (cloned.query) { + cloned.query = cloneQuery(cloned.query); + } + return cloned; + } + static isInstance(request) { + if (!request) { + return false; + } + const req = request; + return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; + } + clone() { + return _HttpRequest.clone(this); + } + }; + } + }); + + // node_modules/@smithy/protocol-http/dist-es/httpResponse.js + var HttpResponse; + var init_httpResponse = __esm({ + "node_modules/@smithy/protocol-http/dist-es/httpResponse.js"() { + HttpResponse = class { + statusCode; + reason; + headers; + body; + constructor(options) { + this.statusCode = options.statusCode; + this.reason = options.reason; + this.headers = options.headers || {}; + this.body = options.body; + } + static isInstance(response) { + if (!response) + return false; + const resp = response; + return typeof resp.statusCode === "number" && typeof resp.headers === "object"; + } + }; + } + }); + + // node_modules/@smithy/protocol-http/dist-es/isValidHostname.js + var init_isValidHostname = __esm({ + "node_modules/@smithy/protocol-http/dist-es/isValidHostname.js"() { + } + }); + + // node_modules/@smithy/protocol-http/dist-es/types.js + var init_types = __esm({ + "node_modules/@smithy/protocol-http/dist-es/types.js"() { + } + }); + + // node_modules/@smithy/protocol-http/dist-es/index.js + var init_dist_es4 = __esm({ + "node_modules/@smithy/protocol-http/dist-es/index.js"() { + init_extensions(); + init_Field(); + init_Fields(); + init_httpHandler(); + init_httpRequest(); + init_httpResponse(); + init_isValidHostname(); + init_types(); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-host-header/dist-es/index.js + function resolveHostHeaderConfig(input) { + return input; + } + var hostHeaderMiddleware, hostHeaderMiddlewareOptions, getHostHeaderPlugin; + var init_dist_es5 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-host-header/dist-es/index.js"() { + init_dist_es4(); + hostHeaderMiddleware = (options) => (next) => async (args) => { + if (!HttpRequest.isInstance(args.request)) + return next(args); + const { request } = args; + const { handlerProtocol = "" } = options.requestHandler.metadata || {}; + if (handlerProtocol.indexOf("h2") >= 0 && !request.headers[":authority"]) { + delete request.headers["host"]; + request.headers[":authority"] = request.hostname + (request.port ? ":" + request.port : ""); + } else if (!request.headers["host"]) { + let host = request.hostname; + if (request.port != null) + host += `:${request.port}`; + request.headers["host"] = host; + } + return next(args); + }; + hostHeaderMiddlewareOptions = { + name: "hostHeaderMiddleware", + step: "build", + priority: "low", + tags: ["HOST"], + override: true + }; + getHostHeaderPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions); + } + }); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-logger/dist-es/loggerMiddleware.js + var loggerMiddleware, loggerMiddlewareOptions, getLoggerPlugin; + var init_loggerMiddleware = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-logger/dist-es/loggerMiddleware.js"() { + loggerMiddleware = () => (next, context) => async (args) => { + try { + const response = await next(args); + const { clientName, commandName, logger: logger2, dynamoDbDocumentClientOptions = {} } = context; + const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions; + const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; + const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog; + const { $metadata, ...outputWithoutMetadata } = response.output; + logger2?.info?.({ + clientName, + commandName, + input: inputFilterSensitiveLog(args.input), + output: outputFilterSensitiveLog(outputWithoutMetadata), + metadata: $metadata + }); + return response; + } catch (error) { + const { clientName, commandName, logger: logger2, dynamoDbDocumentClientOptions = {} } = context; + const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions; + const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; + logger2?.error?.({ + clientName, + commandName, + input: inputFilterSensitiveLog(args.input), + error, + metadata: error.$metadata + }); + throw error; + } + }; + loggerMiddlewareOptions = { + name: "loggerMiddleware", + tags: ["LOGGER"], + step: "initialize", + override: true + }; + getLoggerPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(loggerMiddleware(), loggerMiddlewareOptions); + } + }); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-logger/dist-es/index.js + var init_dist_es6 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-logger/dist-es/index.js"() { + init_loggerMiddleware(); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-recursion-detection/dist-es/configuration.js + var recursionDetectionMiddlewareOptions; + var init_configuration = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-recursion-detection/dist-es/configuration.js"() { + recursionDetectionMiddlewareOptions = { + step: "build", + tags: ["RECURSION_DETECTION"], + name: "recursionDetectionMiddleware", + override: true, + priority: "low" + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-recursion-detection/dist-es/recursionDetectionMiddleware.browser.js + var recursionDetectionMiddleware; + var init_recursionDetectionMiddleware_browser = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-recursion-detection/dist-es/recursionDetectionMiddleware.browser.js"() { + recursionDetectionMiddleware = () => (next) => async (args) => next(args); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-recursion-detection/dist-es/getRecursionDetectionPlugin.js + var getRecursionDetectionPlugin; + var init_getRecursionDetectionPlugin = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-recursion-detection/dist-es/getRecursionDetectionPlugin.js"() { + init_configuration(); + init_recursionDetectionMiddleware_browser(); + getRecursionDetectionPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(recursionDetectionMiddleware(), recursionDetectionMiddlewareOptions); + } + }); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-recursion-detection/dist-es/index.js + var init_dist_es7 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-recursion-detection/dist-es/index.js"() { + init_getRecursionDetectionPlugin(); + init_recursionDetectionMiddleware_browser(); + } + }); + + // node_modules/@smithy/core/dist-es/getSmithyContext.js + var init_getSmithyContext = __esm({ + "node_modules/@smithy/core/dist-es/getSmithyContext.js"() { + } + }); + + // node_modules/@smithy/util-middleware/dist-es/getSmithyContext.js + var getSmithyContext; + var init_getSmithyContext2 = __esm({ + "node_modules/@smithy/util-middleware/dist-es/getSmithyContext.js"() { + init_dist_es3(); + getSmithyContext = (context) => context[SMITHY_CONTEXT_KEY] || (context[SMITHY_CONTEXT_KEY] = {}); + } + }); + + // node_modules/@smithy/util-middleware/dist-es/normalizeProvider.js + var normalizeProvider; + var init_normalizeProvider = __esm({ + "node_modules/@smithy/util-middleware/dist-es/normalizeProvider.js"() { + normalizeProvider = (input) => { + if (typeof input === "function") + return input; + const promisified = Promise.resolve(input); + return () => promisified; + }; + } + }); + + // node_modules/@smithy/util-middleware/dist-es/index.js + var init_dist_es8 = __esm({ + "node_modules/@smithy/util-middleware/dist-es/index.js"() { + init_getSmithyContext2(); + init_normalizeProvider(); + } + }); + + // node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/resolveAuthOptions.js + var resolveAuthOptions; + var init_resolveAuthOptions = __esm({ + "node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/resolveAuthOptions.js"() { + resolveAuthOptions = (candidateAuthOptions, authSchemePreference) => { + if (!authSchemePreference || authSchemePreference.length === 0) { + return candidateAuthOptions; + } + const preferredAuthOptions = []; + for (const preferredSchemeName of authSchemePreference) { + for (const candidateAuthOption of candidateAuthOptions) { + const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1]; + if (candidateAuthSchemeName === preferredSchemeName) { + preferredAuthOptions.push(candidateAuthOption); + } + } + } + for (const candidateAuthOption of candidateAuthOptions) { + if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) { + preferredAuthOptions.push(candidateAuthOption); + } + } + return preferredAuthOptions; + }; + } + }); + + // node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js + function convertHttpAuthSchemesToMap(httpAuthSchemes) { + const map2 = /* @__PURE__ */ new Map(); + for (const scheme of httpAuthSchemes) { + map2.set(scheme.schemeId, scheme); + } + return map2; + } + var httpAuthSchemeMiddleware; + var init_httpAuthSchemeMiddleware = __esm({ + "node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js"() { + init_dist_es8(); + init_resolveAuthOptions(); + httpAuthSchemeMiddleware = (config, mwOptions) => (next, context) => async (args) => { + const options = config.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input)); + const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : []; + const resolvedOptions = resolveAuthOptions(options, authSchemePreference); + const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); + const smithyContext = getSmithyContext(context); + const failureReasons = []; + for (const option of resolvedOptions) { + const scheme = authSchemes.get(option.schemeId); + if (!scheme) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); + continue; + } + const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); + if (!identityProvider) { + failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); + continue; + } + const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; + option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); + option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); + smithyContext.selectedHttpAuthScheme = { + httpAuthOption: option, + identity: await identityProvider(option.identityProperties), + signer: scheme.signer + }; + break; + } + if (!smithyContext.selectedHttpAuthScheme) { + throw new Error(failureReasons.join("\n")); + } + return next(args); + }; + } + }); + + // node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js + var httpAuthSchemeEndpointRuleSetMiddlewareOptions, getHttpAuthSchemeEndpointRuleSetPlugin; + var init_getHttpAuthSchemeEndpointRuleSetPlugin = __esm({ + "node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js"() { + init_httpAuthSchemeMiddleware(); + httpAuthSchemeEndpointRuleSetMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: "endpointV2Middleware" + }; + getHttpAuthSchemeEndpointRuleSetPlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider }) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, { + httpAuthSchemeParametersProvider, + identityProviderConfigProvider + }), httpAuthSchemeEndpointRuleSetMiddlewareOptions); + } + }); + } + }); + + // node_modules/@smithy/middleware-serde/dist-es/deserializerMiddleware.js + var deserializerMiddleware, findHeader; + var init_deserializerMiddleware = __esm({ + "node_modules/@smithy/middleware-serde/dist-es/deserializerMiddleware.js"() { + init_dist_es4(); + deserializerMiddleware = (options, deserializer) => (next, context) => async (args) => { + const { response } = await next(args); + try { + const parsed = await deserializer(response, options); + return { + response, + output: parsed + }; + } catch (error) { + Object.defineProperty(error, "$response", { + value: response + }); + if (!("$metadata" in error)) { + const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + try { + error.message += "\n " + hint; + } catch (e2) { + if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { + console.warn(hint); + } else { + context.logger?.warn?.(hint); + } + } + if (typeof error.$responseBodyText !== "undefined") { + if (error.$response) { + error.$response.body = error.$responseBodyText; + } + } + try { + if (HttpResponse.isInstance(response)) { + const { headers = {} } = response; + const headerEntries = Object.entries(headers); + error.$metadata = { + httpStatusCode: response.statusCode, + requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), + extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), + cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries) + }; + } + } catch (e2) { + } + } + throw error; + } + }; + findHeader = (pattern, headers) => { + return (headers.find(([k3]) => { + return k3.match(pattern); + }) || [void 0, void 0])[1]; + }; + } + }); + + // node_modules/@smithy/middleware-serde/dist-es/serializerMiddleware.js + var serializerMiddleware; + var init_serializerMiddleware = __esm({ + "node_modules/@smithy/middleware-serde/dist-es/serializerMiddleware.js"() { + serializerMiddleware = (options, serializer) => (next, context) => async (args) => { + const endpointConfig = options; + const endpoint = context.endpointV2?.url && endpointConfig.urlParser ? async () => endpointConfig.urlParser(context.endpointV2.url) : endpointConfig.endpoint; + if (!endpoint) { + throw new Error("No valid endpoint provider available."); + } + const request = await serializer(args.input, { ...options, endpoint }); + return next({ + ...args, + request + }); + }; + } + }); + + // node_modules/@smithy/middleware-serde/dist-es/serdePlugin.js + function getSerdePlugin(config, serializer, deserializer) { + return { + applyToStack: (commandStack) => { + commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption); + commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption); + } + }; + } + var deserializerMiddlewareOption, serializerMiddlewareOption; + var init_serdePlugin = __esm({ + "node_modules/@smithy/middleware-serde/dist-es/serdePlugin.js"() { + init_deserializerMiddleware(); + init_serializerMiddleware(); + deserializerMiddlewareOption = { + name: "deserializerMiddleware", + step: "deserialize", + tags: ["DESERIALIZER"], + override: true + }; + serializerMiddlewareOption = { + name: "serializerMiddleware", + step: "serialize", + tags: ["SERIALIZER"], + override: true + }; + } + }); + + // node_modules/@smithy/middleware-serde/dist-es/index.js + var init_dist_es9 = __esm({ + "node_modules/@smithy/middleware-serde/dist-es/index.js"() { + init_deserializerMiddleware(); + init_serdePlugin(); + init_serializerMiddleware(); + } + }); + + // node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js + var httpAuthSchemeMiddlewareOptions; + var init_getHttpAuthSchemePlugin = __esm({ + "node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js"() { + init_dist_es9(); + httpAuthSchemeMiddlewareOptions = { + step: "serialize", + tags: ["HTTP_AUTH_SCHEME"], + name: "httpAuthSchemeMiddleware", + override: true, + relation: "before", + toMiddleware: serializerMiddlewareOption.name + }; + } + }); + + // node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js + var init_middleware_http_auth_scheme = __esm({ + "node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js"() { + init_httpAuthSchemeMiddleware(); + init_getHttpAuthSchemeEndpointRuleSetPlugin(); + init_getHttpAuthSchemePlugin(); + } + }); + + // node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js + var defaultErrorHandler, defaultSuccessHandler, httpSigningMiddleware; + var init_httpSigningMiddleware = __esm({ + "node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js"() { + init_dist_es4(); + init_dist_es8(); + defaultErrorHandler = (signingProperties) => (error) => { + throw error; + }; + defaultSuccessHandler = (httpResponse, signingProperties) => { + }; + httpSigningMiddleware = (config) => (next, context) => async (args) => { + if (!HttpRequest.isInstance(args.request)) { + return next(args); + } + const smithyContext = getSmithyContext(context); + const scheme = smithyContext.selectedHttpAuthScheme; + if (!scheme) { + throw new Error(`No HttpAuthScheme was selected: unable to sign request`); + } + const { httpAuthOption: { signingProperties = {} }, identity, signer } = scheme; + const output = await next({ + ...args, + request: await signer.sign(args.request, identity, signingProperties) + }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); + (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); + return output; + }; + } + }); + + // node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js + var httpSigningMiddlewareOptions, getHttpSigningPlugin; + var init_getHttpSigningMiddleware = __esm({ + "node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js"() { + init_httpSigningMiddleware(); + httpSigningMiddlewareOptions = { + step: "finalizeRequest", + tags: ["HTTP_SIGNING"], + name: "httpSigningMiddleware", + aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], + override: true, + relation: "after", + toMiddleware: "retryMiddleware" + }; + getHttpSigningPlugin = (config) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(httpSigningMiddleware(config), httpSigningMiddlewareOptions); + } + }); + } + }); + + // node_modules/@smithy/core/dist-es/middleware-http-signing/index.js + var init_middleware_http_signing = __esm({ + "node_modules/@smithy/core/dist-es/middleware-http-signing/index.js"() { + init_httpSigningMiddleware(); + init_getHttpSigningMiddleware(); + } + }); + + // node_modules/@smithy/core/dist-es/normalizeProvider.js + var normalizeProvider2; + var init_normalizeProvider2 = __esm({ + "node_modules/@smithy/core/dist-es/normalizeProvider.js"() { + normalizeProvider2 = (input) => { + if (typeof input === "function") + return input; + const promisified = Promise.resolve(input); + return () => promisified; + }; + } + }); + + // node_modules/@smithy/core/dist-es/pagination/createPaginator.js + function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { + return async function* paginateOperation(config, input, ...additionalArguments) { + const _input = input; + let token = config.startingToken ?? _input[inputTokenName]; + let hasNext = true; + let page; + while (hasNext) { + _input[inputTokenName] = token; + if (pageSizeTokenName) { + _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize; + } + if (config.client instanceof ClientCtor) { + page = await makePagedClientRequest(CommandCtor, config.client, input, config.withCommand, ...additionalArguments); + } else { + throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); + } + yield page; + const prevToken = token; + token = get2(page, outputTokenName); + hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); + } + return void 0; + }; + } + var makePagedClientRequest, get2; + var init_createPaginator = __esm({ + "node_modules/@smithy/core/dist-es/pagination/createPaginator.js"() { + makePagedClientRequest = async (CommandCtor, client2, input, withCommand = (_2) => _2, ...args) => { + let command = new CommandCtor(input); + command = withCommand(command) ?? command; + return await client2.send(command, ...args); + }; + get2 = (fromObject, path) => { + let cursor = fromObject; + const pathComponents = path.split("."); + for (const step of pathComponents) { + if (!cursor || typeof cursor !== "object") { + return void 0; + } + cursor = cursor[step]; + } + return cursor; + }; + } + }); + + // node_modules/@smithy/util-base64/dist-es/constants.browser.js + var alphabetByEncoding, alphabetByValue, bitsPerLetter, bitsPerByte, maxLetterValue; + var init_constants_browser = __esm({ + "node_modules/@smithy/util-base64/dist-es/constants.browser.js"() { + alphabetByEncoding = {}; + alphabetByValue = new Array(64); + for (let i2 = 0, start = "A".charCodeAt(0), limit = "Z".charCodeAt(0); i2 + start <= limit; i2++) { + const char = String.fromCharCode(i2 + start); + alphabetByEncoding[char] = i2; + alphabetByValue[i2] = char; + } + for (let i2 = 0, start = "a".charCodeAt(0), limit = "z".charCodeAt(0); i2 + start <= limit; i2++) { + const char = String.fromCharCode(i2 + start); + const index2 = i2 + 26; + alphabetByEncoding[char] = index2; + alphabetByValue[index2] = char; + } + for (let i2 = 0; i2 < 10; i2++) { + alphabetByEncoding[i2.toString(10)] = i2 + 52; + const char = i2.toString(10); + const index2 = i2 + 52; + alphabetByEncoding[char] = index2; + alphabetByValue[index2] = char; + } + alphabetByEncoding["+"] = 62; + alphabetByValue[62] = "+"; + alphabetByEncoding["/"] = 63; + alphabetByValue[63] = "/"; + bitsPerLetter = 6; + bitsPerByte = 8; + maxLetterValue = 63; + } + }); + + // node_modules/@smithy/util-base64/dist-es/fromBase64.browser.js + var fromBase64; + var init_fromBase64_browser = __esm({ + "node_modules/@smithy/util-base64/dist-es/fromBase64.browser.js"() { + init_constants_browser(); + fromBase64 = (input) => { + let totalByteLength = input.length / 4 * 3; + if (input.slice(-2) === "==") { + totalByteLength -= 2; + } else if (input.slice(-1) === "=") { + totalByteLength--; + } + const out = new ArrayBuffer(totalByteLength); + const dataView = new DataView(out); + for (let i2 = 0; i2 < input.length; i2 += 4) { + let bits = 0; + let bitLength = 0; + for (let j3 = i2, limit = i2 + 3; j3 <= limit; j3++) { + if (input[j3] !== "=") { + if (!(input[j3] in alphabetByEncoding)) { + throw new TypeError(`Invalid character ${input[j3]} in base64 string.`); + } + bits |= alphabetByEncoding[input[j3]] << (limit - j3) * bitsPerLetter; + bitLength += bitsPerLetter; + } else { + bits >>= bitsPerLetter; + } + } + const chunkOffset = i2 / 4 * 3; + bits >>= bitLength % bitsPerByte; + const byteLength = Math.floor(bitLength / bitsPerByte); + for (let k3 = 0; k3 < byteLength; k3++) { + const offset = (byteLength - k3 - 1) * bitsPerByte; + dataView.setUint8(chunkOffset + k3, (bits & 255 << offset) >> offset); + } + } + return new Uint8Array(out); + }; + } + }); + + // node_modules/@smithy/util-utf8/dist-es/fromUtf8.browser.js + var fromUtf83; + var init_fromUtf8_browser2 = __esm({ + "node_modules/@smithy/util-utf8/dist-es/fromUtf8.browser.js"() { + fromUtf83 = (input) => new TextEncoder().encode(input); + } + }); + + // node_modules/@smithy/util-utf8/dist-es/toUint8Array.js + var toUint8Array; + var init_toUint8Array2 = __esm({ + "node_modules/@smithy/util-utf8/dist-es/toUint8Array.js"() { + init_fromUtf8_browser2(); + toUint8Array = (data) => { + if (typeof data === "string") { + return fromUtf83(data); + } + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); + } + return new Uint8Array(data); + }; + } + }); + + // node_modules/@smithy/util-utf8/dist-es/toUtf8.browser.js + var toUtf8; + var init_toUtf8_browser2 = __esm({ + "node_modules/@smithy/util-utf8/dist-es/toUtf8.browser.js"() { + toUtf8 = (input) => { + if (typeof input === "string") { + return input; + } + if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { + throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); + } + return new TextDecoder("utf-8").decode(input); + }; + } + }); + + // node_modules/@smithy/util-utf8/dist-es/index.js + var init_dist_es10 = __esm({ + "node_modules/@smithy/util-utf8/dist-es/index.js"() { + init_fromUtf8_browser2(); + init_toUint8Array2(); + init_toUtf8_browser2(); + } + }); + + // node_modules/@smithy/util-base64/dist-es/toBase64.browser.js + function toBase64(_input) { + let input; + if (typeof _input === "string") { + input = fromUtf83(_input); + } else { + input = _input; + } + const isArrayLike = typeof input === "object" && typeof input.length === "number"; + const isUint8Array = typeof input === "object" && typeof input.byteOffset === "number" && typeof input.byteLength === "number"; + if (!isArrayLike && !isUint8Array) { + throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array."); + } + let str = ""; + for (let i2 = 0; i2 < input.length; i2 += 3) { + let bits = 0; + let bitLength = 0; + for (let j3 = i2, limit = Math.min(i2 + 3, input.length); j3 < limit; j3++) { + bits |= input[j3] << (limit - j3 - 1) * bitsPerByte; + bitLength += bitsPerByte; + } + const bitClusterCount = Math.ceil(bitLength / bitsPerLetter); + bits <<= bitClusterCount * bitsPerLetter - bitLength; + for (let k3 = 1; k3 <= bitClusterCount; k3++) { + const offset = (bitClusterCount - k3) * bitsPerLetter; + str += alphabetByValue[(bits & maxLetterValue << offset) >> offset]; + } + str += "==".slice(0, 4 - bitClusterCount); + } + return str; + } + var init_toBase64_browser = __esm({ + "node_modules/@smithy/util-base64/dist-es/toBase64.browser.js"() { + init_dist_es10(); + init_constants_browser(); + } + }); + + // node_modules/@smithy/util-base64/dist-es/index.js + var init_dist_es11 = __esm({ + "node_modules/@smithy/util-base64/dist-es/index.js"() { + init_fromBase64_browser(); + init_toBase64_browser(); + } + }); + + // node_modules/@smithy/util-stream/dist-es/blob/transforms.js + function transformToString(payload, encoding = "utf-8") { + if (encoding === "base64") { + return toBase64(payload); + } + return toUtf8(payload); + } + function transformFromString(str, encoding) { + if (encoding === "base64") { + return Uint8ArrayBlobAdapter.mutate(fromBase64(str)); + } + return Uint8ArrayBlobAdapter.mutate(fromUtf83(str)); + } + var init_transforms = __esm({ + "node_modules/@smithy/util-stream/dist-es/blob/transforms.js"() { + init_dist_es11(); + init_dist_es10(); + init_Uint8ArrayBlobAdapter(); + } + }); + + // node_modules/@smithy/util-stream/dist-es/blob/Uint8ArrayBlobAdapter.js + var Uint8ArrayBlobAdapter; + var init_Uint8ArrayBlobAdapter = __esm({ + "node_modules/@smithy/util-stream/dist-es/blob/Uint8ArrayBlobAdapter.js"() { + init_transforms(); + Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array { + static fromString(source, encoding = "utf-8") { + switch (typeof source) { + case "string": + return transformFromString(source, encoding); + default: + throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); + } + } + static mutate(source) { + Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype); + return source; + } + transformToString(encoding = "utf-8") { + return transformToString(this, encoding); + } + }; + } + }); + + // node_modules/@smithy/util-stream/dist-es/checksum/ChecksumStream.browser.js + var init_ChecksumStream_browser = __esm({ + "node_modules/@smithy/util-stream/dist-es/checksum/ChecksumStream.browser.js"() { + } + }); + + // node_modules/@smithy/util-stream/dist-es/stream-type-check.js + var init_stream_type_check = __esm({ + "node_modules/@smithy/util-stream/dist-es/stream-type-check.js"() { + } + }); + + // node_modules/@smithy/util-stream/dist-es/checksum/createChecksumStream.browser.js + var init_createChecksumStream_browser = __esm({ + "node_modules/@smithy/util-stream/dist-es/checksum/createChecksumStream.browser.js"() { + } + }); + + // node_modules/@smithy/util-stream/dist-es/createBufferedReadableStream.js + var init_createBufferedReadableStream = __esm({ + "node_modules/@smithy/util-stream/dist-es/createBufferedReadableStream.js"() { + } + }); + + // node_modules/@smithy/util-stream/dist-es/getAwsChunkedEncodingStream.browser.js + var init_getAwsChunkedEncodingStream_browser = __esm({ + "node_modules/@smithy/util-stream/dist-es/getAwsChunkedEncodingStream.browser.js"() { + } + }); + + // node_modules/@smithy/util-stream/dist-es/headStream.browser.js + var init_headStream_browser = __esm({ + "node_modules/@smithy/util-stream/dist-es/headStream.browser.js"() { + } + }); + + // node_modules/@smithy/util-uri-escape/dist-es/escape-uri.js + var escapeUri, hexEncode; + var init_escape_uri = __esm({ + "node_modules/@smithy/util-uri-escape/dist-es/escape-uri.js"() { + escapeUri = (uri2) => encodeURIComponent(uri2).replace(/[!'()*]/g, hexEncode); + hexEncode = (c3) => `%${c3.charCodeAt(0).toString(16).toUpperCase()}`; + } + }); + + // node_modules/@smithy/util-uri-escape/dist-es/escape-uri-path.js + var init_escape_uri_path = __esm({ + "node_modules/@smithy/util-uri-escape/dist-es/escape-uri-path.js"() { + } + }); + + // node_modules/@smithy/util-uri-escape/dist-es/index.js + var init_dist_es12 = __esm({ + "node_modules/@smithy/util-uri-escape/dist-es/index.js"() { + init_escape_uri(); + init_escape_uri_path(); + } + }); + + // node_modules/@smithy/querystring-builder/dist-es/index.js + function buildQueryString(query) { + const parts = []; + for (let key of Object.keys(query).sort()) { + const value = query[key]; + key = escapeUri(key); + if (Array.isArray(value)) { + for (let i2 = 0, iLen = value.length; i2 < iLen; i2++) { + parts.push(`${key}=${escapeUri(value[i2])}`); + } + } else { + let qsEntry = key; + if (value || typeof value === "string") { + qsEntry += `=${escapeUri(value)}`; + } + parts.push(qsEntry); + } + } + return parts.join("&"); + } + var init_dist_es13 = __esm({ + "node_modules/@smithy/querystring-builder/dist-es/index.js"() { + init_dist_es12(); + } + }); + + // node_modules/@smithy/fetch-http-handler/dist-es/create-request.js + function createRequest(url, requestOptions) { + return new Request(url, requestOptions); + } + var init_create_request = __esm({ + "node_modules/@smithy/fetch-http-handler/dist-es/create-request.js"() { + } + }); + + // node_modules/@smithy/fetch-http-handler/dist-es/request-timeout.js + function requestTimeout(timeoutInMs = 0) { + return new Promise((resolve, reject) => { + if (timeoutInMs) { + setTimeout(() => { + const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); + timeoutError.name = "TimeoutError"; + reject(timeoutError); + }, timeoutInMs); + } + }); + } + var init_request_timeout = __esm({ + "node_modules/@smithy/fetch-http-handler/dist-es/request-timeout.js"() { + } + }); + + // node_modules/@smithy/fetch-http-handler/dist-es/fetch-http-handler.js + var keepAliveSupport, FetchHttpHandler; + var init_fetch_http_handler = __esm({ + "node_modules/@smithy/fetch-http-handler/dist-es/fetch-http-handler.js"() { + init_dist_es4(); + init_dist_es13(); + init_create_request(); + init_request_timeout(); + keepAliveSupport = { + supported: void 0 + }; + FetchHttpHandler = class _FetchHttpHandler { + config; + configProvider; + static create(instanceOrOptions) { + if (typeof instanceOrOptions?.handle === "function") { + return instanceOrOptions; + } + return new _FetchHttpHandler(instanceOrOptions); + } + constructor(options) { + if (typeof options === "function") { + this.configProvider = options().then((opts) => opts || {}); + } else { + this.config = options ?? {}; + this.configProvider = Promise.resolve(this.config); + } + if (keepAliveSupport.supported === void 0) { + keepAliveSupport.supported = Boolean(typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]")); + } + } + destroy() { + } + async handle(request, { abortSignal, requestTimeout: requestTimeout2 } = {}) { + if (!this.config) { + this.config = await this.configProvider; + } + const requestTimeoutInMs = requestTimeout2 ?? this.config.requestTimeout; + const keepAlive = this.config.keepAlive === true; + const credentials = this.config.credentials; + if (abortSignal?.aborted) { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + return Promise.reject(abortError); + } + let path = request.path; + const queryString = buildQueryString(request.query || {}); + if (queryString) { + path += `?${queryString}`; + } + if (request.fragment) { + path += `#${request.fragment}`; + } + let auth = ""; + if (request.username != null || request.password != null) { + const username = request.username ?? ""; + const password = request.password ?? ""; + auth = `${username}:${password}@`; + } + const { port, method } = request; + const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; + const body = method === "GET" || method === "HEAD" ? void 0 : request.body; + const requestOptions = { + body, + headers: new Headers(request.headers), + method, + credentials + }; + if (this.config?.cache) { + requestOptions.cache = this.config.cache; + } + if (body) { + requestOptions.duplex = "half"; + } + if (typeof AbortController !== "undefined") { + requestOptions.signal = abortSignal; + } + if (keepAliveSupport.supported) { + requestOptions.keepalive = keepAlive; + } + if (typeof this.config.requestInit === "function") { + Object.assign(requestOptions, this.config.requestInit(request)); + } + let removeSignalEventListener = () => { + }; + const fetchRequest = createRequest(url, requestOptions); + const raceOfPromises = [ + fetch(fetchRequest).then((response) => { + const fetchHeaders = response.headers; + const transformedHeaders = {}; + for (const pair of fetchHeaders.entries()) { + transformedHeaders[pair[0]] = pair[1]; + } + const hasReadableStream = response.body != void 0; + if (!hasReadableStream) { + return response.blob().then((body2) => ({ + response: new HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: body2 + }) + })); + } + return { + response: new HttpResponse({ + headers: transformedHeaders, + reason: response.statusText, + statusCode: response.status, + body: response.body + }) + }; + }), + requestTimeout(requestTimeoutInMs) + ]; + if (abortSignal) { + raceOfPromises.push(new Promise((resolve, reject) => { + const onAbort = () => { + const abortError = new Error("Request aborted"); + abortError.name = "AbortError"; + reject(abortError); + }; + if (typeof abortSignal.addEventListener === "function") { + const signal = abortSignal; + signal.addEventListener("abort", onAbort, { once: true }); + removeSignalEventListener = () => signal.removeEventListener("abort", onAbort); + } else { + abortSignal.onabort = onAbort; + } + })); + } + return Promise.race(raceOfPromises).finally(removeSignalEventListener); + } + updateHttpClientConfig(key, value) { + this.config = void 0; + this.configProvider = this.configProvider.then((config) => { + config[key] = value; + return config; + }); + } + httpHandlerConfigs() { + return this.config ?? {}; + } + }; + } + }); + + // node_modules/@smithy/fetch-http-handler/dist-es/stream-collector.js + async function collectBlob(blob) { + const base64 = await readToBase64(blob); + const arrayBuffer = fromBase64(base64); + return new Uint8Array(arrayBuffer); + } + async function collectStream(stream) { + const chunks = []; + const reader = stream.getReader(); + let isDone = false; + let length = 0; + while (!isDone) { + const { done, value } = await reader.read(); + if (value) { + chunks.push(value); + length += value.length; + } + isDone = done; + } + const collected = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { + collected.set(chunk, offset); + offset += chunk.length; + } + return collected; + } + function readToBase64(blob) { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onloadend = () => { + if (reader.readyState !== 2) { + return reject(new Error("Reader aborted too early")); + } + const result = reader.result ?? ""; + const commaIndex = result.indexOf(","); + const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; + resolve(result.substring(dataOffset)); + }; + reader.onabort = () => reject(new Error("Read aborted")); + reader.onerror = () => reject(reader.error); + reader.readAsDataURL(blob); + }); + } + var streamCollector; + var init_stream_collector = __esm({ + "node_modules/@smithy/fetch-http-handler/dist-es/stream-collector.js"() { + init_dist_es11(); + streamCollector = async (stream) => { + if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") { + if (Blob.prototype.arrayBuffer !== void 0) { + return new Uint8Array(await stream.arrayBuffer()); + } + return collectBlob(stream); + } + return collectStream(stream); + }; + } + }); + + // node_modules/@smithy/fetch-http-handler/dist-es/index.js + var init_dist_es14 = __esm({ + "node_modules/@smithy/fetch-http-handler/dist-es/index.js"() { + init_fetch_http_handler(); + init_stream_collector(); + } + }); + + // node_modules/@smithy/util-hex-encoding/dist-es/index.js + function fromHex(encoded) { + if (encoded.length % 2 !== 0) { + throw new Error("Hex encoded strings must have an even number length"); + } + const out = new Uint8Array(encoded.length / 2); + for (let i2 = 0; i2 < encoded.length; i2 += 2) { + const encodedByte = encoded.slice(i2, i2 + 2).toLowerCase(); + if (encodedByte in HEX_TO_SHORT) { + out[i2 / 2] = HEX_TO_SHORT[encodedByte]; + } else { + throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); + } + } + return out; + } + function toHex(bytes) { + let out = ""; + for (let i2 = 0; i2 < bytes.byteLength; i2++) { + out += SHORT_TO_HEX[bytes[i2]]; + } + return out; + } + var SHORT_TO_HEX, HEX_TO_SHORT; + var init_dist_es15 = __esm({ + "node_modules/@smithy/util-hex-encoding/dist-es/index.js"() { + SHORT_TO_HEX = {}; + HEX_TO_SHORT = {}; + for (let i2 = 0; i2 < 256; i2++) { + let encodedByte = i2.toString(16).toLowerCase(); + if (encodedByte.length === 1) { + encodedByte = `0${encodedByte}`; + } + SHORT_TO_HEX[i2] = encodedByte; + HEX_TO_SHORT[encodedByte] = i2; + } + } + }); + + // node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.browser.js + var init_sdk_stream_mixin_browser = __esm({ + "node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.browser.js"() { + } + }); + + // node_modules/@smithy/util-stream/dist-es/splitStream.browser.js + var init_splitStream_browser = __esm({ + "node_modules/@smithy/util-stream/dist-es/splitStream.browser.js"() { + } + }); + + // node_modules/@smithy/util-stream/dist-es/index.js + var init_dist_es16 = __esm({ + "node_modules/@smithy/util-stream/dist-es/index.js"() { + init_Uint8ArrayBlobAdapter(); + init_ChecksumStream_browser(); + init_createChecksumStream_browser(); + init_createBufferedReadableStream(); + init_getAwsChunkedEncodingStream_browser(); + init_headStream_browser(); + init_sdk_stream_mixin_browser(); + init_splitStream_browser(); + init_stream_type_check(); + } + }); + + // node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js + var collectBody; + var init_collect_stream_body = __esm({ + "node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js"() { + init_dist_es16(); + collectBody = async (streamBody = new Uint8Array(), context) => { + if (streamBody instanceof Uint8Array) { + return Uint8ArrayBlobAdapter.mutate(streamBody); + } + if (!streamBody) { + return Uint8ArrayBlobAdapter.mutate(new Uint8Array()); + } + const fromContext = context.streamCollector(streamBody); + return Uint8ArrayBlobAdapter.mutate(await fromContext); + }; + } + }); + + // node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js + var init_extended_encode_uri_component = __esm({ + "node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js"() { + } + }); + + // node_modules/@smithy/core/dist-es/submodules/schema/deref.js + var deref; + var init_deref = __esm({ + "node_modules/@smithy/core/dist-es/submodules/schema/deref.js"() { + deref = (schemaRef) => { + if (typeof schemaRef === "function") { + return schemaRef(); + } + return schemaRef; + }; + } + }); + + // node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js + var init_getSchemaSerdePlugin = __esm({ + "node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js"() { + } + }); + + // node_modules/@smithy/core/dist-es/submodules/schema/TypeRegistry.js + var TypeRegistry; + var init_TypeRegistry = __esm({ + "node_modules/@smithy/core/dist-es/submodules/schema/TypeRegistry.js"() { + TypeRegistry = class _TypeRegistry { + namespace; + schemas; + exceptions; + static registries = /* @__PURE__ */ new Map(); + constructor(namespace, schemas2 = /* @__PURE__ */ new Map(), exceptions = /* @__PURE__ */ new Map()) { + this.namespace = namespace; + this.schemas = schemas2; + this.exceptions = exceptions; + } + static for(namespace) { + if (!_TypeRegistry.registries.has(namespace)) { + _TypeRegistry.registries.set(namespace, new _TypeRegistry(namespace)); + } + return _TypeRegistry.registries.get(namespace); + } + register(shapeId, schema4) { + const qualifiedName = this.normalizeShapeId(shapeId); + this.schemas.set(qualifiedName, schema4); + } + getSchema(shapeId) { + const id = this.normalizeShapeId(shapeId); + if (!this.schemas.has(id)) { + throw new Error(`@smithy/core/schema - schema not found for ${id}`); + } + return this.schemas.get(id); + } + registerError(errorSchema, ctor) { + this.exceptions.set(errorSchema, ctor); + } + getErrorCtor(errorSchema) { + return this.exceptions.get(errorSchema); + } + getBaseException() { + for (const [id, schema4] of this.schemas.entries()) { + if (id.startsWith("smithy.ts.sdk.synthetic.") && id.endsWith("ServiceException")) { + return schema4; + } + } + return void 0; + } + find(predicate) { + return [...this.schemas.values()].find(predicate); + } + clear() { + this.schemas.clear(); + this.exceptions.clear(); + } + normalizeShapeId(shapeId) { + if (shapeId.includes("#")) { + return shapeId; + } + return this.namespace + "#" + shapeId; + } + getNamespace(shapeId) { + return this.normalizeShapeId(shapeId).split("#")[0]; + } + }; + } + }); + + // node_modules/@smithy/core/dist-es/submodules/schema/schemas/Schema.js + var Schema; + var init_Schema = __esm({ + "node_modules/@smithy/core/dist-es/submodules/schema/schemas/Schema.js"() { + init_TypeRegistry(); + Schema = class { + name; + namespace; + traits; + static assign(instance, values) { + const schema4 = Object.assign(instance, values); + TypeRegistry.for(schema4.namespace).register(schema4.name, schema4); + return schema4; + } + static [Symbol.hasInstance](lhs) { + const isPrototype = this.prototype.isPrototypeOf(lhs); + if (!isPrototype && typeof lhs === "object" && lhs !== null) { + const list = lhs; + return list.symbol === this.symbol; + } + return isPrototype; + } + getName() { + return this.namespace + "#" + this.name; + } + }; + } + }); + + // node_modules/@smithy/core/dist-es/submodules/schema/schemas/ListSchema.js + var ListSchema; + var init_ListSchema = __esm({ + "node_modules/@smithy/core/dist-es/submodules/schema/schemas/ListSchema.js"() { + init_Schema(); + ListSchema = class _ListSchema extends Schema { + static symbol = Symbol.for("@smithy/lis"); + name; + traits; + valueSchema; + symbol = _ListSchema.symbol; + }; + } + }); + + // node_modules/@smithy/core/dist-es/submodules/schema/schemas/MapSchema.js + var MapSchema; + var init_MapSchema = __esm({ + "node_modules/@smithy/core/dist-es/submodules/schema/schemas/MapSchema.js"() { + init_Schema(); + MapSchema = class _MapSchema extends Schema { + static symbol = Symbol.for("@smithy/map"); + name; + traits; + keySchema; + valueSchema; + symbol = _MapSchema.symbol; + }; + } + }); + + // node_modules/@smithy/core/dist-es/submodules/schema/schemas/OperationSchema.js + var OperationSchema; + var init_OperationSchema = __esm({ + "node_modules/@smithy/core/dist-es/submodules/schema/schemas/OperationSchema.js"() { + init_Schema(); + OperationSchema = class _OperationSchema extends Schema { + static symbol = Symbol.for("@smithy/ope"); + name; + traits; + input; + output; + symbol = _OperationSchema.symbol; + }; + } + }); + + // node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js + var StructureSchema; + var init_StructureSchema = __esm({ + "node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js"() { + init_Schema(); + StructureSchema = class _StructureSchema extends Schema { + static symbol = Symbol.for("@smithy/str"); + name; + traits; + memberNames; + memberList; + symbol = _StructureSchema.symbol; + }; + } + }); + + // node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js + var ErrorSchema; + var init_ErrorSchema = __esm({ + "node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js"() { + init_StructureSchema(); + ErrorSchema = class _ErrorSchema extends StructureSchema { + static symbol = Symbol.for("@smithy/err"); + ctor; + symbol = _ErrorSchema.symbol; + }; + } + }); + + // node_modules/@smithy/core/dist-es/submodules/schema/schemas/sentinels.js + var SCHEMA; + var init_sentinels2 = __esm({ + "node_modules/@smithy/core/dist-es/submodules/schema/schemas/sentinels.js"() { + SCHEMA = { + BLOB: 21, + STREAMING_BLOB: 42, + BOOLEAN: 2, + STRING: 0, + NUMERIC: 1, + BIG_INTEGER: 17, + BIG_DECIMAL: 19, + DOCUMENT: 15, + TIMESTAMP_DEFAULT: 4, + TIMESTAMP_DATE_TIME: 5, + TIMESTAMP_HTTP_DATE: 6, + TIMESTAMP_EPOCH_SECONDS: 7, + LIST_MODIFIER: 64, + MAP_MODIFIER: 128 + }; + } + }); + + // node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js + var SimpleSchema; + var init_SimpleSchema = __esm({ + "node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js"() { + init_Schema(); + SimpleSchema = class _SimpleSchema extends Schema { + static symbol = Symbol.for("@smithy/sim"); + name; + schemaRef; + traits; + symbol = _SimpleSchema.symbol; + }; + } + }); + + // node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js + var NormalizedSchema; + var init_NormalizedSchema = __esm({ + "node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js"() { + init_deref(); + init_ListSchema(); + init_MapSchema(); + init_Schema(); + init_sentinels2(); + init_SimpleSchema(); + init_StructureSchema(); + NormalizedSchema = class _NormalizedSchema { + ref; + memberName; + static symbol = Symbol.for("@smithy/nor"); + symbol = _NormalizedSchema.symbol; + name; + schema; + _isMemberSchema; + traits; + memberTraits; + normalizedTraits; + constructor(ref, memberName) { + this.ref = ref; + this.memberName = memberName; + const traitStack = []; + let _ref = ref; + let schema4 = ref; + this._isMemberSchema = false; + while (Array.isArray(_ref)) { + traitStack.push(_ref[1]); + _ref = _ref[0]; + schema4 = deref(_ref); + this._isMemberSchema = true; + } + if (traitStack.length > 0) { + this.memberTraits = {}; + for (let i2 = traitStack.length - 1; i2 >= 0; --i2) { + const traitSet = traitStack[i2]; + Object.assign(this.memberTraits, _NormalizedSchema.translateTraits(traitSet)); + } + } else { + this.memberTraits = 0; + } + if (schema4 instanceof _NormalizedSchema) { + const computedMemberTraits = this.memberTraits; + Object.assign(this, schema4); + this.memberTraits = Object.assign({}, computedMemberTraits, schema4.getMemberTraits(), this.getMemberTraits()); + this.normalizedTraits = void 0; + this.memberName = memberName ?? schema4.memberName; + return; + } + this.schema = deref(schema4); + if (this.schema && typeof this.schema === "object") { + this.traits = this.schema?.traits ?? {}; + } else { + this.traits = 0; + } + this.name = (this.schema instanceof Schema ? this.schema.getName?.() : void 0) ?? this.memberName ?? this.getSchemaName(); + if (this._isMemberSchema && !memberName) { + throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(true)} missing member name.`); + } + } + static [Symbol.hasInstance](lhs) { + return Schema[Symbol.hasInstance].bind(this)(lhs); + } + static of(ref) { + if (ref instanceof _NormalizedSchema) { + return ref; + } + if (Array.isArray(ref)) { + const [ns, traits] = ref; + if (ns instanceof _NormalizedSchema) { + Object.assign(ns.getMergedTraits(), _NormalizedSchema.translateTraits(traits)); + return ns; + } + throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref, null, 2)}.`); + } + return new _NormalizedSchema(ref); + } + static translateTraits(indicator) { + if (typeof indicator === "object") { + return indicator; + } + indicator = indicator | 0; + const traits = {}; + let i2 = 0; + for (const trait of [ + "httpLabel", + "idempotent", + "idempotencyToken", + "sensitive", + "httpPayload", + "httpResponseCode", + "httpQueryParams" + ]) { + if ((indicator >> i2++ & 1) === 1) { + traits[trait] = 1; + } + } + return traits; + } + getSchema() { + if (this.schema instanceof _NormalizedSchema) { + Object.assign(this, { schema: this.schema.getSchema() }); + return this.schema; + } + if (this.schema instanceof SimpleSchema) { + return deref(this.schema.schemaRef); + } + return deref(this.schema); + } + getName(withNamespace = false) { + if (!withNamespace) { + if (this.name && this.name.includes("#")) { + return this.name.split("#")[1]; + } + } + return this.name || void 0; + } + getMemberName() { + if (!this.isMemberSchema()) { + throw new Error(`@smithy/core/schema - non-member schema: ${this.getName(true)}`); + } + return this.memberName; + } + isMemberSchema() { + return this._isMemberSchema; + } + isUnitSchema() { + return this.getSchema() === "unit"; + } + isListSchema() { + const inner = this.getSchema(); + if (typeof inner === "number") { + return inner >= SCHEMA.LIST_MODIFIER && inner < SCHEMA.MAP_MODIFIER; + } + return inner instanceof ListSchema; + } + isMapSchema() { + const inner = this.getSchema(); + if (typeof inner === "number") { + return inner >= SCHEMA.MAP_MODIFIER && inner <= 255; + } + return inner instanceof MapSchema; + } + isStructSchema() { + const inner = this.getSchema(); + return inner !== null && typeof inner === "object" && "members" in inner || inner instanceof StructureSchema; + } + isBlobSchema() { + return this.getSchema() === SCHEMA.BLOB || this.getSchema() === SCHEMA.STREAMING_BLOB; + } + isTimestampSchema() { + const schema4 = this.getSchema(); + return typeof schema4 === "number" && schema4 >= SCHEMA.TIMESTAMP_DEFAULT && schema4 <= SCHEMA.TIMESTAMP_EPOCH_SECONDS; + } + isDocumentSchema() { + return this.getSchema() === SCHEMA.DOCUMENT; + } + isStringSchema() { + return this.getSchema() === SCHEMA.STRING; + } + isBooleanSchema() { + return this.getSchema() === SCHEMA.BOOLEAN; + } + isNumericSchema() { + return this.getSchema() === SCHEMA.NUMERIC; + } + isBigIntegerSchema() { + return this.getSchema() === SCHEMA.BIG_INTEGER; + } + isBigDecimalSchema() { + return this.getSchema() === SCHEMA.BIG_DECIMAL; + } + isStreaming() { + const streaming = !!this.getMergedTraits().streaming; + if (streaming) { + return true; + } + return this.getSchema() === SCHEMA.STREAMING_BLOB; + } + isIdempotencyToken() { + if (this.normalizedTraits) { + return !!this.normalizedTraits.idempotencyToken; + } + for (const traits of [this.traits, this.memberTraits]) { + if (typeof traits === "number") { + if ((traits & 4) === 4) { + return true; + } + } else if (typeof traits === "object") { + if (!!traits.idempotencyToken) { + return true; + } + } + } + return false; + } + getMergedTraits() { + return this.normalizedTraits ?? (this.normalizedTraits = { + ...this.getOwnTraits(), + ...this.getMemberTraits() + }); + } + getMemberTraits() { + return _NormalizedSchema.translateTraits(this.memberTraits); + } + getOwnTraits() { + return _NormalizedSchema.translateTraits(this.traits); + } + getKeySchema() { + if (this.isDocumentSchema()) { + return this.memberFrom([SCHEMA.DOCUMENT, 0], "key"); + } + if (!this.isMapSchema()) { + throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(true)}`); + } + const schema4 = this.getSchema(); + if (typeof schema4 === "number") { + return this.memberFrom([63 & schema4, 0], "key"); + } + return this.memberFrom([schema4.keySchema, 0], "key"); + } + getValueSchema() { + const schema4 = this.getSchema(); + if (typeof schema4 === "number") { + if (this.isMapSchema()) { + return this.memberFrom([63 & schema4, 0], "value"); + } else if (this.isListSchema()) { + return this.memberFrom([63 & schema4, 0], "member"); + } + } + if (schema4 && typeof schema4 === "object") { + if (this.isStructSchema()) { + throw new Error(`may not getValueSchema() on structure ${this.getName(true)}`); + } + const collection = schema4; + if ("valueSchema" in collection) { + if (this.isMapSchema()) { + return this.memberFrom([collection.valueSchema, 0], "value"); + } else if (this.isListSchema()) { + return this.memberFrom([collection.valueSchema, 0], "member"); + } + } + } + if (this.isDocumentSchema()) { + return this.memberFrom([SCHEMA.DOCUMENT, 0], "value"); + } + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no value member.`); + } + hasMemberSchema(member) { + if (this.isStructSchema()) { + const struct = this.getSchema(); + return struct.memberNames.includes(member); + } + return false; + } + getMemberSchema(member) { + if (this.isStructSchema()) { + const struct = this.getSchema(); + if (!struct.memberNames.includes(member)) { + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no member=${member}.`); + } + const i2 = struct.memberNames.indexOf(member); + const memberSchema = struct.memberList[i2]; + return this.memberFrom(Array.isArray(memberSchema) ? memberSchema : [memberSchema, 0], member); + } + if (this.isDocumentSchema()) { + return this.memberFrom([SCHEMA.DOCUMENT, 0], member); + } + throw new Error(`@smithy/core/schema - ${this.getName(true)} has no members.`); + } + getMemberSchemas() { + const buffer = {}; + try { + for (const [k3, v6] of this.structIterator()) { + buffer[k3] = v6; + } + } catch (ignored) { + } + return buffer; + } + getEventStreamMember() { + if (this.isStructSchema()) { + for (const [memberName, memberSchema] of this.structIterator()) { + if (memberSchema.isStreaming() && memberSchema.isStructSchema()) { + return memberName; + } + } + } + return ""; + } + *structIterator() { + if (this.isUnitSchema()) { + return; + } + if (!this.isStructSchema()) { + throw new Error("@smithy/core/schema - cannot iterate non-struct schema."); + } + const struct = this.getSchema(); + for (let i2 = 0; i2 < struct.memberNames.length; ++i2) { + yield [struct.memberNames[i2], this.memberFrom([struct.memberList[i2], 0], struct.memberNames[i2])]; + } + } + memberFrom(memberSchema, memberName) { + if (memberSchema instanceof _NormalizedSchema) { + return Object.assign(memberSchema, { + memberName, + _isMemberSchema: true + }); + } + return new _NormalizedSchema(memberSchema, memberName); + } + getSchemaName() { + const schema4 = this.getSchema(); + if (typeof schema4 === "number") { + const _schema = 63 & schema4; + const container = 192 & schema4; + const type = Object.entries(SCHEMA).find(([, value]) => { + return value === _schema; + })?.[0] ?? "Unknown"; + switch (container) { + case SCHEMA.MAP_MODIFIER: + return `${type}Map`; + case SCHEMA.LIST_MODIFIER: + return `${type}List`; + case 0: + return type; + } + } + return "Unknown"; + } + }; + } + }); + + // node_modules/@smithy/core/dist-es/submodules/schema/index.js + var init_schema2 = __esm({ + "node_modules/@smithy/core/dist-es/submodules/schema/index.js"() { + init_deref(); + init_getSchemaSerdePlugin(); + init_ListSchema(); + init_MapSchema(); + init_OperationSchema(); + init_ErrorSchema(); + init_NormalizedSchema(); + init_Schema(); + init_SimpleSchema(); + init_StructureSchema(); + init_sentinels2(); + init_TypeRegistry(); + } + }); + + // node_modules/@smithy/core/dist-es/submodules/serde/copyDocumentWithTransform.js + var init_copyDocumentWithTransform = __esm({ + "node_modules/@smithy/core/dist-es/submodules/serde/copyDocumentWithTransform.js"() { + } + }); + + // node_modules/@smithy/core/dist-es/submodules/serde/parse-utils.js + var expectNumber, MAX_FLOAT, expectNonNull, expectString, strictParseDouble, NUMBER_REGEX, parseNumber, stackTraceWarning, logger; + var init_parse_utils = __esm({ + "node_modules/@smithy/core/dist-es/submodules/serde/parse-utils.js"() { + expectNumber = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "string") { + const parsed = parseFloat(value); + if (!Number.isNaN(parsed)) { + if (String(parsed) !== String(value)) { + logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); + } + return parsed; + } + } + if (typeof value === "number") { + return value; + } + throw new TypeError(`Expected number, got ${typeof value}: ${value}`); + }; + MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); + expectNonNull = (value, location2) => { + if (value === null || value === void 0) { + if (location2) { + throw new TypeError(`Expected a non-null value for ${location2}`); + } + throw new TypeError("Expected a non-null value"); + } + return value; + }; + expectString = (value) => { + if (value === null || value === void 0) { + return void 0; + } + if (typeof value === "string") { + return value; + } + if (["boolean", "number", "bigint"].includes(typeof value)) { + logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); + return String(value); + } + throw new TypeError(`Expected string, got ${typeof value}: ${value}`); + }; + strictParseDouble = (value) => { + if (typeof value == "string") { + return expectNumber(parseNumber(value)); + } + return expectNumber(value); + }; + NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; + parseNumber = (value) => { + const matches = value.match(NUMBER_REGEX); + if (matches === null || matches[0].length !== value.length) { + throw new TypeError(`Expected real number, got implicit NaN`); + } + return parseFloat(value); + }; + stackTraceWarning = (message) => { + return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s2) => !s2.includes("stackTraceWarning")).join("\n"); + }; + logger = { + warn: console.warn + }; + } + }); + + // node_modules/@smithy/core/dist-es/submodules/serde/date-utils.js + var RFC3339, RFC3339_WITH_OFFSET, IMF_FIXDATE, RFC_850_DATE, ASC_TIME, parseEpochTimestamp, FIFTY_YEARS_IN_MILLIS; + var init_date_utils = __esm({ + "node_modules/@smithy/core/dist-es/submodules/serde/date-utils.js"() { + init_parse_utils(); + RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); + RFC3339_WITH_OFFSET = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/); + IMF_FIXDATE = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); + RFC_850_DATE = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); + ASC_TIME = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/); + parseEpochTimestamp = (value) => { + if (value === null || value === void 0) { + return void 0; + } + let valueAsDouble; + if (typeof value === "number") { + valueAsDouble = value; + } else if (typeof value === "string") { + valueAsDouble = strictParseDouble(value); + } else if (typeof value === "object" && value.tag === 1) { + valueAsDouble = value.value; + } else { + throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); + } + if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { + throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); + } + return new Date(Math.round(valueAsDouble * 1e3)); + }; + FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3; + } + }); + + // node_modules/@smithy/uuid/dist-es/randomUUID.browser.js + var randomUUID2; + var init_randomUUID_browser = __esm({ + "node_modules/@smithy/uuid/dist-es/randomUUID.browser.js"() { + randomUUID2 = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto); + } + }); + + // node_modules/@smithy/uuid/dist-es/v4.js + var decimalToHex, v42; + var init_v4 = __esm({ + "node_modules/@smithy/uuid/dist-es/v4.js"() { + init_randomUUID_browser(); + decimalToHex = Array.from({ length: 256 }, (_2, i2) => i2.toString(16).padStart(2, "0")); + v42 = () => { + if (randomUUID2) { + return randomUUID2(); + } + const rnds = new Uint8Array(16); + crypto.getRandomValues(rnds); + rnds[6] = rnds[6] & 15 | 64; + rnds[8] = rnds[8] & 63 | 128; + return decimalToHex[rnds[0]] + decimalToHex[rnds[1]] + decimalToHex[rnds[2]] + decimalToHex[rnds[3]] + "-" + decimalToHex[rnds[4]] + decimalToHex[rnds[5]] + "-" + decimalToHex[rnds[6]] + decimalToHex[rnds[7]] + "-" + decimalToHex[rnds[8]] + decimalToHex[rnds[9]] + "-" + decimalToHex[rnds[10]] + decimalToHex[rnds[11]] + decimalToHex[rnds[12]] + decimalToHex[rnds[13]] + decimalToHex[rnds[14]] + decimalToHex[rnds[15]]; + }; + } + }); + + // node_modules/@smithy/uuid/dist-es/index.js + var init_dist_es17 = __esm({ + "node_modules/@smithy/uuid/dist-es/index.js"() { + init_v4(); + } + }); + + // node_modules/@smithy/core/dist-es/submodules/serde/generateIdempotencyToken.js + var init_generateIdempotencyToken = __esm({ + "node_modules/@smithy/core/dist-es/submodules/serde/generateIdempotencyToken.js"() { + } + }); + + // node_modules/@smithy/core/dist-es/submodules/serde/lazy-json.js + var LazyJsonString; + var init_lazy_json = __esm({ + "node_modules/@smithy/core/dist-es/submodules/serde/lazy-json.js"() { + LazyJsonString = function LazyJsonString2(val) { + const str = Object.assign(new String(val), { + deserializeJSON() { + return JSON.parse(String(val)); + }, + toString() { + return String(val); + }, + toJSON() { + return String(val); + } + }); + return str; + }; + LazyJsonString.from = (object) => { + if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) { + return object; + } else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) { + return LazyJsonString(String(object)); + } + return LazyJsonString(JSON.stringify(object)); + }; + LazyJsonString.fromObject = LazyJsonString.from; + } + }); + + // node_modules/@smithy/core/dist-es/submodules/serde/quote-header.js + var init_quote_header = __esm({ + "node_modules/@smithy/core/dist-es/submodules/serde/quote-header.js"() { + } + }); + + // node_modules/@smithy/core/dist-es/submodules/serde/split-every.js + var init_split_every = __esm({ + "node_modules/@smithy/core/dist-es/submodules/serde/split-every.js"() { + } + }); + + // node_modules/@smithy/core/dist-es/submodules/serde/split-header.js + var init_split_header = __esm({ + "node_modules/@smithy/core/dist-es/submodules/serde/split-header.js"() { + } + }); + + // node_modules/@smithy/core/dist-es/submodules/serde/value/NumericValue.js + var init_NumericValue = __esm({ + "node_modules/@smithy/core/dist-es/submodules/serde/value/NumericValue.js"() { + } + }); + + // node_modules/@smithy/core/dist-es/submodules/serde/index.js + var init_serde2 = __esm({ + "node_modules/@smithy/core/dist-es/submodules/serde/index.js"() { + init_copyDocumentWithTransform(); + init_date_utils(); + init_generateIdempotencyToken(); + init_lazy_json(); + init_parse_utils(); + init_quote_header(); + init_split_every(); + init_split_header(); + init_NumericValue(); + } + }); + + // node_modules/@smithy/core/dist-es/submodules/protocols/HttpProtocol.js + var init_HttpProtocol = __esm({ + "node_modules/@smithy/core/dist-es/submodules/protocols/HttpProtocol.js"() { + } + }); + + // node_modules/@smithy/core/dist-es/submodules/protocols/HttpBindingProtocol.js + var init_HttpBindingProtocol = __esm({ + "node_modules/@smithy/core/dist-es/submodules/protocols/HttpBindingProtocol.js"() { + } + }); + + // node_modules/@smithy/core/dist-es/submodules/protocols/RpcProtocol.js + var init_RpcProtocol = __esm({ + "node_modules/@smithy/core/dist-es/submodules/protocols/RpcProtocol.js"() { + } + }); + + // node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js + var init_resolve_path = __esm({ + "node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js"() { + } + }); + + // node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js + var init_requestBuilder = __esm({ + "node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js"() { + } + }); + + // node_modules/@smithy/core/dist-es/submodules/protocols/serde/determineTimestampFormat.js + var init_determineTimestampFormat = __esm({ + "node_modules/@smithy/core/dist-es/submodules/protocols/serde/determineTimestampFormat.js"() { + } + }); + + // node_modules/@smithy/core/dist-es/submodules/protocols/serde/FromStringShapeDeserializer.js + var init_FromStringShapeDeserializer = __esm({ + "node_modules/@smithy/core/dist-es/submodules/protocols/serde/FromStringShapeDeserializer.js"() { + } + }); + + // node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeDeserializer.js + var init_HttpInterceptingShapeDeserializer = __esm({ + "node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeDeserializer.js"() { + } + }); + + // node_modules/@smithy/core/dist-es/submodules/protocols/serde/ToStringShapeSerializer.js + var init_ToStringShapeSerializer = __esm({ + "node_modules/@smithy/core/dist-es/submodules/protocols/serde/ToStringShapeSerializer.js"() { + } + }); + + // node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeSerializer.js + var init_HttpInterceptingShapeSerializer = __esm({ + "node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeSerializer.js"() { + } + }); + + // node_modules/@smithy/core/dist-es/submodules/protocols/index.js + var init_protocols = __esm({ + "node_modules/@smithy/core/dist-es/submodules/protocols/index.js"() { + init_collect_stream_body(); + init_extended_encode_uri_component(); + init_HttpBindingProtocol(); + init_HttpProtocol(); + init_RpcProtocol(); + init_requestBuilder(); + init_resolve_path(); + init_FromStringShapeDeserializer(); + init_HttpInterceptingShapeDeserializer(); + init_HttpInterceptingShapeSerializer(); + init_ToStringShapeSerializer(); + init_determineTimestampFormat(); + } + }); + + // node_modules/@smithy/core/dist-es/protocols/requestBuilder.js + var init_requestBuilder2 = __esm({ + "node_modules/@smithy/core/dist-es/protocols/requestBuilder.js"() { + } + }); + + // node_modules/@smithy/core/dist-es/setFeature.js + function setFeature(context, feature, value) { + if (!context.__smithy_context) { + context.__smithy_context = { + features: {} + }; + } else if (!context.__smithy_context.features) { + context.__smithy_context.features = {}; + } + context.__smithy_context.features[feature] = value; + } + var init_setFeature = __esm({ + "node_modules/@smithy/core/dist-es/setFeature.js"() { + } + }); + + // node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js + var DefaultIdentityProviderConfig; + var init_DefaultIdentityProviderConfig = __esm({ + "node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js"() { + DefaultIdentityProviderConfig = class { + authSchemes = /* @__PURE__ */ new Map(); + constructor(config) { + for (const [key, value] of Object.entries(config)) { + if (value !== void 0) { + this.authSchemes.set(key, value); + } + } + } + getIdentityProvider(schemeId) { + return this.authSchemes.get(schemeId); + } + }; + } + }); + + // node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js + var init_httpApiKeyAuth = __esm({ + "node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js"() { + } + }); + + // node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js + var init_httpBearerAuth = __esm({ + "node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js"() { + } + }); + + // node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js + var NoAuthSigner; + var init_noAuth = __esm({ + "node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js"() { + NoAuthSigner = class { + async sign(httpRequest, identity, signingProperties) { + return httpRequest; + } + }; + } + }); + + // node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js + var init_httpAuthSchemes = __esm({ + "node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js"() { + init_httpApiKeyAuth(); + init_httpBearerAuth(); + init_noAuth(); + } + }); + + // node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js + var createIsIdentityExpiredFunction, EXPIRATION_MS, isIdentityExpired, doesIdentityRequireRefresh, memoizeIdentityProvider; + var init_memoizeIdentityProvider = __esm({ + "node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js"() { + createIsIdentityExpiredFunction = (expirationMs) => function isIdentityExpired2(identity) { + return doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs; + }; + EXPIRATION_MS = 3e5; + isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); + doesIdentityRequireRefresh = (identity) => identity.expiration !== void 0; + memoizeIdentityProvider = (provider, isExpired, requiresRefresh) => { + if (provider === void 0) { + return void 0; + } + const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; + let resolved; + let pending; + let hasResult; + let isConstant = false; + const coalesceProvider = async (options) => { + if (!pending) { + pending = normalizedProvider(options); + } + try { + resolved = await pending; + hasResult = true; + isConstant = false; + } finally { + pending = void 0; + } + return resolved; + }; + if (isExpired === void 0) { + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); + } + return resolved; + }; + } + return async (options) => { + if (!hasResult || options?.forceRefresh) { + resolved = await coalesceProvider(options); + } + if (isConstant) { + return resolved; + } + if (!requiresRefresh(resolved)) { + isConstant = true; + return resolved; + } + if (isExpired(resolved)) { + await coalesceProvider(options); + return resolved; + } + return resolved; + }; + }; + } + }); + + // node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js + var init_util_identity_and_auth = __esm({ + "node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js"() { + init_DefaultIdentityProviderConfig(); + init_httpAuthSchemes(); + init_memoizeIdentityProvider(); + } + }); + + // node_modules/@smithy/core/dist-es/index.js + var init_dist_es18 = __esm({ + "node_modules/@smithy/core/dist-es/index.js"() { + init_getSmithyContext(); + init_middleware_http_auth_scheme(); + init_middleware_http_signing(); + init_normalizeProvider2(); + init_createPaginator(); + init_requestBuilder2(); + init_setFeature(); + init_util_identity_and_auth(); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-user-agent/dist-es/configurations.js + function isValidUserAgentAppId(appId) { + if (appId === void 0) { + return true; + } + return typeof appId === "string" && appId.length <= 50; + } + function resolveUserAgentConfig(input) { + const normalizedAppIdProvider = normalizeProvider2(input.userAgentAppId ?? DEFAULT_UA_APP_ID); + const { customUserAgent } = input; + return Object.assign(input, { + customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent, + userAgentAppId: async () => { + const appId = await normalizedAppIdProvider(); + if (!isValidUserAgentAppId(appId)) { + const logger2 = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger; + if (typeof appId !== "string") { + logger2?.warn("userAgentAppId must be a string or undefined."); + } else if (appId.length > 50) { + logger2?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters."); + } + } + return appId; + } + }); + } + var DEFAULT_UA_APP_ID; + var init_configurations = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-user-agent/dist-es/configurations.js"() { + init_dist_es18(); + DEFAULT_UA_APP_ID = void 0; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/cache/EndpointCache.js + var EndpointCache; + var init_EndpointCache = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/cache/EndpointCache.js"() { + EndpointCache = class { + capacity; + data = /* @__PURE__ */ new Map(); + parameters = []; + constructor({ size, params }) { + this.capacity = size ?? 50; + if (params) { + this.parameters = params; + } + } + get(endpointParams, resolver) { + const key = this.hash(endpointParams); + if (key === false) { + return resolver(); + } + if (!this.data.has(key)) { + if (this.data.size > this.capacity + 10) { + const keys = this.data.keys(); + let i2 = 0; + while (true) { + const { value, done } = keys.next(); + this.data.delete(value); + if (done || ++i2 > 10) { + break; + } + } + } + this.data.set(key, resolver()); + } + return this.data.get(key); + } + size() { + return this.data.size; + } + hash(endpointParams) { + let buffer = ""; + const { parameters } = this; + if (parameters.length === 0) { + return false; + } + for (const param of parameters) { + const val = String(endpointParams[param] ?? ""); + if (val.includes("|;")) { + return false; + } + buffer += val + "|;"; + } + return buffer; + } + }; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/lib/isIpAddress.js + var IP_V4_REGEX, isIpAddress; + var init_isIpAddress = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/lib/isIpAddress.js"() { + IP_V4_REGEX = new RegExp(`^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$`); + isIpAddress = (value) => IP_V4_REGEX.test(value) || value.startsWith("[") && value.endsWith("]"); + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/lib/isValidHostLabel.js + var VALID_HOST_LABEL_REGEX, isValidHostLabel; + var init_isValidHostLabel = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/lib/isValidHostLabel.js"() { + VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`); + isValidHostLabel = (value, allowSubDomains = false) => { + if (!allowSubDomains) { + return VALID_HOST_LABEL_REGEX.test(value); + } + const labels = value.split("."); + for (const label of labels) { + if (!isValidHostLabel(label)) { + return false; + } + } + return true; + }; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/utils/customEndpointFunctions.js + var customEndpointFunctions; + var init_customEndpointFunctions = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/utils/customEndpointFunctions.js"() { + customEndpointFunctions = {}; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/debug/debugId.js + var debugId; + var init_debugId = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/debug/debugId.js"() { + debugId = "endpoints"; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/debug/toDebugString.js + function toDebugString(input) { + if (typeof input !== "object" || input == null) { + return input; + } + if ("ref" in input) { + return `$${toDebugString(input.ref)}`; + } + if ("fn" in input) { + return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`; + } + return JSON.stringify(input, null, 2); + } + var init_toDebugString = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/debug/toDebugString.js"() { + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/debug/index.js + var init_debug = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/debug/index.js"() { + init_debugId(); + init_toDebugString(); + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/types/EndpointError.js + var EndpointError; + var init_EndpointError = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/types/EndpointError.js"() { + EndpointError = class extends Error { + constructor(message) { + super(message); + this.name = "EndpointError"; + } + }; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/types/EndpointFunctions.js + var init_EndpointFunctions = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/types/EndpointFunctions.js"() { + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/types/EndpointRuleObject.js + var init_EndpointRuleObject2 = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/types/EndpointRuleObject.js"() { + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/types/ErrorRuleObject.js + var init_ErrorRuleObject2 = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/types/ErrorRuleObject.js"() { + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/types/RuleSetObject.js + var init_RuleSetObject2 = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/types/RuleSetObject.js"() { + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/types/TreeRuleObject.js + var init_TreeRuleObject2 = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/types/TreeRuleObject.js"() { + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/types/shared.js + var init_shared2 = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/types/shared.js"() { + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/types/index.js + var init_types2 = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/types/index.js"() { + init_EndpointError(); + init_EndpointFunctions(); + init_EndpointRuleObject2(); + init_ErrorRuleObject2(); + init_RuleSetObject2(); + init_TreeRuleObject2(); + init_shared2(); + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/lib/booleanEquals.js + var booleanEquals; + var init_booleanEquals = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/lib/booleanEquals.js"() { + booleanEquals = (value1, value2) => value1 === value2; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/lib/getAttrPathList.js + var getAttrPathList; + var init_getAttrPathList = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/lib/getAttrPathList.js"() { + init_types2(); + getAttrPathList = (path) => { + const parts = path.split("."); + const pathList = []; + for (const part of parts) { + const squareBracketIndex = part.indexOf("["); + if (squareBracketIndex !== -1) { + if (part.indexOf("]") !== part.length - 1) { + throw new EndpointError(`Path: '${path}' does not end with ']'`); + } + const arrayIndex = part.slice(squareBracketIndex + 1, -1); + if (Number.isNaN(parseInt(arrayIndex))) { + throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path}'`); + } + if (squareBracketIndex !== 0) { + pathList.push(part.slice(0, squareBracketIndex)); + } + pathList.push(arrayIndex); + } else { + pathList.push(part); + } + } + return pathList; + }; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/lib/getAttr.js + var getAttr; + var init_getAttr = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/lib/getAttr.js"() { + init_types2(); + init_getAttrPathList(); + getAttr = (value, path) => getAttrPathList(path).reduce((acc, index2) => { + if (typeof acc !== "object") { + throw new EndpointError(`Index '${index2}' in '${path}' not found in '${JSON.stringify(value)}'`); + } else if (Array.isArray(acc)) { + return acc[parseInt(index2)]; + } + return acc[index2]; + }, value); + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/lib/isSet.js + var isSet; + var init_isSet = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/lib/isSet.js"() { + isSet = (value) => value != null; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/lib/not.js + var not; + var init_not = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/lib/not.js"() { + not = (value) => !value; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/lib/parseURL.js + var DEFAULT_PORTS, parseURL; + var init_parseURL = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/lib/parseURL.js"() { + init_dist_es3(); + init_isIpAddress(); + DEFAULT_PORTS = { + [EndpointURLScheme.HTTP]: 80, + [EndpointURLScheme.HTTPS]: 443 + }; + parseURL = (value) => { + const whatwgURL = (() => { + try { + if (value instanceof URL) { + return value; + } + if (typeof value === "object" && "hostname" in value) { + const { hostname: hostname2, port, protocol: protocol2 = "", path = "", query = {} } = value; + const url = new URL(`${protocol2}//${hostname2}${port ? `:${port}` : ""}${path}`); + url.search = Object.entries(query).map(([k3, v6]) => `${k3}=${v6}`).join("&"); + return url; + } + return new URL(value); + } catch (error) { + return null; + } + })(); + if (!whatwgURL) { + console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`); + return null; + } + const urlString = whatwgURL.href; + const { host, hostname, pathname, protocol, search: search3 } = whatwgURL; + if (search3) { + return null; + } + const scheme = protocol.slice(0, -1); + if (!Object.values(EndpointURLScheme).includes(scheme)) { + return null; + } + const isIp = isIpAddress(hostname); + const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) || typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`); + const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS[scheme]}` : ``}`; + return { + scheme, + authority, + path: pathname, + normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`, + isIp + }; + }; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/lib/stringEquals.js + var stringEquals; + var init_stringEquals = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/lib/stringEquals.js"() { + stringEquals = (value1, value2) => value1 === value2; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/lib/substring.js + var substring; + var init_substring = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/lib/substring.js"() { + substring = (input, start, stop, reverse) => { + if (start >= stop || input.length < stop) { + return null; + } + if (!reverse) { + return input.substring(start, stop); + } + return input.substring(input.length - stop, input.length - start); + }; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/lib/uriEncode.js + var uriEncode; + var init_uriEncode = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/lib/uriEncode.js"() { + uriEncode = (value) => encodeURIComponent(value).replace(/[!*'()]/g, (c3) => `%${c3.charCodeAt(0).toString(16).toUpperCase()}`); + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/lib/index.js + var init_lib = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/lib/index.js"() { + init_booleanEquals(); + init_getAttr(); + init_isSet(); + init_isValidHostLabel(); + init_not(); + init_parseURL(); + init_stringEquals(); + init_substring(); + init_uriEncode(); + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/utils/endpointFunctions.js + var endpointFunctions; + var init_endpointFunctions = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/utils/endpointFunctions.js"() { + init_lib(); + endpointFunctions = { + booleanEquals, + getAttr, + isSet, + isValidHostLabel, + not, + parseURL, + stringEquals, + substring, + uriEncode + }; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTemplate.js + var evaluateTemplate; + var init_evaluateTemplate = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTemplate.js"() { + init_lib(); + evaluateTemplate = (template, options) => { + const evaluatedTemplateArr = []; + const templateContext = { + ...options.endpointParams, + ...options.referenceRecord + }; + let currentIndex = 0; + while (currentIndex < template.length) { + const openingBraceIndex = template.indexOf("{", currentIndex); + if (openingBraceIndex === -1) { + evaluatedTemplateArr.push(template.slice(currentIndex)); + break; + } + evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex)); + const closingBraceIndex = template.indexOf("}", openingBraceIndex); + if (closingBraceIndex === -1) { + evaluatedTemplateArr.push(template.slice(openingBraceIndex)); + break; + } + if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") { + evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex)); + currentIndex = closingBraceIndex + 2; + } + const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex); + if (parameterName.includes("#")) { + const [refName, attrName] = parameterName.split("#"); + evaluatedTemplateArr.push(getAttr(templateContext[refName], attrName)); + } else { + evaluatedTemplateArr.push(templateContext[parameterName]); + } + currentIndex = closingBraceIndex + 1; + } + return evaluatedTemplateArr.join(""); + }; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/utils/getReferenceValue.js + var getReferenceValue; + var init_getReferenceValue = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/utils/getReferenceValue.js"() { + getReferenceValue = ({ ref }, options) => { + const referenceRecord = { + ...options.endpointParams, + ...options.referenceRecord + }; + return referenceRecord[ref]; + }; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/utils/evaluateExpression.js + var evaluateExpression; + var init_evaluateExpression = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/utils/evaluateExpression.js"() { + init_types2(); + init_callFunction(); + init_evaluateTemplate(); + init_getReferenceValue(); + evaluateExpression = (obj, keyName, options) => { + if (typeof obj === "string") { + return evaluateTemplate(obj, options); + } else if (obj["fn"]) { + return callFunction(obj, options); + } else if (obj["ref"]) { + return getReferenceValue(obj, options); + } + throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`); + }; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/utils/callFunction.js + var callFunction; + var init_callFunction = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/utils/callFunction.js"() { + init_customEndpointFunctions(); + init_endpointFunctions(); + init_evaluateExpression(); + callFunction = ({ fn, argv }, options) => { + const evaluatedArgs = argv.map((arg) => ["boolean", "number"].includes(typeof arg) ? arg : evaluateExpression(arg, "arg", options)); + const fnSegments = fn.split("."); + if (fnSegments[0] in customEndpointFunctions && fnSegments[1] != null) { + return customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs); + } + return endpointFunctions[fn](...evaluatedArgs); + }; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/utils/evaluateCondition.js + var evaluateCondition; + var init_evaluateCondition = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/utils/evaluateCondition.js"() { + init_debug(); + init_types2(); + init_callFunction(); + evaluateCondition = ({ assign, ...fnArgs }, options) => { + if (assign && assign in options.referenceRecord) { + throw new EndpointError(`'${assign}' is already defined in Reference Record.`); + } + const value = callFunction(fnArgs, options); + options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`); + return { + result: value === "" ? true : !!value, + ...assign != null && { toAssign: { name: assign, value } } + }; + }; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/utils/evaluateConditions.js + var evaluateConditions; + var init_evaluateConditions = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/utils/evaluateConditions.js"() { + init_debug(); + init_evaluateCondition(); + evaluateConditions = (conditions = [], options) => { + const conditionsReferenceRecord = {}; + for (const condition of conditions) { + const { result, toAssign } = evaluateCondition(condition, { + ...options, + referenceRecord: { + ...options.referenceRecord, + ...conditionsReferenceRecord + } + }); + if (!result) { + return { result }; + } + if (toAssign) { + conditionsReferenceRecord[toAssign.name] = toAssign.value; + options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`); + } + } + return { result: true, referenceRecord: conditionsReferenceRecord }; + }; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointHeaders.js + var getEndpointHeaders; + var init_getEndpointHeaders = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointHeaders.js"() { + init_types2(); + init_evaluateExpression(); + getEndpointHeaders = (headers, options) => Object.entries(headers).reduce((acc, [headerKey, headerVal]) => ({ + ...acc, + [headerKey]: headerVal.map((headerValEntry) => { + const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options); + if (typeof processedExpr !== "string") { + throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`); + } + return processedExpr; + }) + }), {}); + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperty.js + var getEndpointProperty; + var init_getEndpointProperty = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperty.js"() { + init_types2(); + init_evaluateTemplate(); + init_getEndpointProperties(); + getEndpointProperty = (property, options) => { + if (Array.isArray(property)) { + return property.map((propertyEntry) => getEndpointProperty(propertyEntry, options)); + } + switch (typeof property) { + case "string": + return evaluateTemplate(property, options); + case "object": + if (property === null) { + throw new EndpointError(`Unexpected endpoint property: ${property}`); + } + return getEndpointProperties(property, options); + case "boolean": + return property; + default: + throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`); + } + }; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperties.js + var getEndpointProperties; + var init_getEndpointProperties = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperties.js"() { + init_getEndpointProperty(); + getEndpointProperties = (properties, options) => Object.entries(properties).reduce((acc, [propertyKey, propertyVal]) => ({ + ...acc, + [propertyKey]: getEndpointProperty(propertyVal, options) + }), {}); + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointUrl.js + var getEndpointUrl; + var init_getEndpointUrl = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointUrl.js"() { + init_types2(); + init_evaluateExpression(); + getEndpointUrl = (endpointUrl, options) => { + const expression = evaluateExpression(endpointUrl, "Endpoint URL", options); + if (typeof expression === "string") { + try { + return new URL(expression); + } catch (error) { + console.error(`Failed to construct URL with ${expression}`, error); + throw error; + } + } + throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`); + }; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/utils/evaluateEndpointRule.js + var evaluateEndpointRule; + var init_evaluateEndpointRule = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/utils/evaluateEndpointRule.js"() { + init_debug(); + init_evaluateConditions(); + init_getEndpointHeaders(); + init_getEndpointProperties(); + init_getEndpointUrl(); + evaluateEndpointRule = (endpointRule, options) => { + const { conditions, endpoint } = endpointRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; + } + const endpointRuleOptions = { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord } + }; + const { url, properties, headers } = endpoint; + options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`); + return { + ...headers != void 0 && { + headers: getEndpointHeaders(headers, endpointRuleOptions) + }, + ...properties != void 0 && { + properties: getEndpointProperties(properties, endpointRuleOptions) + }, + url: getEndpointUrl(url, endpointRuleOptions) + }; + }; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/utils/evaluateErrorRule.js + var evaluateErrorRule; + var init_evaluateErrorRule = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/utils/evaluateErrorRule.js"() { + init_types2(); + init_evaluateConditions(); + init_evaluateExpression(); + evaluateErrorRule = (errorRule, options) => { + const { conditions, error } = errorRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; + } + throw new EndpointError(evaluateExpression(error, "Error", { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord } + })); + }; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTreeRule.js + var evaluateTreeRule; + var init_evaluateTreeRule = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTreeRule.js"() { + init_evaluateConditions(); + init_evaluateRules(); + evaluateTreeRule = (treeRule, options) => { + const { conditions, rules } = treeRule; + const { result, referenceRecord } = evaluateConditions(conditions, options); + if (!result) { + return; + } + return evaluateRules(rules, { + ...options, + referenceRecord: { ...options.referenceRecord, ...referenceRecord } + }); + }; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/utils/evaluateRules.js + var evaluateRules; + var init_evaluateRules = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/utils/evaluateRules.js"() { + init_types2(); + init_evaluateEndpointRule(); + init_evaluateErrorRule(); + init_evaluateTreeRule(); + evaluateRules = (rules, options) => { + for (const rule of rules) { + if (rule.type === "endpoint") { + const endpointOrUndefined = evaluateEndpointRule(rule, options); + if (endpointOrUndefined) { + return endpointOrUndefined; + } + } else if (rule.type === "error") { + evaluateErrorRule(rule, options); + } else if (rule.type === "tree") { + const endpointOrUndefined = evaluateTreeRule(rule, options); + if (endpointOrUndefined) { + return endpointOrUndefined; + } + } else { + throw new EndpointError(`Unknown endpoint rule: ${rule}`); + } + } + throw new EndpointError(`Rules evaluation failed`); + }; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/utils/index.js + var init_utils = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/utils/index.js"() { + init_customEndpointFunctions(); + init_evaluateRules(); + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/resolveEndpoint.js + var resolveEndpoint; + var init_resolveEndpoint = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/resolveEndpoint.js"() { + init_debug(); + init_types2(); + init_utils(); + resolveEndpoint = (ruleSetObject, options) => { + const { endpointParams, logger: logger2 } = options; + const { parameters, rules } = ruleSetObject; + options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`); + const paramsWithDefault = Object.entries(parameters).filter(([, v6]) => v6.default != null).map(([k3, v6]) => [k3, v6.default]); + if (paramsWithDefault.length > 0) { + for (const [paramKey, paramDefaultValue] of paramsWithDefault) { + endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue; + } + } + const requiredParams = Object.entries(parameters).filter(([, v6]) => v6.required).map(([k3]) => k3); + for (const requiredParam of requiredParams) { + if (endpointParams[requiredParam] == null) { + throw new EndpointError(`Missing required parameter: '${requiredParam}'`); + } + } + const endpoint = evaluateRules(rules, { endpointParams, logger: logger2, referenceRecord: {} }); + options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`); + return endpoint; + }; + } + }); + + // node_modules/@smithy/util-endpoints/dist-es/index.js + var init_dist_es19 = __esm({ + "node_modules/@smithy/util-endpoints/dist-es/index.js"() { + init_EndpointCache(); + init_isIpAddress(); + init_isValidHostLabel(); + init_customEndpointFunctions(); + init_resolveEndpoint(); + init_types2(); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/lib/isIpAddress.js + var init_isIpAddress2 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/lib/isIpAddress.js"() { + init_dist_es19(); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/isVirtualHostableS3Bucket.js + var isVirtualHostableS3Bucket; + var init_isVirtualHostableS3Bucket = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/isVirtualHostableS3Bucket.js"() { + init_dist_es19(); + init_isIpAddress2(); + isVirtualHostableS3Bucket = (value, allowSubDomains = false) => { + if (allowSubDomains) { + for (const label of value.split(".")) { + if (!isVirtualHostableS3Bucket(label)) { + return false; + } + } + return true; + } + if (!isValidHostLabel(value)) { + return false; + } + if (value.length < 3 || value.length > 63) { + return false; + } + if (value !== value.toLowerCase()) { + return false; + } + if (isIpAddress(value)) { + return false; + } + return true; + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/parseArn.js + var ARN_DELIMITER, RESOURCE_DELIMITER, parseArn; + var init_parseArn = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/parseArn.js"() { + ARN_DELIMITER = ":"; + RESOURCE_DELIMITER = "/"; + parseArn = (value) => { + const segments = value.split(ARN_DELIMITER); + if (segments.length < 6) + return null; + const [arn, partition2, service, region2, accountId, ...resourcePath] = segments; + if (arn !== "arn" || partition2 === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "") + return null; + const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat(); + return { + partition: partition2, + service, + region: region2, + accountId, + resourceId + }; + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partitions.json + var partitions_default; + var init_partitions = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partitions.json"() { + partitions_default = { + partitions: [{ + id: "aws", + outputs: { + dnsSuffix: "amazonaws.com", + dualStackDnsSuffix: "api.aws", + implicitGlobalRegion: "us-east-1", + name: "aws", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$", + regions: { + "af-south-1": { + description: "Africa (Cape Town)" + }, + "ap-east-1": { + description: "Asia Pacific (Hong Kong)" + }, + "ap-east-2": { + description: "Asia Pacific (Taipei)" + }, + "ap-northeast-1": { + description: "Asia Pacific (Tokyo)" + }, + "ap-northeast-2": { + description: "Asia Pacific (Seoul)" + }, + "ap-northeast-3": { + description: "Asia Pacific (Osaka)" + }, + "ap-south-1": { + description: "Asia Pacific (Mumbai)" + }, + "ap-south-2": { + description: "Asia Pacific (Hyderabad)" + }, + "ap-southeast-1": { + description: "Asia Pacific (Singapore)" + }, + "ap-southeast-2": { + description: "Asia Pacific (Sydney)" + }, + "ap-southeast-3": { + description: "Asia Pacific (Jakarta)" + }, + "ap-southeast-4": { + description: "Asia Pacific (Melbourne)" + }, + "ap-southeast-5": { + description: "Asia Pacific (Malaysia)" + }, + "ap-southeast-6": { + description: "Asia Pacific (New Zealand)" + }, + "ap-southeast-7": { + description: "Asia Pacific (Thailand)" + }, + "aws-global": { + description: "aws global region" + }, + "ca-central-1": { + description: "Canada (Central)" + }, + "ca-west-1": { + description: "Canada West (Calgary)" + }, + "eu-central-1": { + description: "Europe (Frankfurt)" + }, + "eu-central-2": { + description: "Europe (Zurich)" + }, + "eu-north-1": { + description: "Europe (Stockholm)" + }, + "eu-south-1": { + description: "Europe (Milan)" + }, + "eu-south-2": { + description: "Europe (Spain)" + }, + "eu-west-1": { + description: "Europe (Ireland)" + }, + "eu-west-2": { + description: "Europe (London)" + }, + "eu-west-3": { + description: "Europe (Paris)" + }, + "il-central-1": { + description: "Israel (Tel Aviv)" + }, + "me-central-1": { + description: "Middle East (UAE)" + }, + "me-south-1": { + description: "Middle East (Bahrain)" + }, + "mx-central-1": { + description: "Mexico (Central)" + }, + "sa-east-1": { + description: "South America (Sao Paulo)" + }, + "us-east-1": { + description: "US East (N. Virginia)" + }, + "us-east-2": { + description: "US East (Ohio)" + }, + "us-west-1": { + description: "US West (N. California)" + }, + "us-west-2": { + description: "US West (Oregon)" + } + } + }, { + id: "aws-cn", + outputs: { + dnsSuffix: "amazonaws.com.cn", + dualStackDnsSuffix: "api.amazonwebservices.com.cn", + implicitGlobalRegion: "cn-northwest-1", + name: "aws-cn", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^cn\\-\\w+\\-\\d+$", + regions: { + "aws-cn-global": { + description: "aws-cn global region" + }, + "cn-north-1": { + description: "China (Beijing)" + }, + "cn-northwest-1": { + description: "China (Ningxia)" + } + } + }, { + id: "aws-eusc", + outputs: { + dnsSuffix: "amazonaws.eu", + dualStackDnsSuffix: "api.amazonwebservices.eu", + implicitGlobalRegion: "eusc-de-east-1", + name: "aws-eusc", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$", + regions: { + "eusc-de-east-1": { + description: "EU (Germany)" + } + } + }, { + id: "aws-iso", + outputs: { + dnsSuffix: "c2s.ic.gov", + dualStackDnsSuffix: "api.aws.ic.gov", + implicitGlobalRegion: "us-iso-east-1", + name: "aws-iso", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-iso\\-\\w+\\-\\d+$", + regions: { + "aws-iso-global": { + description: "aws-iso global region" + }, + "us-iso-east-1": { + description: "US ISO East" + }, + "us-iso-west-1": { + description: "US ISO WEST" + } + } + }, { + id: "aws-iso-b", + outputs: { + dnsSuffix: "sc2s.sgov.gov", + dualStackDnsSuffix: "api.aws.scloud", + implicitGlobalRegion: "us-isob-east-1", + name: "aws-iso-b", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-isob\\-\\w+\\-\\d+$", + regions: { + "aws-iso-b-global": { + description: "aws-iso-b global region" + }, + "us-isob-east-1": { + description: "US ISOB East (Ohio)" + } + } + }, { + id: "aws-iso-e", + outputs: { + dnsSuffix: "cloud.adc-e.uk", + dualStackDnsSuffix: "api.cloud-aws.adc-e.uk", + implicitGlobalRegion: "eu-isoe-west-1", + name: "aws-iso-e", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^eu\\-isoe\\-\\w+\\-\\d+$", + regions: { + "aws-iso-e-global": { + description: "aws-iso-e global region" + }, + "eu-isoe-west-1": { + description: "EU ISOE West" + } + } + }, { + id: "aws-iso-f", + outputs: { + dnsSuffix: "csp.hci.ic.gov", + dualStackDnsSuffix: "api.aws.hci.ic.gov", + implicitGlobalRegion: "us-isof-south-1", + name: "aws-iso-f", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-isof\\-\\w+\\-\\d+$", + regions: { + "aws-iso-f-global": { + description: "aws-iso-f global region" + }, + "us-isof-east-1": { + description: "US ISOF EAST" + }, + "us-isof-south-1": { + description: "US ISOF SOUTH" + } + } + }, { + id: "aws-us-gov", + outputs: { + dnsSuffix: "amazonaws.com", + dualStackDnsSuffix: "api.aws", + implicitGlobalRegion: "us-gov-west-1", + name: "aws-us-gov", + supportsDualStack: true, + supportsFIPS: true + }, + regionRegex: "^us\\-gov\\-\\w+\\-\\d+$", + regions: { + "aws-us-gov-global": { + description: "aws-us-gov global region" + }, + "us-gov-east-1": { + description: "AWS GovCloud (US-East)" + }, + "us-gov-west-1": { + description: "AWS GovCloud (US-West)" + } + } + }], + version: "1.1" + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js + var selectedPartitionsInfo, selectedUserAgentPrefix, partition, getUserAgentPrefix; + var init_partition = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js"() { + init_partitions(); + selectedPartitionsInfo = partitions_default; + selectedUserAgentPrefix = ""; + partition = (value) => { + const { partitions } = selectedPartitionsInfo; + for (const partition2 of partitions) { + const { regions, outputs } = partition2; + for (const [region2, regionData] of Object.entries(regions)) { + if (region2 === value) { + return { + ...outputs, + ...regionData + }; + } + } + } + for (const partition2 of partitions) { + const { regionRegex, outputs } = partition2; + if (new RegExp(regionRegex).test(value)) { + return { + ...outputs + }; + } + } + const DEFAULT_PARTITION = partitions.find((partition2) => partition2.id === "aws"); + if (!DEFAULT_PARTITION) { + throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist."); + } + return { + ...DEFAULT_PARTITION.outputs + }; + }; + getUserAgentPrefix = () => selectedUserAgentPrefix; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/aws.js + var awsEndpointFunctions; + var init_aws = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/aws.js"() { + init_dist_es19(); + init_isVirtualHostableS3Bucket(); + init_parseArn(); + init_partition(); + awsEndpointFunctions = { + isVirtualHostableS3Bucket, + parseArn, + partition + }; + customEndpointFunctions.aws = awsEndpointFunctions; + } + }); + + // node_modules/@smithy/querystring-parser/dist-es/index.js + function parseQueryString(querystring) { + const query = {}; + querystring = querystring.replace(/^\?/, ""); + if (querystring) { + for (const pair of querystring.split("&")) { + let [key, value = null] = pair.split("="); + key = decodeURIComponent(key); + if (value) { + value = decodeURIComponent(value); + } + if (!(key in query)) { + query[key] = value; + } else if (Array.isArray(query[key])) { + query[key].push(value); + } else { + query[key] = [query[key], value]; + } + } + } + return query; + } + var init_dist_es20 = __esm({ + "node_modules/@smithy/querystring-parser/dist-es/index.js"() { + } + }); + + // node_modules/@smithy/url-parser/dist-es/index.js + var parseUrl; + var init_dist_es21 = __esm({ + "node_modules/@smithy/url-parser/dist-es/index.js"() { + init_dist_es20(); + parseUrl = (url) => { + if (typeof url === "string") { + return parseUrl(new URL(url)); + } + const { hostname, pathname, port, protocol, search: search3 } = url; + let query; + if (search3) { + query = parseQueryString(search3); + } + return { + hostname, + port: port ? parseInt(port) : void 0, + protocol, + path: pathname, + query + }; + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/resolveDefaultAwsRegionalEndpointsConfig.js + var init_resolveDefaultAwsRegionalEndpointsConfig = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/resolveDefaultAwsRegionalEndpointsConfig.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/resolveEndpoint.js + var init_resolveEndpoint2 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/resolveEndpoint.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointError.js + var init_EndpointError2 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointError.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointRuleObject.js + var init_EndpointRuleObject3 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointRuleObject.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/types/ErrorRuleObject.js + var init_ErrorRuleObject3 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/types/ErrorRuleObject.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/types/RuleSetObject.js + var init_RuleSetObject3 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/types/RuleSetObject.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/types/TreeRuleObject.js + var init_TreeRuleObject3 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/types/TreeRuleObject.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/types/shared.js + var init_shared3 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/types/shared.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/types/index.js + var init_types3 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/types/index.js"() { + init_EndpointError2(); + init_EndpointRuleObject3(); + init_ErrorRuleObject3(); + init_RuleSetObject3(); + init_TreeRuleObject3(); + init_shared3(); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/index.js + var init_dist_es22 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints/dist-es/index.js"() { + init_aws(); + init_partition(); + init_isIpAddress2(); + init_resolveDefaultAwsRegionalEndpointsConfig(); + init_resolveEndpoint2(); + init_types3(); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/client/emitWarningIfUnsupportedVersion.js + var init_emitWarningIfUnsupportedVersion = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/client/emitWarningIfUnsupportedVersion.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/client/setCredentialFeature.js + function setCredentialFeature(credentials, feature, value) { + if (!credentials.$source) { + credentials.$source = {}; + } + credentials.$source[feature] = value; + return credentials; + } + var init_setCredentialFeature = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/client/setCredentialFeature.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/client/setFeature.js + function setFeature2(context, feature, value) { + if (!context.__aws_sdk_context) { + context.__aws_sdk_context = { + features: {} + }; + } else if (!context.__aws_sdk_context.features) { + context.__aws_sdk_context.features = {}; + } + context.__aws_sdk_context.features[feature] = value; + } + var init_setFeature2 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/client/setFeature.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/client/setTokenFeature.js + var init_setTokenFeature = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/client/setTokenFeature.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/client/index.js + var init_client2 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/client/index.js"() { + init_emitWarningIfUnsupportedVersion(); + init_setCredentialFeature(); + init_setFeature2(); + init_setTokenFeature(); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js + var getDateHeader; + var init_getDateHeader = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js"() { + init_dist_es4(); + getDateHeader = (response) => HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : void 0; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js + var getSkewCorrectedDate; + var init_getSkewCorrectedDate = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js"() { + getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js + var isClockSkewed; + var init_isClockSkewed = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js"() { + init_getSkewCorrectedDate(); + isClockSkewed = (clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 3e5; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js + var getUpdatedSystemClockOffset; + var init_getUpdatedSystemClockOffset = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js"() { + init_isClockSkewed(); + getUpdatedSystemClockOffset = (clockTime, currentSystemClockOffset) => { + const clockTimeInMs = Date.parse(clockTime); + if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) { + return clockTimeInMs - Date.now(); + } + return currentSystemClockOffset; + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/index.js + var init_utils2 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/index.js"() { + init_getDateHeader(); + init_getSkewCorrectedDate(); + init_getUpdatedSystemClockOffset(); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js + var throwSigningPropertyError, validateSigningProperties, AwsSdkSigV4Signer; + var init_AwsSdkSigV4Signer = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js"() { + init_dist_es4(); + init_utils2(); + throwSigningPropertyError = (name, property) => { + if (!property) { + throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`); + } + return property; + }; + validateSigningProperties = async (signingProperties) => { + const context = throwSigningPropertyError("context", signingProperties.context); + const config = throwSigningPropertyError("config", signingProperties.config); + const authScheme = context.endpointV2?.properties?.authSchemes?.[0]; + const signerFunction = throwSigningPropertyError("signer", config.signer); + const signer = await signerFunction(authScheme); + const signingRegion = signingProperties?.signingRegion; + const signingRegionSet = signingProperties?.signingRegionSet; + const signingName = signingProperties?.signingName; + return { + config, + signer, + signingRegion, + signingRegionSet, + signingName + }; + }; + AwsSdkSigV4Signer = class { + async sign(httpRequest, identity, signingProperties) { + if (!HttpRequest.isInstance(httpRequest)) { + throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); + } + const validatedProps = await validateSigningProperties(signingProperties); + const { config, signer } = validatedProps; + let { signingRegion, signingName } = validatedProps; + const handlerExecutionContext = signingProperties.context; + if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) { + const [first, second2] = handlerExecutionContext.authSchemes; + if (first?.name === "sigv4a" && second2?.name === "sigv4") { + signingRegion = second2?.signingRegion ?? signingRegion; + signingName = second2?.signingName ?? signingName; + } + } + const signedRequest = await signer.sign(httpRequest, { + signingDate: getSkewCorrectedDate(config.systemClockOffset), + signingRegion, + signingService: signingName + }); + return signedRequest; + } + errorHandler(signingProperties) { + return (error) => { + const serverTime = error.ServerTime ?? getDateHeader(error.$response); + if (serverTime) { + const config = throwSigningPropertyError("config", signingProperties.config); + const initialSystemClockOffset = config.systemClockOffset; + config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset); + const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset; + if (clockSkewCorrected && error.$metadata) { + error.$metadata.clockSkewCorrected = true; + } + } + throw error; + }; + } + successHandler(httpResponse, signingProperties) { + const dateHeader = getDateHeader(httpResponse); + if (dateHeader) { + const config = throwSigningPropertyError("config", signingProperties.config); + config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset); + } + } + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.js + var init_getBearerTokenEnvKey = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.js + var init_NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.js + var init_resolveAwsSdkSigV4AConfig = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.js"() { + } + }); + + // node_modules/@smithy/signature-v4/dist-es/constants.js + var ALGORITHM_QUERY_PARAM, CREDENTIAL_QUERY_PARAM, AMZ_DATE_QUERY_PARAM, SIGNED_HEADERS_QUERY_PARAM, EXPIRES_QUERY_PARAM, SIGNATURE_QUERY_PARAM, TOKEN_QUERY_PARAM, AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER, GENERATED_HEADERS, SIGNATURE_HEADER, SHA256_HEADER, TOKEN_HEADER, ALWAYS_UNSIGNABLE_HEADERS, PROXY_HEADER_PATTERN, SEC_HEADER_PATTERN, ALGORITHM_IDENTIFIER, EVENT_ALGORITHM_IDENTIFIER, UNSIGNED_PAYLOAD, MAX_CACHE_SIZE, KEY_TYPE_IDENTIFIER, MAX_PRESIGNED_TTL; + var init_constants2 = __esm({ + "node_modules/@smithy/signature-v4/dist-es/constants.js"() { + ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm"; + CREDENTIAL_QUERY_PARAM = "X-Amz-Credential"; + AMZ_DATE_QUERY_PARAM = "X-Amz-Date"; + SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders"; + EXPIRES_QUERY_PARAM = "X-Amz-Expires"; + SIGNATURE_QUERY_PARAM = "X-Amz-Signature"; + TOKEN_QUERY_PARAM = "X-Amz-Security-Token"; + AUTH_HEADER = "authorization"; + AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase(); + DATE_HEADER = "date"; + GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER]; + SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase(); + SHA256_HEADER = "x-amz-content-sha256"; + TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase(); + ALWAYS_UNSIGNABLE_HEADERS = { + authorization: true, + "cache-control": true, + connection: true, + expect: true, + from: true, + "keep-alive": true, + "max-forwards": true, + pragma: true, + referer: true, + te: true, + trailer: true, + "transfer-encoding": true, + upgrade: true, + "user-agent": true, + "x-amzn-trace-id": true + }; + PROXY_HEADER_PATTERN = /^proxy-/; + SEC_HEADER_PATTERN = /^sec-/; + ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256"; + EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD"; + UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; + MAX_CACHE_SIZE = 50; + KEY_TYPE_IDENTIFIER = "aws4_request"; + MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7; + } + }); + + // node_modules/@smithy/signature-v4/dist-es/credentialDerivation.js + var signingKeyCache, cacheQueue, createScope, getSigningKey, hmac; + var init_credentialDerivation = __esm({ + "node_modules/@smithy/signature-v4/dist-es/credentialDerivation.js"() { + init_dist_es15(); + init_dist_es10(); + init_constants2(); + signingKeyCache = {}; + cacheQueue = []; + createScope = (shortDate, region2, service) => `${shortDate}/${region2}/${service}/${KEY_TYPE_IDENTIFIER}`; + getSigningKey = async (sha256Constructor, credentials, shortDate, region2, service) => { + const credsHash = await hmac(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId); + const cacheKey = `${shortDate}:${region2}:${service}:${toHex(credsHash)}:${credentials.sessionToken}`; + if (cacheKey in signingKeyCache) { + return signingKeyCache[cacheKey]; + } + cacheQueue.push(cacheKey); + while (cacheQueue.length > MAX_CACHE_SIZE) { + delete signingKeyCache[cacheQueue.shift()]; + } + let key = `AWS4${credentials.secretAccessKey}`; + for (const signable of [shortDate, region2, service, KEY_TYPE_IDENTIFIER]) { + key = await hmac(sha256Constructor, key, signable); + } + return signingKeyCache[cacheKey] = key; + }; + hmac = (ctor, secret, data) => { + const hash = new ctor(secret); + hash.update(toUint8Array(data)); + return hash.digest(); + }; + } + }); + + // node_modules/@smithy/signature-v4/dist-es/getCanonicalHeaders.js + var getCanonicalHeaders; + var init_getCanonicalHeaders = __esm({ + "node_modules/@smithy/signature-v4/dist-es/getCanonicalHeaders.js"() { + init_constants2(); + getCanonicalHeaders = ({ headers }, unsignableHeaders, signableHeaders) => { + const canonical = {}; + for (const headerName of Object.keys(headers).sort()) { + if (headers[headerName] == void 0) { + continue; + } + const canonicalHeaderName = headerName.toLowerCase(); + if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || unsignableHeaders?.has(canonicalHeaderName) || PROXY_HEADER_PATTERN.test(canonicalHeaderName) || SEC_HEADER_PATTERN.test(canonicalHeaderName)) { + if (!signableHeaders || signableHeaders && !signableHeaders.has(canonicalHeaderName)) { + continue; + } + } + canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " "); + } + return canonical; + }; + } + }); + + // node_modules/@smithy/is-array-buffer/dist-es/index.js + var isArrayBuffer; + var init_dist_es23 = __esm({ + "node_modules/@smithy/is-array-buffer/dist-es/index.js"() { + isArrayBuffer = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; + } + }); + + // node_modules/@smithy/signature-v4/dist-es/getPayloadHash.js + var getPayloadHash; + var init_getPayloadHash = __esm({ + "node_modules/@smithy/signature-v4/dist-es/getPayloadHash.js"() { + init_dist_es23(); + init_dist_es15(); + init_dist_es10(); + init_constants2(); + getPayloadHash = async ({ headers, body }, hashConstructor) => { + for (const headerName of Object.keys(headers)) { + if (headerName.toLowerCase() === SHA256_HEADER) { + return headers[headerName]; + } + } + if (body == void 0) { + return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + } else if (typeof body === "string" || ArrayBuffer.isView(body) || isArrayBuffer(body)) { + const hashCtor = new hashConstructor(); + hashCtor.update(toUint8Array(body)); + return toHex(await hashCtor.digest()); + } + return UNSIGNED_PAYLOAD; + }; + } + }); + + // node_modules/@smithy/signature-v4/dist-es/HeaderFormatter.js + function negate(bytes) { + for (let i2 = 0; i2 < 8; i2++) { + bytes[i2] ^= 255; + } + for (let i2 = 7; i2 > -1; i2--) { + bytes[i2]++; + if (bytes[i2] !== 0) + break; + } + } + var HeaderFormatter, HEADER_VALUE_TYPE, UUID_PATTERN, Int64; + var init_HeaderFormatter = __esm({ + "node_modules/@smithy/signature-v4/dist-es/HeaderFormatter.js"() { + init_dist_es15(); + init_dist_es10(); + HeaderFormatter = class { + format(headers) { + const chunks = []; + for (const headerName of Object.keys(headers)) { + const bytes = fromUtf83(headerName); + chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); + } + const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); + let position = 0; + for (const chunk of chunks) { + out.set(chunk, position); + position += chunk.byteLength; + } + return out; + } + formatHeaderValue(header) { + switch (header.type) { + case "boolean": + return Uint8Array.from([header.value ? 0 : 1]); + case "byte": + return Uint8Array.from([2, header.value]); + case "short": + const shortView = new DataView(new ArrayBuffer(3)); + shortView.setUint8(0, 3); + shortView.setInt16(1, header.value, false); + return new Uint8Array(shortView.buffer); + case "integer": + const intView = new DataView(new ArrayBuffer(5)); + intView.setUint8(0, 4); + intView.setInt32(1, header.value, false); + return new Uint8Array(intView.buffer); + case "long": + const longBytes = new Uint8Array(9); + longBytes[0] = 5; + longBytes.set(header.value.bytes, 1); + return longBytes; + case "binary": + const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); + binView.setUint8(0, 6); + binView.setUint16(1, header.value.byteLength, false); + const binBytes = new Uint8Array(binView.buffer); + binBytes.set(header.value, 3); + return binBytes; + case "string": + const utf8Bytes = fromUtf83(header.value); + const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); + strView.setUint8(0, 7); + strView.setUint16(1, utf8Bytes.byteLength, false); + const strBytes = new Uint8Array(strView.buffer); + strBytes.set(utf8Bytes, 3); + return strBytes; + case "timestamp": + const tsBytes = new Uint8Array(9); + tsBytes[0] = 8; + tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); + return tsBytes; + case "uuid": + if (!UUID_PATTERN.test(header.value)) { + throw new Error(`Invalid UUID received: ${header.value}`); + } + const uuidBytes = new Uint8Array(17); + uuidBytes[0] = 9; + uuidBytes.set(fromHex(header.value.replace(/\-/g, "")), 1); + return uuidBytes; + } + } + }; + (function(HEADER_VALUE_TYPE3) { + HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["boolTrue"] = 0] = "boolTrue"; + HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["boolFalse"] = 1] = "boolFalse"; + HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["byte"] = 2] = "byte"; + HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["short"] = 3] = "short"; + HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["integer"] = 4] = "integer"; + HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["long"] = 5] = "long"; + HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["byteArray"] = 6] = "byteArray"; + HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["string"] = 7] = "string"; + HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["timestamp"] = 8] = "timestamp"; + HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["uuid"] = 9] = "uuid"; + })(HEADER_VALUE_TYPE || (HEADER_VALUE_TYPE = {})); + UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; + Int64 = class _Int64 { + bytes; + constructor(bytes) { + this.bytes = bytes; + if (bytes.byteLength !== 8) { + throw new Error("Int64 buffers must be exactly 8 bytes"); + } + } + static fromNumber(number) { + if (number > 9223372036854776e3 || number < -9223372036854776e3) { + throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); + } + const bytes = new Uint8Array(8); + for (let i2 = 7, remaining = Math.abs(Math.round(number)); i2 > -1 && remaining > 0; i2--, remaining /= 256) { + bytes[i2] = remaining; + } + if (number < 0) { + negate(bytes); + } + return new _Int64(bytes); + } + valueOf() { + const bytes = this.bytes.slice(0); + const negative = bytes[0] & 128; + if (negative) { + negate(bytes); + } + return parseInt(toHex(bytes), 16) * (negative ? -1 : 1); + } + toString() { + return String(this.valueOf()); + } + }; + } + }); + + // node_modules/@smithy/signature-v4/dist-es/headerUtil.js + var hasHeader; + var init_headerUtil = __esm({ + "node_modules/@smithy/signature-v4/dist-es/headerUtil.js"() { + hasHeader = (soughtHeader, headers) => { + soughtHeader = soughtHeader.toLowerCase(); + for (const headerName of Object.keys(headers)) { + if (soughtHeader === headerName.toLowerCase()) { + return true; + } + } + return false; + }; + } + }); + + // node_modules/@smithy/signature-v4/dist-es/moveHeadersToQuery.js + var moveHeadersToQuery; + var init_moveHeadersToQuery = __esm({ + "node_modules/@smithy/signature-v4/dist-es/moveHeadersToQuery.js"() { + init_dist_es4(); + moveHeadersToQuery = (request, options = {}) => { + const { headers, query = {} } = HttpRequest.clone(request); + for (const name of Object.keys(headers)) { + const lname = name.toLowerCase(); + if (lname.slice(0, 6) === "x-amz-" && !options.unhoistableHeaders?.has(lname) || options.hoistableHeaders?.has(lname)) { + query[name] = headers[name]; + delete headers[name]; + } + } + return { + ...request, + headers, + query + }; + }; + } + }); + + // node_modules/@smithy/signature-v4/dist-es/prepareRequest.js + var prepareRequest; + var init_prepareRequest = __esm({ + "node_modules/@smithy/signature-v4/dist-es/prepareRequest.js"() { + init_dist_es4(); + init_constants2(); + prepareRequest = (request) => { + request = HttpRequest.clone(request); + for (const headerName of Object.keys(request.headers)) { + if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) { + delete request.headers[headerName]; + } + } + return request; + }; + } + }); + + // node_modules/@smithy/signature-v4/dist-es/getCanonicalQuery.js + var getCanonicalQuery; + var init_getCanonicalQuery = __esm({ + "node_modules/@smithy/signature-v4/dist-es/getCanonicalQuery.js"() { + init_dist_es12(); + init_constants2(); + getCanonicalQuery = ({ query = {} }) => { + const keys = []; + const serialized = {}; + for (const key of Object.keys(query)) { + if (key.toLowerCase() === SIGNATURE_HEADER) { + continue; + } + const encodedKey = escapeUri(key); + keys.push(encodedKey); + const value = query[key]; + if (typeof value === "string") { + serialized[encodedKey] = `${encodedKey}=${escapeUri(value)}`; + } else if (Array.isArray(value)) { + serialized[encodedKey] = value.slice(0).reduce((encoded, value2) => encoded.concat([`${encodedKey}=${escapeUri(value2)}`]), []).sort().join("&"); + } + } + return keys.sort().map((key) => serialized[key]).filter((serialized2) => serialized2).join("&"); + }; + } + }); + + // node_modules/@smithy/signature-v4/dist-es/utilDate.js + var iso8601, toDate; + var init_utilDate = __esm({ + "node_modules/@smithy/signature-v4/dist-es/utilDate.js"() { + iso8601 = (time2) => toDate(time2).toISOString().replace(/\.\d{3}Z$/, "Z"); + toDate = (time2) => { + if (typeof time2 === "number") { + return new Date(time2 * 1e3); + } + if (typeof time2 === "string") { + if (Number(time2)) { + return new Date(Number(time2) * 1e3); + } + return new Date(time2); + } + return time2; + }; + } + }); + + // node_modules/@smithy/signature-v4/dist-es/SignatureV4Base.js + var SignatureV4Base; + var init_SignatureV4Base = __esm({ + "node_modules/@smithy/signature-v4/dist-es/SignatureV4Base.js"() { + init_dist_es15(); + init_dist_es8(); + init_dist_es12(); + init_dist_es10(); + init_getCanonicalQuery(); + init_utilDate(); + SignatureV4Base = class { + service; + regionProvider; + credentialProvider; + sha256; + uriEscapePath; + applyChecksum; + constructor({ applyChecksum, credentials, region: region2, service, sha256, uriEscapePath = true }) { + this.service = service; + this.sha256 = sha256; + this.uriEscapePath = uriEscapePath; + this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true; + this.regionProvider = normalizeProvider(region2); + this.credentialProvider = normalizeProvider(credentials); + } + createCanonicalRequest(request, canonicalHeaders, payloadHash) { + const sortedHeaders = Object.keys(canonicalHeaders).sort(); + return `${request.method} +${this.getCanonicalPath(request)} +${getCanonicalQuery(request)} +${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")} + +${sortedHeaders.join(";")} +${payloadHash}`; + } + async createStringToSign(longDate, credentialScope, canonicalRequest, algorithmIdentifier) { + const hash = new this.sha256(); + hash.update(toUint8Array(canonicalRequest)); + const hashedRequest = await hash.digest(); + return `${algorithmIdentifier} +${longDate} +${credentialScope} +${toHex(hashedRequest)}`; + } + getCanonicalPath({ path }) { + if (this.uriEscapePath) { + const normalizedPathSegments = []; + for (const pathSegment of path.split("/")) { + if (pathSegment?.length === 0) + continue; + if (pathSegment === ".") + continue; + if (pathSegment === "..") { + normalizedPathSegments.pop(); + } else { + normalizedPathSegments.push(pathSegment); + } + } + const normalizedPath = `${path?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path?.endsWith("/") ? "/" : ""}`; + const doubleEncoded = escapeUri(normalizedPath); + return doubleEncoded.replace(/%2F/g, "/"); + } + return path; + } + validateResolvedCredentials(credentials) { + if (typeof credentials !== "object" || typeof credentials.accessKeyId !== "string" || typeof credentials.secretAccessKey !== "string") { + throw new Error("Resolved credential object is not valid"); + } + } + formatDate(now2) { + const longDate = iso8601(now2).replace(/[\-:]/g, ""); + return { + longDate, + shortDate: longDate.slice(0, 8) + }; + } + getCanonicalHeaderList(headers) { + return Object.keys(headers).sort().join(";"); + } + }; + } + }); + + // node_modules/@smithy/signature-v4/dist-es/SignatureV4.js + var SignatureV4; + var init_SignatureV4 = __esm({ + "node_modules/@smithy/signature-v4/dist-es/SignatureV4.js"() { + init_dist_es15(); + init_dist_es10(); + init_constants2(); + init_credentialDerivation(); + init_getCanonicalHeaders(); + init_getPayloadHash(); + init_HeaderFormatter(); + init_headerUtil(); + init_moveHeadersToQuery(); + init_prepareRequest(); + init_SignatureV4Base(); + SignatureV4 = class extends SignatureV4Base { + headerFormatter = new HeaderFormatter(); + constructor({ applyChecksum, credentials, region: region2, service, sha256, uriEscapePath = true }) { + super({ + applyChecksum, + credentials, + region: region2, + service, + sha256, + uriEscapePath + }); + } + async presign(originalRequest, options = {}) { + const { signingDate = /* @__PURE__ */ new Date(), expiresIn = 3600, unsignableHeaders, unhoistableHeaders, signableHeaders, hoistableHeaders, signingRegion, signingService } = options; + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region2 = signingRegion ?? await this.regionProvider(); + const { longDate, shortDate } = this.formatDate(signingDate); + if (expiresIn > MAX_PRESIGNED_TTL) { + return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future"); + } + const scope = createScope(shortDate, region2, signingService ?? this.service); + const request = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders, hoistableHeaders }); + if (credentials.sessionToken) { + request.query[TOKEN_QUERY_PARAM] = credentials.sessionToken; + } + request.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER; + request.query[CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`; + request.query[AMZ_DATE_QUERY_PARAM] = longDate; + request.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10); + const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); + request.query[SIGNED_HEADERS_QUERY_PARAM] = this.getCanonicalHeaderList(canonicalHeaders); + request.query[SIGNATURE_QUERY_PARAM] = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region2, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256))); + return request; + } + async sign(toSign, options) { + if (typeof toSign === "string") { + return this.signString(toSign, options); + } else if (toSign.headers && toSign.payload) { + return this.signEvent(toSign, options); + } else if (toSign.message) { + return this.signMessage(toSign, options); + } else { + return this.signRequest(toSign, options); + } + } + async signEvent({ headers, payload }, { signingDate = /* @__PURE__ */ new Date(), priorSignature, signingRegion, signingService }) { + const region2 = signingRegion ?? await this.regionProvider(); + const { shortDate, longDate } = this.formatDate(signingDate); + const scope = createScope(shortDate, region2, signingService ?? this.service); + const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256); + const hash = new this.sha256(); + hash.update(headers); + const hashedHeaders = toHex(await hash.digest()); + const stringToSign = [ + EVENT_ALGORITHM_IDENTIFIER, + longDate, + scope, + priorSignature, + hashedHeaders, + hashedPayload + ].join("\n"); + return this.signString(stringToSign, { signingDate, signingRegion: region2, signingService }); + } + async signMessage(signableMessage, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService }) { + const promise = this.signEvent({ + headers: this.headerFormatter.format(signableMessage.message.headers), + payload: signableMessage.message.body + }, { + signingDate, + signingRegion, + signingService, + priorSignature: signableMessage.priorSignature + }); + return promise.then((signature) => { + return { message: signableMessage.message, signature }; + }); + } + async signString(stringToSign, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService } = {}) { + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region2 = signingRegion ?? await this.regionProvider(); + const { shortDate } = this.formatDate(signingDate); + const hash = new this.sha256(await this.getSigningKey(credentials, region2, shortDate, signingService)); + hash.update(toUint8Array(stringToSign)); + return toHex(await hash.digest()); + } + async signRequest(requestToSign, { signingDate = /* @__PURE__ */ new Date(), signableHeaders, unsignableHeaders, signingRegion, signingService } = {}) { + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region2 = signingRegion ?? await this.regionProvider(); + const request = prepareRequest(requestToSign); + const { longDate, shortDate } = this.formatDate(signingDate); + const scope = createScope(shortDate, region2, signingService ?? this.service); + request.headers[AMZ_DATE_HEADER] = longDate; + if (credentials.sessionToken) { + request.headers[TOKEN_HEADER] = credentials.sessionToken; + } + const payloadHash = await getPayloadHash(request, this.sha256); + if (!hasHeader(SHA256_HEADER, request.headers) && this.applyChecksum) { + request.headers[SHA256_HEADER] = payloadHash; + } + const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); + const signature = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region2, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, payloadHash)); + request.headers[AUTH_HEADER] = `${ALGORITHM_IDENTIFIER} Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${this.getCanonicalHeaderList(canonicalHeaders)}, Signature=${signature}`; + return request; + } + async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) { + const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest, ALGORITHM_IDENTIFIER); + const hash = new this.sha256(await keyPromise); + hash.update(toUint8Array(stringToSign)); + return toHex(await hash.digest()); + } + getSigningKey(credentials, region2, shortDate, service) { + return getSigningKey(this.sha256, credentials, shortDate, region2, service || this.service); + } + }; + } + }); + + // node_modules/@smithy/signature-v4/dist-es/signature-v4a-container.js + var init_signature_v4a_container = __esm({ + "node_modules/@smithy/signature-v4/dist-es/signature-v4a-container.js"() { + } + }); + + // node_modules/@smithy/signature-v4/dist-es/index.js + var init_dist_es24 = __esm({ + "node_modules/@smithy/signature-v4/dist-es/index.js"() { + init_SignatureV4(); + init_constants2(); + init_credentialDerivation(); + init_signature_v4a_container(); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js + function normalizeCredentialProvider(config, { credentials, credentialDefaultProvider }) { + let credentialsProvider; + if (credentials) { + if (!credentials?.memoized) { + credentialsProvider = memoizeIdentityProvider(credentials, isIdentityExpired, doesIdentityRequireRefresh); + } else { + credentialsProvider = credentials; + } + } else { + if (credentialDefaultProvider) { + credentialsProvider = normalizeProvider2(credentialDefaultProvider(Object.assign({}, config, { + parentClientConfig: config + }))); + } else { + credentialsProvider = async () => { + throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured."); + }; + } + } + credentialsProvider.memoized = true; + return credentialsProvider; + } + function bindCallerConfig(config, credentialsProvider) { + if (credentialsProvider.configBound) { + return credentialsProvider; + } + const fn = async (options) => credentialsProvider({ ...options, callerClientConfig: config }); + fn.memoized = credentialsProvider.memoized; + fn.configBound = true; + return fn; + } + var resolveAwsSdkSigV4Config; + var init_resolveAwsSdkSigV4Config = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js"() { + init_client2(); + init_dist_es18(); + init_dist_es24(); + resolveAwsSdkSigV4Config = (config) => { + let inputCredentials = config.credentials; + let isUserSupplied = !!config.credentials; + let resolvedCredentials = void 0; + Object.defineProperty(config, "credentials", { + set(credentials) { + if (credentials && credentials !== inputCredentials && credentials !== resolvedCredentials) { + isUserSupplied = true; + } + inputCredentials = credentials; + const memoizedProvider = normalizeCredentialProvider(config, { + credentials: inputCredentials, + credentialDefaultProvider: config.credentialDefaultProvider + }); + const boundProvider = bindCallerConfig(config, memoizedProvider); + if (isUserSupplied && !boundProvider.attributed) { + resolvedCredentials = async (options) => boundProvider(options).then((creds) => setCredentialFeature(creds, "CREDENTIALS_CODE", "e")); + resolvedCredentials.memoized = boundProvider.memoized; + resolvedCredentials.configBound = boundProvider.configBound; + resolvedCredentials.attributed = true; + } else { + resolvedCredentials = boundProvider; + } + }, + get() { + return resolvedCredentials; + }, + enumerable: true, + configurable: true + }); + config.credentials = inputCredentials; + const { signingEscapePath = true, systemClockOffset = config.systemClockOffset || 0, sha256 } = config; + let signer; + if (config.signer) { + signer = normalizeProvider2(config.signer); + } else if (config.regionInfoProvider) { + signer = () => normalizeProvider2(config.region)().then(async (region2) => [ + await config.regionInfoProvider(region2, { + useFipsEndpoint: await config.useFipsEndpoint(), + useDualstackEndpoint: await config.useDualstackEndpoint() + }) || {}, + region2 + ]).then(([regionInfo, region2]) => { + const { signingRegion, signingService } = regionInfo; + config.signingRegion = config.signingRegion || signingRegion || region2; + config.signingName = config.signingName || signingService || config.serviceId; + const params = { + ...config, + credentials: config.credentials, + region: config.signingRegion, + service: config.signingName, + sha256, + uriEscapePath: signingEscapePath + }; + const SignerCtor = config.signerConstructor || SignatureV4; + return new SignerCtor(params); + }); + } else { + signer = async (authScheme) => { + authScheme = Object.assign({}, { + name: "sigv4", + signingName: config.signingName || config.defaultSigningName, + signingRegion: await normalizeProvider2(config.region)(), + properties: {} + }, authScheme); + const signingRegion = authScheme.signingRegion; + const signingService = authScheme.signingName; + config.signingRegion = config.signingRegion || signingRegion; + config.signingName = config.signingName || signingService || config.serviceId; + const params = { + ...config, + credentials: config.credentials, + region: config.signingRegion, + service: config.signingName, + sha256, + uriEscapePath: signingEscapePath + }; + const SignerCtor = config.signerConstructor || SignatureV4; + return new SignerCtor(params); + }; + } + const resolvedConfig = Object.assign(config, { + systemClockOffset, + signingEscapePath, + signer + }); + return resolvedConfig; + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/index.js + var init_aws_sdk = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/index.js"() { + init_AwsSdkSigV4Signer(); + init_NODE_AUTH_SCHEME_PREFERENCE_OPTIONS(); + init_resolveAwsSdkSigV4AConfig(); + init_resolveAwsSdkSigV4Config(); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/index.js + var init_httpAuthSchemes2 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/index.js"() { + init_aws_sdk(); + init_getBearerTokenEnvKey(); + } + }); + + // node_modules/@smithy/util-body-length-browser/dist-es/calculateBodyLength.js + var TEXT_ENCODER, calculateBodyLength; + var init_calculateBodyLength = __esm({ + "node_modules/@smithy/util-body-length-browser/dist-es/calculateBodyLength.js"() { + TEXT_ENCODER = typeof TextEncoder == "function" ? new TextEncoder() : null; + calculateBodyLength = (body) => { + if (typeof body === "string") { + if (TEXT_ENCODER) { + return TEXT_ENCODER.encode(body).byteLength; + } + let len = body.length; + for (let i2 = len - 1; i2 >= 0; i2--) { + const code = body.charCodeAt(i2); + if (code > 127 && code <= 2047) + len++; + else if (code > 2047 && code <= 65535) + len += 2; + if (code >= 56320 && code <= 57343) + i2--; + } + return len; + } else if (typeof body.byteLength === "number") { + return body.byteLength; + } else if (typeof body.size === "number") { + return body.size; + } + throw new Error(`Body Length computation failed for ${body}`); + }; + } + }); + + // node_modules/@smithy/util-body-length-browser/dist-es/index.js + var init_dist_es25 = __esm({ + "node_modules/@smithy/util-body-length-browser/dist-es/index.js"() { + init_calculateBodyLength(); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/cbor/AwsSmithyRpcV2CborProtocol.js + var init_AwsSmithyRpcV2CborProtocol = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/cbor/AwsSmithyRpcV2CborProtocol.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/coercing-serializers.js + var init_coercing_serializers = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/coercing-serializers.js"() { + } + }); + + // node_modules/@smithy/middleware-stack/dist-es/MiddlewareStack.js + var getAllAliases, getMiddlewareNameWithAliases, constructStack, stepWeights, priorityWeights; + var init_MiddlewareStack = __esm({ + "node_modules/@smithy/middleware-stack/dist-es/MiddlewareStack.js"() { + getAllAliases = (name, aliases) => { + const _aliases = []; + if (name) { + _aliases.push(name); + } + if (aliases) { + for (const alias of aliases) { + _aliases.push(alias); + } + } + return _aliases; + }; + getMiddlewareNameWithAliases = (name, aliases) => { + return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`; + }; + constructStack = () => { + let absoluteEntries = []; + let relativeEntries = []; + let identifyOnResolve = false; + const entriesNameSet = /* @__PURE__ */ new Set(); + const sort = (entries2) => entries2.sort((a2, b3) => stepWeights[b3.step] - stepWeights[a2.step] || priorityWeights[b3.priority || "normal"] - priorityWeights[a2.priority || "normal"]); + const removeByName = (toRemove) => { + let isRemoved = false; + const filterCb = (entry) => { + const aliases = getAllAliases(entry.name, entry.aliases); + if (aliases.includes(toRemove)) { + isRemoved = true; + for (const alias of aliases) { + entriesNameSet.delete(alias); + } + return false; + } + return true; + }; + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }; + const removeByReference = (toRemove) => { + let isRemoved = false; + const filterCb = (entry) => { + if (entry.middleware === toRemove) { + isRemoved = true; + for (const alias of getAllAliases(entry.name, entry.aliases)) { + entriesNameSet.delete(alias); + } + return false; + } + return true; + }; + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }; + const cloneTo = (toStack) => { + absoluteEntries.forEach((entry) => { + toStack.add(entry.middleware, { ...entry }); + }); + relativeEntries.forEach((entry) => { + toStack.addRelativeTo(entry.middleware, { ...entry }); + }); + toStack.identifyOnResolve?.(stack.identifyOnResolve()); + return toStack; + }; + const expandRelativeMiddlewareList = (from) => { + const expandedMiddlewareList = []; + from.before.forEach((entry) => { + if (entry.before.length === 0 && entry.after.length === 0) { + expandedMiddlewareList.push(entry); + } else { + expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); + } + }); + expandedMiddlewareList.push(from); + from.after.reverse().forEach((entry) => { + if (entry.before.length === 0 && entry.after.length === 0) { + expandedMiddlewareList.push(entry); + } else { + expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); + } + }); + return expandedMiddlewareList; + }; + const getMiddlewareList = (debug = false) => { + const normalizedAbsoluteEntries = []; + const normalizedRelativeEntries = []; + const normalizedEntriesNameMap = {}; + absoluteEntries.forEach((entry) => { + const normalizedEntry = { + ...entry, + before: [], + after: [] + }; + for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { + normalizedEntriesNameMap[alias] = normalizedEntry; + } + normalizedAbsoluteEntries.push(normalizedEntry); + }); + relativeEntries.forEach((entry) => { + const normalizedEntry = { + ...entry, + before: [], + after: [] + }; + for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { + normalizedEntriesNameMap[alias] = normalizedEntry; + } + normalizedRelativeEntries.push(normalizedEntry); + }); + normalizedRelativeEntries.forEach((entry) => { + if (entry.toMiddleware) { + const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware]; + if (toMiddleware === void 0) { + if (debug) { + return; + } + throw new Error(`${entry.toMiddleware} is not found when adding ${getMiddlewareNameWithAliases(entry.name, entry.aliases)} middleware ${entry.relation} ${entry.toMiddleware}`); + } + if (entry.relation === "after") { + toMiddleware.after.push(entry); + } + if (entry.relation === "before") { + toMiddleware.before.push(entry); + } + } + }); + const mainChain = sort(normalizedAbsoluteEntries).map(expandRelativeMiddlewareList).reduce((wholeList, expandedMiddlewareList) => { + wholeList.push(...expandedMiddlewareList); + return wholeList; + }, []); + return mainChain; + }; + const stack = { + add: (middleware, options = {}) => { + const { name, override, aliases: _aliases } = options; + const entry = { + step: "initialize", + priority: "normal", + middleware, + ...options + }; + const aliases = getAllAliases(name, _aliases); + if (aliases.length > 0) { + if (aliases.some((alias) => entriesNameSet.has(alias))) { + if (!override) + throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); + for (const alias of aliases) { + const toOverrideIndex = absoluteEntries.findIndex((entry2) => entry2.name === alias || entry2.aliases?.some((a2) => a2 === alias)); + if (toOverrideIndex === -1) { + continue; + } + const toOverride = absoluteEntries[toOverrideIndex]; + if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) { + throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ${toOverride.priority} priority in ${toOverride.step} step cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware with ${entry.priority} priority in ${entry.step} step.`); + } + absoluteEntries.splice(toOverrideIndex, 1); + } + } + for (const alias of aliases) { + entriesNameSet.add(alias); + } + } + absoluteEntries.push(entry); + }, + addRelativeTo: (middleware, options) => { + const { name, override, aliases: _aliases } = options; + const entry = { + middleware, + ...options + }; + const aliases = getAllAliases(name, _aliases); + if (aliases.length > 0) { + if (aliases.some((alias) => entriesNameSet.has(alias))) { + if (!override) + throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); + for (const alias of aliases) { + const toOverrideIndex = relativeEntries.findIndex((entry2) => entry2.name === alias || entry2.aliases?.some((a2) => a2 === alias)); + if (toOverrideIndex === -1) { + continue; + } + const toOverride = relativeEntries[toOverrideIndex]; + if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) { + throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware ${entry.relation} "${entry.toMiddleware}" middleware.`); + } + relativeEntries.splice(toOverrideIndex, 1); + } + } + for (const alias of aliases) { + entriesNameSet.add(alias); + } + } + relativeEntries.push(entry); + }, + clone: () => cloneTo(constructStack()), + use: (plugin) => { + plugin.applyToStack(stack); + }, + remove: (toRemove) => { + if (typeof toRemove === "string") + return removeByName(toRemove); + else + return removeByReference(toRemove); + }, + removeByTag: (toRemove) => { + let isRemoved = false; + const filterCb = (entry) => { + const { tags, name, aliases: _aliases } = entry; + if (tags && tags.includes(toRemove)) { + const aliases = getAllAliases(name, _aliases); + for (const alias of aliases) { + entriesNameSet.delete(alias); + } + isRemoved = true; + return false; + } + return true; + }; + absoluteEntries = absoluteEntries.filter(filterCb); + relativeEntries = relativeEntries.filter(filterCb); + return isRemoved; + }, + concat: (from) => { + const cloned = cloneTo(constructStack()); + cloned.use(from); + cloned.identifyOnResolve(identifyOnResolve || cloned.identifyOnResolve() || (from.identifyOnResolve?.() ?? false)); + return cloned; + }, + applyToStack: cloneTo, + identify: () => { + return getMiddlewareList(true).map((mw) => { + const step = mw.step ?? mw.relation + " " + mw.toMiddleware; + return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step; + }); + }, + identifyOnResolve(toggle) { + if (typeof toggle === "boolean") + identifyOnResolve = toggle; + return identifyOnResolve; + }, + resolve: (handler, context) => { + for (const middleware of getMiddlewareList().map((entry) => entry.middleware).reverse()) { + handler = middleware(handler, context); + } + if (identifyOnResolve) { + console.log(stack.identify()); + } + return handler; + } + }; + return stack; + }; + stepWeights = { + initialize: 5, + serialize: 4, + build: 3, + finalizeRequest: 2, + deserialize: 1 + }; + priorityWeights = { + high: 3, + normal: 2, + low: 1 + }; + } + }); + + // node_modules/@smithy/middleware-stack/dist-es/index.js + var init_dist_es26 = __esm({ + "node_modules/@smithy/middleware-stack/dist-es/index.js"() { + init_MiddlewareStack(); + } + }); + + // node_modules/@smithy/smithy-client/dist-es/client.js + var Client2; + var init_client3 = __esm({ + "node_modules/@smithy/smithy-client/dist-es/client.js"() { + init_dist_es26(); + Client2 = class { + config; + middlewareStack = constructStack(); + initConfig; + handlers; + constructor(config) { + this.config = config; + } + send(command, optionsOrCb, cb) { + const options = typeof optionsOrCb !== "function" ? optionsOrCb : void 0; + const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb; + const useHandlerCache = options === void 0 && this.config.cacheMiddleware === true; + let handler; + if (useHandlerCache) { + if (!this.handlers) { + this.handlers = /* @__PURE__ */ new WeakMap(); + } + const handlers = this.handlers; + if (handlers.has(command.constructor)) { + handler = handlers.get(command.constructor); + } else { + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + handlers.set(command.constructor, handler); + } + } else { + delete this.handlers; + handler = command.resolveMiddleware(this.middlewareStack, this.config, options); + } + if (callback) { + handler(command).then((result) => callback(null, result.output), (err) => callback(err)).catch(() => { + }); + } else { + return handler(command).then((result) => result.output); + } + } + destroy() { + this.config?.requestHandler?.destroy?.(); + delete this.handlers; + } + }; + } + }); + + // node_modules/@smithy/smithy-client/dist-es/collect-stream-body.js + var init_collect_stream_body2 = __esm({ + "node_modules/@smithy/smithy-client/dist-es/collect-stream-body.js"() { + init_protocols(); + } + }); + + // node_modules/@smithy/smithy-client/dist-es/schemaLogFilter.js + function schemaLogFilter(schema4, data) { + if (data == null) { + return data; + } + const ns = NormalizedSchema.of(schema4); + if (ns.getMergedTraits().sensitive) { + return SENSITIVE_STRING; + } + if (ns.isListSchema()) { + const isSensitive = !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING; + } + } else if (ns.isMapSchema()) { + const isSensitive = !!ns.getKeySchema().getMergedTraits().sensitive || !!ns.getValueSchema().getMergedTraits().sensitive; + if (isSensitive) { + return SENSITIVE_STRING; + } + } else if (ns.isStructSchema() && typeof data === "object") { + const object = data; + const newObject = {}; + for (const [member, memberNs] of ns.structIterator()) { + if (object[member] != null) { + newObject[member] = schemaLogFilter(memberNs, object[member]); + } + } + return newObject; + } + return data; + } + var SENSITIVE_STRING; + var init_schemaLogFilter = __esm({ + "node_modules/@smithy/smithy-client/dist-es/schemaLogFilter.js"() { + init_schema2(); + SENSITIVE_STRING = "***SensitiveInformation***"; + } + }); + + // node_modules/@smithy/smithy-client/dist-es/command.js + var Command2, ClassBuilder; + var init_command2 = __esm({ + "node_modules/@smithy/smithy-client/dist-es/command.js"() { + init_dist_es26(); + init_dist_es3(); + init_schemaLogFilter(); + Command2 = class { + middlewareStack = constructStack(); + schema; + static classBuilder() { + return new ClassBuilder(); + } + resolveMiddlewareWithContext(clientStack, configuration, options, { middlewareFn, clientName, commandName, inputFilterSensitiveLog, outputFilterSensitiveLog, smithyContext, additionalContext, CommandCtor }) { + for (const mw of middlewareFn.bind(this)(CommandCtor, clientStack, configuration, options)) { + this.middlewareStack.use(mw); + } + const stack = clientStack.concat(this.middlewareStack); + const { logger: logger2 } = configuration; + const handlerExecutionContext = { + logger: logger2, + clientName, + commandName, + inputFilterSensitiveLog, + outputFilterSensitiveLog, + [SMITHY_CONTEXT_KEY]: { + commandInstance: this, + ...smithyContext + }, + ...additionalContext + }; + const { requestHandler } = configuration; + return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); + } + }; + ClassBuilder = class { + _init = () => { + }; + _ep = {}; + _middlewareFn = () => []; + _commandName = ""; + _clientName = ""; + _additionalContext = {}; + _smithyContext = {}; + _inputFilterSensitiveLog = void 0; + _outputFilterSensitiveLog = void 0; + _serializer = null; + _deserializer = null; + _operationSchema; + init(cb) { + this._init = cb; + } + ep(endpointParameterInstructions) { + this._ep = endpointParameterInstructions; + return this; + } + m(middlewareSupplier) { + this._middlewareFn = middlewareSupplier; + return this; + } + s(service, operation, smithyContext = {}) { + this._smithyContext = { + service, + operation, + ...smithyContext + }; + return this; + } + c(additionalContext = {}) { + this._additionalContext = additionalContext; + return this; + } + n(clientName, commandName) { + this._clientName = clientName; + this._commandName = commandName; + return this; + } + f(inputFilter = (_2) => _2, outputFilter = (_2) => _2) { + this._inputFilterSensitiveLog = inputFilter; + this._outputFilterSensitiveLog = outputFilter; + return this; + } + ser(serializer) { + this._serializer = serializer; + return this; + } + de(deserializer) { + this._deserializer = deserializer; + return this; + } + sc(operation) { + this._operationSchema = operation; + this._smithyContext.operationSchema = operation; + return this; + } + build() { + const closure = this; + let CommandRef; + return CommandRef = class extends Command2 { + input; + static getEndpointParameterInstructions() { + return closure._ep; + } + constructor(...[input]) { + super(); + this.input = input ?? {}; + closure._init(this); + this.schema = closure._operationSchema; + } + resolveMiddleware(stack, configuration, options) { + return this.resolveMiddlewareWithContext(stack, configuration, options, { + CommandCtor: CommandRef, + middlewareFn: closure._middlewareFn, + clientName: closure._clientName, + commandName: closure._commandName, + inputFilterSensitiveLog: closure._inputFilterSensitiveLog ?? (closure._operationSchema ? schemaLogFilter.bind(null, closure._operationSchema.input) : (_2) => _2), + outputFilterSensitiveLog: closure._outputFilterSensitiveLog ?? (closure._operationSchema ? schemaLogFilter.bind(null, closure._operationSchema.output) : (_2) => _2), + smithyContext: closure._smithyContext, + additionalContext: closure._additionalContext + }); + } + serialize = closure._serializer; + deserialize = closure._deserializer; + }; + } + }; + } + }); + + // node_modules/@smithy/smithy-client/dist-es/constants.js + var SENSITIVE_STRING2; + var init_constants3 = __esm({ + "node_modules/@smithy/smithy-client/dist-es/constants.js"() { + SENSITIVE_STRING2 = "***SensitiveInformation***"; + } + }); + + // node_modules/@smithy/smithy-client/dist-es/create-aggregated-client.js + var createAggregatedClient; + var init_create_aggregated_client = __esm({ + "node_modules/@smithy/smithy-client/dist-es/create-aggregated-client.js"() { + createAggregatedClient = (commands2, Client3) => { + for (const command of Object.keys(commands2)) { + const CommandCtor = commands2[command]; + const methodImpl = async function(args, optionsOrCb, cb) { + const command2 = new CommandCtor(args); + if (typeof optionsOrCb === "function") { + this.send(command2, optionsOrCb); + } else if (typeof cb === "function") { + if (typeof optionsOrCb !== "object") + throw new Error(`Expected http options but got ${typeof optionsOrCb}`); + this.send(command2, optionsOrCb || {}, cb); + } else { + return this.send(command2, optionsOrCb); + } + }; + const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); + Client3.prototype[methodName] = methodImpl; + } + }; + } + }); + + // node_modules/@smithy/smithy-client/dist-es/exceptions.js + var ServiceException, decorateServiceException; + var init_exceptions = __esm({ + "node_modules/@smithy/smithy-client/dist-es/exceptions.js"() { + ServiceException = class _ServiceException extends Error { + $fault; + $response; + $retryable; + $metadata; + constructor(options) { + super(options.message); + Object.setPrototypeOf(this, Object.getPrototypeOf(this).constructor.prototype); + this.name = options.name; + this.$fault = options.$fault; + this.$metadata = options.$metadata; + } + static isInstance(value) { + if (!value) + return false; + const candidate = value; + return _ServiceException.prototype.isPrototypeOf(candidate) || Boolean(candidate.$fault) && Boolean(candidate.$metadata) && (candidate.$fault === "client" || candidate.$fault === "server"); + } + static [Symbol.hasInstance](instance) { + if (!instance) + return false; + const candidate = instance; + if (this === _ServiceException) { + return _ServiceException.isInstance(instance); + } + if (_ServiceException.isInstance(instance)) { + if (candidate.name && this.name) { + return this.prototype.isPrototypeOf(instance) || candidate.name === this.name; + } + return this.prototype.isPrototypeOf(instance); + } + return false; + } + }; + decorateServiceException = (exception, additions = {}) => { + Object.entries(additions).filter(([, v6]) => v6 !== void 0).forEach(([k3, v6]) => { + if (exception[k3] == void 0 || exception[k3] === "") { + exception[k3] = v6; + } + }); + const message = exception.message || exception.Message || "UnknownError"; + exception.message = message; + delete exception.Message; + return exception; + }; + } + }); + + // node_modules/@smithy/smithy-client/dist-es/default-error-handler.js + var throwDefaultError, withBaseException, deserializeMetadata; + var init_default_error_handler = __esm({ + "node_modules/@smithy/smithy-client/dist-es/default-error-handler.js"() { + init_exceptions(); + throwDefaultError = ({ output, parsedBody, exceptionCtor, errorCode }) => { + const $metadata = deserializeMetadata(output); + const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : void 0; + const response = new exceptionCtor({ + name: parsedBody?.code || parsedBody?.Code || errorCode || statusCode || "UnknownError", + $fault: "client", + $metadata + }); + throw decorateServiceException(response, parsedBody); + }; + withBaseException = (ExceptionCtor) => { + return ({ output, parsedBody, errorCode }) => { + throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode }); + }; + }; + deserializeMetadata = (output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"] + }); + } + }); + + // node_modules/@smithy/smithy-client/dist-es/defaults-mode.js + var loadConfigsForDefaultMode; + var init_defaults_mode = __esm({ + "node_modules/@smithy/smithy-client/dist-es/defaults-mode.js"() { + loadConfigsForDefaultMode = (mode) => { + switch (mode) { + case "standard": + return { + retryMode: "standard", + connectionTimeout: 3100 + }; + case "in-region": + return { + retryMode: "standard", + connectionTimeout: 1100 + }; + case "cross-region": + return { + retryMode: "standard", + connectionTimeout: 3100 + }; + case "mobile": + return { + retryMode: "standard", + connectionTimeout: 3e4 + }; + default: + return {}; + } + }; + } + }); + + // node_modules/@smithy/smithy-client/dist-es/emitWarningIfUnsupportedVersion.js + var init_emitWarningIfUnsupportedVersion2 = __esm({ + "node_modules/@smithy/smithy-client/dist-es/emitWarningIfUnsupportedVersion.js"() { + } + }); + + // node_modules/@smithy/smithy-client/dist-es/extended-encode-uri-component.js + var init_extended_encode_uri_component2 = __esm({ + "node_modules/@smithy/smithy-client/dist-es/extended-encode-uri-component.js"() { + } + }); + + // node_modules/@smithy/smithy-client/dist-es/extensions/checksum.js + var getChecksumConfiguration, resolveChecksumRuntimeConfig; + var init_checksum3 = __esm({ + "node_modules/@smithy/smithy-client/dist-es/extensions/checksum.js"() { + init_dist_es3(); + getChecksumConfiguration = (runtimeConfig) => { + const checksumAlgorithms = []; + for (const id in AlgorithmId) { + const algorithmId = AlgorithmId[id]; + if (runtimeConfig[algorithmId] === void 0) { + continue; + } + checksumAlgorithms.push({ + algorithmId: () => algorithmId, + checksumConstructor: () => runtimeConfig[algorithmId] + }); + } + return { + addChecksumAlgorithm(algo) { + checksumAlgorithms.push(algo); + }, + checksumAlgorithms() { + return checksumAlgorithms; + } + }; + }; + resolveChecksumRuntimeConfig = (clientConfig) => { + const runtimeConfig = {}; + clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { + runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); + }); + return runtimeConfig; + }; + } + }); + + // node_modules/@smithy/smithy-client/dist-es/extensions/retry.js + var getRetryConfiguration, resolveRetryRuntimeConfig; + var init_retry2 = __esm({ + "node_modules/@smithy/smithy-client/dist-es/extensions/retry.js"() { + getRetryConfiguration = (runtimeConfig) => { + return { + setRetryStrategy(retryStrategy) { + runtimeConfig.retryStrategy = retryStrategy; + }, + retryStrategy() { + return runtimeConfig.retryStrategy; + } + }; + }; + resolveRetryRuntimeConfig = (retryStrategyConfiguration) => { + const runtimeConfig = {}; + runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy(); + return runtimeConfig; + }; + } + }); + + // node_modules/@smithy/smithy-client/dist-es/extensions/defaultExtensionConfiguration.js + var getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig; + var init_defaultExtensionConfiguration2 = __esm({ + "node_modules/@smithy/smithy-client/dist-es/extensions/defaultExtensionConfiguration.js"() { + init_checksum3(); + init_retry2(); + getDefaultExtensionConfiguration = (runtimeConfig) => { + return Object.assign(getChecksumConfiguration(runtimeConfig), getRetryConfiguration(runtimeConfig)); + }; + resolveDefaultRuntimeConfig = (config) => { + return Object.assign(resolveChecksumRuntimeConfig(config), resolveRetryRuntimeConfig(config)); + }; + } + }); + + // node_modules/@smithy/smithy-client/dist-es/extensions/index.js + var init_extensions3 = __esm({ + "node_modules/@smithy/smithy-client/dist-es/extensions/index.js"() { + init_defaultExtensionConfiguration2(); + } + }); + + // node_modules/@smithy/smithy-client/dist-es/get-array-if-single-item.js + var init_get_array_if_single_item = __esm({ + "node_modules/@smithy/smithy-client/dist-es/get-array-if-single-item.js"() { + } + }); + + // node_modules/@smithy/smithy-client/dist-es/get-value-from-text-node.js + var init_get_value_from_text_node = __esm({ + "node_modules/@smithy/smithy-client/dist-es/get-value-from-text-node.js"() { + } + }); + + // node_modules/@smithy/smithy-client/dist-es/is-serializable-header-value.js + var init_is_serializable_header_value = __esm({ + "node_modules/@smithy/smithy-client/dist-es/is-serializable-header-value.js"() { + } + }); + + // node_modules/@smithy/smithy-client/dist-es/NoOpLogger.js + var NoOpLogger; + var init_NoOpLogger = __esm({ + "node_modules/@smithy/smithy-client/dist-es/NoOpLogger.js"() { + NoOpLogger = class { + trace() { + } + debug() { + } + info() { + } + warn() { + } + error() { + } + }; + } + }); + + // node_modules/@smithy/smithy-client/dist-es/object-mapping.js + var take, applyInstruction, nonNullish, pass; + var init_object_mapping = __esm({ + "node_modules/@smithy/smithy-client/dist-es/object-mapping.js"() { + take = (source, instructions) => { + const out = {}; + for (const key in instructions) { + applyInstruction(out, source, instructions, key); + } + return out; + }; + applyInstruction = (target, source, instructions, targetKey) => { + if (source !== null) { + let instruction = instructions[targetKey]; + if (typeof instruction === "function") { + instruction = [, instruction]; + } + const [filter2 = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction; + if (typeof filter2 === "function" && filter2(source[sourceKey]) || typeof filter2 !== "function" && !!filter2) { + target[targetKey] = valueFn(source[sourceKey]); + } + return; + } + let [filter, value] = instructions[targetKey]; + if (typeof value === "function") { + let _value; + const defaultFilterPassed = filter === void 0 && (_value = value()) != null; + const customFilterPassed = typeof filter === "function" && !!filter(void 0) || typeof filter !== "function" && !!filter; + if (defaultFilterPassed) { + target[targetKey] = _value; + } else if (customFilterPassed) { + target[targetKey] = value(); + } + } else { + const defaultFilterPassed = filter === void 0 && value != null; + const customFilterPassed = typeof filter === "function" && !!filter(value) || typeof filter !== "function" && !!filter; + if (defaultFilterPassed || customFilterPassed) { + target[targetKey] = value; + } + } + }; + nonNullish = (_2) => _2 != null; + pass = (_2) => _2; + } + }); + + // node_modules/@smithy/smithy-client/dist-es/resolve-path.js + var init_resolve_path2 = __esm({ + "node_modules/@smithy/smithy-client/dist-es/resolve-path.js"() { + } + }); + + // node_modules/@smithy/smithy-client/dist-es/ser-utils.js + var init_ser_utils = __esm({ + "node_modules/@smithy/smithy-client/dist-es/ser-utils.js"() { + } + }); + + // node_modules/@smithy/smithy-client/dist-es/serde-json.js + var _json; + var init_serde_json = __esm({ + "node_modules/@smithy/smithy-client/dist-es/serde-json.js"() { + _json = (obj) => { + if (obj == null) { + return {}; + } + if (Array.isArray(obj)) { + return obj.filter((_2) => _2 != null).map(_json); + } + if (typeof obj === "object") { + const target = {}; + for (const key of Object.keys(obj)) { + if (obj[key] == null) { + continue; + } + target[key] = _json(obj[key]); + } + return target; + } + return obj; + }; + } + }); + + // node_modules/@smithy/smithy-client/dist-es/index.js + var init_dist_es27 = __esm({ + "node_modules/@smithy/smithy-client/dist-es/index.js"() { + init_client3(); + init_collect_stream_body2(); + init_command2(); + init_constants3(); + init_create_aggregated_client(); + init_default_error_handler(); + init_defaults_mode(); + init_emitWarningIfUnsupportedVersion2(); + init_exceptions(); + init_extended_encode_uri_component2(); + init_extensions3(); + init_get_array_if_single_item(); + init_get_value_from_text_node(); + init_is_serializable_header_value(); + init_NoOpLogger(); + init_object_mapping(); + init_resolve_path2(); + init_ser_utils(); + init_serde_json(); + init_serde2(); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js + var collectBodyString; + var init_common = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js"() { + init_dist_es27(); + init_dist_es10(); + collectBodyString = (streamBody, context) => collectBody(streamBody, context).then((body) => (context?.utf8Encoder ?? toUtf8)(body)); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js + var parseJsonBody, parseJsonErrorBody, loadRestJsonErrorCode; + var init_parseJsonBody = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js"() { + init_common(); + parseJsonBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { + if (encoded.length) { + try { + return JSON.parse(encoded); + } catch (e2) { + if (e2?.name === "SyntaxError") { + Object.defineProperty(e2, "$responseBodyText", { + value: encoded + }); + } + throw e2; + } + } + return {}; + }); + parseJsonErrorBody = async (errorBody, context) => { + const value = await parseJsonBody(errorBody, context); + value.message = value.message ?? value.Message; + return value; + }; + loadRestJsonErrorCode = (output, data) => { + const findKey = (object, key) => Object.keys(object).find((k3) => k3.toLowerCase() === key.toLowerCase()); + const sanitizeErrorCode = (rawValue) => { + let cleanValue = rawValue; + if (typeof cleanValue === "number") { + cleanValue = cleanValue.toString(); + } + if (cleanValue.indexOf(",") >= 0) { + cleanValue = cleanValue.split(",")[0]; + } + if (cleanValue.indexOf(":") >= 0) { + cleanValue = cleanValue.split(":")[0]; + } + if (cleanValue.indexOf("#") >= 0) { + cleanValue = cleanValue.split("#")[1]; + } + return cleanValue; + }; + const headerKey = findKey(output.headers, "x-amzn-errortype"); + if (headerKey !== void 0) { + return sanitizeErrorCode(output.headers[headerKey]); + } + if (data && typeof data === "object") { + const codeKey = findKey(data, "code"); + if (codeKey && data[codeKey] !== void 0) { + return sanitizeErrorCode(data[codeKey]); + } + if (data["__type"] !== void 0) { + return sanitizeErrorCode(data["__type"]); + } + } + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonShapeDeserializer.js + var init_JsonShapeDeserializer = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonShapeDeserializer.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonShapeSerializer.js + var init_JsonShapeSerializer = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonShapeSerializer.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonCodec.js + var init_JsonCodec = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonCodec.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJsonRpcProtocol.js + var init_AwsJsonRpcProtocol = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJsonRpcProtocol.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJson1_0Protocol.js + var init_AwsJson1_0Protocol = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJson1_0Protocol.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJson1_1Protocol.js + var init_AwsJson1_1Protocol = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJson1_1Protocol.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsRestJsonProtocol.js + var init_AwsRestJsonProtocol = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsRestJsonProtocol.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/awsExpectUnion.js + var init_awsExpectUnion = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/awsExpectUnion.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlShapeDeserializer.js + var init_XmlShapeDeserializer = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlShapeDeserializer.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/AwsQueryProtocol.js + var init_AwsQueryProtocol = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/AwsQueryProtocol.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/AwsEc2QueryProtocol.js + var init_AwsEc2QueryProtocol = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/AwsEc2QueryProtocol.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/parseXmlBody.js + var init_parseXmlBody = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/parseXmlBody.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlShapeSerializer.js + var init_XmlShapeSerializer = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlShapeSerializer.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlCodec.js + var init_XmlCodec = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlCodec.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/AwsRestXmlProtocol.js + var init_AwsRestXmlProtocol = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/AwsRestXmlProtocol.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/index.js + var init_protocols2 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/submodules/protocols/index.js"() { + init_AwsSmithyRpcV2CborProtocol(); + init_coercing_serializers(); + init_AwsJson1_0Protocol(); + init_AwsJson1_1Protocol(); + init_AwsJsonRpcProtocol(); + init_AwsRestJsonProtocol(); + init_JsonCodec(); + init_JsonShapeDeserializer(); + init_JsonShapeSerializer(); + init_awsExpectUnion(); + init_parseJsonBody(); + init_AwsEc2QueryProtocol(); + init_AwsQueryProtocol(); + init_AwsRestXmlProtocol(); + init_XmlCodec(); + init_XmlShapeDeserializer(); + init_XmlShapeSerializer(); + init_parseXmlBody(); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/index.js + var init_dist_es28 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core/dist-es/index.js"() { + init_client2(); + init_httpAuthSchemes2(); + init_protocols2(); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-user-agent/dist-es/check-features.js + async function checkFeatures(context, config, args) { + const request = args.request; + if (request?.headers?.["smithy-protocol"] === "rpc-v2-cbor") { + setFeature2(context, "PROTOCOL_RPC_V2_CBOR", "M"); + } + if (typeof config.retryStrategy === "function") { + const retryStrategy = await config.retryStrategy(); + if (typeof retryStrategy.acquireInitialRetryToken === "function") { + if (retryStrategy.constructor?.name?.includes("Adaptive")) { + setFeature2(context, "RETRY_MODE_ADAPTIVE", "F"); + } else { + setFeature2(context, "RETRY_MODE_STANDARD", "E"); + } + } else { + setFeature2(context, "RETRY_MODE_LEGACY", "D"); + } + } + if (typeof config.accountIdEndpointMode === "function") { + const endpointV2 = context.endpointV2; + if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) { + setFeature2(context, "ACCOUNT_ID_ENDPOINT", "O"); + } + switch (await config.accountIdEndpointMode?.()) { + case "disabled": + setFeature2(context, "ACCOUNT_ID_MODE_DISABLED", "Q"); + break; + case "preferred": + setFeature2(context, "ACCOUNT_ID_MODE_PREFERRED", "P"); + break; + case "required": + setFeature2(context, "ACCOUNT_ID_MODE_REQUIRED", "R"); + break; + } + } + const identity = context.__smithy_context?.selectedHttpAuthScheme?.identity; + if (identity?.$source) { + const credentials = identity; + if (credentials.accountId) { + setFeature2(context, "RESOLVED_ACCOUNT_ID", "T"); + } + for (const [key, value] of Object.entries(credentials.$source ?? {})) { + setFeature2(context, key, value); + } + } + } + var ACCOUNT_ID_ENDPOINT_REGEX; + var init_check_features = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-user-agent/dist-es/check-features.js"() { + init_dist_es28(); + ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-user-agent/dist-es/constants.js + var USER_AGENT, X_AMZ_USER_AGENT, SPACE, UA_NAME_SEPARATOR, UA_NAME_ESCAPE_REGEX, UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR; + var init_constants4 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-user-agent/dist-es/constants.js"() { + USER_AGENT = "user-agent"; + X_AMZ_USER_AGENT = "x-amz-user-agent"; + SPACE = " "; + UA_NAME_SEPARATOR = "/"; + UA_NAME_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g; + UA_VALUE_ESCAPE_REGEX = /[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g; + UA_ESCAPE_CHAR = "-"; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-user-agent/dist-es/encode-features.js + function encodeFeatures(features) { + let buffer = ""; + for (const key in features) { + const val = features[key]; + if (buffer.length + val.length + 1 <= BYTE_LIMIT) { + if (buffer.length) { + buffer += "," + val; + } else { + buffer += val; + } + continue; + } + break; + } + return buffer; + } + var BYTE_LIMIT; + var init_encode_features = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-user-agent/dist-es/encode-features.js"() { + BYTE_LIMIT = 1024; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-user-agent/dist-es/user-agent-middleware.js + var userAgentMiddleware, escapeUserAgent, getUserAgentMiddlewareOptions, getUserAgentPlugin; + var init_user_agent_middleware = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-user-agent/dist-es/user-agent-middleware.js"() { + init_dist_es22(); + init_dist_es4(); + init_check_features(); + init_constants4(); + init_encode_features(); + userAgentMiddleware = (options) => (next, context) => async (args) => { + const { request } = args; + if (!HttpRequest.isInstance(request)) { + return next(args); + } + const { headers } = request; + const userAgent = context?.userAgent?.map(escapeUserAgent) || []; + const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent); + await checkFeatures(context, options, args); + const awsContext = context; + defaultUserAgent.push(`m/${encodeFeatures(Object.assign({}, context.__smithy_context?.features, awsContext.__aws_sdk_context?.features))}`); + const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || []; + const appId = await options.userAgentAppId(); + if (appId) { + defaultUserAgent.push(escapeUserAgent([`app/${appId}`])); + } + const prefix = getUserAgentPrefix(); + const sdkUserAgentValue = (prefix ? [prefix] : []).concat([...defaultUserAgent, ...userAgent, ...customUserAgent]).join(SPACE); + const normalUAValue = [ + ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")), + ...customUserAgent + ].join(SPACE); + if (options.runtime !== "browser") { + if (normalUAValue) { + headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] ? `${headers[USER_AGENT]} ${normalUAValue}` : normalUAValue; + } + headers[USER_AGENT] = sdkUserAgentValue; + } else { + headers[X_AMZ_USER_AGENT] = sdkUserAgentValue; + } + return next({ + ...args, + request + }); + }; + escapeUserAgent = (userAgentPair) => { + const name = userAgentPair[0].split(UA_NAME_SEPARATOR).map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR); + const version = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR); + const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR); + const prefix = name.substring(0, prefixSeparatorIndex); + let uaName = name.substring(prefixSeparatorIndex + 1); + if (prefix === "api") { + uaName = uaName.toLowerCase(); + } + return [prefix, uaName, version].filter((item) => item && item.length > 0).reduce((acc, item, index2) => { + switch (index2) { + case 0: + return item; + case 1: + return `${acc}/${item}`; + default: + return `${acc}#${item}`; + } + }, ""); + }; + getUserAgentMiddlewareOptions = { + name: "getUserAgentMiddleware", + step: "build", + priority: "low", + tags: ["SET_USER_AGENT", "USER_AGENT"], + override: true + }; + getUserAgentPlugin = (config) => ({ + applyToStack: (clientStack) => { + clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions); + } + }); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-user-agent/dist-es/index.js + var init_dist_es29 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-user-agent/dist-es/index.js"() { + init_configurations(); + init_user_agent_middleware(); + } + }); + + // node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseDualstackEndpointConfigOptions.js + var DEFAULT_USE_DUALSTACK_ENDPOINT; + var init_NodeUseDualstackEndpointConfigOptions = __esm({ + "node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseDualstackEndpointConfigOptions.js"() { + DEFAULT_USE_DUALSTACK_ENDPOINT = false; + } + }); + + // node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseFipsEndpointConfigOptions.js + var DEFAULT_USE_FIPS_ENDPOINT; + var init_NodeUseFipsEndpointConfigOptions = __esm({ + "node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseFipsEndpointConfigOptions.js"() { + DEFAULT_USE_FIPS_ENDPOINT = false; + } + }); + + // node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveCustomEndpointsConfig.js + var init_resolveCustomEndpointsConfig = __esm({ + "node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveCustomEndpointsConfig.js"() { + } + }); + + // node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveEndpointsConfig.js + var init_resolveEndpointsConfig = __esm({ + "node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveEndpointsConfig.js"() { + } + }); + + // node_modules/@smithy/config-resolver/dist-es/endpointsConfig/index.js + var init_endpointsConfig = __esm({ + "node_modules/@smithy/config-resolver/dist-es/endpointsConfig/index.js"() { + init_NodeUseDualstackEndpointConfigOptions(); + init_NodeUseFipsEndpointConfigOptions(); + init_resolveCustomEndpointsConfig(); + init_resolveEndpointsConfig(); + } + }); + + // node_modules/@smithy/config-resolver/dist-es/regionConfig/config.js + var init_config2 = __esm({ + "node_modules/@smithy/config-resolver/dist-es/regionConfig/config.js"() { + } + }); + + // node_modules/@smithy/config-resolver/dist-es/regionConfig/isFipsRegion.js + var isFipsRegion; + var init_isFipsRegion = __esm({ + "node_modules/@smithy/config-resolver/dist-es/regionConfig/isFipsRegion.js"() { + isFipsRegion = (region2) => typeof region2 === "string" && (region2.startsWith("fips-") || region2.endsWith("-fips")); + } + }); + + // node_modules/@smithy/config-resolver/dist-es/regionConfig/getRealRegion.js + var getRealRegion; + var init_getRealRegion = __esm({ + "node_modules/@smithy/config-resolver/dist-es/regionConfig/getRealRegion.js"() { + init_isFipsRegion(); + getRealRegion = (region2) => isFipsRegion(region2) ? ["fips-aws-global", "aws-fips"].includes(region2) ? "us-east-1" : region2.replace(/fips-(dkr-|prod-)?|-fips/, "") : region2; + } + }); + + // node_modules/@smithy/config-resolver/dist-es/regionConfig/resolveRegionConfig.js + var resolveRegionConfig; + var init_resolveRegionConfig = __esm({ + "node_modules/@smithy/config-resolver/dist-es/regionConfig/resolveRegionConfig.js"() { + init_getRealRegion(); + init_isFipsRegion(); + resolveRegionConfig = (input) => { + const { region: region2, useFipsEndpoint } = input; + if (!region2) { + throw new Error("Region is missing"); + } + return Object.assign(input, { + region: async () => { + if (typeof region2 === "string") { + return getRealRegion(region2); + } + const providedRegion = await region2(); + return getRealRegion(providedRegion); + }, + useFipsEndpoint: async () => { + const providedRegion = typeof region2 === "string" ? region2 : await region2(); + if (isFipsRegion(providedRegion)) { + return true; + } + return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); + } + }); + }; + } + }); + + // node_modules/@smithy/config-resolver/dist-es/regionConfig/index.js + var init_regionConfig = __esm({ + "node_modules/@smithy/config-resolver/dist-es/regionConfig/index.js"() { + init_config2(); + init_resolveRegionConfig(); + } + }); + + // node_modules/@smithy/config-resolver/dist-es/regionInfo/PartitionHash.js + var init_PartitionHash = __esm({ + "node_modules/@smithy/config-resolver/dist-es/regionInfo/PartitionHash.js"() { + } + }); + + // node_modules/@smithy/config-resolver/dist-es/regionInfo/RegionHash.js + var init_RegionHash = __esm({ + "node_modules/@smithy/config-resolver/dist-es/regionInfo/RegionHash.js"() { + } + }); + + // node_modules/@smithy/config-resolver/dist-es/regionInfo/getRegionInfo.js + var init_getRegionInfo = __esm({ + "node_modules/@smithy/config-resolver/dist-es/regionInfo/getRegionInfo.js"() { + } + }); + + // node_modules/@smithy/config-resolver/dist-es/regionInfo/index.js + var init_regionInfo = __esm({ + "node_modules/@smithy/config-resolver/dist-es/regionInfo/index.js"() { + init_PartitionHash(); + init_RegionHash(); + init_getRegionInfo(); + } + }); + + // node_modules/@smithy/config-resolver/dist-es/index.js + var init_dist_es30 = __esm({ + "node_modules/@smithy/config-resolver/dist-es/index.js"() { + init_endpointsConfig(); + init_regionConfig(); + init_regionInfo(); + } + }); + + // node_modules/@smithy/middleware-content-length/dist-es/index.js + function contentLengthMiddleware(bodyLengthChecker) { + return (next) => async (args) => { + const request = args.request; + if (HttpRequest.isInstance(request)) { + const { body, headers } = request; + if (body && Object.keys(headers).map((str) => str.toLowerCase()).indexOf(CONTENT_LENGTH_HEADER) === -1) { + try { + const length = bodyLengthChecker(body); + request.headers = { + ...request.headers, + [CONTENT_LENGTH_HEADER]: String(length) + }; + } catch (error) { + } + } + } + return next({ + ...args, + request + }); + }; + } + var CONTENT_LENGTH_HEADER, contentLengthMiddlewareOptions, getContentLengthPlugin; + var init_dist_es31 = __esm({ + "node_modules/@smithy/middleware-content-length/dist-es/index.js"() { + init_dist_es4(); + CONTENT_LENGTH_HEADER = "content-length"; + contentLengthMiddlewareOptions = { + step: "build", + tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"], + name: "contentLengthMiddleware", + override: true + }; + getContentLengthPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions); + } + }); + } + }); + + // node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/s3.js + var resolveParamsForS3, DOMAIN_PATTERN, IP_ADDRESS_PATTERN, DOTS_PATTERN, isDnsCompatibleBucketName, isArnBucketName; + var init_s3 = __esm({ + "node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/s3.js"() { + resolveParamsForS3 = async (endpointParams) => { + const bucket = endpointParams?.Bucket || ""; + if (typeof endpointParams.Bucket === "string") { + endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?")); + } + if (isArnBucketName(bucket)) { + if (endpointParams.ForcePathStyle === true) { + throw new Error("Path-style addressing cannot be used with ARN buckets"); + } + } else if (!isDnsCompatibleBucketName(bucket) || bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:") || bucket.toLowerCase() !== bucket || bucket.length < 3) { + endpointParams.ForcePathStyle = true; + } + if (endpointParams.DisableMultiRegionAccessPoints) { + endpointParams.disableMultiRegionAccessPoints = true; + endpointParams.DisableMRAP = true; + } + return endpointParams; + }; + DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/; + IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; + DOTS_PATTERN = /\.\./; + isDnsCompatibleBucketName = (bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName); + isArnBucketName = (bucketName) => { + const [arn, partition2, service, , , bucket] = bucketName.split(":"); + const isArn = arn === "arn" && bucketName.split(":").length >= 6; + const isValidArn = Boolean(isArn && partition2 && service && bucket); + if (isArn && !isValidArn) { + throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`); + } + return isValidArn; + }; + } + }); + + // node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/index.js + var init_service_customizations = __esm({ + "node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/index.js"() { + init_s3(); + } + }); + + // node_modules/@smithy/middleware-endpoint/dist-es/adaptors/createConfigValueProvider.js + var createConfigValueProvider; + var init_createConfigValueProvider = __esm({ + "node_modules/@smithy/middleware-endpoint/dist-es/adaptors/createConfigValueProvider.js"() { + createConfigValueProvider = (configKey, canonicalEndpointParamKey, config) => { + const configProvider = async () => { + const configValue = config[configKey] ?? config[canonicalEndpointParamKey]; + if (typeof configValue === "function") { + return configValue(); + } + return configValue; + }; + if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") { + return async () => { + const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; + const configValue = credentials?.credentialScope ?? credentials?.CredentialScope; + return configValue; + }; + } + if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") { + return async () => { + const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; + const configValue = credentials?.accountId ?? credentials?.AccountId; + return configValue; + }; + } + if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") { + return async () => { + if (config.isCustomEndpoint === false) { + return void 0; + } + const endpoint = await configProvider(); + if (endpoint && typeof endpoint === "object") { + if ("url" in endpoint) { + return endpoint.url.href; + } + if ("hostname" in endpoint) { + const { protocol, hostname, port, path } = endpoint; + return `${protocol}//${hostname}${port ? ":" + port : ""}${path}`; + } + } + return endpoint; + }; + } + return configProvider; + }; + } + }); + + // node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromConfig.browser.js + var getEndpointFromConfig; + var init_getEndpointFromConfig_browser = __esm({ + "node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromConfig.browser.js"() { + getEndpointFromConfig = async (serviceId) => void 0; + } + }); + + // node_modules/@smithy/middleware-endpoint/dist-es/adaptors/toEndpointV1.js + var toEndpointV1; + var init_toEndpointV1 = __esm({ + "node_modules/@smithy/middleware-endpoint/dist-es/adaptors/toEndpointV1.js"() { + init_dist_es21(); + toEndpointV1 = (endpoint) => { + if (typeof endpoint === "object") { + if ("url" in endpoint) { + return parseUrl(endpoint.url); + } + return endpoint; + } + return parseUrl(endpoint); + }; + } + }); + + // node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromInstructions.js + var getEndpointFromInstructions, resolveParams; + var init_getEndpointFromInstructions = __esm({ + "node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromInstructions.js"() { + init_service_customizations(); + init_createConfigValueProvider(); + init_getEndpointFromConfig_browser(); + init_toEndpointV1(); + getEndpointFromInstructions = async (commandInput, instructionsSupplier, clientConfig, context) => { + if (!clientConfig.isCustomEndpoint) { + let endpointFromConfig; + if (clientConfig.serviceConfiguredEndpoint) { + endpointFromConfig = await clientConfig.serviceConfiguredEndpoint(); + } else { + endpointFromConfig = await getEndpointFromConfig(clientConfig.serviceId); + } + if (endpointFromConfig) { + clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig)); + clientConfig.isCustomEndpoint = true; + } + } + const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig); + if (typeof clientConfig.endpointProvider !== "function") { + throw new Error("config.endpointProvider is not set."); + } + const endpoint = clientConfig.endpointProvider(endpointParams, context); + return endpoint; + }; + resolveParams = async (commandInput, instructionsSupplier, clientConfig) => { + const endpointParams = {}; + const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {}; + for (const [name, instruction] of Object.entries(instructions)) { + switch (instruction.type) { + case "staticContextParams": + endpointParams[name] = instruction.value; + break; + case "contextParams": + endpointParams[name] = commandInput[instruction.name]; + break; + case "clientContextParams": + case "builtInParams": + endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig)(); + break; + case "operationContextParams": + endpointParams[name] = instruction.get(commandInput); + break; + default: + throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction)); + } + } + if (Object.keys(instructions).length === 0) { + Object.assign(endpointParams, clientConfig); + } + if (String(clientConfig.serviceId).toLowerCase() === "s3") { + await resolveParamsForS3(endpointParams); + } + return endpointParams; + }; + } + }); + + // node_modules/@smithy/middleware-endpoint/dist-es/adaptors/index.js + var init_adaptors = __esm({ + "node_modules/@smithy/middleware-endpoint/dist-es/adaptors/index.js"() { + init_getEndpointFromInstructions(); + init_toEndpointV1(); + } + }); + + // node_modules/@smithy/middleware-endpoint/dist-es/endpointMiddleware.js + var endpointMiddleware; + var init_endpointMiddleware = __esm({ + "node_modules/@smithy/middleware-endpoint/dist-es/endpointMiddleware.js"() { + init_dist_es18(); + init_dist_es8(); + init_getEndpointFromInstructions(); + endpointMiddleware = ({ config, instructions }) => { + return (next, context) => async (args) => { + if (config.isCustomEndpoint) { + setFeature(context, "ENDPOINT_OVERRIDE", "N"); + } + const endpoint = await getEndpointFromInstructions(args.input, { + getEndpointParameterInstructions() { + return instructions; + } + }, { ...config }, context); + context.endpointV2 = endpoint; + context.authSchemes = endpoint.properties?.authSchemes; + const authScheme = context.authSchemes?.[0]; + if (authScheme) { + context["signing_region"] = authScheme.signingRegion; + context["signing_service"] = authScheme.signingName; + const smithyContext = getSmithyContext(context); + const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption; + if (httpAuthOption) { + httpAuthOption.signingProperties = Object.assign(httpAuthOption.signingProperties || {}, { + signing_region: authScheme.signingRegion, + signingRegion: authScheme.signingRegion, + signing_service: authScheme.signingName, + signingName: authScheme.signingName, + signingRegionSet: authScheme.signingRegionSet + }, authScheme.properties); + } + } + return next({ + ...args + }); + }; + }; + } + }); + + // node_modules/@smithy/middleware-endpoint/dist-es/getEndpointPlugin.js + var endpointMiddlewareOptions, getEndpointPlugin; + var init_getEndpointPlugin = __esm({ + "node_modules/@smithy/middleware-endpoint/dist-es/getEndpointPlugin.js"() { + init_dist_es9(); + init_endpointMiddleware(); + endpointMiddlewareOptions = { + step: "serialize", + tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"], + name: "endpointV2Middleware", + override: true, + relation: "before", + toMiddleware: serializerMiddlewareOption.name + }; + getEndpointPlugin = (config, instructions) => ({ + applyToStack: (clientStack) => { + clientStack.addRelativeTo(endpointMiddleware({ + config, + instructions + }), endpointMiddlewareOptions); + } + }); + } + }); + + // node_modules/@smithy/middleware-endpoint/dist-es/resolveEndpointConfig.js + var resolveEndpointConfig; + var init_resolveEndpointConfig = __esm({ + "node_modules/@smithy/middleware-endpoint/dist-es/resolveEndpointConfig.js"() { + init_dist_es8(); + init_getEndpointFromConfig_browser(); + init_toEndpointV1(); + resolveEndpointConfig = (input) => { + const tls = input.tls ?? true; + const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input; + const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await normalizeProvider(endpoint)()) : void 0; + const isCustomEndpoint = !!endpoint; + const resolvedConfig = Object.assign(input, { + endpoint: customEndpointProvider, + tls, + isCustomEndpoint, + useDualstackEndpoint: normalizeProvider(useDualstackEndpoint ?? false), + useFipsEndpoint: normalizeProvider(useFipsEndpoint ?? false) + }); + let configuredEndpointPromise = void 0; + resolvedConfig.serviceConfiguredEndpoint = async () => { + if (input.serviceId && !configuredEndpointPromise) { + configuredEndpointPromise = getEndpointFromConfig(input.serviceId); + } + return configuredEndpointPromise; + }; + return resolvedConfig; + }; + } + }); + + // node_modules/@smithy/middleware-endpoint/dist-es/resolveEndpointRequiredConfig.js + var init_resolveEndpointRequiredConfig = __esm({ + "node_modules/@smithy/middleware-endpoint/dist-es/resolveEndpointRequiredConfig.js"() { + } + }); + + // node_modules/@smithy/middleware-endpoint/dist-es/types.js + var init_types4 = __esm({ + "node_modules/@smithy/middleware-endpoint/dist-es/types.js"() { + } + }); + + // node_modules/@smithy/middleware-endpoint/dist-es/index.js + var init_dist_es32 = __esm({ + "node_modules/@smithy/middleware-endpoint/dist-es/index.js"() { + init_adaptors(); + init_endpointMiddleware(); + init_getEndpointPlugin(); + init_resolveEndpointConfig(); + init_resolveEndpointRequiredConfig(); + init_types4(); + } + }); + + // node_modules/@smithy/util-retry/dist-es/config.js + var RETRY_MODES, DEFAULT_MAX_ATTEMPTS, DEFAULT_RETRY_MODE; + var init_config3 = __esm({ + "node_modules/@smithy/util-retry/dist-es/config.js"() { + (function(RETRY_MODES2) { + RETRY_MODES2["STANDARD"] = "standard"; + RETRY_MODES2["ADAPTIVE"] = "adaptive"; + })(RETRY_MODES || (RETRY_MODES = {})); + DEFAULT_MAX_ATTEMPTS = 3; + DEFAULT_RETRY_MODE = RETRY_MODES.STANDARD; + } + }); + + // node_modules/@smithy/service-error-classification/dist-es/constants.js + var THROTTLING_ERROR_CODES, TRANSIENT_ERROR_CODES, TRANSIENT_ERROR_STATUS_CODES, NODEJS_TIMEOUT_ERROR_CODES, NODEJS_NETWORK_ERROR_CODES; + var init_constants5 = __esm({ + "node_modules/@smithy/service-error-classification/dist-es/constants.js"() { + THROTTLING_ERROR_CODES = [ + "BandwidthLimitExceeded", + "EC2ThrottledException", + "LimitExceededException", + "PriorRequestNotComplete", + "ProvisionedThroughputExceededException", + "RequestLimitExceeded", + "RequestThrottled", + "RequestThrottledException", + "SlowDown", + "ThrottledException", + "Throttling", + "ThrottlingException", + "TooManyRequestsException", + "TransactionInProgressException" + ]; + TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"]; + TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504]; + NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"]; + NODEJS_NETWORK_ERROR_CODES = ["EHOSTUNREACH", "ENETUNREACH", "ENOTFOUND"]; + } + }); + + // node_modules/@smithy/service-error-classification/dist-es/index.js + var isRetryableByTrait, isClockSkewCorrectedError, isBrowserNetworkError, isThrottlingError, isTransientError, isServerError; + var init_dist_es33 = __esm({ + "node_modules/@smithy/service-error-classification/dist-es/index.js"() { + init_constants5(); + isRetryableByTrait = (error) => error?.$retryable !== void 0; + isClockSkewCorrectedError = (error) => error.$metadata?.clockSkewCorrected; + isBrowserNetworkError = (error) => { + const errorMessages = /* @__PURE__ */ new Set([ + "Failed to fetch", + "NetworkError when attempting to fetch resource", + "The Internet connection appears to be offline", + "Load failed", + "Network request failed" + ]); + const isValid = error && error instanceof TypeError; + if (!isValid) { + return false; + } + return errorMessages.has(error.message); + }; + isThrottlingError = (error) => error.$metadata?.httpStatusCode === 429 || THROTTLING_ERROR_CODES.includes(error.name) || error.$retryable?.throttling == true; + isTransientError = (error, depth = 0) => isRetryableByTrait(error) || isClockSkewCorrectedError(error) || TRANSIENT_ERROR_CODES.includes(error.name) || NODEJS_TIMEOUT_ERROR_CODES.includes(error?.code || "") || NODEJS_NETWORK_ERROR_CODES.includes(error?.code || "") || TRANSIENT_ERROR_STATUS_CODES.includes(error.$metadata?.httpStatusCode || 0) || isBrowserNetworkError(error) || error.cause !== void 0 && depth <= 10 && isTransientError(error.cause, depth + 1); + isServerError = (error) => { + if (error.$metadata?.httpStatusCode !== void 0) { + const statusCode = error.$metadata.httpStatusCode; + if (500 <= statusCode && statusCode <= 599 && !isTransientError(error)) { + return true; + } + return false; + } + return false; + }; + } + }); + + // node_modules/@smithy/util-retry/dist-es/DefaultRateLimiter.js + var DefaultRateLimiter; + var init_DefaultRateLimiter = __esm({ + "node_modules/@smithy/util-retry/dist-es/DefaultRateLimiter.js"() { + init_dist_es33(); + DefaultRateLimiter = class _DefaultRateLimiter { + static setTimeoutFn = setTimeout; + beta; + minCapacity; + minFillRate; + scaleConstant; + smooth; + currentCapacity = 0; + enabled = false; + lastMaxRate = 0; + measuredTxRate = 0; + requestCount = 0; + fillRate; + lastThrottleTime; + lastTimestamp = 0; + lastTxRateBucket; + maxCapacity; + timeWindow = 0; + constructor(options) { + this.beta = options?.beta ?? 0.7; + this.minCapacity = options?.minCapacity ?? 1; + this.minFillRate = options?.minFillRate ?? 0.5; + this.scaleConstant = options?.scaleConstant ?? 0.4; + this.smooth = options?.smooth ?? 0.8; + const currentTimeInSeconds = this.getCurrentTimeInSeconds(); + this.lastThrottleTime = currentTimeInSeconds; + this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds()); + this.fillRate = this.minFillRate; + this.maxCapacity = this.minCapacity; + } + getCurrentTimeInSeconds() { + return Date.now() / 1e3; + } + async getSendToken() { + return this.acquireTokenBucket(1); + } + async acquireTokenBucket(amount) { + if (!this.enabled) { + return; + } + this.refillTokenBucket(); + if (amount > this.currentCapacity) { + const delay = (amount - this.currentCapacity) / this.fillRate * 1e3; + await new Promise((resolve) => _DefaultRateLimiter.setTimeoutFn(resolve, delay)); + } + this.currentCapacity = this.currentCapacity - amount; + } + refillTokenBucket() { + const timestamp2 = this.getCurrentTimeInSeconds(); + if (!this.lastTimestamp) { + this.lastTimestamp = timestamp2; + return; + } + const fillAmount = (timestamp2 - this.lastTimestamp) * this.fillRate; + this.currentCapacity = Math.min(this.maxCapacity, this.currentCapacity + fillAmount); + this.lastTimestamp = timestamp2; + } + updateClientSendingRate(response) { + let calculatedRate; + this.updateMeasuredRate(); + if (isThrottlingError(response)) { + const rateToUse = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate); + this.lastMaxRate = rateToUse; + this.calculateTimeWindow(); + this.lastThrottleTime = this.getCurrentTimeInSeconds(); + calculatedRate = this.cubicThrottle(rateToUse); + this.enableTokenBucket(); + } else { + this.calculateTimeWindow(); + calculatedRate = this.cubicSuccess(this.getCurrentTimeInSeconds()); + } + const newRate = Math.min(calculatedRate, 2 * this.measuredTxRate); + this.updateTokenBucketRate(newRate); + } + calculateTimeWindow() { + this.timeWindow = this.getPrecise(Math.pow(this.lastMaxRate * (1 - this.beta) / this.scaleConstant, 1 / 3)); + } + cubicThrottle(rateToUse) { + return this.getPrecise(rateToUse * this.beta); + } + cubicSuccess(timestamp2) { + return this.getPrecise(this.scaleConstant * Math.pow(timestamp2 - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate); + } + enableTokenBucket() { + this.enabled = true; + } + updateTokenBucketRate(newRate) { + this.refillTokenBucket(); + this.fillRate = Math.max(newRate, this.minFillRate); + this.maxCapacity = Math.max(newRate, this.minCapacity); + this.currentCapacity = Math.min(this.currentCapacity, this.maxCapacity); + } + updateMeasuredRate() { + const t2 = this.getCurrentTimeInSeconds(); + const timeBucket = Math.floor(t2 * 2) / 2; + this.requestCount++; + if (timeBucket > this.lastTxRateBucket) { + const currentRate = this.requestCount / (timeBucket - this.lastTxRateBucket); + this.measuredTxRate = this.getPrecise(currentRate * this.smooth + this.measuredTxRate * (1 - this.smooth)); + this.requestCount = 0; + this.lastTxRateBucket = timeBucket; + } + } + getPrecise(num) { + return parseFloat(num.toFixed(8)); + } + }; + } + }); + + // node_modules/@smithy/util-retry/dist-es/constants.js + var DEFAULT_RETRY_DELAY_BASE, MAXIMUM_RETRY_DELAY, THROTTLING_RETRY_DELAY_BASE, INITIAL_RETRY_TOKENS, RETRY_COST, TIMEOUT_RETRY_COST, NO_RETRY_INCREMENT, INVOCATION_ID_HEADER, REQUEST_HEADER; + var init_constants6 = __esm({ + "node_modules/@smithy/util-retry/dist-es/constants.js"() { + DEFAULT_RETRY_DELAY_BASE = 100; + MAXIMUM_RETRY_DELAY = 20 * 1e3; + THROTTLING_RETRY_DELAY_BASE = 500; + INITIAL_RETRY_TOKENS = 500; + RETRY_COST = 5; + TIMEOUT_RETRY_COST = 10; + NO_RETRY_INCREMENT = 1; + INVOCATION_ID_HEADER = "amz-sdk-invocation-id"; + REQUEST_HEADER = "amz-sdk-request"; + } + }); + + // node_modules/@smithy/util-retry/dist-es/defaultRetryBackoffStrategy.js + var getDefaultRetryBackoffStrategy; + var init_defaultRetryBackoffStrategy = __esm({ + "node_modules/@smithy/util-retry/dist-es/defaultRetryBackoffStrategy.js"() { + init_constants6(); + getDefaultRetryBackoffStrategy = () => { + let delayBase = DEFAULT_RETRY_DELAY_BASE; + const computeNextBackoffDelay = (attempts) => { + return Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)); + }; + const setDelayBase = (delay) => { + delayBase = delay; + }; + return { + computeNextBackoffDelay, + setDelayBase + }; + }; + } + }); + + // node_modules/@smithy/util-retry/dist-es/defaultRetryToken.js + var createDefaultRetryToken; + var init_defaultRetryToken = __esm({ + "node_modules/@smithy/util-retry/dist-es/defaultRetryToken.js"() { + init_constants6(); + createDefaultRetryToken = ({ retryDelay, retryCount, retryCost }) => { + const getRetryCount = () => retryCount; + const getRetryDelay = () => Math.min(MAXIMUM_RETRY_DELAY, retryDelay); + const getRetryCost = () => retryCost; + return { + getRetryCount, + getRetryDelay, + getRetryCost + }; + }; + } + }); + + // node_modules/@smithy/util-retry/dist-es/StandardRetryStrategy.js + var StandardRetryStrategy; + var init_StandardRetryStrategy = __esm({ + "node_modules/@smithy/util-retry/dist-es/StandardRetryStrategy.js"() { + init_config3(); + init_constants6(); + init_defaultRetryBackoffStrategy(); + init_defaultRetryToken(); + StandardRetryStrategy = class { + maxAttempts; + mode = RETRY_MODES.STANDARD; + capacity = INITIAL_RETRY_TOKENS; + retryBackoffStrategy = getDefaultRetryBackoffStrategy(); + maxAttemptsProvider; + constructor(maxAttempts) { + this.maxAttempts = maxAttempts; + this.maxAttemptsProvider = typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts; + } + async acquireInitialRetryToken(retryTokenScope) { + return createDefaultRetryToken({ + retryDelay: DEFAULT_RETRY_DELAY_BASE, + retryCount: 0 + }); + } + async refreshRetryTokenForRetry(token, errorInfo) { + const maxAttempts = await this.getMaxAttempts(); + if (this.shouldRetry(token, errorInfo, maxAttempts)) { + const errorType = errorInfo.errorType; + this.retryBackoffStrategy.setDelayBase(errorType === "THROTTLING" ? THROTTLING_RETRY_DELAY_BASE : DEFAULT_RETRY_DELAY_BASE); + const delayFromErrorType = this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount()); + const retryDelay = errorInfo.retryAfterHint ? Math.max(errorInfo.retryAfterHint.getTime() - Date.now() || 0, delayFromErrorType) : delayFromErrorType; + const capacityCost = this.getCapacityCost(errorType); + this.capacity -= capacityCost; + return createDefaultRetryToken({ + retryDelay, + retryCount: token.getRetryCount() + 1, + retryCost: capacityCost + }); + } + throw new Error("No retry token available"); + } + recordSuccess(token) { + this.capacity = Math.max(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT)); + } + getCapacity() { + return this.capacity; + } + async getMaxAttempts() { + try { + return await this.maxAttemptsProvider(); + } catch (error) { + console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`); + return DEFAULT_MAX_ATTEMPTS; + } + } + shouldRetry(tokenToRenew, errorInfo, maxAttempts) { + const attempts = tokenToRenew.getRetryCount() + 1; + return attempts < maxAttempts && this.capacity >= this.getCapacityCost(errorInfo.errorType) && this.isRetryableError(errorInfo.errorType); + } + getCapacityCost(errorType) { + return errorType === "TRANSIENT" ? TIMEOUT_RETRY_COST : RETRY_COST; + } + isRetryableError(errorType) { + return errorType === "THROTTLING" || errorType === "TRANSIENT"; + } + }; + } + }); + + // node_modules/@smithy/util-retry/dist-es/AdaptiveRetryStrategy.js + var AdaptiveRetryStrategy; + var init_AdaptiveRetryStrategy = __esm({ + "node_modules/@smithy/util-retry/dist-es/AdaptiveRetryStrategy.js"() { + init_config3(); + init_DefaultRateLimiter(); + init_StandardRetryStrategy(); + AdaptiveRetryStrategy = class { + maxAttemptsProvider; + rateLimiter; + standardRetryStrategy; + mode = RETRY_MODES.ADAPTIVE; + constructor(maxAttemptsProvider, options) { + this.maxAttemptsProvider = maxAttemptsProvider; + const { rateLimiter } = options ?? {}; + this.rateLimiter = rateLimiter ?? new DefaultRateLimiter(); + this.standardRetryStrategy = new StandardRetryStrategy(maxAttemptsProvider); + } + async acquireInitialRetryToken(retryTokenScope) { + await this.rateLimiter.getSendToken(); + return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope); + } + async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { + this.rateLimiter.updateClientSendingRate(errorInfo); + return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo); + } + recordSuccess(token) { + this.rateLimiter.updateClientSendingRate({}); + this.standardRetryStrategy.recordSuccess(token); + } + }; + } + }); + + // node_modules/@smithy/util-retry/dist-es/ConfiguredRetryStrategy.js + var init_ConfiguredRetryStrategy = __esm({ + "node_modules/@smithy/util-retry/dist-es/ConfiguredRetryStrategy.js"() { + } + }); + + // node_modules/@smithy/util-retry/dist-es/types.js + var init_types5 = __esm({ + "node_modules/@smithy/util-retry/dist-es/types.js"() { + } + }); + + // node_modules/@smithy/util-retry/dist-es/index.js + var init_dist_es34 = __esm({ + "node_modules/@smithy/util-retry/dist-es/index.js"() { + init_AdaptiveRetryStrategy(); + init_ConfiguredRetryStrategy(); + init_DefaultRateLimiter(); + init_StandardRetryStrategy(); + init_config3(); + init_constants6(); + init_types5(); + } + }); + + // node_modules/@smithy/middleware-retry/dist-es/delayDecider.js + var init_delayDecider = __esm({ + "node_modules/@smithy/middleware-retry/dist-es/delayDecider.js"() { + } + }); + + // node_modules/@smithy/middleware-retry/dist-es/retryDecider.js + var init_retryDecider = __esm({ + "node_modules/@smithy/middleware-retry/dist-es/retryDecider.js"() { + } + }); + + // node_modules/@smithy/middleware-retry/dist-es/util.js + var asSdkError; + var init_util2 = __esm({ + "node_modules/@smithy/middleware-retry/dist-es/util.js"() { + asSdkError = (error) => { + if (error instanceof Error) + return error; + if (error instanceof Object) + return Object.assign(new Error(), error); + if (typeof error === "string") + return new Error(error); + return new Error(`AWS SDK error wrapper for ${error}`); + }; + } + }); + + // node_modules/@smithy/middleware-retry/dist-es/StandardRetryStrategy.js + var init_StandardRetryStrategy2 = __esm({ + "node_modules/@smithy/middleware-retry/dist-es/StandardRetryStrategy.js"() { + } + }); + + // node_modules/@smithy/middleware-retry/dist-es/AdaptiveRetryStrategy.js + var init_AdaptiveRetryStrategy2 = __esm({ + "node_modules/@smithy/middleware-retry/dist-es/AdaptiveRetryStrategy.js"() { + } + }); + + // node_modules/@smithy/middleware-retry/dist-es/configurations.js + var resolveRetryConfig; + var init_configurations2 = __esm({ + "node_modules/@smithy/middleware-retry/dist-es/configurations.js"() { + init_dist_es8(); + init_dist_es34(); + resolveRetryConfig = (input) => { + const { retryStrategy, retryMode: _retryMode, maxAttempts: _maxAttempts } = input; + const maxAttempts = normalizeProvider(_maxAttempts ?? DEFAULT_MAX_ATTEMPTS); + return Object.assign(input, { + maxAttempts, + retryStrategy: async () => { + if (retryStrategy) { + return retryStrategy; + } + const retryMode = await normalizeProvider(_retryMode)(); + if (retryMode === RETRY_MODES.ADAPTIVE) { + return new AdaptiveRetryStrategy(maxAttempts); + } + return new StandardRetryStrategy(maxAttempts); + } + }); + }; + } + }); + + // node_modules/@smithy/middleware-retry/dist-es/omitRetryHeadersMiddleware.js + var init_omitRetryHeadersMiddleware = __esm({ + "node_modules/@smithy/middleware-retry/dist-es/omitRetryHeadersMiddleware.js"() { + } + }); + + // node_modules/@smithy/middleware-retry/dist-es/isStreamingPayload/isStreamingPayload.browser.js + var isStreamingPayload; + var init_isStreamingPayload_browser = __esm({ + "node_modules/@smithy/middleware-retry/dist-es/isStreamingPayload/isStreamingPayload.browser.js"() { + isStreamingPayload = (request) => request?.body instanceof ReadableStream; + } + }); + + // node_modules/@smithy/middleware-retry/dist-es/retryMiddleware.js + var retryMiddleware, isRetryStrategyV2, getRetryErrorInfo, getRetryErrorType, retryMiddlewareOptions, getRetryPlugin, getRetryAfterHint; + var init_retryMiddleware = __esm({ + "node_modules/@smithy/middleware-retry/dist-es/retryMiddleware.js"() { + init_dist_es4(); + init_dist_es33(); + init_dist_es27(); + init_dist_es34(); + init_dist_es17(); + init_isStreamingPayload_browser(); + init_util2(); + retryMiddleware = (options) => (next, context) => async (args) => { + let retryStrategy = await options.retryStrategy(); + const maxAttempts = await options.maxAttempts(); + if (isRetryStrategyV2(retryStrategy)) { + retryStrategy = retryStrategy; + let retryToken = await retryStrategy.acquireInitialRetryToken(context["partition_id"]); + let lastError = new Error(); + let attempts = 0; + let totalRetryDelay = 0; + const { request } = args; + const isRequest = HttpRequest.isInstance(request); + if (isRequest) { + request.headers[INVOCATION_ID_HEADER] = v42(); + } + while (true) { + try { + if (isRequest) { + request.headers[REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; + } + const { response, output } = await next(args); + retryStrategy.recordSuccess(retryToken); + output.$metadata.attempts = attempts + 1; + output.$metadata.totalRetryDelay = totalRetryDelay; + return { response, output }; + } catch (e2) { + const retryErrorInfo = getRetryErrorInfo(e2); + lastError = asSdkError(e2); + if (isRequest && isStreamingPayload(request)) { + (context.logger instanceof NoOpLogger ? console : context.logger)?.warn("An error was encountered in a non-retryable streaming request."); + throw lastError; + } + try { + retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo); + } catch (refreshError) { + if (!lastError.$metadata) { + lastError.$metadata = {}; + } + lastError.$metadata.attempts = attempts + 1; + lastError.$metadata.totalRetryDelay = totalRetryDelay; + throw lastError; + } + attempts = retryToken.getRetryCount(); + const delay = retryToken.getRetryDelay(); + totalRetryDelay += delay; + await new Promise((resolve) => setTimeout(resolve, delay)); + } + } + } else { + retryStrategy = retryStrategy; + if (retryStrategy?.mode) + context.userAgent = [...context.userAgent || [], ["cfg/retry-mode", retryStrategy.mode]]; + return retryStrategy.retry(next, args); + } + }; + isRetryStrategyV2 = (retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && typeof retryStrategy.recordSuccess !== "undefined"; + getRetryErrorInfo = (error) => { + const errorInfo = { + error, + errorType: getRetryErrorType(error) + }; + const retryAfterHint = getRetryAfterHint(error.$response); + if (retryAfterHint) { + errorInfo.retryAfterHint = retryAfterHint; + } + return errorInfo; + }; + getRetryErrorType = (error) => { + if (isThrottlingError(error)) + return "THROTTLING"; + if (isTransientError(error)) + return "TRANSIENT"; + if (isServerError(error)) + return "SERVER_ERROR"; + return "CLIENT_ERROR"; + }; + retryMiddlewareOptions = { + name: "retryMiddleware", + tags: ["RETRY"], + step: "finalizeRequest", + priority: "high", + override: true + }; + getRetryPlugin = (options) => ({ + applyToStack: (clientStack) => { + clientStack.add(retryMiddleware(options), retryMiddlewareOptions); + } + }); + getRetryAfterHint = (response) => { + if (!HttpResponse.isInstance(response)) + return; + const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after"); + if (!retryAfterHeaderName) + return; + const retryAfter = response.headers[retryAfterHeaderName]; + const retryAfterSeconds = Number(retryAfter); + if (!Number.isNaN(retryAfterSeconds)) + return new Date(retryAfterSeconds * 1e3); + const retryAfterDate = new Date(retryAfter); + return retryAfterDate; + }; + } + }); + + // node_modules/@smithy/middleware-retry/dist-es/index.js + var init_dist_es35 = __esm({ + "node_modules/@smithy/middleware-retry/dist-es/index.js"() { + init_AdaptiveRetryStrategy2(); + init_StandardRetryStrategy2(); + init_configurations2(); + init_delayDecider(); + init_omitRetryHeadersMiddleware(); + init_retryDecider(); + init_retryMiddleware(); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/auth/httpAuthSchemeProvider.js + function createAwsAuthSigv4HttpAuthOption(authParameters) { + return { + schemeId: "aws.auth#sigv4", + signingProperties: { + name: "cognito-identity", + region: authParameters.region + }, + propertiesExtractor: (config, context) => ({ + signingProperties: { + config, + context + } + }) + }; + } + function createSmithyApiNoAuthHttpAuthOption(authParameters) { + return { + schemeId: "smithy.api#noAuth" + }; + } + var defaultCognitoIdentityHttpAuthSchemeParametersProvider, defaultCognitoIdentityHttpAuthSchemeProvider, resolveHttpAuthSchemeConfig; + var init_httpAuthSchemeProvider = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/auth/httpAuthSchemeProvider.js"() { + init_dist_es28(); + init_dist_es8(); + defaultCognitoIdentityHttpAuthSchemeParametersProvider = async (config, context, input) => { + return { + operation: getSmithyContext(context).operation, + region: await normalizeProvider(config.region)() || (() => { + throw new Error("expected `region` to be configured for `aws.auth#sigv4`"); + })() + }; + }; + defaultCognitoIdentityHttpAuthSchemeProvider = (authParameters) => { + const options = []; + switch (authParameters.operation) { + case "GetCredentialsForIdentity": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + case "GetId": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + case "GetOpenIdToken": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + case "UnlinkIdentity": { + options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); + break; + } + default: { + options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); + } + } + return options; + }; + resolveHttpAuthSchemeConfig = (config) => { + const config_0 = resolveAwsSdkSigV4Config(config); + return Object.assign(config_0, { + authSchemePreference: normalizeProvider(config.authSchemePreference ?? []) + }); + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/endpoint/EndpointParameters.js + var resolveClientEndpointParameters, commonParams; + var init_EndpointParameters = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/endpoint/EndpointParameters.js"() { + resolveClientEndpointParameters = (options) => { + return Object.assign(options, { + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "cognito-identity" + }); + }; + commonParams = { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" } + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/package.json + var package_default; + var init_package = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/package.json"() { + package_default = { + name: "@aws-sdk/client-cognito-identity", + description: "AWS SDK for JavaScript Cognito Identity Client for Node.js, Browser and React Native", + version: "3.901.0", + scripts: { + build: "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'", + "build:cjs": "node ../../scripts/compilation/inline client-cognito-identity", + "build:es": "tsc -p tsconfig.es.json", + "build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build", + "build:types": "tsc -p tsconfig.types.json", + "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4", + clean: "rimraf ./dist-* && rimraf *.tsbuildinfo", + "extract:docs": "api-extractor run --local", + "generate:client": "node ../../scripts/generate-clients/single-service --solo cognito-identity", + "test:e2e": "yarn g:vitest run -c vitest.config.e2e.mts --mode development", + "test:e2e:watch": "yarn g:vitest watch -c vitest.config.e2e.mts" + }, + main: "./dist-cjs/index.js", + types: "./dist-types/index.d.ts", + module: "./dist-es/index.js", + sideEffects: false, + dependencies: { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.901.0", + "@aws-sdk/credential-provider-node": "3.901.0", + "@aws-sdk/middleware-host-header": "3.901.0", + "@aws-sdk/middleware-logger": "3.901.0", + "@aws-sdk/middleware-recursion-detection": "3.901.0", + "@aws-sdk/middleware-user-agent": "3.901.0", + "@aws-sdk/region-config-resolver": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@aws-sdk/util-endpoints": "3.901.0", + "@aws-sdk/util-user-agent-browser": "3.901.0", + "@aws-sdk/util-user-agent-node": "3.901.0", + "@smithy/config-resolver": "^4.3.0", + "@smithy/core": "^3.14.0", + "@smithy/fetch-http-handler": "^5.3.0", + "@smithy/hash-node": "^4.2.0", + "@smithy/invalid-dependency": "^4.2.0", + "@smithy/middleware-content-length": "^4.2.0", + "@smithy/middleware-endpoint": "^4.3.0", + "@smithy/middleware-retry": "^4.4.0", + "@smithy/middleware-serde": "^4.2.0", + "@smithy/middleware-stack": "^4.2.0", + "@smithy/node-config-provider": "^4.3.0", + "@smithy/node-http-handler": "^4.3.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/smithy-client": "^4.7.0", + "@smithy/types": "^4.6.0", + "@smithy/url-parser": "^4.2.0", + "@smithy/util-base64": "^4.2.0", + "@smithy/util-body-length-browser": "^4.2.0", + "@smithy/util-body-length-node": "^4.2.0", + "@smithy/util-defaults-mode-browser": "^4.2.0", + "@smithy/util-defaults-mode-node": "^4.2.0", + "@smithy/util-endpoints": "^3.2.0", + "@smithy/util-middleware": "^4.2.0", + "@smithy/util-retry": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", + tslib: "^2.6.2" + }, + devDependencies: { + "@aws-sdk/client-iam": "3.901.0", + "@tsconfig/node18": "18.2.4", + "@types/chai": "^4.2.11", + "@types/node": "^18.19.69", + concurrently: "7.0.0", + "downlevel-dts": "0.10.1", + rimraf: "3.0.2", + typescript: "~5.8.3" + }, + engines: { + node: ">=18.0.0" + }, + typesVersions: { + "<4.0": { + "dist-types/*": [ + "dist-types/ts3.4/*" + ] + } + }, + files: [ + "dist-*/**" + ], + author: { + name: "AWS SDK for JavaScript Team", + url: "https://aws.amazon.com/javascript/" + }, + license: "Apache-2.0", + browser: { + "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser" + }, + "react-native": { + "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native" + }, + homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-cognito-identity", + repository: { + type: "git", + url: "https://github.com/aws/aws-sdk-js-v3.git", + directory: "clients/client-cognito-identity" + } + }; + } + }); + + // node_modules/@aws-crypto/sha256-browser/build/module/constants.js + var SHA_256_HASH, SHA_256_HMAC_ALGO, EMPTY_DATA_SHA_256; + var init_constants7 = __esm({ + "node_modules/@aws-crypto/sha256-browser/build/module/constants.js"() { + SHA_256_HASH = { name: "SHA-256" }; + SHA_256_HMAC_ALGO = { + name: "HMAC", + hash: SHA_256_HASH + }; + EMPTY_DATA_SHA_256 = new Uint8Array([ + 227, + 176, + 196, + 66, + 152, + 252, + 28, + 20, + 154, + 251, + 244, + 200, + 153, + 111, + 185, + 36, + 39, + 174, + 65, + 228, + 100, + 155, + 147, + 76, + 164, + 149, + 153, + 27, + 120, + 82, + 184, + 85 + ]); + } + }); + + // node_modules/@aws-sdk/util-locate-window/dist-es/index.js + function locateWindow() { + if (typeof window !== "undefined") { + return window; + } else if (typeof self !== "undefined") { + return self; + } + return fallbackWindow; + } + var fallbackWindow; + var init_dist_es36 = __esm({ + "node_modules/@aws-sdk/util-locate-window/dist-es/index.js"() { + fallbackWindow = {}; + } + }); + + // node_modules/@aws-crypto/sha256-browser/build/module/webCryptoSha256.js + var Sha2562; + var init_webCryptoSha256 = __esm({ + "node_modules/@aws-crypto/sha256-browser/build/module/webCryptoSha256.js"() { + init_module(); + init_constants7(); + init_dist_es36(); + Sha2562 = /** @class */ + (function() { + function Sha2564(secret) { + this.toHash = new Uint8Array(0); + this.secret = secret; + this.reset(); + } + Sha2564.prototype.update = function(data) { + if (isEmptyData(data)) { + return; + } + var update2 = convertToBuffer(data); + var typedArray = new Uint8Array(this.toHash.byteLength + update2.byteLength); + typedArray.set(this.toHash, 0); + typedArray.set(update2, this.toHash.byteLength); + this.toHash = typedArray; + }; + Sha2564.prototype.digest = function() { + var _this = this; + if (this.key) { + return this.key.then(function(key) { + return locateWindow().crypto.subtle.sign(SHA_256_HMAC_ALGO, key, _this.toHash).then(function(data) { + return new Uint8Array(data); + }); + }); + } + if (isEmptyData(this.toHash)) { + return Promise.resolve(EMPTY_DATA_SHA_256); + } + return Promise.resolve().then(function() { + return locateWindow().crypto.subtle.digest(SHA_256_HASH, _this.toHash); + }).then(function(data) { + return Promise.resolve(new Uint8Array(data)); + }); + }; + Sha2564.prototype.reset = function() { + var _this = this; + this.toHash = new Uint8Array(0); + if (this.secret && this.secret !== void 0) { + this.key = new Promise(function(resolve, reject) { + locateWindow().crypto.subtle.importKey("raw", convertToBuffer(_this.secret), SHA_256_HMAC_ALGO, false, ["sign"]).then(resolve, reject); + }); + this.key.catch(function() { + }); + } + }; + return Sha2564; + })(); + } + }); + + // node_modules/@aws-crypto/supports-web-crypto/build/module/supportsWebCrypto.js + function supportsWebCrypto(window2) { + if (supportsSecureRandom(window2) && typeof window2.crypto.subtle === "object") { + var subtle = window2.crypto.subtle; + return supportsSubtleCrypto(subtle); + } + return false; + } + function supportsSecureRandom(window2) { + if (typeof window2 === "object" && typeof window2.crypto === "object") { + var getRandomValues2 = window2.crypto.getRandomValues; + return typeof getRandomValues2 === "function"; + } + return false; + } + function supportsSubtleCrypto(subtle) { + return subtle && subtleCryptoMethods.every(function(methodName) { + return typeof subtle[methodName] === "function"; + }); + } + var subtleCryptoMethods; + var init_supportsWebCrypto = __esm({ + "node_modules/@aws-crypto/supports-web-crypto/build/module/supportsWebCrypto.js"() { + subtleCryptoMethods = [ + "decrypt", + "digest", + "encrypt", + "exportKey", + "generateKey", + "importKey", + "sign", + "verify" + ]; + } + }); + + // node_modules/@aws-crypto/supports-web-crypto/build/module/index.js + var init_module3 = __esm({ + "node_modules/@aws-crypto/supports-web-crypto/build/module/index.js"() { + init_supportsWebCrypto(); + } + }); + + // node_modules/@aws-crypto/sha256-browser/build/module/crossPlatformSha256.js + var Sha2563; + var init_crossPlatformSha256 = __esm({ + "node_modules/@aws-crypto/sha256-browser/build/module/crossPlatformSha256.js"() { + init_webCryptoSha256(); + init_module2(); + init_module3(); + init_dist_es36(); + init_module(); + Sha2563 = /** @class */ + (function() { + function Sha2564(secret) { + if (supportsWebCrypto(locateWindow())) { + this.hash = new Sha2562(secret); + } else { + this.hash = new Sha256(secret); + } + } + Sha2564.prototype.update = function(data, encoding) { + this.hash.update(convertToBuffer(data)); + }; + Sha2564.prototype.digest = function() { + return this.hash.digest(); + }; + Sha2564.prototype.reset = function() { + this.hash.reset(); + }; + return Sha2564; + })(); + } + }); + + // node_modules/@aws-crypto/sha256-browser/build/module/index.js + var init_module4 = __esm({ + "node_modules/@aws-crypto/sha256-browser/build/module/index.js"() { + init_crossPlatformSha256(); + init_webCryptoSha256(); + } + }); + + // node_modules/bowser/es5.js + var require_es5 = __commonJS({ + "node_modules/bowser/es5.js"(exports, module) { + !(function(e2, t2) { + "object" == typeof exports && "object" == typeof module ? module.exports = t2() : "function" == typeof define && define.amd ? define([], t2) : "object" == typeof exports ? exports.bowser = t2() : e2.bowser = t2(); + })(exports, (function() { + return (function(e2) { + var t2 = {}; + function r2(i2) { + if (t2[i2]) return t2[i2].exports; + var n2 = t2[i2] = { i: i2, l: false, exports: {} }; + return e2[i2].call(n2.exports, n2, n2.exports, r2), n2.l = true, n2.exports; + } + return r2.m = e2, r2.c = t2, r2.d = function(e3, t3, i2) { + r2.o(e3, t3) || Object.defineProperty(e3, t3, { enumerable: true, get: i2 }); + }, r2.r = function(e3) { + "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e3, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(e3, "__esModule", { value: true }); + }, r2.t = function(e3, t3) { + if (1 & t3 && (e3 = r2(e3)), 8 & t3) return e3; + if (4 & t3 && "object" == typeof e3 && e3 && e3.__esModule) return e3; + var i2 = /* @__PURE__ */ Object.create(null); + if (r2.r(i2), Object.defineProperty(i2, "default", { enumerable: true, value: e3 }), 2 & t3 && "string" != typeof e3) for (var n2 in e3) r2.d(i2, n2, function(t4) { + return e3[t4]; + }.bind(null, n2)); + return i2; + }, r2.n = function(e3) { + var t3 = e3 && e3.__esModule ? function() { + return e3.default; + } : function() { + return e3; + }; + return r2.d(t3, "a", t3), t3; + }, r2.o = function(e3, t3) { + return Object.prototype.hasOwnProperty.call(e3, t3); + }, r2.p = "", r2(r2.s = 90); + })({ 17: function(e2, t2, r2) { + "use strict"; + t2.__esModule = true, t2.default = void 0; + var i2 = r2(18), n2 = (function() { + function e3() { + } + return e3.getFirstMatch = function(e4, t3) { + var r3 = t3.match(e4); + return r3 && r3.length > 0 && r3[1] || ""; + }, e3.getSecondMatch = function(e4, t3) { + var r3 = t3.match(e4); + return r3 && r3.length > 1 && r3[2] || ""; + }, e3.matchAndReturnConst = function(e4, t3, r3) { + if (e4.test(t3)) return r3; + }, e3.getWindowsVersionName = function(e4) { + switch (e4) { + case "NT": + return "NT"; + case "XP": + return "XP"; + case "NT 5.0": + return "2000"; + case "NT 5.1": + return "XP"; + case "NT 5.2": + return "2003"; + case "NT 6.0": + return "Vista"; + case "NT 6.1": + return "7"; + case "NT 6.2": + return "8"; + case "NT 6.3": + return "8.1"; + case "NT 10.0": + return "10"; + default: + return; + } + }, e3.getMacOSVersionName = function(e4) { + var t3 = e4.split(".").splice(0, 2).map((function(e5) { + return parseInt(e5, 10) || 0; + })); + if (t3.push(0), 10 === t3[0]) switch (t3[1]) { + case 5: + return "Leopard"; + case 6: + return "Snow Leopard"; + case 7: + return "Lion"; + case 8: + return "Mountain Lion"; + case 9: + return "Mavericks"; + case 10: + return "Yosemite"; + case 11: + return "El Capitan"; + case 12: + return "Sierra"; + case 13: + return "High Sierra"; + case 14: + return "Mojave"; + case 15: + return "Catalina"; + default: + return; + } + }, e3.getAndroidVersionName = function(e4) { + var t3 = e4.split(".").splice(0, 2).map((function(e5) { + return parseInt(e5, 10) || 0; + })); + if (t3.push(0), !(1 === t3[0] && t3[1] < 5)) return 1 === t3[0] && t3[1] < 6 ? "Cupcake" : 1 === t3[0] && t3[1] >= 6 ? "Donut" : 2 === t3[0] && t3[1] < 2 ? "Eclair" : 2 === t3[0] && 2 === t3[1] ? "Froyo" : 2 === t3[0] && t3[1] > 2 ? "Gingerbread" : 3 === t3[0] ? "Honeycomb" : 4 === t3[0] && t3[1] < 1 ? "Ice Cream Sandwich" : 4 === t3[0] && t3[1] < 4 ? "Jelly Bean" : 4 === t3[0] && t3[1] >= 4 ? "KitKat" : 5 === t3[0] ? "Lollipop" : 6 === t3[0] ? "Marshmallow" : 7 === t3[0] ? "Nougat" : 8 === t3[0] ? "Oreo" : 9 === t3[0] ? "Pie" : void 0; + }, e3.getVersionPrecision = function(e4) { + return e4.split(".").length; + }, e3.compareVersions = function(t3, r3, i3) { + void 0 === i3 && (i3 = false); + var n3 = e3.getVersionPrecision(t3), s2 = e3.getVersionPrecision(r3), a2 = Math.max(n3, s2), o2 = 0, u4 = e3.map([t3, r3], (function(t4) { + var r4 = a2 - e3.getVersionPrecision(t4), i4 = t4 + new Array(r4 + 1).join(".0"); + return e3.map(i4.split("."), (function(e4) { + return new Array(20 - e4.length).join("0") + e4; + })).reverse(); + })); + for (i3 && (o2 = a2 - Math.min(n3, s2)), a2 -= 1; a2 >= o2; ) { + if (u4[0][a2] > u4[1][a2]) return 1; + if (u4[0][a2] === u4[1][a2]) { + if (a2 === o2) return 0; + a2 -= 1; + } else if (u4[0][a2] < u4[1][a2]) return -1; + } + }, e3.map = function(e4, t3) { + var r3, i3 = []; + if (Array.prototype.map) return Array.prototype.map.call(e4, t3); + for (r3 = 0; r3 < e4.length; r3 += 1) i3.push(t3(e4[r3])); + return i3; + }, e3.find = function(e4, t3) { + var r3, i3; + if (Array.prototype.find) return Array.prototype.find.call(e4, t3); + for (r3 = 0, i3 = e4.length; r3 < i3; r3 += 1) { + var n3 = e4[r3]; + if (t3(n3, r3)) return n3; + } + }, e3.assign = function(e4) { + for (var t3, r3, i3 = e4, n3 = arguments.length, s2 = new Array(n3 > 1 ? n3 - 1 : 0), a2 = 1; a2 < n3; a2++) s2[a2 - 1] = arguments[a2]; + if (Object.assign) return Object.assign.apply(Object, [e4].concat(s2)); + var o2 = function() { + var e5 = s2[t3]; + "object" == typeof e5 && null !== e5 && Object.keys(e5).forEach((function(t4) { + i3[t4] = e5[t4]; + })); + }; + for (t3 = 0, r3 = s2.length; t3 < r3; t3 += 1) o2(); + return e4; + }, e3.getBrowserAlias = function(e4) { + return i2.BROWSER_ALIASES_MAP[e4]; + }, e3.getBrowserTypeByAlias = function(e4) { + return i2.BROWSER_MAP[e4] || ""; + }, e3; + })(); + t2.default = n2, e2.exports = t2.default; + }, 18: function(e2, t2, r2) { + "use strict"; + t2.__esModule = true, t2.ENGINE_MAP = t2.OS_MAP = t2.PLATFORMS_MAP = t2.BROWSER_MAP = t2.BROWSER_ALIASES_MAP = void 0; + t2.BROWSER_ALIASES_MAP = { "Amazon Silk": "amazon_silk", "Android Browser": "android", Bada: "bada", BlackBerry: "blackberry", Chrome: "chrome", Chromium: "chromium", Electron: "electron", Epiphany: "epiphany", Firefox: "firefox", Focus: "focus", Generic: "generic", "Google Search": "google_search", Googlebot: "googlebot", "Internet Explorer": "ie", "K-Meleon": "k_meleon", Maxthon: "maxthon", "Microsoft Edge": "edge", "MZ Browser": "mz", "NAVER Whale Browser": "naver", Opera: "opera", "Opera Coast": "opera_coast", "Pale Moon": "pale_moon", PhantomJS: "phantomjs", Puffin: "puffin", QupZilla: "qupzilla", QQ: "qq", QQLite: "qqlite", Safari: "safari", Sailfish: "sailfish", "Samsung Internet for Android": "samsung_internet", SeaMonkey: "seamonkey", Sleipnir: "sleipnir", Swing: "swing", Tizen: "tizen", "UC Browser": "uc", Vivaldi: "vivaldi", "WebOS Browser": "webos", WeChat: "wechat", "Yandex Browser": "yandex", Roku: "roku" }; + t2.BROWSER_MAP = { amazon_silk: "Amazon Silk", android: "Android Browser", bada: "Bada", blackberry: "BlackBerry", chrome: "Chrome", chromium: "Chromium", electron: "Electron", epiphany: "Epiphany", firefox: "Firefox", focus: "Focus", generic: "Generic", googlebot: "Googlebot", google_search: "Google Search", ie: "Internet Explorer", k_meleon: "K-Meleon", maxthon: "Maxthon", edge: "Microsoft Edge", mz: "MZ Browser", naver: "NAVER Whale Browser", opera: "Opera", opera_coast: "Opera Coast", pale_moon: "Pale Moon", phantomjs: "PhantomJS", puffin: "Puffin", qupzilla: "QupZilla", qq: "QQ Browser", qqlite: "QQ Browser Lite", safari: "Safari", sailfish: "Sailfish", samsung_internet: "Samsung Internet for Android", seamonkey: "SeaMonkey", sleipnir: "Sleipnir", swing: "Swing", tizen: "Tizen", uc: "UC Browser", vivaldi: "Vivaldi", webos: "WebOS Browser", wechat: "WeChat", yandex: "Yandex Browser" }; + t2.PLATFORMS_MAP = { tablet: "tablet", mobile: "mobile", desktop: "desktop", tv: "tv", bot: "bot" }; + t2.OS_MAP = { WindowsPhone: "Windows Phone", Windows: "Windows", MacOS: "macOS", iOS: "iOS", Android: "Android", WebOS: "WebOS", BlackBerry: "BlackBerry", Bada: "Bada", Tizen: "Tizen", Linux: "Linux", ChromeOS: "Chrome OS", PlayStation4: "PlayStation 4", Roku: "Roku" }; + t2.ENGINE_MAP = { EdgeHTML: "EdgeHTML", Blink: "Blink", Trident: "Trident", Presto: "Presto", Gecko: "Gecko", WebKit: "WebKit" }; + }, 90: function(e2, t2, r2) { + "use strict"; + t2.__esModule = true, t2.default = void 0; + var i2, n2 = (i2 = r2(91)) && i2.__esModule ? i2 : { default: i2 }, s2 = r2(18); + function a2(e3, t3) { + for (var r3 = 0; r3 < t3.length; r3++) { + var i3 = t3[r3]; + i3.enumerable = i3.enumerable || false, i3.configurable = true, "value" in i3 && (i3.writable = true), Object.defineProperty(e3, i3.key, i3); + } + } + var o2 = (function() { + function e3() { + } + var t3, r3, i3; + return e3.getParser = function(e4, t4) { + if (void 0 === t4 && (t4 = false), "string" != typeof e4) throw new Error("UserAgent should be a string"); + return new n2.default(e4, t4); + }, e3.parse = function(e4) { + return new n2.default(e4).getResult(); + }, t3 = e3, i3 = [{ key: "BROWSER_MAP", get: function() { + return s2.BROWSER_MAP; + } }, { key: "ENGINE_MAP", get: function() { + return s2.ENGINE_MAP; + } }, { key: "OS_MAP", get: function() { + return s2.OS_MAP; + } }, { key: "PLATFORMS_MAP", get: function() { + return s2.PLATFORMS_MAP; + } }], (r3 = null) && a2(t3.prototype, r3), i3 && a2(t3, i3), e3; + })(); + t2.default = o2, e2.exports = t2.default; + }, 91: function(e2, t2, r2) { + "use strict"; + t2.__esModule = true, t2.default = void 0; + var i2 = u4(r2(92)), n2 = u4(r2(93)), s2 = u4(r2(94)), a2 = u4(r2(95)), o2 = u4(r2(17)); + function u4(e3) { + return e3 && e3.__esModule ? e3 : { default: e3 }; + } + var d3 = (function() { + function e3(e4, t4) { + if (void 0 === t4 && (t4 = false), null == e4 || "" === e4) throw new Error("UserAgent parameter can't be empty"); + this._ua = e4, this.parsedResult = {}, true !== t4 && this.parse(); + } + var t3 = e3.prototype; + return t3.getUA = function() { + return this._ua; + }, t3.test = function(e4) { + return e4.test(this._ua); + }, t3.parseBrowser = function() { + var e4 = this; + this.parsedResult.browser = {}; + var t4 = o2.default.find(i2.default, (function(t5) { + if ("function" == typeof t5.test) return t5.test(e4); + if (Array.isArray(t5.test)) return t5.test.some((function(t6) { + return e4.test(t6); + })); + throw new Error("Browser's test function is not valid"); + })); + return t4 && (this.parsedResult.browser = t4.describe(this.getUA())), this.parsedResult.browser; + }, t3.getBrowser = function() { + return this.parsedResult.browser ? this.parsedResult.browser : this.parseBrowser(); + }, t3.getBrowserName = function(e4) { + return e4 ? String(this.getBrowser().name).toLowerCase() || "" : this.getBrowser().name || ""; + }, t3.getBrowserVersion = function() { + return this.getBrowser().version; + }, t3.getOS = function() { + return this.parsedResult.os ? this.parsedResult.os : this.parseOS(); + }, t3.parseOS = function() { + var e4 = this; + this.parsedResult.os = {}; + var t4 = o2.default.find(n2.default, (function(t5) { + if ("function" == typeof t5.test) return t5.test(e4); + if (Array.isArray(t5.test)) return t5.test.some((function(t6) { + return e4.test(t6); + })); + throw new Error("Browser's test function is not valid"); + })); + return t4 && (this.parsedResult.os = t4.describe(this.getUA())), this.parsedResult.os; + }, t3.getOSName = function(e4) { + var t4 = this.getOS().name; + return e4 ? String(t4).toLowerCase() || "" : t4 || ""; + }, t3.getOSVersion = function() { + return this.getOS().version; + }, t3.getPlatform = function() { + return this.parsedResult.platform ? this.parsedResult.platform : this.parsePlatform(); + }, t3.getPlatformType = function(e4) { + void 0 === e4 && (e4 = false); + var t4 = this.getPlatform().type; + return e4 ? String(t4).toLowerCase() || "" : t4 || ""; + }, t3.parsePlatform = function() { + var e4 = this; + this.parsedResult.platform = {}; + var t4 = o2.default.find(s2.default, (function(t5) { + if ("function" == typeof t5.test) return t5.test(e4); + if (Array.isArray(t5.test)) return t5.test.some((function(t6) { + return e4.test(t6); + })); + throw new Error("Browser's test function is not valid"); + })); + return t4 && (this.parsedResult.platform = t4.describe(this.getUA())), this.parsedResult.platform; + }, t3.getEngine = function() { + return this.parsedResult.engine ? this.parsedResult.engine : this.parseEngine(); + }, t3.getEngineName = function(e4) { + return e4 ? String(this.getEngine().name).toLowerCase() || "" : this.getEngine().name || ""; + }, t3.parseEngine = function() { + var e4 = this; + this.parsedResult.engine = {}; + var t4 = o2.default.find(a2.default, (function(t5) { + if ("function" == typeof t5.test) return t5.test(e4); + if (Array.isArray(t5.test)) return t5.test.some((function(t6) { + return e4.test(t6); + })); + throw new Error("Browser's test function is not valid"); + })); + return t4 && (this.parsedResult.engine = t4.describe(this.getUA())), this.parsedResult.engine; + }, t3.parse = function() { + return this.parseBrowser(), this.parseOS(), this.parsePlatform(), this.parseEngine(), this; + }, t3.getResult = function() { + return o2.default.assign({}, this.parsedResult); + }, t3.satisfies = function(e4) { + var t4 = this, r3 = {}, i3 = 0, n3 = {}, s3 = 0; + if (Object.keys(e4).forEach((function(t5) { + var a4 = e4[t5]; + "string" == typeof a4 ? (n3[t5] = a4, s3 += 1) : "object" == typeof a4 && (r3[t5] = a4, i3 += 1); + })), i3 > 0) { + var a3 = Object.keys(r3), u5 = o2.default.find(a3, (function(e5) { + return t4.isOS(e5); + })); + if (u5) { + var d4 = this.satisfies(r3[u5]); + if (void 0 !== d4) return d4; + } + var c3 = o2.default.find(a3, (function(e5) { + return t4.isPlatform(e5); + })); + if (c3) { + var f3 = this.satisfies(r3[c3]); + if (void 0 !== f3) return f3; + } + } + if (s3 > 0) { + var l2 = Object.keys(n3), h2 = o2.default.find(l2, (function(e5) { + return t4.isBrowser(e5, true); + })); + if (void 0 !== h2) return this.compareVersion(n3[h2]); + } + }, t3.isBrowser = function(e4, t4) { + void 0 === t4 && (t4 = false); + var r3 = this.getBrowserName().toLowerCase(), i3 = e4.toLowerCase(), n3 = o2.default.getBrowserTypeByAlias(i3); + return t4 && n3 && (i3 = n3.toLowerCase()), i3 === r3; + }, t3.compareVersion = function(e4) { + var t4 = [0], r3 = e4, i3 = false, n3 = this.getBrowserVersion(); + if ("string" == typeof n3) return ">" === e4[0] || "<" === e4[0] ? (r3 = e4.substr(1), "=" === e4[1] ? (i3 = true, r3 = e4.substr(2)) : t4 = [], ">" === e4[0] ? t4.push(1) : t4.push(-1)) : "=" === e4[0] ? r3 = e4.substr(1) : "~" === e4[0] && (i3 = true, r3 = e4.substr(1)), t4.indexOf(o2.default.compareVersions(n3, r3, i3)) > -1; + }, t3.isOS = function(e4) { + return this.getOSName(true) === String(e4).toLowerCase(); + }, t3.isPlatform = function(e4) { + return this.getPlatformType(true) === String(e4).toLowerCase(); + }, t3.isEngine = function(e4) { + return this.getEngineName(true) === String(e4).toLowerCase(); + }, t3.is = function(e4, t4) { + return void 0 === t4 && (t4 = false), this.isBrowser(e4, t4) || this.isOS(e4) || this.isPlatform(e4); + }, t3.some = function(e4) { + var t4 = this; + return void 0 === e4 && (e4 = []), e4.some((function(e5) { + return t4.is(e5); + })); + }, e3; + })(); + t2.default = d3, e2.exports = t2.default; + }, 92: function(e2, t2, r2) { + "use strict"; + t2.__esModule = true, t2.default = void 0; + var i2, n2 = (i2 = r2(17)) && i2.__esModule ? i2 : { default: i2 }; + var s2 = /version\/(\d+(\.?_?\d+)+)/i, a2 = [{ test: [/googlebot/i], describe: function(e3) { + var t3 = { name: "Googlebot" }, r3 = n2.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i, e3) || n2.default.getFirstMatch(s2, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/opera/i], describe: function(e3) { + var t3 = { name: "Opera" }, r3 = n2.default.getFirstMatch(s2, e3) || n2.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/opr\/|opios/i], describe: function(e3) { + var t3 = { name: "Opera" }, r3 = n2.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i, e3) || n2.default.getFirstMatch(s2, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/SamsungBrowser/i], describe: function(e3) { + var t3 = { name: "Samsung Internet for Android" }, r3 = n2.default.getFirstMatch(s2, e3) || n2.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/Whale/i], describe: function(e3) { + var t3 = { name: "NAVER Whale Browser" }, r3 = n2.default.getFirstMatch(s2, e3) || n2.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/PaleMoon/i], describe: function(e3) { + var t3 = { name: "Pale Moon" }, r3 = n2.default.getFirstMatch(s2, e3) || n2.default.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/MZBrowser/i], describe: function(e3) { + var t3 = { name: "MZ Browser" }, r3 = n2.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i, e3) || n2.default.getFirstMatch(s2, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/focus/i], describe: function(e3) { + var t3 = { name: "Focus" }, r3 = n2.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i, e3) || n2.default.getFirstMatch(s2, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/swing/i], describe: function(e3) { + var t3 = { name: "Swing" }, r3 = n2.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i, e3) || n2.default.getFirstMatch(s2, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/coast/i], describe: function(e3) { + var t3 = { name: "Opera Coast" }, r3 = n2.default.getFirstMatch(s2, e3) || n2.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/opt\/\d+(?:.?_?\d+)+/i], describe: function(e3) { + var t3 = { name: "Opera Touch" }, r3 = n2.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i, e3) || n2.default.getFirstMatch(s2, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/yabrowser/i], describe: function(e3) { + var t3 = { name: "Yandex Browser" }, r3 = n2.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i, e3) || n2.default.getFirstMatch(s2, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/ucbrowser/i], describe: function(e3) { + var t3 = { name: "UC Browser" }, r3 = n2.default.getFirstMatch(s2, e3) || n2.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/Maxthon|mxios/i], describe: function(e3) { + var t3 = { name: "Maxthon" }, r3 = n2.default.getFirstMatch(s2, e3) || n2.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/epiphany/i], describe: function(e3) { + var t3 = { name: "Epiphany" }, r3 = n2.default.getFirstMatch(s2, e3) || n2.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/puffin/i], describe: function(e3) { + var t3 = { name: "Puffin" }, r3 = n2.default.getFirstMatch(s2, e3) || n2.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/sleipnir/i], describe: function(e3) { + var t3 = { name: "Sleipnir" }, r3 = n2.default.getFirstMatch(s2, e3) || n2.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/k-meleon/i], describe: function(e3) { + var t3 = { name: "K-Meleon" }, r3 = n2.default.getFirstMatch(s2, e3) || n2.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/micromessenger/i], describe: function(e3) { + var t3 = { name: "WeChat" }, r3 = n2.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i, e3) || n2.default.getFirstMatch(s2, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/qqbrowser/i], describe: function(e3) { + var t3 = { name: /qqbrowserlite/i.test(e3) ? "QQ Browser Lite" : "QQ Browser" }, r3 = n2.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i, e3) || n2.default.getFirstMatch(s2, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/msie|trident/i], describe: function(e3) { + var t3 = { name: "Internet Explorer" }, r3 = n2.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/\sedg\//i], describe: function(e3) { + var t3 = { name: "Microsoft Edge" }, r3 = n2.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/edg([ea]|ios)/i], describe: function(e3) { + var t3 = { name: "Microsoft Edge" }, r3 = n2.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/vivaldi/i], describe: function(e3) { + var t3 = { name: "Vivaldi" }, r3 = n2.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/seamonkey/i], describe: function(e3) { + var t3 = { name: "SeaMonkey" }, r3 = n2.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/sailfish/i], describe: function(e3) { + var t3 = { name: "Sailfish" }, r3 = n2.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/silk/i], describe: function(e3) { + var t3 = { name: "Amazon Silk" }, r3 = n2.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/phantom/i], describe: function(e3) { + var t3 = { name: "PhantomJS" }, r3 = n2.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/slimerjs/i], describe: function(e3) { + var t3 = { name: "SlimerJS" }, r3 = n2.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/blackberry|\bbb\d+/i, /rim\stablet/i], describe: function(e3) { + var t3 = { name: "BlackBerry" }, r3 = n2.default.getFirstMatch(s2, e3) || n2.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/(web|hpw)[o0]s/i], describe: function(e3) { + var t3 = { name: "WebOS Browser" }, r3 = n2.default.getFirstMatch(s2, e3) || n2.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/bada/i], describe: function(e3) { + var t3 = { name: "Bada" }, r3 = n2.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/tizen/i], describe: function(e3) { + var t3 = { name: "Tizen" }, r3 = n2.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i, e3) || n2.default.getFirstMatch(s2, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/qupzilla/i], describe: function(e3) { + var t3 = { name: "QupZilla" }, r3 = n2.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i, e3) || n2.default.getFirstMatch(s2, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/firefox|iceweasel|fxios/i], describe: function(e3) { + var t3 = { name: "Firefox" }, r3 = n2.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/electron/i], describe: function(e3) { + var t3 = { name: "Electron" }, r3 = n2.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/MiuiBrowser/i], describe: function(e3) { + var t3 = { name: "Miui" }, r3 = n2.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/chromium/i], describe: function(e3) { + var t3 = { name: "Chromium" }, r3 = n2.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i, e3) || n2.default.getFirstMatch(s2, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/chrome|crios|crmo/i], describe: function(e3) { + var t3 = { name: "Chrome" }, r3 = n2.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/GSA/i], describe: function(e3) { + var t3 = { name: "Google Search" }, r3 = n2.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: function(e3) { + var t3 = !e3.test(/like android/i), r3 = e3.test(/android/i); + return t3 && r3; + }, describe: function(e3) { + var t3 = { name: "Android Browser" }, r3 = n2.default.getFirstMatch(s2, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/playstation 4/i], describe: function(e3) { + var t3 = { name: "PlayStation 4" }, r3 = n2.default.getFirstMatch(s2, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/safari|applewebkit/i], describe: function(e3) { + var t3 = { name: "Safari" }, r3 = n2.default.getFirstMatch(s2, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/.*/i], describe: function(e3) { + var t3 = -1 !== e3.search("\\(") ? /^(.*)\/(.*)[ \t]\((.*)/ : /^(.*)\/(.*) /; + return { name: n2.default.getFirstMatch(t3, e3), version: n2.default.getSecondMatch(t3, e3) }; + } }]; + t2.default = a2, e2.exports = t2.default; + }, 93: function(e2, t2, r2) { + "use strict"; + t2.__esModule = true, t2.default = void 0; + var i2, n2 = (i2 = r2(17)) && i2.__esModule ? i2 : { default: i2 }, s2 = r2(18); + var a2 = [{ test: [/Roku\/DVP/], describe: function(e3) { + var t3 = n2.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i, e3); + return { name: s2.OS_MAP.Roku, version: t3 }; + } }, { test: [/windows phone/i], describe: function(e3) { + var t3 = n2.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i, e3); + return { name: s2.OS_MAP.WindowsPhone, version: t3 }; + } }, { test: [/windows /i], describe: function(e3) { + var t3 = n2.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i, e3), r3 = n2.default.getWindowsVersionName(t3); + return { name: s2.OS_MAP.Windows, version: t3, versionName: r3 }; + } }, { test: [/Macintosh(.*?) FxiOS(.*?)\//], describe: function(e3) { + var t3 = { name: s2.OS_MAP.iOS }, r3 = n2.default.getSecondMatch(/(Version\/)(\d[\d.]+)/, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/macintosh/i], describe: function(e3) { + var t3 = n2.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i, e3).replace(/[_\s]/g, "."), r3 = n2.default.getMacOSVersionName(t3), i3 = { name: s2.OS_MAP.MacOS, version: t3 }; + return r3 && (i3.versionName = r3), i3; + } }, { test: [/(ipod|iphone|ipad)/i], describe: function(e3) { + var t3 = n2.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i, e3).replace(/[_\s]/g, "."); + return { name: s2.OS_MAP.iOS, version: t3 }; + } }, { test: function(e3) { + var t3 = !e3.test(/like android/i), r3 = e3.test(/android/i); + return t3 && r3; + }, describe: function(e3) { + var t3 = n2.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i, e3), r3 = n2.default.getAndroidVersionName(t3), i3 = { name: s2.OS_MAP.Android, version: t3 }; + return r3 && (i3.versionName = r3), i3; + } }, { test: [/(web|hpw)[o0]s/i], describe: function(e3) { + var t3 = n2.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i, e3), r3 = { name: s2.OS_MAP.WebOS }; + return t3 && t3.length && (r3.version = t3), r3; + } }, { test: [/blackberry|\bbb\d+/i, /rim\stablet/i], describe: function(e3) { + var t3 = n2.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i, e3) || n2.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i, e3) || n2.default.getFirstMatch(/\bbb(\d+)/i, e3); + return { name: s2.OS_MAP.BlackBerry, version: t3 }; + } }, { test: [/bada/i], describe: function(e3) { + var t3 = n2.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i, e3); + return { name: s2.OS_MAP.Bada, version: t3 }; + } }, { test: [/tizen/i], describe: function(e3) { + var t3 = n2.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i, e3); + return { name: s2.OS_MAP.Tizen, version: t3 }; + } }, { test: [/linux/i], describe: function() { + return { name: s2.OS_MAP.Linux }; + } }, { test: [/CrOS/], describe: function() { + return { name: s2.OS_MAP.ChromeOS }; + } }, { test: [/PlayStation 4/], describe: function(e3) { + var t3 = n2.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i, e3); + return { name: s2.OS_MAP.PlayStation4, version: t3 }; + } }]; + t2.default = a2, e2.exports = t2.default; + }, 94: function(e2, t2, r2) { + "use strict"; + t2.__esModule = true, t2.default = void 0; + var i2, n2 = (i2 = r2(17)) && i2.__esModule ? i2 : { default: i2 }, s2 = r2(18); + var a2 = [{ test: [/googlebot/i], describe: function() { + return { type: s2.PLATFORMS_MAP.bot, vendor: "Google" }; + } }, { test: [/huawei/i], describe: function(e3) { + var t3 = n2.default.getFirstMatch(/(can-l01)/i, e3) && "Nova", r3 = { type: s2.PLATFORMS_MAP.mobile, vendor: "Huawei" }; + return t3 && (r3.model = t3), r3; + } }, { test: [/nexus\s*(?:7|8|9|10).*/i], describe: function() { + return { type: s2.PLATFORMS_MAP.tablet, vendor: "Nexus" }; + } }, { test: [/ipad/i], describe: function() { + return { type: s2.PLATFORMS_MAP.tablet, vendor: "Apple", model: "iPad" }; + } }, { test: [/Macintosh(.*?) FxiOS(.*?)\//], describe: function() { + return { type: s2.PLATFORMS_MAP.tablet, vendor: "Apple", model: "iPad" }; + } }, { test: [/kftt build/i], describe: function() { + return { type: s2.PLATFORMS_MAP.tablet, vendor: "Amazon", model: "Kindle Fire HD 7" }; + } }, { test: [/silk/i], describe: function() { + return { type: s2.PLATFORMS_MAP.tablet, vendor: "Amazon" }; + } }, { test: [/tablet(?! pc)/i], describe: function() { + return { type: s2.PLATFORMS_MAP.tablet }; + } }, { test: function(e3) { + var t3 = e3.test(/ipod|iphone/i), r3 = e3.test(/like (ipod|iphone)/i); + return t3 && !r3; + }, describe: function(e3) { + var t3 = n2.default.getFirstMatch(/(ipod|iphone)/i, e3); + return { type: s2.PLATFORMS_MAP.mobile, vendor: "Apple", model: t3 }; + } }, { test: [/nexus\s*[0-6].*/i, /galaxy nexus/i], describe: function() { + return { type: s2.PLATFORMS_MAP.mobile, vendor: "Nexus" }; + } }, { test: [/Nokia/i], describe: function(e3) { + var t3 = n2.default.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i, e3), r3 = { type: s2.PLATFORMS_MAP.mobile, vendor: "Nokia" }; + return t3 && (r3.model = t3), r3; + } }, { test: [/[^-]mobi/i], describe: function() { + return { type: s2.PLATFORMS_MAP.mobile }; + } }, { test: function(e3) { + return "blackberry" === e3.getBrowserName(true); + }, describe: function() { + return { type: s2.PLATFORMS_MAP.mobile, vendor: "BlackBerry" }; + } }, { test: function(e3) { + return "bada" === e3.getBrowserName(true); + }, describe: function() { + return { type: s2.PLATFORMS_MAP.mobile }; + } }, { test: function(e3) { + return "windows phone" === e3.getBrowserName(); + }, describe: function() { + return { type: s2.PLATFORMS_MAP.mobile, vendor: "Microsoft" }; + } }, { test: function(e3) { + var t3 = Number(String(e3.getOSVersion()).split(".")[0]); + return "android" === e3.getOSName(true) && t3 >= 3; + }, describe: function() { + return { type: s2.PLATFORMS_MAP.tablet }; + } }, { test: function(e3) { + return "android" === e3.getOSName(true); + }, describe: function() { + return { type: s2.PLATFORMS_MAP.mobile }; + } }, { test: function(e3) { + return "macos" === e3.getOSName(true); + }, describe: function() { + return { type: s2.PLATFORMS_MAP.desktop, vendor: "Apple" }; + } }, { test: function(e3) { + return "windows" === e3.getOSName(true); + }, describe: function() { + return { type: s2.PLATFORMS_MAP.desktop }; + } }, { test: function(e3) { + return "linux" === e3.getOSName(true); + }, describe: function() { + return { type: s2.PLATFORMS_MAP.desktop }; + } }, { test: function(e3) { + return "playstation 4" === e3.getOSName(true); + }, describe: function() { + return { type: s2.PLATFORMS_MAP.tv }; + } }, { test: function(e3) { + return "roku" === e3.getOSName(true); + }, describe: function() { + return { type: s2.PLATFORMS_MAP.tv }; + } }]; + t2.default = a2, e2.exports = t2.default; + }, 95: function(e2, t2, r2) { + "use strict"; + t2.__esModule = true, t2.default = void 0; + var i2, n2 = (i2 = r2(17)) && i2.__esModule ? i2 : { default: i2 }, s2 = r2(18); + var a2 = [{ test: function(e3) { + return "microsoft edge" === e3.getBrowserName(true); + }, describe: function(e3) { + if (/\sedg\//i.test(e3)) return { name: s2.ENGINE_MAP.Blink }; + var t3 = n2.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i, e3); + return { name: s2.ENGINE_MAP.EdgeHTML, version: t3 }; + } }, { test: [/trident/i], describe: function(e3) { + var t3 = { name: s2.ENGINE_MAP.Trident }, r3 = n2.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: function(e3) { + return e3.test(/presto/i); + }, describe: function(e3) { + var t3 = { name: s2.ENGINE_MAP.Presto }, r3 = n2.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: function(e3) { + var t3 = e3.test(/gecko/i), r3 = e3.test(/like gecko/i); + return t3 && !r3; + }, describe: function(e3) { + var t3 = { name: s2.ENGINE_MAP.Gecko }, r3 = n2.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }, { test: [/(apple)?webkit\/537\.36/i], describe: function() { + return { name: s2.ENGINE_MAP.Blink }; + } }, { test: [/(apple)?webkit/i], describe: function(e3) { + var t3 = { name: s2.ENGINE_MAP.WebKit }, r3 = n2.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i, e3); + return r3 && (t3.version = r3), t3; + } }]; + t2.default = a2, e2.exports = t2.default; + } }); + })); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-user-agent-browser/dist-es/index.js + var import_bowser, createDefaultUserAgentProvider; + var init_dist_es37 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-user-agent-browser/dist-es/index.js"() { + import_bowser = __toESM(require_es5()); + createDefaultUserAgentProvider = ({ serviceId, clientVersion }) => async (config) => { + const parsedUA = typeof window !== "undefined" && window?.navigator?.userAgent ? import_bowser.default.parse(window.navigator.userAgent) : void 0; + const sections = [ + ["aws-sdk-js", clientVersion], + ["ua", "2.1"], + [`os/${parsedUA?.os?.name || "other"}`, parsedUA?.os?.version], + ["lang/js"], + ["md/browser", `${parsedUA?.browser?.name ?? "unknown"}_${parsedUA?.browser?.version ?? "unknown"}`] + ]; + if (serviceId) { + sections.push([`api/${serviceId}`, clientVersion]); + } + const appId = await config?.userAgentAppId?.(); + if (appId) { + sections.push([`app/${appId}`]); + } + return sections; + }; + } + }); + + // node_modules/@smithy/invalid-dependency/dist-es/invalidFunction.js + var init_invalidFunction = __esm({ + "node_modules/@smithy/invalid-dependency/dist-es/invalidFunction.js"() { + } + }); + + // node_modules/@smithy/invalid-dependency/dist-es/invalidProvider.js + var invalidProvider; + var init_invalidProvider = __esm({ + "node_modules/@smithy/invalid-dependency/dist-es/invalidProvider.js"() { + invalidProvider = (message) => () => Promise.reject(message); + } + }); + + // node_modules/@smithy/invalid-dependency/dist-es/index.js + var init_dist_es38 = __esm({ + "node_modules/@smithy/invalid-dependency/dist-es/index.js"() { + init_invalidFunction(); + init_invalidProvider(); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/endpoint/ruleset.js + var w2, x2, y2, z2, a, b2, c2, d2, e, f2, g, h, i, j2, k2, l, m2, n, o, p, q2, r, s, t, u3, v3, _data, ruleSet; + var init_ruleset = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/endpoint/ruleset.js"() { + w2 = "required"; + x2 = "fn"; + y2 = "argv"; + z2 = "ref"; + a = true; + b2 = "isSet"; + c2 = "booleanEquals"; + d2 = "error"; + e = "endpoint"; + f2 = "tree"; + g = "PartitionResult"; + h = "getAttr"; + i = "stringEquals"; + j2 = { [w2]: false, "type": "String" }; + k2 = { [w2]: true, "default": false, "type": "Boolean" }; + l = { [z2]: "Endpoint" }; + m2 = { [x2]: c2, [y2]: [{ [z2]: "UseFIPS" }, true] }; + n = { [x2]: c2, [y2]: [{ [z2]: "UseDualStack" }, true] }; + o = {}; + p = { [z2]: "Region" }; + q2 = { [x2]: h, [y2]: [{ [z2]: g }, "supportsFIPS"] }; + r = { [z2]: g }; + s = { [x2]: c2, [y2]: [true, { [x2]: h, [y2]: [r, "supportsDualStack"] }] }; + t = [m2]; + u3 = [n]; + v3 = [p]; + _data = { version: "1.0", parameters: { Region: j2, UseDualStack: k2, UseFIPS: k2, Endpoint: j2 }, rules: [{ conditions: [{ [x2]: b2, [y2]: [l] }], rules: [{ conditions: t, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d2 }, { conditions: u3, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d2 }, { endpoint: { url: l, properties: o, headers: o }, type: e }], type: f2 }, { conditions: [{ [x2]: b2, [y2]: v3 }], rules: [{ conditions: [{ [x2]: "aws.partition", [y2]: v3, assign: g }], rules: [{ conditions: [m2, n], rules: [{ conditions: [{ [x2]: c2, [y2]: [a, q2] }, s], rules: [{ conditions: [{ [x2]: i, [y2]: [p, "us-east-1"] }], endpoint: { url: "https://cognito-identity-fips.us-east-1.amazonaws.com", properties: o, headers: o }, type: e }, { conditions: [{ [x2]: i, [y2]: [p, "us-east-2"] }], endpoint: { url: "https://cognito-identity-fips.us-east-2.amazonaws.com", properties: o, headers: o }, type: e }, { conditions: [{ [x2]: i, [y2]: [p, "us-west-1"] }], endpoint: { url: "https://cognito-identity-fips.us-west-1.amazonaws.com", properties: o, headers: o }, type: e }, { conditions: [{ [x2]: i, [y2]: [p, "us-west-2"] }], endpoint: { url: "https://cognito-identity-fips.us-west-2.amazonaws.com", properties: o, headers: o }, type: e }, { endpoint: { url: "https://cognito-identity-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: o, headers: o }, type: e }], type: f2 }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d2 }], type: f2 }, { conditions: t, rules: [{ conditions: [{ [x2]: c2, [y2]: [q2, a] }], rules: [{ endpoint: { url: "https://cognito-identity-fips.{Region}.{PartitionResult#dnsSuffix}", properties: o, headers: o }, type: e }], type: f2 }, { error: "FIPS is enabled but this partition does not support FIPS", type: d2 }], type: f2 }, { conditions: u3, rules: [{ conditions: [s], rules: [{ conditions: [{ [x2]: i, [y2]: ["aws", { [x2]: h, [y2]: [r, "name"] }] }], endpoint: { url: "https://cognito-identity.{Region}.amazonaws.com", properties: o, headers: o }, type: e }, { endpoint: { url: "https://cognito-identity.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: o, headers: o }, type: e }], type: f2 }, { error: "DualStack is enabled but this partition does not support DualStack", type: d2 }], type: f2 }, { endpoint: { url: "https://cognito-identity.{Region}.{PartitionResult#dnsSuffix}", properties: o, headers: o }, type: e }], type: f2 }], type: f2 }, { error: "Invalid Configuration: Missing Region", type: d2 }] }; + ruleSet = _data; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/endpoint/endpointResolver.js + var cache, defaultEndpointResolver; + var init_endpointResolver = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/endpoint/endpointResolver.js"() { + init_dist_es22(); + init_dist_es19(); + init_ruleset(); + cache = new EndpointCache({ + size: 50, + params: ["Endpoint", "Region", "UseDualStack", "UseFIPS"] + }); + defaultEndpointResolver = (endpointParams, context = {}) => { + return cache.get(endpointParams, () => resolveEndpoint(ruleSet, { + endpointParams, + logger: context.logger + })); + }; + customEndpointFunctions.aws = awsEndpointFunctions; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/runtimeConfig.shared.js + var getRuntimeConfig; + var init_runtimeConfig_shared = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/runtimeConfig.shared.js"() { + init_dist_es28(); + init_dist_es18(); + init_dist_es27(); + init_dist_es21(); + init_dist_es11(); + init_dist_es10(); + init_httpAuthSchemeProvider(); + init_endpointResolver(); + getRuntimeConfig = (config) => { + return { + apiVersion: "2014-06-30", + base64Decoder: config?.base64Decoder ?? fromBase64, + base64Encoder: config?.base64Encoder ?? toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? defaultEndpointResolver, + extensions: config?.extensions ?? [], + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultCognitoIdentityHttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new AwsSdkSigV4Signer() + }, + { + schemeId: "smithy.api#noAuth", + identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), + signer: new NoAuthSigner() + } + ], + logger: config?.logger ?? new NoOpLogger(), + serviceId: config?.serviceId ?? "Cognito Identity", + urlParser: config?.urlParser ?? parseUrl, + utf8Decoder: config?.utf8Decoder ?? fromUtf83, + utf8Encoder: config?.utf8Encoder ?? toUtf8 + }; + }; + } + }); + + // node_modules/@smithy/util-defaults-mode-browser/dist-es/constants.js + var DEFAULTS_MODE_OPTIONS; + var init_constants8 = __esm({ + "node_modules/@smithy/util-defaults-mode-browser/dist-es/constants.js"() { + DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"]; + } + }); + + // node_modules/@smithy/util-defaults-mode-browser/dist-es/resolveDefaultsModeConfig.js + var import_bowser2, resolveDefaultsModeConfig, isMobileBrowser; + var init_resolveDefaultsModeConfig = __esm({ + "node_modules/@smithy/util-defaults-mode-browser/dist-es/resolveDefaultsModeConfig.js"() { + init_dist_es2(); + import_bowser2 = __toESM(require_es5()); + init_constants8(); + resolveDefaultsModeConfig = ({ defaultsMode } = {}) => memoize(async () => { + const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode; + switch (mode?.toLowerCase()) { + case "auto": + return Promise.resolve(isMobileBrowser() ? "mobile" : "standard"); + case "mobile": + case "in-region": + case "cross-region": + case "standard": + case "legacy": + return Promise.resolve(mode?.toLocaleLowerCase()); + case void 0: + return Promise.resolve("legacy"); + default: + throw new Error(`Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}`); + } + }); + isMobileBrowser = () => { + const parsedUA = typeof window !== "undefined" && window?.navigator?.userAgent ? import_bowser2.default.parse(window.navigator.userAgent) : void 0; + const platform = parsedUA?.platform?.type; + return platform === "tablet" || platform === "mobile"; + }; + } + }); + + // node_modules/@smithy/util-defaults-mode-browser/dist-es/index.js + var init_dist_es39 = __esm({ + "node_modules/@smithy/util-defaults-mode-browser/dist-es/index.js"() { + init_resolveDefaultsModeConfig(); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/runtimeConfig.browser.js + var getRuntimeConfig2; + var init_runtimeConfig_browser = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/runtimeConfig.browser.js"() { + init_package(); + init_module4(); + init_dist_es37(); + init_dist_es30(); + init_dist_es14(); + init_dist_es38(); + init_dist_es25(); + init_dist_es34(); + init_runtimeConfig_shared(); + init_dist_es27(); + init_dist_es39(); + getRuntimeConfig2 = (config) => { + const defaultsMode = resolveDefaultsModeConfig(config); + const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode); + const clientSharedValues = getRuntimeConfig(config); + return { + ...clientSharedValues, + ...config, + runtime: "browser", + defaultsMode, + bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength, + credentialDefaultProvider: config?.credentialDefaultProvider ?? ((_2) => () => Promise.reject(new Error("Credential is missing"))), + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: package_default.version }), + maxAttempts: config?.maxAttempts ?? DEFAULT_MAX_ATTEMPTS, + region: config?.region ?? invalidProvider("Region is missing"), + requestHandler: FetchHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), + retryMode: config?.retryMode ?? (async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE), + sha256: config?.sha256 ?? Sha2563, + streamCollector: config?.streamCollector ?? streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? (() => Promise.resolve(DEFAULT_USE_DUALSTACK_ENDPOINT)), + useFipsEndpoint: config?.useFipsEndpoint ?? (() => Promise.resolve(DEFAULT_USE_FIPS_ENDPOINT)) + }; + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/region-config-resolver/dist-es/extensions/index.js + var getAwsRegionExtensionConfiguration, resolveAwsRegionExtensionConfiguration; + var init_extensions4 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/region-config-resolver/dist-es/extensions/index.js"() { + getAwsRegionExtensionConfiguration = (runtimeConfig) => { + return { + setRegion(region2) { + runtimeConfig.region = region2; + }, + region() { + return runtimeConfig.region; + } + }; + }; + resolveAwsRegionExtensionConfiguration = (awsRegionExtensionConfiguration) => { + return { + region: awsRegionExtensionConfiguration.region() + }; + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/config.js + var init_config4 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/config.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/resolveRegionConfig.js + var init_resolveRegionConfig2 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/resolveRegionConfig.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/index.js + var init_regionConfig2 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/index.js"() { + init_config4(); + init_resolveRegionConfig2(); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/region-config-resolver/dist-es/index.js + var init_dist_es40 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/region-config-resolver/dist-es/index.js"() { + init_extensions4(); + init_regionConfig2(); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/auth/httpAuthExtensionConfiguration.js + var getHttpAuthExtensionConfiguration, resolveHttpAuthRuntimeConfig; + var init_httpAuthExtensionConfiguration = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/auth/httpAuthExtensionConfiguration.js"() { + getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index2 === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } else { + _httpAuthSchemes.splice(index2, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + } + }; + }; + resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials() + }; + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/runtimeExtensions.js + var resolveRuntimeExtensions; + var init_runtimeExtensions = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/runtimeExtensions.js"() { + init_dist_es40(); + init_dist_es4(); + init_dist_es27(); + init_httpAuthExtensionConfiguration(); + resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig), getDefaultExtensionConfiguration(runtimeConfig), getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, resolveAwsRegionExtensionConfiguration(extensionConfiguration), resolveDefaultRuntimeConfig(extensionConfiguration), resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/CognitoIdentityClient.js + var CognitoIdentityClient; + var init_CognitoIdentityClient = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/CognitoIdentityClient.js"() { + init_dist_es5(); + init_dist_es6(); + init_dist_es7(); + init_dist_es29(); + init_dist_es30(); + init_dist_es18(); + init_dist_es31(); + init_dist_es32(); + init_dist_es35(); + init_dist_es27(); + init_httpAuthSchemeProvider(); + init_EndpointParameters(); + init_runtimeConfig_browser(); + init_runtimeExtensions(); + CognitoIdentityClient = class extends Client2 { + config; + constructor(...[configuration]) { + const _config_0 = getRuntimeConfig2(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = resolveUserAgentConfig(_config_1); + const _config_3 = resolveRetryConfig(_config_2); + const _config_4 = resolveRegionConfig(_config_3); + const _config_5 = resolveHostHeaderConfig(_config_4); + const _config_6 = resolveEndpointConfig(_config_5); + const _config_7 = resolveHttpAuthSchemeConfig(_config_6); + const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); + this.config = _config_8; + this.middlewareStack.use(getUserAgentPlugin(this.config)); + this.middlewareStack.use(getRetryPlugin(this.config)); + this.middlewareStack.use(getContentLengthPlugin(this.config)); + this.middlewareStack.use(getHostHeaderPlugin(this.config)); + this.middlewareStack.use(getLoggerPlugin(this.config)); + this.middlewareStack.use(getRecursionDetectionPlugin(this.config)); + this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: defaultCognitoIdentityHttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials + }) + })); + this.middlewareStack.use(getHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/models/CognitoIdentityServiceException.js + var CognitoIdentityServiceException; + var init_CognitoIdentityServiceException = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/models/CognitoIdentityServiceException.js"() { + init_dist_es27(); + CognitoIdentityServiceException = class _CognitoIdentityServiceException extends ServiceException { + constructor(options) { + super(options); + Object.setPrototypeOf(this, _CognitoIdentityServiceException.prototype); + } + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/models/models_0.js + var InternalErrorException, InvalidParameterException, LimitExceededException, NotAuthorizedException, ResourceConflictException, TooManyRequestsException, ResourceNotFoundException, ExternalServiceException, InvalidIdentityPoolConfigurationException, DeveloperUserAlreadyRegisteredException, ConcurrentModificationException, GetCredentialsForIdentityInputFilterSensitiveLog, CredentialsFilterSensitiveLog, GetCredentialsForIdentityResponseFilterSensitiveLog, GetIdInputFilterSensitiveLog, GetOpenIdTokenInputFilterSensitiveLog, GetOpenIdTokenResponseFilterSensitiveLog, GetOpenIdTokenForDeveloperIdentityInputFilterSensitiveLog, GetOpenIdTokenForDeveloperIdentityResponseFilterSensitiveLog, UnlinkIdentityInputFilterSensitiveLog; + var init_models_0 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/models/models_0.js"() { + init_dist_es27(); + init_CognitoIdentityServiceException(); + InternalErrorException = class _InternalErrorException extends CognitoIdentityServiceException { + name = "InternalErrorException"; + $fault = "server"; + constructor(opts) { + super({ + name: "InternalErrorException", + $fault: "server", + ...opts + }); + Object.setPrototypeOf(this, _InternalErrorException.prototype); + } + }; + InvalidParameterException = class _InvalidParameterException extends CognitoIdentityServiceException { + name = "InvalidParameterException"; + $fault = "client"; + constructor(opts) { + super({ + name: "InvalidParameterException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidParameterException.prototype); + } + }; + LimitExceededException = class _LimitExceededException extends CognitoIdentityServiceException { + name = "LimitExceededException"; + $fault = "client"; + constructor(opts) { + super({ + name: "LimitExceededException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _LimitExceededException.prototype); + } + }; + NotAuthorizedException = class _NotAuthorizedException extends CognitoIdentityServiceException { + name = "NotAuthorizedException"; + $fault = "client"; + constructor(opts) { + super({ + name: "NotAuthorizedException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _NotAuthorizedException.prototype); + } + }; + ResourceConflictException = class _ResourceConflictException extends CognitoIdentityServiceException { + name = "ResourceConflictException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ResourceConflictException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _ResourceConflictException.prototype); + } + }; + TooManyRequestsException = class _TooManyRequestsException extends CognitoIdentityServiceException { + name = "TooManyRequestsException"; + $fault = "client"; + constructor(opts) { + super({ + name: "TooManyRequestsException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _TooManyRequestsException.prototype); + } + }; + ResourceNotFoundException = class _ResourceNotFoundException extends CognitoIdentityServiceException { + name = "ResourceNotFoundException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ResourceNotFoundException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _ResourceNotFoundException.prototype); + } + }; + ExternalServiceException = class _ExternalServiceException extends CognitoIdentityServiceException { + name = "ExternalServiceException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ExternalServiceException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _ExternalServiceException.prototype); + } + }; + InvalidIdentityPoolConfigurationException = class _InvalidIdentityPoolConfigurationException extends CognitoIdentityServiceException { + name = "InvalidIdentityPoolConfigurationException"; + $fault = "client"; + constructor(opts) { + super({ + name: "InvalidIdentityPoolConfigurationException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _InvalidIdentityPoolConfigurationException.prototype); + } + }; + DeveloperUserAlreadyRegisteredException = class _DeveloperUserAlreadyRegisteredException extends CognitoIdentityServiceException { + name = "DeveloperUserAlreadyRegisteredException"; + $fault = "client"; + constructor(opts) { + super({ + name: "DeveloperUserAlreadyRegisteredException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _DeveloperUserAlreadyRegisteredException.prototype); + } + }; + ConcurrentModificationException = class _ConcurrentModificationException extends CognitoIdentityServiceException { + name = "ConcurrentModificationException"; + $fault = "client"; + constructor(opts) { + super({ + name: "ConcurrentModificationException", + $fault: "client", + ...opts + }); + Object.setPrototypeOf(this, _ConcurrentModificationException.prototype); + } + }; + GetCredentialsForIdentityInputFilterSensitiveLog = (obj) => ({ + ...obj, + ...obj.Logins && { Logins: SENSITIVE_STRING2 } + }); + CredentialsFilterSensitiveLog = (obj) => ({ + ...obj, + ...obj.SecretKey && { SecretKey: SENSITIVE_STRING2 } + }); + GetCredentialsForIdentityResponseFilterSensitiveLog = (obj) => ({ + ...obj, + ...obj.Credentials && { Credentials: CredentialsFilterSensitiveLog(obj.Credentials) } + }); + GetIdInputFilterSensitiveLog = (obj) => ({ + ...obj, + ...obj.Logins && { Logins: SENSITIVE_STRING2 } + }); + GetOpenIdTokenInputFilterSensitiveLog = (obj) => ({ + ...obj, + ...obj.Logins && { Logins: SENSITIVE_STRING2 } + }); + GetOpenIdTokenResponseFilterSensitiveLog = (obj) => ({ + ...obj, + ...obj.Token && { Token: SENSITIVE_STRING2 } + }); + GetOpenIdTokenForDeveloperIdentityInputFilterSensitiveLog = (obj) => ({ + ...obj, + ...obj.Logins && { Logins: SENSITIVE_STRING2 } + }); + GetOpenIdTokenForDeveloperIdentityResponseFilterSensitiveLog = (obj) => ({ + ...obj, + ...obj.Token && { Token: SENSITIVE_STRING2 } + }); + UnlinkIdentityInputFilterSensitiveLog = (obj) => ({ + ...obj, + ...obj.Logins && { Logins: SENSITIVE_STRING2 } + }); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/protocols/Aws_json1_1.js + function sharedHeaders(operation) { + return { + "content-type": "application/x-amz-json-1.1", + "x-amz-target": `AWSCognitoIdentityService.${operation}` + }; + } + var se_CreateIdentityPoolCommand, se_DeleteIdentitiesCommand, se_DeleteIdentityPoolCommand, se_DescribeIdentityCommand, se_DescribeIdentityPoolCommand, se_GetCredentialsForIdentityCommand, se_GetIdCommand, se_GetIdentityPoolRolesCommand, se_GetOpenIdTokenCommand, se_GetOpenIdTokenForDeveloperIdentityCommand, se_GetPrincipalTagAttributeMapCommand, se_ListIdentitiesCommand, se_ListIdentityPoolsCommand, se_ListTagsForResourceCommand, se_LookupDeveloperIdentityCommand, se_MergeDeveloperIdentitiesCommand, se_SetIdentityPoolRolesCommand, se_SetPrincipalTagAttributeMapCommand, se_TagResourceCommand, se_UnlinkDeveloperIdentityCommand, se_UnlinkIdentityCommand, se_UntagResourceCommand, se_UpdateIdentityPoolCommand, de_CreateIdentityPoolCommand, de_DeleteIdentitiesCommand, de_DeleteIdentityPoolCommand, de_DescribeIdentityCommand, de_DescribeIdentityPoolCommand, de_GetCredentialsForIdentityCommand, de_GetIdCommand, de_GetIdentityPoolRolesCommand, de_GetOpenIdTokenCommand, de_GetOpenIdTokenForDeveloperIdentityCommand, de_GetPrincipalTagAttributeMapCommand, de_ListIdentitiesCommand, de_ListIdentityPoolsCommand, de_ListTagsForResourceCommand, de_LookupDeveloperIdentityCommand, de_MergeDeveloperIdentitiesCommand, de_SetIdentityPoolRolesCommand, de_SetPrincipalTagAttributeMapCommand, de_TagResourceCommand, de_UnlinkDeveloperIdentityCommand, de_UnlinkIdentityCommand, de_UntagResourceCommand, de_UpdateIdentityPoolCommand, de_CommandError, de_ConcurrentModificationExceptionRes, de_DeveloperUserAlreadyRegisteredExceptionRes, de_ExternalServiceExceptionRes, de_InternalErrorExceptionRes, de_InvalidIdentityPoolConfigurationExceptionRes, de_InvalidParameterExceptionRes, de_LimitExceededExceptionRes, de_NotAuthorizedExceptionRes, de_ResourceConflictExceptionRes, de_ResourceNotFoundExceptionRes, de_TooManyRequestsExceptionRes, de_Credentials, de_GetCredentialsForIdentityResponse, de_IdentitiesList, de_IdentityDescription, de_ListIdentitiesResponse, deserializeMetadata2, throwDefaultError2, buildHttpRpcRequest; + var init_Aws_json1_1 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/protocols/Aws_json1_1.js"() { + init_dist_es28(); + init_dist_es4(); + init_dist_es27(); + init_CognitoIdentityServiceException(); + init_models_0(); + se_CreateIdentityPoolCommand = async (input, context) => { + const headers = sharedHeaders("CreateIdentityPool"); + let body; + body = JSON.stringify(_json(input)); + return buildHttpRpcRequest(context, headers, "/", void 0, body); + }; + se_DeleteIdentitiesCommand = async (input, context) => { + const headers = sharedHeaders("DeleteIdentities"); + let body; + body = JSON.stringify(_json(input)); + return buildHttpRpcRequest(context, headers, "/", void 0, body); + }; + se_DeleteIdentityPoolCommand = async (input, context) => { + const headers = sharedHeaders("DeleteIdentityPool"); + let body; + body = JSON.stringify(_json(input)); + return buildHttpRpcRequest(context, headers, "/", void 0, body); + }; + se_DescribeIdentityCommand = async (input, context) => { + const headers = sharedHeaders("DescribeIdentity"); + let body; + body = JSON.stringify(_json(input)); + return buildHttpRpcRequest(context, headers, "/", void 0, body); + }; + se_DescribeIdentityPoolCommand = async (input, context) => { + const headers = sharedHeaders("DescribeIdentityPool"); + let body; + body = JSON.stringify(_json(input)); + return buildHttpRpcRequest(context, headers, "/", void 0, body); + }; + se_GetCredentialsForIdentityCommand = async (input, context) => { + const headers = sharedHeaders("GetCredentialsForIdentity"); + let body; + body = JSON.stringify(_json(input)); + return buildHttpRpcRequest(context, headers, "/", void 0, body); + }; + se_GetIdCommand = async (input, context) => { + const headers = sharedHeaders("GetId"); + let body; + body = JSON.stringify(_json(input)); + return buildHttpRpcRequest(context, headers, "/", void 0, body); + }; + se_GetIdentityPoolRolesCommand = async (input, context) => { + const headers = sharedHeaders("GetIdentityPoolRoles"); + let body; + body = JSON.stringify(_json(input)); + return buildHttpRpcRequest(context, headers, "/", void 0, body); + }; + se_GetOpenIdTokenCommand = async (input, context) => { + const headers = sharedHeaders("GetOpenIdToken"); + let body; + body = JSON.stringify(_json(input)); + return buildHttpRpcRequest(context, headers, "/", void 0, body); + }; + se_GetOpenIdTokenForDeveloperIdentityCommand = async (input, context) => { + const headers = sharedHeaders("GetOpenIdTokenForDeveloperIdentity"); + let body; + body = JSON.stringify(_json(input)); + return buildHttpRpcRequest(context, headers, "/", void 0, body); + }; + se_GetPrincipalTagAttributeMapCommand = async (input, context) => { + const headers = sharedHeaders("GetPrincipalTagAttributeMap"); + let body; + body = JSON.stringify(_json(input)); + return buildHttpRpcRequest(context, headers, "/", void 0, body); + }; + se_ListIdentitiesCommand = async (input, context) => { + const headers = sharedHeaders("ListIdentities"); + let body; + body = JSON.stringify(_json(input)); + return buildHttpRpcRequest(context, headers, "/", void 0, body); + }; + se_ListIdentityPoolsCommand = async (input, context) => { + const headers = sharedHeaders("ListIdentityPools"); + let body; + body = JSON.stringify(_json(input)); + return buildHttpRpcRequest(context, headers, "/", void 0, body); + }; + se_ListTagsForResourceCommand = async (input, context) => { + const headers = sharedHeaders("ListTagsForResource"); + let body; + body = JSON.stringify(_json(input)); + return buildHttpRpcRequest(context, headers, "/", void 0, body); + }; + se_LookupDeveloperIdentityCommand = async (input, context) => { + const headers = sharedHeaders("LookupDeveloperIdentity"); + let body; + body = JSON.stringify(_json(input)); + return buildHttpRpcRequest(context, headers, "/", void 0, body); + }; + se_MergeDeveloperIdentitiesCommand = async (input, context) => { + const headers = sharedHeaders("MergeDeveloperIdentities"); + let body; + body = JSON.stringify(_json(input)); + return buildHttpRpcRequest(context, headers, "/", void 0, body); + }; + se_SetIdentityPoolRolesCommand = async (input, context) => { + const headers = sharedHeaders("SetIdentityPoolRoles"); + let body; + body = JSON.stringify(_json(input)); + return buildHttpRpcRequest(context, headers, "/", void 0, body); + }; + se_SetPrincipalTagAttributeMapCommand = async (input, context) => { + const headers = sharedHeaders("SetPrincipalTagAttributeMap"); + let body; + body = JSON.stringify(_json(input)); + return buildHttpRpcRequest(context, headers, "/", void 0, body); + }; + se_TagResourceCommand = async (input, context) => { + const headers = sharedHeaders("TagResource"); + let body; + body = JSON.stringify(_json(input)); + return buildHttpRpcRequest(context, headers, "/", void 0, body); + }; + se_UnlinkDeveloperIdentityCommand = async (input, context) => { + const headers = sharedHeaders("UnlinkDeveloperIdentity"); + let body; + body = JSON.stringify(_json(input)); + return buildHttpRpcRequest(context, headers, "/", void 0, body); + }; + se_UnlinkIdentityCommand = async (input, context) => { + const headers = sharedHeaders("UnlinkIdentity"); + let body; + body = JSON.stringify(_json(input)); + return buildHttpRpcRequest(context, headers, "/", void 0, body); + }; + se_UntagResourceCommand = async (input, context) => { + const headers = sharedHeaders("UntagResource"); + let body; + body = JSON.stringify(_json(input)); + return buildHttpRpcRequest(context, headers, "/", void 0, body); + }; + se_UpdateIdentityPoolCommand = async (input, context) => { + const headers = sharedHeaders("UpdateIdentityPool"); + let body; + body = JSON.stringify(_json(input)); + return buildHttpRpcRequest(context, headers, "/", void 0, body); + }; + de_CreateIdentityPoolCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await parseJsonBody(output.body, context); + let contents = {}; + contents = _json(data); + const response = { + $metadata: deserializeMetadata2(output), + ...contents + }; + return response; + }; + de_DeleteIdentitiesCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await parseJsonBody(output.body, context); + let contents = {}; + contents = _json(data); + const response = { + $metadata: deserializeMetadata2(output), + ...contents + }; + return response; + }; + de_DeleteIdentityPoolCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + await collectBody(output.body, context); + const response = { + $metadata: deserializeMetadata2(output) + }; + return response; + }; + de_DescribeIdentityCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await parseJsonBody(output.body, context); + let contents = {}; + contents = de_IdentityDescription(data, context); + const response = { + $metadata: deserializeMetadata2(output), + ...contents + }; + return response; + }; + de_DescribeIdentityPoolCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await parseJsonBody(output.body, context); + let contents = {}; + contents = _json(data); + const response = { + $metadata: deserializeMetadata2(output), + ...contents + }; + return response; + }; + de_GetCredentialsForIdentityCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await parseJsonBody(output.body, context); + let contents = {}; + contents = de_GetCredentialsForIdentityResponse(data, context); + const response = { + $metadata: deserializeMetadata2(output), + ...contents + }; + return response; + }; + de_GetIdCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await parseJsonBody(output.body, context); + let contents = {}; + contents = _json(data); + const response = { + $metadata: deserializeMetadata2(output), + ...contents + }; + return response; + }; + de_GetIdentityPoolRolesCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await parseJsonBody(output.body, context); + let contents = {}; + contents = _json(data); + const response = { + $metadata: deserializeMetadata2(output), + ...contents + }; + return response; + }; + de_GetOpenIdTokenCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await parseJsonBody(output.body, context); + let contents = {}; + contents = _json(data); + const response = { + $metadata: deserializeMetadata2(output), + ...contents + }; + return response; + }; + de_GetOpenIdTokenForDeveloperIdentityCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await parseJsonBody(output.body, context); + let contents = {}; + contents = _json(data); + const response = { + $metadata: deserializeMetadata2(output), + ...contents + }; + return response; + }; + de_GetPrincipalTagAttributeMapCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await parseJsonBody(output.body, context); + let contents = {}; + contents = _json(data); + const response = { + $metadata: deserializeMetadata2(output), + ...contents + }; + return response; + }; + de_ListIdentitiesCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await parseJsonBody(output.body, context); + let contents = {}; + contents = de_ListIdentitiesResponse(data, context); + const response = { + $metadata: deserializeMetadata2(output), + ...contents + }; + return response; + }; + de_ListIdentityPoolsCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await parseJsonBody(output.body, context); + let contents = {}; + contents = _json(data); + const response = { + $metadata: deserializeMetadata2(output), + ...contents + }; + return response; + }; + de_ListTagsForResourceCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await parseJsonBody(output.body, context); + let contents = {}; + contents = _json(data); + const response = { + $metadata: deserializeMetadata2(output), + ...contents + }; + return response; + }; + de_LookupDeveloperIdentityCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await parseJsonBody(output.body, context); + let contents = {}; + contents = _json(data); + const response = { + $metadata: deserializeMetadata2(output), + ...contents + }; + return response; + }; + de_MergeDeveloperIdentitiesCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await parseJsonBody(output.body, context); + let contents = {}; + contents = _json(data); + const response = { + $metadata: deserializeMetadata2(output), + ...contents + }; + return response; + }; + de_SetIdentityPoolRolesCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + await collectBody(output.body, context); + const response = { + $metadata: deserializeMetadata2(output) + }; + return response; + }; + de_SetPrincipalTagAttributeMapCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await parseJsonBody(output.body, context); + let contents = {}; + contents = _json(data); + const response = { + $metadata: deserializeMetadata2(output), + ...contents + }; + return response; + }; + de_TagResourceCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await parseJsonBody(output.body, context); + let contents = {}; + contents = _json(data); + const response = { + $metadata: deserializeMetadata2(output), + ...contents + }; + return response; + }; + de_UnlinkDeveloperIdentityCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + await collectBody(output.body, context); + const response = { + $metadata: deserializeMetadata2(output) + }; + return response; + }; + de_UnlinkIdentityCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + await collectBody(output.body, context); + const response = { + $metadata: deserializeMetadata2(output) + }; + return response; + }; + de_UntagResourceCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await parseJsonBody(output.body, context); + let contents = {}; + contents = _json(data); + const response = { + $metadata: deserializeMetadata2(output), + ...contents + }; + return response; + }; + de_UpdateIdentityPoolCommand = async (output, context) => { + if (output.statusCode >= 300) { + return de_CommandError(output, context); + } + const data = await parseJsonBody(output.body, context); + let contents = {}; + contents = _json(data); + const response = { + $metadata: deserializeMetadata2(output), + ...contents + }; + return response; + }; + de_CommandError = async (output, context) => { + const parsedOutput = { + ...output, + body: await parseJsonErrorBody(output.body, context) + }; + const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); + switch (errorCode) { + case "InternalErrorException": + case "com.amazonaws.cognitoidentity#InternalErrorException": + throw await de_InternalErrorExceptionRes(parsedOutput, context); + case "InvalidParameterException": + case "com.amazonaws.cognitoidentity#InvalidParameterException": + throw await de_InvalidParameterExceptionRes(parsedOutput, context); + case "LimitExceededException": + case "com.amazonaws.cognitoidentity#LimitExceededException": + throw await de_LimitExceededExceptionRes(parsedOutput, context); + case "NotAuthorizedException": + case "com.amazonaws.cognitoidentity#NotAuthorizedException": + throw await de_NotAuthorizedExceptionRes(parsedOutput, context); + case "ResourceConflictException": + case "com.amazonaws.cognitoidentity#ResourceConflictException": + throw await de_ResourceConflictExceptionRes(parsedOutput, context); + case "TooManyRequestsException": + case "com.amazonaws.cognitoidentity#TooManyRequestsException": + throw await de_TooManyRequestsExceptionRes(parsedOutput, context); + case "ResourceNotFoundException": + case "com.amazonaws.cognitoidentity#ResourceNotFoundException": + throw await de_ResourceNotFoundExceptionRes(parsedOutput, context); + case "ExternalServiceException": + case "com.amazonaws.cognitoidentity#ExternalServiceException": + throw await de_ExternalServiceExceptionRes(parsedOutput, context); + case "InvalidIdentityPoolConfigurationException": + case "com.amazonaws.cognitoidentity#InvalidIdentityPoolConfigurationException": + throw await de_InvalidIdentityPoolConfigurationExceptionRes(parsedOutput, context); + case "DeveloperUserAlreadyRegisteredException": + case "com.amazonaws.cognitoidentity#DeveloperUserAlreadyRegisteredException": + throw await de_DeveloperUserAlreadyRegisteredExceptionRes(parsedOutput, context); + case "ConcurrentModificationException": + case "com.amazonaws.cognitoidentity#ConcurrentModificationException": + throw await de_ConcurrentModificationExceptionRes(parsedOutput, context); + default: + const parsedBody = parsedOutput.body; + return throwDefaultError2({ + output, + parsedBody, + errorCode + }); + } + }; + de_ConcurrentModificationExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = _json(body); + const exception = new ConcurrentModificationException({ + $metadata: deserializeMetadata2(parsedOutput), + ...deserialized + }); + return decorateServiceException(exception, body); + }; + de_DeveloperUserAlreadyRegisteredExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = _json(body); + const exception = new DeveloperUserAlreadyRegisteredException({ + $metadata: deserializeMetadata2(parsedOutput), + ...deserialized + }); + return decorateServiceException(exception, body); + }; + de_ExternalServiceExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = _json(body); + const exception = new ExternalServiceException({ + $metadata: deserializeMetadata2(parsedOutput), + ...deserialized + }); + return decorateServiceException(exception, body); + }; + de_InternalErrorExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = _json(body); + const exception = new InternalErrorException({ + $metadata: deserializeMetadata2(parsedOutput), + ...deserialized + }); + return decorateServiceException(exception, body); + }; + de_InvalidIdentityPoolConfigurationExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = _json(body); + const exception = new InvalidIdentityPoolConfigurationException({ + $metadata: deserializeMetadata2(parsedOutput), + ...deserialized + }); + return decorateServiceException(exception, body); + }; + de_InvalidParameterExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = _json(body); + const exception = new InvalidParameterException({ + $metadata: deserializeMetadata2(parsedOutput), + ...deserialized + }); + return decorateServiceException(exception, body); + }; + de_LimitExceededExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = _json(body); + const exception = new LimitExceededException({ + $metadata: deserializeMetadata2(parsedOutput), + ...deserialized + }); + return decorateServiceException(exception, body); + }; + de_NotAuthorizedExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = _json(body); + const exception = new NotAuthorizedException({ + $metadata: deserializeMetadata2(parsedOutput), + ...deserialized + }); + return decorateServiceException(exception, body); + }; + de_ResourceConflictExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = _json(body); + const exception = new ResourceConflictException({ + $metadata: deserializeMetadata2(parsedOutput), + ...deserialized + }); + return decorateServiceException(exception, body); + }; + de_ResourceNotFoundExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = _json(body); + const exception = new ResourceNotFoundException({ + $metadata: deserializeMetadata2(parsedOutput), + ...deserialized + }); + return decorateServiceException(exception, body); + }; + de_TooManyRequestsExceptionRes = async (parsedOutput, context) => { + const body = parsedOutput.body; + const deserialized = _json(body); + const exception = new TooManyRequestsException({ + $metadata: deserializeMetadata2(parsedOutput), + ...deserialized + }); + return decorateServiceException(exception, body); + }; + de_Credentials = (output, context) => { + return take(output, { + AccessKeyId: expectString, + Expiration: (_2) => expectNonNull(parseEpochTimestamp(expectNumber(_2))), + SecretKey: expectString, + SessionToken: expectString + }); + }; + de_GetCredentialsForIdentityResponse = (output, context) => { + return take(output, { + Credentials: (_2) => de_Credentials(_2, context), + IdentityId: expectString + }); + }; + de_IdentitiesList = (output, context) => { + const retVal = (output || []).filter((e2) => e2 != null).map((entry) => { + return de_IdentityDescription(entry, context); + }); + return retVal; + }; + de_IdentityDescription = (output, context) => { + return take(output, { + CreationDate: (_2) => expectNonNull(parseEpochTimestamp(expectNumber(_2))), + IdentityId: expectString, + LastModifiedDate: (_2) => expectNonNull(parseEpochTimestamp(expectNumber(_2))), + Logins: _json + }); + }; + de_ListIdentitiesResponse = (output, context) => { + return take(output, { + Identities: (_2) => de_IdentitiesList(_2, context), + IdentityPoolId: expectString, + NextToken: expectString + }); + }; + deserializeMetadata2 = (output) => ({ + httpStatusCode: output.statusCode, + requestId: output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"] + }); + throwDefaultError2 = withBaseException(CognitoIdentityServiceException); + buildHttpRpcRequest = async (context, headers, path, resolvedHostname, body) => { + const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); + const contents = { + protocol, + hostname, + port, + method: "POST", + path: basePath.endsWith("/") ? basePath.slice(0, -1) + path : basePath + path, + headers + }; + if (resolvedHostname !== void 0) { + contents.hostname = resolvedHostname; + } + if (body !== void 0) { + contents.body = body; + } + return new HttpRequest(contents); + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/CreateIdentityPoolCommand.js + var CreateIdentityPoolCommand; + var init_CreateIdentityPoolCommand = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/CreateIdentityPoolCommand.js"() { + init_dist_es32(); + init_dist_es9(); + init_dist_es27(); + init_EndpointParameters(); + init_Aws_json1_1(); + CreateIdentityPoolCommand = class extends Command2.classBuilder().ep(commonParams).m(function(Command3, cs, config, o2) { + return [ + getSerdePlugin(config, this.serialize, this.deserialize), + getEndpointPlugin(config, Command3.getEndpointParameterInstructions()) + ]; + }).s("AWSCognitoIdentityService", "CreateIdentityPool", {}).n("CognitoIdentityClient", "CreateIdentityPoolCommand").f(void 0, void 0).ser(se_CreateIdentityPoolCommand).de(de_CreateIdentityPoolCommand).build() { + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/DeleteIdentitiesCommand.js + var DeleteIdentitiesCommand; + var init_DeleteIdentitiesCommand = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/DeleteIdentitiesCommand.js"() { + init_dist_es32(); + init_dist_es9(); + init_dist_es27(); + init_EndpointParameters(); + init_Aws_json1_1(); + DeleteIdentitiesCommand = class extends Command2.classBuilder().ep(commonParams).m(function(Command3, cs, config, o2) { + return [ + getSerdePlugin(config, this.serialize, this.deserialize), + getEndpointPlugin(config, Command3.getEndpointParameterInstructions()) + ]; + }).s("AWSCognitoIdentityService", "DeleteIdentities", {}).n("CognitoIdentityClient", "DeleteIdentitiesCommand").f(void 0, void 0).ser(se_DeleteIdentitiesCommand).de(de_DeleteIdentitiesCommand).build() { + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/DeleteIdentityPoolCommand.js + var DeleteIdentityPoolCommand; + var init_DeleteIdentityPoolCommand = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/DeleteIdentityPoolCommand.js"() { + init_dist_es32(); + init_dist_es9(); + init_dist_es27(); + init_EndpointParameters(); + init_Aws_json1_1(); + DeleteIdentityPoolCommand = class extends Command2.classBuilder().ep(commonParams).m(function(Command3, cs, config, o2) { + return [ + getSerdePlugin(config, this.serialize, this.deserialize), + getEndpointPlugin(config, Command3.getEndpointParameterInstructions()) + ]; + }).s("AWSCognitoIdentityService", "DeleteIdentityPool", {}).n("CognitoIdentityClient", "DeleteIdentityPoolCommand").f(void 0, void 0).ser(se_DeleteIdentityPoolCommand).de(de_DeleteIdentityPoolCommand).build() { + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/DescribeIdentityCommand.js + var DescribeIdentityCommand; + var init_DescribeIdentityCommand = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/DescribeIdentityCommand.js"() { + init_dist_es32(); + init_dist_es9(); + init_dist_es27(); + init_EndpointParameters(); + init_Aws_json1_1(); + DescribeIdentityCommand = class extends Command2.classBuilder().ep(commonParams).m(function(Command3, cs, config, o2) { + return [ + getSerdePlugin(config, this.serialize, this.deserialize), + getEndpointPlugin(config, Command3.getEndpointParameterInstructions()) + ]; + }).s("AWSCognitoIdentityService", "DescribeIdentity", {}).n("CognitoIdentityClient", "DescribeIdentityCommand").f(void 0, void 0).ser(se_DescribeIdentityCommand).de(de_DescribeIdentityCommand).build() { + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/DescribeIdentityPoolCommand.js + var DescribeIdentityPoolCommand; + var init_DescribeIdentityPoolCommand = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/DescribeIdentityPoolCommand.js"() { + init_dist_es32(); + init_dist_es9(); + init_dist_es27(); + init_EndpointParameters(); + init_Aws_json1_1(); + DescribeIdentityPoolCommand = class extends Command2.classBuilder().ep(commonParams).m(function(Command3, cs, config, o2) { + return [ + getSerdePlugin(config, this.serialize, this.deserialize), + getEndpointPlugin(config, Command3.getEndpointParameterInstructions()) + ]; + }).s("AWSCognitoIdentityService", "DescribeIdentityPool", {}).n("CognitoIdentityClient", "DescribeIdentityPoolCommand").f(void 0, void 0).ser(se_DescribeIdentityPoolCommand).de(de_DescribeIdentityPoolCommand).build() { + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetCredentialsForIdentityCommand.js + var GetCredentialsForIdentityCommand; + var init_GetCredentialsForIdentityCommand = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetCredentialsForIdentityCommand.js"() { + init_dist_es32(); + init_dist_es9(); + init_dist_es27(); + init_EndpointParameters(); + init_models_0(); + init_Aws_json1_1(); + GetCredentialsForIdentityCommand = class extends Command2.classBuilder().ep(commonParams).m(function(Command3, cs, config, o2) { + return [ + getSerdePlugin(config, this.serialize, this.deserialize), + getEndpointPlugin(config, Command3.getEndpointParameterInstructions()) + ]; + }).s("AWSCognitoIdentityService", "GetCredentialsForIdentity", {}).n("CognitoIdentityClient", "GetCredentialsForIdentityCommand").f(GetCredentialsForIdentityInputFilterSensitiveLog, GetCredentialsForIdentityResponseFilterSensitiveLog).ser(se_GetCredentialsForIdentityCommand).de(de_GetCredentialsForIdentityCommand).build() { + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetIdCommand.js + var GetIdCommand; + var init_GetIdCommand = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetIdCommand.js"() { + init_dist_es32(); + init_dist_es9(); + init_dist_es27(); + init_EndpointParameters(); + init_models_0(); + init_Aws_json1_1(); + GetIdCommand = class extends Command2.classBuilder().ep(commonParams).m(function(Command3, cs, config, o2) { + return [ + getSerdePlugin(config, this.serialize, this.deserialize), + getEndpointPlugin(config, Command3.getEndpointParameterInstructions()) + ]; + }).s("AWSCognitoIdentityService", "GetId", {}).n("CognitoIdentityClient", "GetIdCommand").f(GetIdInputFilterSensitiveLog, void 0).ser(se_GetIdCommand).de(de_GetIdCommand).build() { + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetIdentityPoolRolesCommand.js + var GetIdentityPoolRolesCommand; + var init_GetIdentityPoolRolesCommand = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetIdentityPoolRolesCommand.js"() { + init_dist_es32(); + init_dist_es9(); + init_dist_es27(); + init_EndpointParameters(); + init_Aws_json1_1(); + GetIdentityPoolRolesCommand = class extends Command2.classBuilder().ep(commonParams).m(function(Command3, cs, config, o2) { + return [ + getSerdePlugin(config, this.serialize, this.deserialize), + getEndpointPlugin(config, Command3.getEndpointParameterInstructions()) + ]; + }).s("AWSCognitoIdentityService", "GetIdentityPoolRoles", {}).n("CognitoIdentityClient", "GetIdentityPoolRolesCommand").f(void 0, void 0).ser(se_GetIdentityPoolRolesCommand).de(de_GetIdentityPoolRolesCommand).build() { + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetOpenIdTokenCommand.js + var GetOpenIdTokenCommand; + var init_GetOpenIdTokenCommand = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetOpenIdTokenCommand.js"() { + init_dist_es32(); + init_dist_es9(); + init_dist_es27(); + init_EndpointParameters(); + init_models_0(); + init_Aws_json1_1(); + GetOpenIdTokenCommand = class extends Command2.classBuilder().ep(commonParams).m(function(Command3, cs, config, o2) { + return [ + getSerdePlugin(config, this.serialize, this.deserialize), + getEndpointPlugin(config, Command3.getEndpointParameterInstructions()) + ]; + }).s("AWSCognitoIdentityService", "GetOpenIdToken", {}).n("CognitoIdentityClient", "GetOpenIdTokenCommand").f(GetOpenIdTokenInputFilterSensitiveLog, GetOpenIdTokenResponseFilterSensitiveLog).ser(se_GetOpenIdTokenCommand).de(de_GetOpenIdTokenCommand).build() { + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetOpenIdTokenForDeveloperIdentityCommand.js + var GetOpenIdTokenForDeveloperIdentityCommand; + var init_GetOpenIdTokenForDeveloperIdentityCommand = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetOpenIdTokenForDeveloperIdentityCommand.js"() { + init_dist_es32(); + init_dist_es9(); + init_dist_es27(); + init_EndpointParameters(); + init_models_0(); + init_Aws_json1_1(); + GetOpenIdTokenForDeveloperIdentityCommand = class extends Command2.classBuilder().ep(commonParams).m(function(Command3, cs, config, o2) { + return [ + getSerdePlugin(config, this.serialize, this.deserialize), + getEndpointPlugin(config, Command3.getEndpointParameterInstructions()) + ]; + }).s("AWSCognitoIdentityService", "GetOpenIdTokenForDeveloperIdentity", {}).n("CognitoIdentityClient", "GetOpenIdTokenForDeveloperIdentityCommand").f(GetOpenIdTokenForDeveloperIdentityInputFilterSensitiveLog, GetOpenIdTokenForDeveloperIdentityResponseFilterSensitiveLog).ser(se_GetOpenIdTokenForDeveloperIdentityCommand).de(de_GetOpenIdTokenForDeveloperIdentityCommand).build() { + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetPrincipalTagAttributeMapCommand.js + var GetPrincipalTagAttributeMapCommand; + var init_GetPrincipalTagAttributeMapCommand = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/GetPrincipalTagAttributeMapCommand.js"() { + init_dist_es32(); + init_dist_es9(); + init_dist_es27(); + init_EndpointParameters(); + init_Aws_json1_1(); + GetPrincipalTagAttributeMapCommand = class extends Command2.classBuilder().ep(commonParams).m(function(Command3, cs, config, o2) { + return [ + getSerdePlugin(config, this.serialize, this.deserialize), + getEndpointPlugin(config, Command3.getEndpointParameterInstructions()) + ]; + }).s("AWSCognitoIdentityService", "GetPrincipalTagAttributeMap", {}).n("CognitoIdentityClient", "GetPrincipalTagAttributeMapCommand").f(void 0, void 0).ser(se_GetPrincipalTagAttributeMapCommand).de(de_GetPrincipalTagAttributeMapCommand).build() { + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/ListIdentitiesCommand.js + var ListIdentitiesCommand; + var init_ListIdentitiesCommand = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/ListIdentitiesCommand.js"() { + init_dist_es32(); + init_dist_es9(); + init_dist_es27(); + init_EndpointParameters(); + init_Aws_json1_1(); + ListIdentitiesCommand = class extends Command2.classBuilder().ep(commonParams).m(function(Command3, cs, config, o2) { + return [ + getSerdePlugin(config, this.serialize, this.deserialize), + getEndpointPlugin(config, Command3.getEndpointParameterInstructions()) + ]; + }).s("AWSCognitoIdentityService", "ListIdentities", {}).n("CognitoIdentityClient", "ListIdentitiesCommand").f(void 0, void 0).ser(se_ListIdentitiesCommand).de(de_ListIdentitiesCommand).build() { + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/ListIdentityPoolsCommand.js + var ListIdentityPoolsCommand; + var init_ListIdentityPoolsCommand = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/ListIdentityPoolsCommand.js"() { + init_dist_es32(); + init_dist_es9(); + init_dist_es27(); + init_EndpointParameters(); + init_Aws_json1_1(); + ListIdentityPoolsCommand = class extends Command2.classBuilder().ep(commonParams).m(function(Command3, cs, config, o2) { + return [ + getSerdePlugin(config, this.serialize, this.deserialize), + getEndpointPlugin(config, Command3.getEndpointParameterInstructions()) + ]; + }).s("AWSCognitoIdentityService", "ListIdentityPools", {}).n("CognitoIdentityClient", "ListIdentityPoolsCommand").f(void 0, void 0).ser(se_ListIdentityPoolsCommand).de(de_ListIdentityPoolsCommand).build() { + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/ListTagsForResourceCommand.js + var ListTagsForResourceCommand; + var init_ListTagsForResourceCommand = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/ListTagsForResourceCommand.js"() { + init_dist_es32(); + init_dist_es9(); + init_dist_es27(); + init_EndpointParameters(); + init_Aws_json1_1(); + ListTagsForResourceCommand = class extends Command2.classBuilder().ep(commonParams).m(function(Command3, cs, config, o2) { + return [ + getSerdePlugin(config, this.serialize, this.deserialize), + getEndpointPlugin(config, Command3.getEndpointParameterInstructions()) + ]; + }).s("AWSCognitoIdentityService", "ListTagsForResource", {}).n("CognitoIdentityClient", "ListTagsForResourceCommand").f(void 0, void 0).ser(se_ListTagsForResourceCommand).de(de_ListTagsForResourceCommand).build() { + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/LookupDeveloperIdentityCommand.js + var LookupDeveloperIdentityCommand; + var init_LookupDeveloperIdentityCommand = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/LookupDeveloperIdentityCommand.js"() { + init_dist_es32(); + init_dist_es9(); + init_dist_es27(); + init_EndpointParameters(); + init_Aws_json1_1(); + LookupDeveloperIdentityCommand = class extends Command2.classBuilder().ep(commonParams).m(function(Command3, cs, config, o2) { + return [ + getSerdePlugin(config, this.serialize, this.deserialize), + getEndpointPlugin(config, Command3.getEndpointParameterInstructions()) + ]; + }).s("AWSCognitoIdentityService", "LookupDeveloperIdentity", {}).n("CognitoIdentityClient", "LookupDeveloperIdentityCommand").f(void 0, void 0).ser(se_LookupDeveloperIdentityCommand).de(de_LookupDeveloperIdentityCommand).build() { + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/MergeDeveloperIdentitiesCommand.js + var MergeDeveloperIdentitiesCommand; + var init_MergeDeveloperIdentitiesCommand = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/MergeDeveloperIdentitiesCommand.js"() { + init_dist_es32(); + init_dist_es9(); + init_dist_es27(); + init_EndpointParameters(); + init_Aws_json1_1(); + MergeDeveloperIdentitiesCommand = class extends Command2.classBuilder().ep(commonParams).m(function(Command3, cs, config, o2) { + return [ + getSerdePlugin(config, this.serialize, this.deserialize), + getEndpointPlugin(config, Command3.getEndpointParameterInstructions()) + ]; + }).s("AWSCognitoIdentityService", "MergeDeveloperIdentities", {}).n("CognitoIdentityClient", "MergeDeveloperIdentitiesCommand").f(void 0, void 0).ser(se_MergeDeveloperIdentitiesCommand).de(de_MergeDeveloperIdentitiesCommand).build() { + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/SetIdentityPoolRolesCommand.js + var SetIdentityPoolRolesCommand; + var init_SetIdentityPoolRolesCommand = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/SetIdentityPoolRolesCommand.js"() { + init_dist_es32(); + init_dist_es9(); + init_dist_es27(); + init_EndpointParameters(); + init_Aws_json1_1(); + SetIdentityPoolRolesCommand = class extends Command2.classBuilder().ep(commonParams).m(function(Command3, cs, config, o2) { + return [ + getSerdePlugin(config, this.serialize, this.deserialize), + getEndpointPlugin(config, Command3.getEndpointParameterInstructions()) + ]; + }).s("AWSCognitoIdentityService", "SetIdentityPoolRoles", {}).n("CognitoIdentityClient", "SetIdentityPoolRolesCommand").f(void 0, void 0).ser(se_SetIdentityPoolRolesCommand).de(de_SetIdentityPoolRolesCommand).build() { + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/SetPrincipalTagAttributeMapCommand.js + var SetPrincipalTagAttributeMapCommand; + var init_SetPrincipalTagAttributeMapCommand = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/SetPrincipalTagAttributeMapCommand.js"() { + init_dist_es32(); + init_dist_es9(); + init_dist_es27(); + init_EndpointParameters(); + init_Aws_json1_1(); + SetPrincipalTagAttributeMapCommand = class extends Command2.classBuilder().ep(commonParams).m(function(Command3, cs, config, o2) { + return [ + getSerdePlugin(config, this.serialize, this.deserialize), + getEndpointPlugin(config, Command3.getEndpointParameterInstructions()) + ]; + }).s("AWSCognitoIdentityService", "SetPrincipalTagAttributeMap", {}).n("CognitoIdentityClient", "SetPrincipalTagAttributeMapCommand").f(void 0, void 0).ser(se_SetPrincipalTagAttributeMapCommand).de(de_SetPrincipalTagAttributeMapCommand).build() { + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/TagResourceCommand.js + var TagResourceCommand; + var init_TagResourceCommand = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/TagResourceCommand.js"() { + init_dist_es32(); + init_dist_es9(); + init_dist_es27(); + init_EndpointParameters(); + init_Aws_json1_1(); + TagResourceCommand = class extends Command2.classBuilder().ep(commonParams).m(function(Command3, cs, config, o2) { + return [ + getSerdePlugin(config, this.serialize, this.deserialize), + getEndpointPlugin(config, Command3.getEndpointParameterInstructions()) + ]; + }).s("AWSCognitoIdentityService", "TagResource", {}).n("CognitoIdentityClient", "TagResourceCommand").f(void 0, void 0).ser(se_TagResourceCommand).de(de_TagResourceCommand).build() { + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/UnlinkDeveloperIdentityCommand.js + var UnlinkDeveloperIdentityCommand; + var init_UnlinkDeveloperIdentityCommand = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/UnlinkDeveloperIdentityCommand.js"() { + init_dist_es32(); + init_dist_es9(); + init_dist_es27(); + init_EndpointParameters(); + init_Aws_json1_1(); + UnlinkDeveloperIdentityCommand = class extends Command2.classBuilder().ep(commonParams).m(function(Command3, cs, config, o2) { + return [ + getSerdePlugin(config, this.serialize, this.deserialize), + getEndpointPlugin(config, Command3.getEndpointParameterInstructions()) + ]; + }).s("AWSCognitoIdentityService", "UnlinkDeveloperIdentity", {}).n("CognitoIdentityClient", "UnlinkDeveloperIdentityCommand").f(void 0, void 0).ser(se_UnlinkDeveloperIdentityCommand).de(de_UnlinkDeveloperIdentityCommand).build() { + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/UnlinkIdentityCommand.js + var UnlinkIdentityCommand; + var init_UnlinkIdentityCommand = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/UnlinkIdentityCommand.js"() { + init_dist_es32(); + init_dist_es9(); + init_dist_es27(); + init_EndpointParameters(); + init_models_0(); + init_Aws_json1_1(); + UnlinkIdentityCommand = class extends Command2.classBuilder().ep(commonParams).m(function(Command3, cs, config, o2) { + return [ + getSerdePlugin(config, this.serialize, this.deserialize), + getEndpointPlugin(config, Command3.getEndpointParameterInstructions()) + ]; + }).s("AWSCognitoIdentityService", "UnlinkIdentity", {}).n("CognitoIdentityClient", "UnlinkIdentityCommand").f(UnlinkIdentityInputFilterSensitiveLog, void 0).ser(se_UnlinkIdentityCommand).de(de_UnlinkIdentityCommand).build() { + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/UntagResourceCommand.js + var UntagResourceCommand; + var init_UntagResourceCommand = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/UntagResourceCommand.js"() { + init_dist_es32(); + init_dist_es9(); + init_dist_es27(); + init_EndpointParameters(); + init_Aws_json1_1(); + UntagResourceCommand = class extends Command2.classBuilder().ep(commonParams).m(function(Command3, cs, config, o2) { + return [ + getSerdePlugin(config, this.serialize, this.deserialize), + getEndpointPlugin(config, Command3.getEndpointParameterInstructions()) + ]; + }).s("AWSCognitoIdentityService", "UntagResource", {}).n("CognitoIdentityClient", "UntagResourceCommand").f(void 0, void 0).ser(se_UntagResourceCommand).de(de_UntagResourceCommand).build() { + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/UpdateIdentityPoolCommand.js + var UpdateIdentityPoolCommand; + var init_UpdateIdentityPoolCommand = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/UpdateIdentityPoolCommand.js"() { + init_dist_es32(); + init_dist_es9(); + init_dist_es27(); + init_EndpointParameters(); + init_Aws_json1_1(); + UpdateIdentityPoolCommand = class extends Command2.classBuilder().ep(commonParams).m(function(Command3, cs, config, o2) { + return [ + getSerdePlugin(config, this.serialize, this.deserialize), + getEndpointPlugin(config, Command3.getEndpointParameterInstructions()) + ]; + }).s("AWSCognitoIdentityService", "UpdateIdentityPool", {}).n("CognitoIdentityClient", "UpdateIdentityPoolCommand").f(void 0, void 0).ser(se_UpdateIdentityPoolCommand).de(de_UpdateIdentityPoolCommand).build() { + }; + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/CognitoIdentity.js + var commands, CognitoIdentity; + var init_CognitoIdentity = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/CognitoIdentity.js"() { + init_dist_es27(); + init_CognitoIdentityClient(); + init_CreateIdentityPoolCommand(); + init_DeleteIdentitiesCommand(); + init_DeleteIdentityPoolCommand(); + init_DescribeIdentityCommand(); + init_DescribeIdentityPoolCommand(); + init_GetCredentialsForIdentityCommand(); + init_GetIdCommand(); + init_GetIdentityPoolRolesCommand(); + init_GetOpenIdTokenCommand(); + init_GetOpenIdTokenForDeveloperIdentityCommand(); + init_GetPrincipalTagAttributeMapCommand(); + init_ListIdentitiesCommand(); + init_ListIdentityPoolsCommand(); + init_ListTagsForResourceCommand(); + init_LookupDeveloperIdentityCommand(); + init_MergeDeveloperIdentitiesCommand(); + init_SetIdentityPoolRolesCommand(); + init_SetPrincipalTagAttributeMapCommand(); + init_TagResourceCommand(); + init_UnlinkDeveloperIdentityCommand(); + init_UnlinkIdentityCommand(); + init_UntagResourceCommand(); + init_UpdateIdentityPoolCommand(); + commands = { + CreateIdentityPoolCommand, + DeleteIdentitiesCommand, + DeleteIdentityPoolCommand, + DescribeIdentityCommand, + DescribeIdentityPoolCommand, + GetCredentialsForIdentityCommand, + GetIdCommand, + GetIdentityPoolRolesCommand, + GetOpenIdTokenCommand, + GetOpenIdTokenForDeveloperIdentityCommand, + GetPrincipalTagAttributeMapCommand, + ListIdentitiesCommand, + ListIdentityPoolsCommand, + ListTagsForResourceCommand, + LookupDeveloperIdentityCommand, + MergeDeveloperIdentitiesCommand, + SetIdentityPoolRolesCommand, + SetPrincipalTagAttributeMapCommand, + TagResourceCommand, + UnlinkDeveloperIdentityCommand, + UnlinkIdentityCommand, + UntagResourceCommand, + UpdateIdentityPoolCommand + }; + CognitoIdentity = class extends CognitoIdentityClient { + }; + createAggregatedClient(commands, CognitoIdentity); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/index.js + var init_commands = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/commands/index.js"() { + init_CreateIdentityPoolCommand(); + init_DeleteIdentitiesCommand(); + init_DeleteIdentityPoolCommand(); + init_DescribeIdentityCommand(); + init_DescribeIdentityPoolCommand(); + init_GetCredentialsForIdentityCommand(); + init_GetIdCommand(); + init_GetIdentityPoolRolesCommand(); + init_GetOpenIdTokenCommand(); + init_GetOpenIdTokenForDeveloperIdentityCommand(); + init_GetPrincipalTagAttributeMapCommand(); + init_ListIdentitiesCommand(); + init_ListIdentityPoolsCommand(); + init_ListTagsForResourceCommand(); + init_LookupDeveloperIdentityCommand(); + init_MergeDeveloperIdentitiesCommand(); + init_SetIdentityPoolRolesCommand(); + init_SetPrincipalTagAttributeMapCommand(); + init_TagResourceCommand(); + init_UnlinkDeveloperIdentityCommand(); + init_UnlinkIdentityCommand(); + init_UntagResourceCommand(); + init_UpdateIdentityPoolCommand(); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/pagination/Interfaces.js + var init_Interfaces = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/pagination/Interfaces.js"() { + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/pagination/ListIdentityPoolsPaginator.js + var paginateListIdentityPools; + var init_ListIdentityPoolsPaginator = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/pagination/ListIdentityPoolsPaginator.js"() { + init_dist_es18(); + init_CognitoIdentityClient(); + init_ListIdentityPoolsCommand(); + paginateListIdentityPools = createPaginator(CognitoIdentityClient, ListIdentityPoolsCommand, "NextToken", "NextToken", "MaxResults"); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/pagination/index.js + var init_pagination2 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/pagination/index.js"() { + init_Interfaces(); + init_ListIdentityPoolsPaginator(); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/models/index.js + var init_models = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/models/index.js"() { + init_models_0(); + } + }); + + // node_modules/@aws-sdk/client-cognito-identity/dist-es/index.js + var init_dist_es41 = __esm({ + "node_modules/@aws-sdk/client-cognito-identity/dist-es/index.js"() { + init_CognitoIdentityClient(); + init_CognitoIdentity(); + init_commands(); + init_pagination2(); + init_models(); + } + }); + + // node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/loadCognitoIdentity.js + var loadCognitoIdentity_exports = {}; + __export(loadCognitoIdentity_exports, { + CognitoIdentityClient: () => CognitoIdentityClient, + GetCredentialsForIdentityCommand: () => GetCredentialsForIdentityCommand, + GetIdCommand: () => GetIdCommand + }); + var init_loadCognitoIdentity = __esm({ + "node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/loadCognitoIdentity.js"() { + init_dist_es41(); + } + }); + + // node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/tslib/tslib.es6.js + var tslib_es6_exports2 = {}; + __export(tslib_es6_exports2, { + __assign: () => __assign2, + __asyncDelegator: () => __asyncDelegator2, + __asyncGenerator: () => __asyncGenerator2, + __asyncValues: () => __asyncValues2, + __await: () => __await2, + __awaiter: () => __awaiter2, + __classPrivateFieldGet: () => __classPrivateFieldGet2, + __classPrivateFieldSet: () => __classPrivateFieldSet2, + __createBinding: () => __createBinding2, + __decorate: () => __decorate2, + __exportStar: () => __exportStar2, + __extends: () => __extends2, + __generator: () => __generator2, + __importDefault: () => __importDefault2, + __importStar: () => __importStar2, + __makeTemplateObject: () => __makeTemplateObject2, + __metadata: () => __metadata2, + __param: () => __param2, + __read: () => __read2, + __rest: () => __rest2, + __spread: () => __spread2, + __spreadArrays: () => __spreadArrays2, + __values: () => __values2 + }); + function __extends2(d3, b3) { + extendStatics2(d3, b3); + function __() { + this.constructor = d3; + } + d3.prototype = b3 === null ? Object.create(b3) : (__.prototype = b3.prototype, new __()); + } + function __rest2(s2, e2) { + var t2 = {}; + for (var p2 in s2) if (Object.prototype.hasOwnProperty.call(s2, p2) && e2.indexOf(p2) < 0) + t2[p2] = s2[p2]; + if (s2 != null && typeof Object.getOwnPropertySymbols === "function") + for (var i2 = 0, p2 = Object.getOwnPropertySymbols(s2); i2 < p2.length; i2++) { + if (e2.indexOf(p2[i2]) < 0 && Object.prototype.propertyIsEnumerable.call(s2, p2[i2])) + t2[p2[i2]] = s2[p2[i2]]; + } + return t2; + } + function __decorate2(decorators, target, key, desc) { + var c3 = arguments.length, r2 = c3 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d3; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r2 = Reflect.decorate(decorators, target, key, desc); + else for (var i2 = decorators.length - 1; i2 >= 0; i2--) if (d3 = decorators[i2]) r2 = (c3 < 3 ? d3(r2) : c3 > 3 ? d3(target, key, r2) : d3(target, key)) || r2; + return c3 > 3 && r2 && Object.defineProperty(target, key, r2), r2; + } + function __param2(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; + } + function __metadata2(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + } + function __awaiter2(thisArg, _arguments, P2, generator) { + function adopt(value) { + return value instanceof P2 ? value : new P2(function(resolve) { + resolve(value); + }); + } + return new (P2 || (P2 = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e2) { + reject(e2); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e2) { + reject(e2); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + } + function __generator2(thisArg, body) { + var _2 = { label: 0, sent: function() { + if (t2[0] & 1) throw t2[1]; + return t2[1]; + }, trys: [], ops: [] }, f3, y3, t2, g2; + return g2 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g2[Symbol.iterator] = function() { + return this; + }), g2; + function verb(n2) { + return function(v6) { + return step([n2, v6]); + }; + } + function step(op) { + if (f3) throw new TypeError("Generator is already executing."); + while (_2) try { + if (f3 = 1, y3 && (t2 = op[0] & 2 ? y3["return"] : op[0] ? y3["throw"] || ((t2 = y3["return"]) && t2.call(y3), 0) : y3.next) && !(t2 = t2.call(y3, op[1])).done) return t2; + if (y3 = 0, t2) op = [op[0] & 2, t2.value]; + switch (op[0]) { + case 0: + case 1: + t2 = op; + break; + case 4: + _2.label++; + return { value: op[1], done: false }; + case 5: + _2.label++; + y3 = op[1]; + op = [0]; + continue; + case 7: + op = _2.ops.pop(); + _2.trys.pop(); + continue; + default: + if (!(t2 = _2.trys, t2 = t2.length > 0 && t2[t2.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _2 = 0; + continue; + } + if (op[0] === 3 && (!t2 || op[1] > t2[0] && op[1] < t2[3])) { + _2.label = op[1]; + break; + } + if (op[0] === 6 && _2.label < t2[1]) { + _2.label = t2[1]; + t2 = op; + break; + } + if (t2 && _2.label < t2[2]) { + _2.label = t2[2]; + _2.ops.push(op); + break; + } + if (t2[2]) _2.ops.pop(); + _2.trys.pop(); + continue; + } + op = body.call(thisArg, _2); + } catch (e2) { + op = [6, e2]; + y3 = 0; + } finally { + f3 = t2 = 0; + } + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; + } + } + function __createBinding2(o2, m3, k3, k22) { + if (k22 === void 0) k22 = k3; + o2[k22] = m3[k3]; + } + function __exportStar2(m3, exports) { + for (var p2 in m3) if (p2 !== "default" && !exports.hasOwnProperty(p2)) exports[p2] = m3[p2]; + } + function __values2(o2) { + var s2 = typeof Symbol === "function" && Symbol.iterator, m3 = s2 && o2[s2], i2 = 0; + if (m3) return m3.call(o2); + if (o2 && typeof o2.length === "number") return { + next: function() { + if (o2 && i2 >= o2.length) o2 = void 0; + return { value: o2 && o2[i2++], done: !o2 }; + } + }; + throw new TypeError(s2 ? "Object is not iterable." : "Symbol.iterator is not defined."); + } + function __read2(o2, n2) { + var m3 = typeof Symbol === "function" && o2[Symbol.iterator]; + if (!m3) return o2; + var i2 = m3.call(o2), r2, ar = [], e2; + try { + while ((n2 === void 0 || n2-- > 0) && !(r2 = i2.next()).done) ar.push(r2.value); + } catch (error) { + e2 = { error }; + } finally { + try { + if (r2 && !r2.done && (m3 = i2["return"])) m3.call(i2); + } finally { + if (e2) throw e2.error; + } + } + return ar; + } + function __spread2() { + for (var ar = [], i2 = 0; i2 < arguments.length; i2++) + ar = ar.concat(__read2(arguments[i2])); + return ar; + } + function __spreadArrays2() { + for (var s2 = 0, i2 = 0, il = arguments.length; i2 < il; i2++) s2 += arguments[i2].length; + for (var r2 = Array(s2), k3 = 0, i2 = 0; i2 < il; i2++) + for (var a2 = arguments[i2], j3 = 0, jl = a2.length; j3 < jl; j3++, k3++) + r2[k3] = a2[j3]; + return r2; + } + function __await2(v6) { + return this instanceof __await2 ? (this.v = v6, this) : new __await2(v6); + } + function __asyncGenerator2(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g2 = generator.apply(thisArg, _arguments || []), i2, q3 = []; + return i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() { + return this; + }, i2; + function verb(n2) { + if (g2[n2]) i2[n2] = function(v6) { + return new Promise(function(a2, b3) { + q3.push([n2, v6, a2, b3]) > 1 || resume(n2, v6); + }); + }; + } + function resume(n2, v6) { + try { + step(g2[n2](v6)); + } catch (e2) { + settle(q3[0][3], e2); + } + } + function step(r2) { + r2.value instanceof __await2 ? Promise.resolve(r2.value.v).then(fulfill, reject) : settle(q3[0][2], r2); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f3, v6) { + if (f3(v6), q3.shift(), q3.length) resume(q3[0][0], q3[0][1]); + } + } + function __asyncDelegator2(o2) { + var i2, p2; + return i2 = {}, verb("next"), verb("throw", function(e2) { + throw e2; + }), verb("return"), i2[Symbol.iterator] = function() { + return this; + }, i2; + function verb(n2, f3) { + i2[n2] = o2[n2] ? function(v6) { + return (p2 = !p2) ? { value: __await2(o2[n2](v6)), done: n2 === "return" } : f3 ? f3(v6) : v6; + } : f3; + } + } + function __asyncValues2(o2) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m3 = o2[Symbol.asyncIterator], i2; + return m3 ? m3.call(o2) : (o2 = typeof __values2 === "function" ? __values2(o2) : o2[Symbol.iterator](), i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() { + return this; + }, i2); + function verb(n2) { + i2[n2] = o2[n2] && function(v6) { + return new Promise(function(resolve, reject) { + v6 = o2[n2](v6), settle(resolve, reject, v6.done, v6.value); + }); + }; + } + function settle(resolve, reject, d3, v6) { + Promise.resolve(v6).then(function(v7) { + resolve({ value: v7, done: d3 }); + }, reject); + } + } + function __makeTemplateObject2(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { value: raw }); + } else { + cooked.raw = raw; + } + return cooked; + } + function __importStar2(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k3 in mod) if (Object.hasOwnProperty.call(mod, k3)) result[k3] = mod[k3]; + } + result.default = mod; + return result; + } + function __importDefault2(mod) { + return mod && mod.__esModule ? mod : { default: mod }; + } + function __classPrivateFieldGet2(receiver, privateMap) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + return privateMap.get(receiver); + } + function __classPrivateFieldSet2(receiver, privateMap, value) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to set private field on non-instance"); + } + privateMap.set(receiver, value); + return value; + } + var extendStatics2, __assign2; + var init_tslib_es62 = __esm({ + "node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/tslib/tslib.es6.js"() { + extendStatics2 = function(d3, b3) { + extendStatics2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d4, b4) { + d4.__proto__ = b4; + } || function(d4, b4) { + for (var p2 in b4) if (b4.hasOwnProperty(p2)) d4[p2] = b4[p2]; + }; + return extendStatics2(d3, b3); + }; + __assign2 = function() { + __assign2 = Object.assign || function __assign3(t2) { + for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) { + s2 = arguments[i2]; + for (var p2 in s2) if (Object.prototype.hasOwnProperty.call(s2, p2)) t2[p2] = s2[p2]; + } + return t2; + }; + return __assign2.apply(this, arguments); + }; + } + }); + + // node_modules/@aws-sdk/util-utf8-browser/dist-cjs/pureJs.js + var require_pureJs = __commonJS({ + "node_modules/@aws-sdk/util-utf8-browser/dist-cjs/pureJs.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.toUtf8 = exports.fromUtf8 = void 0; + var fromUtf85 = (input) => { + const bytes = []; + for (let i2 = 0, len = input.length; i2 < len; i2++) { + const value = input.charCodeAt(i2); + if (value < 128) { + bytes.push(value); + } else if (value < 2048) { + bytes.push(value >> 6 | 192, value & 63 | 128); + } else if (i2 + 1 < input.length && (value & 64512) === 55296 && (input.charCodeAt(i2 + 1) & 64512) === 56320) { + const surrogatePair = 65536 + ((value & 1023) << 10) + (input.charCodeAt(++i2) & 1023); + bytes.push(surrogatePair >> 18 | 240, surrogatePair >> 12 & 63 | 128, surrogatePair >> 6 & 63 | 128, surrogatePair & 63 | 128); + } else { + bytes.push(value >> 12 | 224, value >> 6 & 63 | 128, value & 63 | 128); + } + } + return Uint8Array.from(bytes); + }; + exports.fromUtf8 = fromUtf85; + var toUtf83 = (input) => { + let decoded = ""; + for (let i2 = 0, len = input.length; i2 < len; i2++) { + const byte = input[i2]; + if (byte < 128) { + decoded += String.fromCharCode(byte); + } else if (192 <= byte && byte < 224) { + const nextByte = input[++i2]; + decoded += String.fromCharCode((byte & 31) << 6 | nextByte & 63); + } else if (240 <= byte && byte < 365) { + const surrogatePair = [byte, input[++i2], input[++i2], input[++i2]]; + const encoded = "%" + surrogatePair.map((byteValue) => byteValue.toString(16)).join("%"); + decoded += decodeURIComponent(encoded); + } else { + decoded += String.fromCharCode((byte & 15) << 12 | (input[++i2] & 63) << 6 | input[++i2] & 63); + } + } + return decoded; + }; + exports.toUtf8 = toUtf83; + } + }); + + // node_modules/@aws-sdk/util-utf8-browser/dist-cjs/whatwgEncodingApi.js + var require_whatwgEncodingApi = __commonJS({ + "node_modules/@aws-sdk/util-utf8-browser/dist-cjs/whatwgEncodingApi.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.toUtf8 = exports.fromUtf8 = void 0; + function fromUtf85(input) { + return new TextEncoder().encode(input); + } + exports.fromUtf8 = fromUtf85; + function toUtf83(input) { + return new TextDecoder("utf-8").decode(input); + } + exports.toUtf8 = toUtf83; + } + }); + + // node_modules/@aws-sdk/util-utf8-browser/dist-cjs/index.js + var require_dist_cjs = __commonJS({ + "node_modules/@aws-sdk/util-utf8-browser/dist-cjs/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.toUtf8 = exports.fromUtf8 = void 0; + var pureJs_1 = require_pureJs(); + var whatwgEncodingApi_1 = require_whatwgEncodingApi(); + var fromUtf85 = (input) => typeof TextEncoder === "function" ? (0, whatwgEncodingApi_1.fromUtf8)(input) : (0, pureJs_1.fromUtf8)(input); + exports.fromUtf8 = fromUtf85; + var toUtf83 = (input) => typeof TextDecoder === "function" ? (0, whatwgEncodingApi_1.toUtf8)(input) : (0, pureJs_1.toUtf8)(input); + exports.toUtf8 = toUtf83; + } + }); + + // node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/util/build/convertToBuffer.js + var require_convertToBuffer = __commonJS({ + "node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/util/build/convertToBuffer.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.convertToBuffer = void 0; + var util_utf8_browser_1 = require_dist_cjs(); + var fromUtf85 = typeof Buffer !== "undefined" && Buffer.from ? function(input) { + return Buffer.from(input, "utf8"); + } : util_utf8_browser_1.fromUtf8; + function convertToBuffer2(data) { + if (data instanceof Uint8Array) + return data; + if (typeof data === "string") { + return fromUtf85(data); + } + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); + } + return new Uint8Array(data); + } + exports.convertToBuffer = convertToBuffer2; + } + }); + + // node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/util/build/isEmptyData.js + var require_isEmptyData = __commonJS({ + "node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/util/build/isEmptyData.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isEmptyData = void 0; + function isEmptyData2(data) { + if (typeof data === "string") { + return data.length === 0; + } + return data.byteLength === 0; + } + exports.isEmptyData = isEmptyData2; + } + }); + + // node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/util/build/numToUint8.js + var require_numToUint8 = __commonJS({ + "node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/util/build/numToUint8.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.numToUint8 = void 0; + function numToUint82(num) { + return new Uint8Array([ + (num & 4278190080) >> 24, + (num & 16711680) >> 16, + (num & 65280) >> 8, + num & 255 + ]); + } + exports.numToUint8 = numToUint82; + } + }); + + // node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/util/build/uint32ArrayFrom.js + var require_uint32ArrayFrom = __commonJS({ + "node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/util/build/uint32ArrayFrom.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.uint32ArrayFrom = void 0; + function uint32ArrayFrom2(a_lookUpTable) { + if (!Uint32Array.from) { + var return_array = new Uint32Array(a_lookUpTable.length); + var a_index = 0; + while (a_index < a_lookUpTable.length) { + return_array[a_index] = a_lookUpTable[a_index]; + a_index += 1; + } + return return_array; + } + return Uint32Array.from(a_lookUpTable); + } + exports.uint32ArrayFrom = uint32ArrayFrom2; + } + }); + + // node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/util/build/index.js + var require_build = __commonJS({ + "node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/util/build/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.uint32ArrayFrom = exports.numToUint8 = exports.isEmptyData = exports.convertToBuffer = void 0; + var convertToBuffer_1 = require_convertToBuffer(); + Object.defineProperty(exports, "convertToBuffer", { enumerable: true, get: function() { + return convertToBuffer_1.convertToBuffer; + } }); + var isEmptyData_1 = require_isEmptyData(); + Object.defineProperty(exports, "isEmptyData", { enumerable: true, get: function() { + return isEmptyData_1.isEmptyData; + } }); + var numToUint8_1 = require_numToUint8(); + Object.defineProperty(exports, "numToUint8", { enumerable: true, get: function() { + return numToUint8_1.numToUint8; + } }); + var uint32ArrayFrom_1 = require_uint32ArrayFrom(); + Object.defineProperty(exports, "uint32ArrayFrom", { enumerable: true, get: function() { + return uint32ArrayFrom_1.uint32ArrayFrom; + } }); + } + }); + + // node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/crc32/build/aws_crc32.js + var require_aws_crc32 = __commonJS({ + "node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/crc32/build/aws_crc32.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AwsCrc32 = void 0; + var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); + var util_1 = require_build(); + var index_1 = require_build2(); + var AwsCrc32 = ( + /** @class */ + (function() { + function AwsCrc322() { + this.crc32 = new index_1.Crc32(); + } + AwsCrc322.prototype.update = function(toHash) { + if ((0, util_1.isEmptyData)(toHash)) + return; + this.crc32.update((0, util_1.convertToBuffer)(toHash)); + }; + AwsCrc322.prototype.digest = function() { + return tslib_1.__awaiter(this, void 0, void 0, function() { + return tslib_1.__generator(this, function(_a) { + return [2, (0, util_1.numToUint8)(this.crc32.digest())]; + }); + }); + }; + AwsCrc322.prototype.reset = function() { + this.crc32 = new index_1.Crc32(); + }; + return AwsCrc322; + })() + ); + exports.AwsCrc32 = AwsCrc32; + } + }); + + // node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/crc32/build/index.js + var require_build2 = __commonJS({ + "node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/crc32/build/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AwsCrc32 = exports.Crc32 = exports.crc32 = void 0; + var tslib_1 = (init_tslib_es62(), __toCommonJS(tslib_es6_exports2)); + var util_1 = require_build(); + function crc32(data) { + return new Crc323().update(data).digest(); + } + exports.crc32 = crc32; + var Crc323 = ( + /** @class */ + (function() { + function Crc324() { + this.checksum = 4294967295; + } + Crc324.prototype.update = function(data) { + var e_1, _a; + try { + for (var data_1 = tslib_1.__values(data), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) { + var byte = data_1_1.value; + this.checksum = this.checksum >>> 8 ^ lookupTable[(this.checksum ^ byte) & 255]; + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (data_1_1 && !data_1_1.done && (_a = data_1.return)) _a.call(data_1); + } finally { + if (e_1) throw e_1.error; + } + } + return this; + }; + Crc324.prototype.digest = function() { + return (this.checksum ^ 4294967295) >>> 0; + }; + return Crc324; + })() + ); + exports.Crc32 = Crc323; + var a_lookUpTable = [ + 0, + 1996959894, + 3993919788, + 2567524794, + 124634137, + 1886057615, + 3915621685, + 2657392035, + 249268274, + 2044508324, + 3772115230, + 2547177864, + 162941995, + 2125561021, + 3887607047, + 2428444049, + 498536548, + 1789927666, + 4089016648, + 2227061214, + 450548861, + 1843258603, + 4107580753, + 2211677639, + 325883990, + 1684777152, + 4251122042, + 2321926636, + 335633487, + 1661365465, + 4195302755, + 2366115317, + 997073096, + 1281953886, + 3579855332, + 2724688242, + 1006888145, + 1258607687, + 3524101629, + 2768942443, + 901097722, + 1119000684, + 3686517206, + 2898065728, + 853044451, + 1172266101, + 3705015759, + 2882616665, + 651767980, + 1373503546, + 3369554304, + 3218104598, + 565507253, + 1454621731, + 3485111705, + 3099436303, + 671266974, + 1594198024, + 3322730930, + 2970347812, + 795835527, + 1483230225, + 3244367275, + 3060149565, + 1994146192, + 31158534, + 2563907772, + 4023717930, + 1907459465, + 112637215, + 2680153253, + 3904427059, + 2013776290, + 251722036, + 2517215374, + 3775830040, + 2137656763, + 141376813, + 2439277719, + 3865271297, + 1802195444, + 476864866, + 2238001368, + 4066508878, + 1812370925, + 453092731, + 2181625025, + 4111451223, + 1706088902, + 314042704, + 2344532202, + 4240017532, + 1658658271, + 366619977, + 2362670323, + 4224994405, + 1303535960, + 984961486, + 2747007092, + 3569037538, + 1256170817, + 1037604311, + 2765210733, + 3554079995, + 1131014506, + 879679996, + 2909243462, + 3663771856, + 1141124467, + 855842277, + 2852801631, + 3708648649, + 1342533948, + 654459306, + 3188396048, + 3373015174, + 1466479909, + 544179635, + 3110523913, + 3462522015, + 1591671054, + 702138776, + 2966460450, + 3352799412, + 1504918807, + 783551873, + 3082640443, + 3233442989, + 3988292384, + 2596254646, + 62317068, + 1957810842, + 3939845945, + 2647816111, + 81470997, + 1943803523, + 3814918930, + 2489596804, + 225274430, + 2053790376, + 3826175755, + 2466906013, + 167816743, + 2097651377, + 4027552580, + 2265490386, + 503444072, + 1762050814, + 4150417245, + 2154129355, + 426522225, + 1852507879, + 4275313526, + 2312317920, + 282753626, + 1742555852, + 4189708143, + 2394877945, + 397917763, + 1622183637, + 3604390888, + 2714866558, + 953729732, + 1340076626, + 3518719985, + 2797360999, + 1068828381, + 1219638859, + 3624741850, + 2936675148, + 906185462, + 1090812512, + 3747672003, + 2825379669, + 829329135, + 1181335161, + 3412177804, + 3160834842, + 628085408, + 1382605366, + 3423369109, + 3138078467, + 570562233, + 1426400815, + 3317316542, + 2998733608, + 733239954, + 1555261956, + 3268935591, + 3050360625, + 752459403, + 1541320221, + 2607071920, + 3965973030, + 1969922972, + 40735498, + 2617837225, + 3943577151, + 1913087877, + 83908371, + 2512341634, + 3803740692, + 2075208622, + 213261112, + 2463272603, + 3855990285, + 2094854071, + 198958881, + 2262029012, + 4057260610, + 1759359992, + 534414190, + 2176718541, + 4139329115, + 1873836001, + 414664567, + 2282248934, + 4279200368, + 1711684554, + 285281116, + 2405801727, + 4167216745, + 1634467795, + 376229701, + 2685067896, + 3608007406, + 1308918612, + 956543938, + 2808555105, + 3495958263, + 1231636301, + 1047427035, + 2932959818, + 3654703836, + 1088359270, + 936918e3, + 2847714899, + 3736837829, + 1202900863, + 817233897, + 3183342108, + 3401237130, + 1404277552, + 615818150, + 3134207493, + 3453421203, + 1423857449, + 601450431, + 3009837614, + 3294710456, + 1567103746, + 711928724, + 3020668471, + 3272380065, + 1510334235, + 755167117 + ]; + var lookupTable = (0, util_1.uint32ArrayFrom)(a_lookUpTable); + var aws_crc32_1 = require_aws_crc32(); + Object.defineProperty(exports, "AwsCrc32", { enumerable: true, get: function() { + return aws_crc32_1.AwsCrc32; + } }); + } + }); + + // node_modules/railroad-memory/dist/chunk-EAGTNQYD.mjs + function calculateDecayedImportance(memory, config) { + if (!config.enableDecay) { + return memory.importance || 5; + } + const lastAccessed = new Date(memory.lastAccessed); + const now2 = /* @__PURE__ */ new Date(); + const daysSinceAccess = (now2.getTime() - lastAccessed.getTime()) / (1e3 * 60 * 60 * 24); + const baseImportance = memory.importance || 5; + const decayFactor = Math.pow(0.5, daysSinceAccess / config.decayHalfLifeDays); + const reinforcement = Math.log2(memory.accessCount + 1) * 0.5; + return Math.min(10, baseImportance * decayFactor + reinforcement); + } + function determineMemoryTier(memory, config) { + const decayedImportance = calculateDecayedImportance(memory, config); + if (decayedImportance >= config.coreFactThreshold) { + return "core"; + } + const createdAt = new Date(memory.createdAt); + const now2 = /* @__PURE__ */ new Date(); + const daysOld = (now2.getTime() - createdAt.getTime()) / (1e3 * 60 * 60 * 24); + if (decayedImportance < config.archiveThreshold) { + return "archived"; + } + if (daysOld <= config.workingMemoryDays) { + return "working"; + } + return "longterm"; + } + function identifyCoreFacts(memories, config = DEFAULT_PRUNING_CONFIG) { + const corePatterns = [ + /\b(name|called)\b.*\b(is|am)\b/i, + // "Name is X", "I am X" + /\b(i am|i'm|my name)\b/i, + // Self-identification + /\b(works? at|cto|ceo|founder|vp|director)\b/i, + // Role/company + /\bpet\b.*\b(named?|called)\b/i, + // Pet names + /\b(hates?|loves?|prefers?|always|never)\b/i, + // Strong preferences + /\bpet peeve\b/i + // Explicit pet peeves + ]; + return memories.filter((m3) => { + if ((m3.importance || 0) >= config.coreFactThreshold) { + return true; + } + return corePatterns.some((pattern) => pattern.test(m3.content)); + }); + } + function groupMemoriesByPeriod(memories, windowDays) { + const groups = /* @__PURE__ */ new Map(); + for (const memory of memories) { + const date2 = new Date(memory.createdAt); + const windowStart = new Date(date2); + windowStart.setDate( + windowStart.getDate() - windowStart.getDate() % windowDays + ); + windowStart.setHours(0, 0, 0, 0); + const key = windowStart.toISOString(); + if (!groups.has(key)) { + groups.set(key, []); + } + groups.get(key).push(memory); + } + return groups; + } + function generateSummaryPrompt(memories, periodStart, periodEnd) { + const memoryList = memories.map((m3) => `- ${m3.content}`).join("\n"); + return `Summarize these memories from ${periodStart} to ${periodEnd} into 2-3 concise sentences that capture the key facts and decisions: + +${memoryList} + +Summary:`; + } + function deduplicateMemories(memories) { + const dominated = /* @__PURE__ */ new Set(); + const sorted = [...memories].sort((a2, b3) => { + const impDiff = (b3.importance || 5) - (a2.importance || 5); + if (impDiff !== 0) return impDiff; + return new Date(b3.createdAt).getTime() - new Date(a2.createdAt).getTime(); + }); + for (let i2 = 0; i2 < sorted.length; i2++) { + if (dominated.has(sorted[i2].id)) continue; + const wordsI = new Set( + sorted[i2].content.toLowerCase().split(/\s+/) + ); + for (let j3 = i2 + 1; j3 < sorted.length; j3++) { + if (dominated.has(sorted[j3].id)) continue; + const wordsJ = sorted[j3].content.toLowerCase().split(/\s+/); + const overlap = wordsJ.filter((w3) => wordsI.has(w3)).length; + const similarity = overlap / Math.max(wordsI.size, wordsJ.length); + if (similarity > 0.6) { + dominated.add(sorted[j3].id); + } + } + } + return sorted.filter((m3) => !dominated.has(m3.id)); + } + function reinforceMemories(memories, query, boost = 1) { + const queryWords = new Set(query.toLowerCase().split(/\s+/)); + return memories.map((m3) => { + const memoryWords = m3.content.toLowerCase().split(/\s+/); + const matches = memoryWords.filter((w3) => queryWords.has(w3)).length; + if (matches > 0) { + return { + ...m3, + importance: Math.min(10, (m3.importance || 5) + boost), + accessCount: m3.accessCount + 1, + lastAccessed: (/* @__PURE__ */ new Date()).toISOString() + }; + } + return m3; + }); + } + function pruneMemories(memories, config = DEFAULT_PRUNING_CONFIG) { + const prunableMemories = memories.map((m3) => ({ + ...m3, + tier: "working", + lastAccessed: m3.lastAccessed || m3.createdAt, + accessCount: m3.accessCount || 0 + })); + const deduped = deduplicateMemories(prunableMemories); + const coreFacts = []; + const workingMemory = []; + const longTermCandidates = []; + const archived = []; + for (const memory of deduped) { + memory.decayedImportance = calculateDecayedImportance(memory, config); + const tier = determineMemoryTier(memory, config); + memory.tier = tier; + switch (tier) { + case "core": + coreFacts.push(memory); + break; + case "working": + workingMemory.push(memory); + break; + case "longterm": + longTermCandidates.push(memory); + break; + case "archived": + archived.push(memory); + break; + } + } + const sortedWorking = workingMemory.sort( + (a2, b3) => new Date(b3.createdAt).getTime() - new Date(a2.createdAt).getTime() + ); + const keptWorking = sortedWorking.slice(0, config.workingMemoryLimit); + const overflowToLongTerm = sortedWorking.slice(config.workingMemoryLimit); + const allLongTerm = [...longTermCandidates, ...overflowToLongTerm]; + const grouped = groupMemoriesByPeriod(allLongTerm, config.summaryWindowDays); + const longTermMemory = []; + let summaryIndex = 0; + for (const [periodKey, periodMemories] of grouped) { + if (summaryIndex >= config.longTermLimit) { + archived.push(...periodMemories); + continue; + } + const periodStart = new Date(periodKey); + const periodEnd = new Date(periodStart); + periodEnd.setDate(periodEnd.getDate() + config.summaryWindowDays); + longTermMemory.push({ + id: `summary-${periodKey}`, + period: { + start: periodStart.toISOString(), + end: periodEnd.toISOString() + }, + summary: `[PENDING SUMMARIZATION: ${periodMemories.length} memories]`, + sourceMemoryIds: periodMemories.map((m3) => m3.id), + createdAt: (/* @__PURE__ */ new Date()).toISOString() + }); + summaryIndex++; + } + return { + coreFacts, + workingMemory: keptWorking, + longTermMemory, + archived + }; + } + function estimateTokens(state) { + const estimate = (text2) => Math.ceil(text2.length / 4); + const core = state.coreFacts.reduce( + (sum, m3) => sum + estimate(m3.content), + 0 + ); + const working = state.workingMemory.reduce( + (sum, m3) => sum + estimate(m3.content), + 0 + ); + const longTerm = state.longTermMemory.reduce( + (sum, s2) => sum + estimate(s2.summary), + 0 + ); + return { + core, + working, + longTerm, + total: core + working + longTerm + }; + } + function formatPrunedStateForPrompt(state) { + const lines = []; + if (state.coreFacts.length > 0) { + lines.push("## Core Facts (Always Remember)"); + state.coreFacts.forEach((m3) => lines.push(`- ${m3.content}`)); + lines.push(""); + } + if (state.workingMemory.length > 0) { + lines.push("## Recent Memory (Last 7 Days)"); + state.workingMemory.forEach((m3) => lines.push(`- ${m3.content}`)); + lines.push(""); + } + if (state.longTermMemory.length > 0) { + lines.push("## Historical Context"); + state.longTermMemory.forEach((s2) => { + const start = new Date(s2.period.start).toLocaleDateString(); + const end = new Date(s2.period.end).toLocaleDateString(); + lines.push(`- [${start} - ${end}]: ${s2.summary}`); + }); + lines.push(""); + } + return lines.join("\n"); + } + var DEFAULT_PRUNING_CONFIG; + var init_chunk_EAGTNQYD = __esm({ + "node_modules/railroad-memory/dist/chunk-EAGTNQYD.mjs"() { + DEFAULT_PRUNING_CONFIG = { + workingMemoryLimit: 100, + workingMemoryDays: 7, + longTermLimit: 50, + summaryWindowDays: 7, + coreFactThreshold: 9, + enableDecay: true, + decayHalfLifeDays: 14, + archiveThreshold: 2 + }; + } + }); + + // node_modules/railroad-memory/dist/pruning-5FCWCEIC.mjs + var pruning_5FCWCEIC_exports = {}; + __export(pruning_5FCWCEIC_exports, { + DEFAULT_PRUNING_CONFIG: () => DEFAULT_PRUNING_CONFIG, + calculateDecayedImportance: () => calculateDecayedImportance, + deduplicateMemories: () => deduplicateMemories, + determineMemoryTier: () => determineMemoryTier, + estimateTokens: () => estimateTokens, + formatPrunedStateForPrompt: () => formatPrunedStateForPrompt, + generateSummaryPrompt: () => generateSummaryPrompt, + groupMemoriesByPeriod: () => groupMemoriesByPeriod, + identifyCoreFacts: () => identifyCoreFacts, + pruneMemories: () => pruneMemories, + reinforceMemories: () => reinforceMemories + }); + var init_pruning_5FCWCEIC = __esm({ + "node_modules/railroad-memory/dist/pruning-5FCWCEIC.mjs"() { + init_chunk_EAGTNQYD(); + } + }); + + // node_modules/railroad-memory/dist/chunk-NM4NC7ZM.mjs + var LocalStorageAdapter, IndexedDBAdapter, SessionStorageAdapter, RemoteAPIAdapter; + var init_chunk_NM4NC7ZM = __esm({ + "node_modules/railroad-memory/dist/chunk-NM4NC7ZM.mjs"() { + LocalStorageAdapter = class { + prefix; + constructor(options = {}) { + this.prefix = options.prefix || "railroad"; + } + getKey(sessionId) { + return `${this.prefix}:${sessionId}`; + } + async load(sessionId) { + try { + const data = localStorage.getItem(this.getKey(sessionId)); + if (!data) return null; + return JSON.parse(data); + } catch (error) { + console.error("LocalStorageAdapter: Failed to load session", error); + return null; + } + } + async save(state) { + try { + const data = JSON.stringify(state); + localStorage.setItem(this.getKey(state.sessionId), data); + } catch (error) { + if (error instanceof Error && error.name === "QuotaExceededError") { + console.error("LocalStorageAdapter: Storage quota exceeded. Consider using IndexedDBAdapter for larger sessions."); + } + throw error; + } + } + async delete(sessionId) { + localStorage.removeItem(this.getKey(sessionId)); + } + async exists(sessionId) { + return localStorage.getItem(this.getKey(sessionId)) !== null; + } + /** + * List all session IDs stored with this prefix + */ + async listSessions() { + const sessions = []; + const prefixWithColon = `${this.prefix}:`; + for (let i2 = 0; i2 < localStorage.length; i2++) { + const key = localStorage.key(i2); + if (key && key.startsWith(prefixWithColon)) { + sessions.push(key.substring(prefixWithColon.length)); + } + } + return sessions; + } + /** + * Clear all sessions with this prefix + */ + async clearAll() { + const sessions = await this.listSessions(); + for (const sessionId of sessions) { + await this.delete(sessionId); + } + } + /** + * Get approximate storage usage in bytes + */ + getStorageUsage() { + let used = 0; + const prefixWithColon = `${this.prefix}:`; + for (let i2 = 0; i2 < localStorage.length; i2++) { + const key = localStorage.key(i2); + if (key && key.startsWith(prefixWithColon)) { + const value = localStorage.getItem(key) || ""; + used += key.length + value.length; + } + } + const available = 5 * 1024 * 1024 - used; + return { used, available }; + } + }; + IndexedDBAdapter = class { + dbName; + storeName; + db = null; + initPromise = null; + constructor(options = {}) { + this.dbName = options.dbName || "railroad-memory"; + this.storeName = options.storeName || "sessions"; + } + /** + * Initialize the database connection + * Must be called before using other methods + */ + async init() { + if (this.db) return; + if (this.initPromise) return this.initPromise; + this.initPromise = new Promise((resolve, reject) => { + const request = indexedDB.open(this.dbName, 1); + request.onerror = () => { + reject(new Error(`IndexedDB: Failed to open database: ${request.error}`)); + }; + request.onsuccess = () => { + this.db = request.result; + resolve(); + }; + request.onupgradeneeded = (event) => { + const db = event.target.result; + if (!db.objectStoreNames.contains(this.storeName)) { + const store2 = db.createObjectStore(this.storeName, { keyPath: "sessionId" }); + store2.createIndex("updatedAt", "updatedAt", { unique: false }); + } + }; + }); + return this.initPromise; + } + async ensureDb() { + if (!this.db) { + await this.init(); + } + if (!this.db) { + throw new Error("IndexedDB: Database not initialized"); + } + return this.db; + } + async load(sessionId) { + const db = await this.ensureDb(); + return new Promise((resolve, reject) => { + const transaction = db.transaction(this.storeName, "readonly"); + const store2 = transaction.objectStore(this.storeName); + const request = store2.get(sessionId); + request.onerror = () => reject(request.error); + request.onsuccess = () => resolve(request.result || null); + }); + } + async save(state) { + const db = await this.ensureDb(); + return new Promise((resolve, reject) => { + const transaction = db.transaction(this.storeName, "readwrite"); + const store2 = transaction.objectStore(this.storeName); + const request = store2.put(state); + request.onerror = () => reject(request.error); + request.onsuccess = () => resolve(); + }); + } + async delete(sessionId) { + const db = await this.ensureDb(); + return new Promise((resolve, reject) => { + const transaction = db.transaction(this.storeName, "readwrite"); + const store2 = transaction.objectStore(this.storeName); + const request = store2.delete(sessionId); + request.onerror = () => reject(request.error); + request.onsuccess = () => resolve(); + }); + } + async exists(sessionId) { + const state = await this.load(sessionId); + return state !== null; + } + /** + * List all session IDs + */ + async listSessions() { + const db = await this.ensureDb(); + return new Promise((resolve, reject) => { + const transaction = db.transaction(this.storeName, "readonly"); + const store2 = transaction.objectStore(this.storeName); + const request = store2.getAllKeys(); + request.onerror = () => reject(request.error); + request.onsuccess = () => resolve(request.result); + }); + } + /** + * Get all sessions + */ + async getAllSessions() { + const db = await this.ensureDb(); + return new Promise((resolve, reject) => { + const transaction = db.transaction(this.storeName, "readonly"); + const store2 = transaction.objectStore(this.storeName); + const request = store2.getAll(); + request.onerror = () => reject(request.error); + request.onsuccess = () => resolve(request.result); + }); + } + /** + * Clear all sessions + */ + async clearAll() { + const db = await this.ensureDb(); + return new Promise((resolve, reject) => { + const transaction = db.transaction(this.storeName, "readwrite"); + const store2 = transaction.objectStore(this.storeName); + const request = store2.clear(); + request.onerror = () => reject(request.error); + request.onsuccess = () => resolve(); + }); + } + /** + * Close the database connection + */ + close() { + if (this.db) { + this.db.close(); + this.db = null; + this.initPromise = null; + } + } + }; + SessionStorageAdapter = class { + prefix; + constructor(options = {}) { + this.prefix = options.prefix || "railroad"; + } + getKey(sessionId) { + return `${this.prefix}:${sessionId}`; + } + async load(sessionId) { + try { + const data = sessionStorage.getItem(this.getKey(sessionId)); + if (!data) return null; + return JSON.parse(data); + } catch (error) { + console.error("SessionStorageAdapter: Failed to load session", error); + return null; + } + } + async save(state) { + const data = JSON.stringify(state); + sessionStorage.setItem(this.getKey(state.sessionId), data); + } + async delete(sessionId) { + sessionStorage.removeItem(this.getKey(sessionId)); + } + async exists(sessionId) { + return sessionStorage.getItem(this.getKey(sessionId)) !== null; + } + }; + RemoteAPIAdapter = class { + baseUrl; + headers; + constructor(options) { + this.baseUrl = options.baseUrl.replace(/\/$/, ""); + this.headers = { + "Content-Type": "application/json", + ...options.headers + }; + } + async load(sessionId) { + try { + const response = await fetch(`${this.baseUrl}/${encodeURIComponent(sessionId)}`, { + method: "GET", + headers: this.headers + }); + if (response.status === 404) return null; + if (!response.ok) throw new Error(`HTTP ${response.status}`); + return await response.json(); + } catch (error) { + console.error("RemoteAPIAdapter: Failed to load session", error); + return null; + } + } + async save(state) { + const response = await fetch(`${this.baseUrl}/${encodeURIComponent(state.sessionId)}`, { + method: "PUT", + headers: this.headers, + body: JSON.stringify(state) + }); + if (!response.ok) { + throw new Error(`RemoteAPIAdapter: Failed to save session: HTTP ${response.status}`); + } + } + async delete(sessionId) { + const response = await fetch(`${this.baseUrl}/${encodeURIComponent(sessionId)}`, { + method: "DELETE", + headers: this.headers + }); + if (!response.ok && response.status !== 404) { + throw new Error(`RemoteAPIAdapter: Failed to delete session: HTTP ${response.status}`); + } + } + async exists(sessionId) { + try { + const response = await fetch(`${this.baseUrl}/${encodeURIComponent(sessionId)}`, { + method: "HEAD", + headers: this.headers + }); + return response.ok; + } catch { + return false; + } + } + }; + } + }); + + // node_modules/railroad-memory/dist/browser-storage-NM532BJM.mjs + var browser_storage_NM532BJM_exports = {}; + __export(browser_storage_NM532BJM_exports, { + IndexedDBAdapter: () => IndexedDBAdapter, + LocalStorageAdapter: () => LocalStorageAdapter, + RemoteAPIAdapter: () => RemoteAPIAdapter, + SessionStorageAdapter: () => SessionStorageAdapter + }); + var init_browser_storage_NM532BJM = __esm({ + "node_modules/railroad-memory/dist/browser-storage-NM532BJM.mjs"() { + init_chunk_NM4NC7ZM(); + } + }); + + // ../../../../../toolkit/content/vendor/marked/marked.mjs + function L() { + return { async: false, breaks: false, extensions: null, gfm: true, hooks: null, pedantic: false, renderer: null, silent: false, tokenizer: null, walkTokens: null }; + } + var T = L(); + function Z(u4) { + T = u4; + } + var C = { exec: () => null }; + function k(u4, e2 = "") { + let t2 = typeof u4 == "string" ? u4 : u4.source, n2 = { replace: (r2, i2) => { + let s2 = typeof i2 == "string" ? i2 : i2.source; + return s2 = s2.replace(m.caret, "$1"), t2 = t2.replace(r2, s2), n2; + }, getRegex: () => new RegExp(t2, e2) }; + return n2; + } + var me = (() => { + try { + return !!new RegExp("(?<=1)(?/, blockquoteSetextReplace: /\n {0,3}((?:=+|-+) *)(?=\n|$)/g, blockquoteSetextReplace2: /^ {0,3}>[ \t]?/gm, listReplaceTabs: /^\t+/, listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g, listIsTask: /^\[[ xX]\] +\S/, listReplaceTask: /^\[[ xX]\] +/, listTaskCheckbox: /\[[ xX]\]/, anyLine: /\n.*\n/, hrefBrackets: /^<(.*)>$/, tableDelimiter: /[:|]/, tableAlignChars: /^\||\| *$/g, tableRowBlankLine: /\n[ \t]*$/, tableAlignRight: /^ *-+: *$/, tableAlignCenter: /^ *:-+: *$/, tableAlignLeft: /^ *:-+ *$/, startATag: /^/i, startPreScriptTag: /^<(pre|code|kbd|script)(\s|>)/i, endPreScriptTag: /^<\/(pre|code|kbd|script)(\s|>)/i, startAngleBracket: /^$/, pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/, unicodeAlphaNumeric: /[\p{L}\p{N}]/u, escapeTest: /[&<>"']/, escapeReplace: /[&<>"']/g, escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/, escapeReplaceNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g, unescapeTest: /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig, caret: /(^|[^\[])\^/g, percentDecode: /%25/g, findPipe: /\|/g, splitPipe: / \|/, slashPipe: /\\\|/g, carriageReturn: /\r\n|\r/g, spaceLine: /^ +$/gm, notSpaceStart: /^\S*/, endingNewline: /\n$/, listItemRegex: (u4) => new RegExp(`^( {0,3}${u4})((?:[ ][^\\n]*)?(?:\\n|$))`), nextBulletRegex: (u4) => new RegExp(`^ {0,${Math.min(3, u4 - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`), hrRegex: (u4) => new RegExp(`^ {0,${Math.min(3, u4 - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`), fencesBeginRegex: (u4) => new RegExp(`^ {0,${Math.min(3, u4 - 1)}}(?:\`\`\`|~~~)`), headingBeginRegex: (u4) => new RegExp(`^ {0,${Math.min(3, u4 - 1)}}#`), htmlBeginRegex: (u4) => new RegExp(`^ {0,${Math.min(3, u4 - 1)}}<(?:[a-z].*>|!--)`, "i") }; + var xe = /^(?:[ \t]*(?:\n|$))+/; + var be = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/; + var Re = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/; + var I = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/; + var Te = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/; + var N = /(?:[*+-]|\d{1,9}[.)])/; + var re = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/; + var se = k(re).replace(/bull/g, N).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/\|table/g, "").getRegex(); + var Oe = k(re).replace(/bull/g, N).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/table/g, / {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(); + var Q = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/; + var we = /^[^\n]+/; + var F = /(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/; + var ye = k(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label", F).replace("title", /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(); + var Pe = k(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g, N).getRegex(); + var v = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul"; + var j = /|$))/; + var Se = k("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))", "i").replace("comment", j).replace("tag", v).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(); + var ie = k(Q).replace("hr", I).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("|table", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", ")|<(?:script|pre|style|textarea|!--)").replace("tag", v).getRegex(); + var $e = k(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph", ie).getRegex(); + var U = { blockquote: $e, code: be, def: ye, fences: Re, heading: Te, hr: I, html: Se, lheading: se, list: Pe, newline: xe, paragraph: ie, table: C, text: we }; + var te = k("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr", I).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("blockquote", " {0,3}>").replace("code", "(?: {4}| {0,3} )[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", ")|<(?:script|pre|style|textarea|!--)").replace("tag", v).getRegex(); + var _e = { ...U, lheading: Oe, table: te, paragraph: k(Q).replace("hr", I).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("table", te).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", ")|<(?:script|pre|style|textarea|!--)").replace("tag", v).getRegex() }; + var Le = { ...U, html: k(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment", j).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(), def: /^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, heading: /^(#{1,6})(.*)(?:\n+|$)/, fences: C, lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/, paragraph: k(Q).replace("hr", I).replace("heading", ` *#{1,6} *[^ +]`).replace("lheading", se).replace("|table", "").replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").replace("|tag", "").getRegex() }; + var Me = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/; + var ze = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/; + var oe = /^( {2,}|\\)\n(?!\s*$)/; + var Ae = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-", me ? "(?`+)[^`]+\k(?!`)/).replace("html", /<(?! )[^<>]*?>/).getRegex(); + var ue = /^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/; + var qe = k(ue, "u").replace(/punct/g, D).getRegex(); + var ve = k(ue, "u").replace(/punct/g, le).getRegex(); + var pe = "^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)"; + var De = k(pe, "gu").replace(/notPunctSpace/g, ae).replace(/punctSpace/g, K).replace(/punct/g, D).getRegex(); + var He = k(pe, "gu").replace(/notPunctSpace/g, Ee).replace(/punctSpace/g, Ie).replace(/punct/g, le).getRegex(); + var Ze = k("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)", "gu").replace(/notPunctSpace/g, ae).replace(/punctSpace/g, K).replace(/punct/g, D).getRegex(); + var Ge = k(/\\(punct)/, "gu").replace(/punct/g, D).getRegex(); + var Ne = k(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme", /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email", /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(); + var Qe = k(j).replace("(?:-->|$)", "-->").getRegex(); + var Fe = k("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment", Qe).replace("attribute", /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(); + var q = /(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/; + var je = k(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label", q).replace("href", /<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title", /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(); + var ce = k(/^!?\[(label)\]\[(ref)\]/).replace("label", q).replace("ref", F).getRegex(); + var he = k(/^!?\[(ref)\](?:\[\])?/).replace("ref", F).getRegex(); + var Ue = k("reflink|nolink(?!\\()", "g").replace("reflink", ce).replace("nolink", he).getRegex(); + var ne = /[hH][tT][tT][pP][sS]?|[fF][tT][pP]/; + var W = { _backpedal: C, anyPunctuation: Ge, autolink: Ne, blockSkip: Be, br: oe, code: ze, del: C, emStrongLDelim: qe, emStrongRDelimAst: De, emStrongRDelimUnd: Ze, escape: Me, link: je, nolink: he, punctuation: Ce, reflink: ce, reflinkSearch: Ue, tag: Fe, text: Ae, url: C }; + var Ke = { ...W, link: k(/^!?\[(label)\]\((.*?)\)/).replace("label", q).getRegex(), reflink: k(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", q).getRegex() }; + var G = { ...W, emStrongRDelimAst: He, emStrongLDelim: ve, url: k(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol", ne).replace("email", /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(), _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/, del: /^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/, text: k(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\": ">", '"': """, "'": "'" }; + var ke = (u4) => Xe[u4]; + function w(u4, e2) { + if (e2) { + if (m.escapeTest.test(u4)) return u4.replace(m.escapeReplace, ke); + } else if (m.escapeTestNoEncode.test(u4)) return u4.replace(m.escapeReplaceNoEncode, ke); + return u4; + } + function X(u4) { + try { + u4 = encodeURI(u4).replace(m.percentDecode, "%"); + } catch { + return null; + } + return u4; + } + function J(u4, e2) { + let t2 = u4.replace(m.findPipe, (i2, s2, a2) => { + let o2 = false, l2 = s2; + for (; --l2 >= 0 && a2[l2] === "\\"; ) o2 = !o2; + return o2 ? "|" : " |"; + }), n2 = t2.split(m.splitPipe), r2 = 0; + if (n2[0].trim() || n2.shift(), n2.length > 0 && !n2.at(-1)?.trim() && n2.pop(), e2) if (n2.length > e2) n2.splice(e2); + else for (; n2.length < e2; ) n2.push(""); + for (; r2 < n2.length; r2++) n2[r2] = n2[r2].trim().replace(m.slashPipe, "|"); + return n2; + } + function z(u4, e2, t2) { + let n2 = u4.length; + if (n2 === 0) return ""; + let r2 = 0; + for (; r2 < n2; ) { + let i2 = u4.charAt(n2 - r2 - 1); + if (i2 === e2 && !t2) r2++; + else if (i2 !== e2 && t2) r2++; + else break; + } + return u4.slice(0, n2 - r2); + } + function de(u4, e2) { + if (u4.indexOf(e2[1]) === -1) return -1; + let t2 = 0; + for (let n2 = 0; n2 < u4.length; n2++) if (u4[n2] === "\\") n2++; + else if (u4[n2] === e2[0]) t2++; + else if (u4[n2] === e2[1] && (t2--, t2 < 0)) return n2; + return t2 > 0 ? -2 : -1; + } + function ge(u4, e2, t2, n2, r2) { + let i2 = e2.href, s2 = e2.title || null, a2 = u4[1].replace(r2.other.outputLinkReplace, "$1"); + n2.state.inLink = true; + let o2 = { type: u4[0].charAt(0) === "!" ? "image" : "link", raw: t2, href: i2, title: s2, text: a2, tokens: n2.inlineTokens(a2) }; + return n2.state.inLink = false, o2; + } + function Je(u4, e2, t2) { + let n2 = u4.match(t2.other.indentCodeCompensation); + if (n2 === null) return e2; + let r2 = n2[1]; + return e2.split(` +`).map((i2) => { + let s2 = i2.match(t2.other.beginningSpace); + if (s2 === null) return i2; + let [a2] = s2; + return a2.length >= r2.length ? i2.slice(r2.length) : i2; + }).join(` +`); + } + var y = class { + options; + rules; + lexer; + constructor(e2) { + this.options = e2 || T; + } + space(e2) { + let t2 = this.rules.block.newline.exec(e2); + if (t2 && t2[0].length > 0) return { type: "space", raw: t2[0] }; + } + code(e2) { + let t2 = this.rules.block.code.exec(e2); + if (t2) { + let n2 = t2[0].replace(this.rules.other.codeRemoveIndent, ""); + return { type: "code", raw: t2[0], codeBlockStyle: "indented", text: this.options.pedantic ? n2 : z(n2, ` +`) }; + } + } + fences(e2) { + let t2 = this.rules.block.fences.exec(e2); + if (t2) { + let n2 = t2[0], r2 = Je(n2, t2[3] || "", this.rules); + return { type: "code", raw: n2, lang: t2[2] ? t2[2].trim().replace(this.rules.inline.anyPunctuation, "$1") : t2[2], text: r2 }; + } + } + heading(e2) { + let t2 = this.rules.block.heading.exec(e2); + if (t2) { + let n2 = t2[2].trim(); + if (this.rules.other.endingHash.test(n2)) { + let r2 = z(n2, "#"); + (this.options.pedantic || !r2 || this.rules.other.endingSpaceChar.test(r2)) && (n2 = r2.trim()); + } + return { type: "heading", raw: t2[0], depth: t2[1].length, text: n2, tokens: this.lexer.inline(n2) }; + } + } + hr(e2) { + let t2 = this.rules.block.hr.exec(e2); + if (t2) return { type: "hr", raw: z(t2[0], ` +`) }; + } + blockquote(e2) { + let t2 = this.rules.block.blockquote.exec(e2); + if (t2) { + let n2 = z(t2[0], ` +`).split(` +`), r2 = "", i2 = "", s2 = []; + for (; n2.length > 0; ) { + let a2 = false, o2 = [], l2; + for (l2 = 0; l2 < n2.length; l2++) if (this.rules.other.blockquoteStart.test(n2[l2])) o2.push(n2[l2]), a2 = true; + else if (!a2) o2.push(n2[l2]); + else break; + n2 = n2.slice(l2); + let p2 = o2.join(` +`), c3 = p2.replace(this.rules.other.blockquoteSetextReplace, ` + $1`).replace(this.rules.other.blockquoteSetextReplace2, ""); + r2 = r2 ? `${r2} +${p2}` : p2, i2 = i2 ? `${i2} +${c3}` : c3; + let g2 = this.lexer.state.top; + if (this.lexer.state.top = true, this.lexer.blockTokens(c3, s2, true), this.lexer.state.top = g2, n2.length === 0) break; + let h2 = s2.at(-1); + if (h2?.type === "code") break; + if (h2?.type === "blockquote") { + let R = h2, f3 = R.raw + ` +` + n2.join(` +`), O = this.blockquote(f3); + s2[s2.length - 1] = O, r2 = r2.substring(0, r2.length - R.raw.length) + O.raw, i2 = i2.substring(0, i2.length - R.text.length) + O.text; + break; + } else if (h2?.type === "list") { + let R = h2, f3 = R.raw + ` +` + n2.join(` +`), O = this.list(f3); + s2[s2.length - 1] = O, r2 = r2.substring(0, r2.length - h2.raw.length) + O.raw, i2 = i2.substring(0, i2.length - R.raw.length) + O.raw, n2 = f3.substring(s2.at(-1).raw.length).split(` +`); + continue; + } + } + return { type: "blockquote", raw: r2, tokens: s2, text: i2 }; + } + } + list(e2) { + let t2 = this.rules.block.list.exec(e2); + if (t2) { + let n2 = t2[1].trim(), r2 = n2.length > 1, i2 = { type: "list", raw: "", ordered: r2, start: r2 ? +n2.slice(0, -1) : "", loose: false, items: [] }; + n2 = r2 ? `\\d{1,9}\\${n2.slice(-1)}` : `\\${n2}`, this.options.pedantic && (n2 = r2 ? n2 : "[*+-]"); + let s2 = this.rules.other.listItemRegex(n2), a2 = false; + for (; e2; ) { + let l2 = false, p2 = "", c3 = ""; + if (!(t2 = s2.exec(e2)) || this.rules.block.hr.test(e2)) break; + p2 = t2[0], e2 = e2.substring(p2.length); + let g2 = t2[2].split(` +`, 1)[0].replace(this.rules.other.listReplaceTabs, (O) => " ".repeat(3 * O.length)), h2 = e2.split(` +`, 1)[0], R = !g2.trim(), f3 = 0; + if (this.options.pedantic ? (f3 = 2, c3 = g2.trimStart()) : R ? f3 = t2[1].length + 1 : (f3 = t2[2].search(this.rules.other.nonSpaceChar), f3 = f3 > 4 ? 1 : f3, c3 = g2.slice(f3), f3 += t2[1].length), R && this.rules.other.blankLine.test(h2) && (p2 += h2 + ` +`, e2 = e2.substring(h2.length + 1), l2 = true), !l2) { + let O = this.rules.other.nextBulletRegex(f3), V2 = this.rules.other.hrRegex(f3), Y = this.rules.other.fencesBeginRegex(f3), ee = this.rules.other.headingBeginRegex(f3), fe = this.rules.other.htmlBeginRegex(f3); + for (; e2; ) { + let H = e2.split(` +`, 1)[0], A; + if (h2 = H, this.options.pedantic ? (h2 = h2.replace(this.rules.other.listReplaceNesting, " "), A = h2) : A = h2.replace(this.rules.other.tabCharGlobal, " "), Y.test(h2) || ee.test(h2) || fe.test(h2) || O.test(h2) || V2.test(h2)) break; + if (A.search(this.rules.other.nonSpaceChar) >= f3 || !h2.trim()) c3 += ` +` + A.slice(f3); + else { + if (R || g2.replace(this.rules.other.tabCharGlobal, " ").search(this.rules.other.nonSpaceChar) >= 4 || Y.test(g2) || ee.test(g2) || V2.test(g2)) break; + c3 += ` +` + h2; + } + !R && !h2.trim() && (R = true), p2 += H + ` +`, e2 = e2.substring(H.length + 1), g2 = A.slice(f3); + } + } + i2.loose || (a2 ? i2.loose = true : this.rules.other.doubleBlankLine.test(p2) && (a2 = true)), i2.items.push({ type: "list_item", raw: p2, task: !!this.options.gfm && this.rules.other.listIsTask.test(c3), loose: false, text: c3, tokens: [] }), i2.raw += p2; + } + let o2 = i2.items.at(-1); + if (o2) o2.raw = o2.raw.trimEnd(), o2.text = o2.text.trimEnd(); + else return; + i2.raw = i2.raw.trimEnd(); + for (let l2 of i2.items) { + if (this.lexer.state.top = false, l2.tokens = this.lexer.blockTokens(l2.text, []), l2.task) { + if (l2.text = l2.text.replace(this.rules.other.listReplaceTask, ""), l2.tokens[0]?.type === "text" || l2.tokens[0]?.type === "paragraph") { + l2.tokens[0].raw = l2.tokens[0].raw.replace(this.rules.other.listReplaceTask, ""), l2.tokens[0].text = l2.tokens[0].text.replace(this.rules.other.listReplaceTask, ""); + for (let c3 = this.lexer.inlineQueue.length - 1; c3 >= 0; c3--) if (this.rules.other.listIsTask.test(this.lexer.inlineQueue[c3].src)) { + this.lexer.inlineQueue[c3].src = this.lexer.inlineQueue[c3].src.replace(this.rules.other.listReplaceTask, ""); + break; + } + } + let p2 = this.rules.other.listTaskCheckbox.exec(l2.raw); + if (p2) { + let c3 = { type: "checkbox", raw: p2[0] + " ", checked: p2[0] !== "[ ]" }; + l2.checked = c3.checked, i2.loose ? l2.tokens[0] && ["paragraph", "text"].includes(l2.tokens[0].type) && "tokens" in l2.tokens[0] && l2.tokens[0].tokens ? (l2.tokens[0].raw = c3.raw + l2.tokens[0].raw, l2.tokens[0].text = c3.raw + l2.tokens[0].text, l2.tokens[0].tokens.unshift(c3)) : l2.tokens.unshift({ type: "paragraph", raw: c3.raw, text: c3.raw, tokens: [c3] }) : l2.tokens.unshift(c3); + } + } + if (!i2.loose) { + let p2 = l2.tokens.filter((g2) => g2.type === "space"), c3 = p2.length > 0 && p2.some((g2) => this.rules.other.anyLine.test(g2.raw)); + i2.loose = c3; + } + } + if (i2.loose) for (let l2 of i2.items) { + l2.loose = true; + for (let p2 of l2.tokens) p2.type === "text" && (p2.type = "paragraph"); + } + return i2; + } + } + html(e2) { + let t2 = this.rules.block.html.exec(e2); + if (t2) return { type: "html", block: true, raw: t2[0], pre: t2[1] === "pre" || t2[1] === "script" || t2[1] === "style", text: t2[0] }; + } + def(e2) { + let t2 = this.rules.block.def.exec(e2); + if (t2) { + let n2 = t2[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, " "), r2 = t2[2] ? t2[2].replace(this.rules.other.hrefBrackets, "$1").replace(this.rules.inline.anyPunctuation, "$1") : "", i2 = t2[3] ? t2[3].substring(1, t2[3].length - 1).replace(this.rules.inline.anyPunctuation, "$1") : t2[3]; + return { type: "def", tag: n2, raw: t2[0], href: r2, title: i2 }; + } + } + table(e2) { + let t2 = this.rules.block.table.exec(e2); + if (!t2 || !this.rules.other.tableDelimiter.test(t2[2])) return; + let n2 = J(t2[1]), r2 = t2[2].replace(this.rules.other.tableAlignChars, "").split("|"), i2 = t2[3]?.trim() ? t2[3].replace(this.rules.other.tableRowBlankLine, "").split(` +`) : [], s2 = { type: "table", raw: t2[0], header: [], align: [], rows: [] }; + if (n2.length === r2.length) { + for (let a2 of r2) this.rules.other.tableAlignRight.test(a2) ? s2.align.push("right") : this.rules.other.tableAlignCenter.test(a2) ? s2.align.push("center") : this.rules.other.tableAlignLeft.test(a2) ? s2.align.push("left") : s2.align.push(null); + for (let a2 = 0; a2 < n2.length; a2++) s2.header.push({ text: n2[a2], tokens: this.lexer.inline(n2[a2]), header: true, align: s2.align[a2] }); + for (let a2 of i2) s2.rows.push(J(a2, s2.header.length).map((o2, l2) => ({ text: o2, tokens: this.lexer.inline(o2), header: false, align: s2.align[l2] }))); + return s2; + } + } + lheading(e2) { + let t2 = this.rules.block.lheading.exec(e2); + if (t2) return { type: "heading", raw: t2[0], depth: t2[2].charAt(0) === "=" ? 1 : 2, text: t2[1], tokens: this.lexer.inline(t2[1]) }; + } + paragraph(e2) { + let t2 = this.rules.block.paragraph.exec(e2); + if (t2) { + let n2 = t2[1].charAt(t2[1].length - 1) === ` +` ? t2[1].slice(0, -1) : t2[1]; + return { type: "paragraph", raw: t2[0], text: n2, tokens: this.lexer.inline(n2) }; + } + } + text(e2) { + let t2 = this.rules.block.text.exec(e2); + if (t2) return { type: "text", raw: t2[0], text: t2[0], tokens: this.lexer.inline(t2[0]) }; + } + escape(e2) { + let t2 = this.rules.inline.escape.exec(e2); + if (t2) return { type: "escape", raw: t2[0], text: t2[1] }; + } + tag(e2) { + let t2 = this.rules.inline.tag.exec(e2); + if (t2) return !this.lexer.state.inLink && this.rules.other.startATag.test(t2[0]) ? this.lexer.state.inLink = true : this.lexer.state.inLink && this.rules.other.endATag.test(t2[0]) && (this.lexer.state.inLink = false), !this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(t2[0]) ? this.lexer.state.inRawBlock = true : this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(t2[0]) && (this.lexer.state.inRawBlock = false), { type: "html", raw: t2[0], inLink: this.lexer.state.inLink, inRawBlock: this.lexer.state.inRawBlock, block: false, text: t2[0] }; + } + link(e2) { + let t2 = this.rules.inline.link.exec(e2); + if (t2) { + let n2 = t2[2].trim(); + if (!this.options.pedantic && this.rules.other.startAngleBracket.test(n2)) { + if (!this.rules.other.endAngleBracket.test(n2)) return; + let s2 = z(n2.slice(0, -1), "\\"); + if ((n2.length - s2.length) % 2 === 0) return; + } else { + let s2 = de(t2[2], "()"); + if (s2 === -2) return; + if (s2 > -1) { + let o2 = (t2[0].indexOf("!") === 0 ? 5 : 4) + t2[1].length + s2; + t2[2] = t2[2].substring(0, s2), t2[0] = t2[0].substring(0, o2).trim(), t2[3] = ""; + } + } + let r2 = t2[2], i2 = ""; + if (this.options.pedantic) { + let s2 = this.rules.other.pedanticHrefTitle.exec(r2); + s2 && (r2 = s2[1], i2 = s2[3]); + } else i2 = t2[3] ? t2[3].slice(1, -1) : ""; + return r2 = r2.trim(), this.rules.other.startAngleBracket.test(r2) && (this.options.pedantic && !this.rules.other.endAngleBracket.test(n2) ? r2 = r2.slice(1) : r2 = r2.slice(1, -1)), ge(t2, { href: r2 && r2.replace(this.rules.inline.anyPunctuation, "$1"), title: i2 && i2.replace(this.rules.inline.anyPunctuation, "$1") }, t2[0], this.lexer, this.rules); + } + } + reflink(e2, t2) { + let n2; + if ((n2 = this.rules.inline.reflink.exec(e2)) || (n2 = this.rules.inline.nolink.exec(e2))) { + let r2 = (n2[2] || n2[1]).replace(this.rules.other.multipleSpaceGlobal, " "), i2 = t2[r2.toLowerCase()]; + if (!i2) { + let s2 = n2[0].charAt(0); + return { type: "text", raw: s2, text: s2 }; + } + return ge(n2, i2, n2[0], this.lexer, this.rules); + } + } + emStrong(e2, t2, n2 = "") { + let r2 = this.rules.inline.emStrongLDelim.exec(e2); + if (!r2 || r2[3] && n2.match(this.rules.other.unicodeAlphaNumeric)) return; + if (!(r2[1] || r2[2] || "") || !n2 || this.rules.inline.punctuation.exec(n2)) { + let s2 = [...r2[0]].length - 1, a2, o2, l2 = s2, p2 = 0, c3 = r2[0][0] === "*" ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd; + for (c3.lastIndex = 0, t2 = t2.slice(-1 * e2.length + s2); (r2 = c3.exec(t2)) != null; ) { + if (a2 = r2[1] || r2[2] || r2[3] || r2[4] || r2[5] || r2[6], !a2) continue; + if (o2 = [...a2].length, r2[3] || r2[4]) { + l2 += o2; + continue; + } else if ((r2[5] || r2[6]) && s2 % 3 && !((s2 + o2) % 3)) { + p2 += o2; + continue; + } + if (l2 -= o2, l2 > 0) continue; + o2 = Math.min(o2, o2 + l2 + p2); + let g2 = [...r2[0]][0].length, h2 = e2.slice(0, s2 + r2.index + g2 + o2); + if (Math.min(s2, o2) % 2) { + let f3 = h2.slice(1, -1); + return { type: "em", raw: h2, text: f3, tokens: this.lexer.inlineTokens(f3) }; + } + let R = h2.slice(2, -2); + return { type: "strong", raw: h2, text: R, tokens: this.lexer.inlineTokens(R) }; + } + } + } + codespan(e2) { + let t2 = this.rules.inline.code.exec(e2); + if (t2) { + let n2 = t2[2].replace(this.rules.other.newLineCharGlobal, " "), r2 = this.rules.other.nonSpaceChar.test(n2), i2 = this.rules.other.startingSpaceChar.test(n2) && this.rules.other.endingSpaceChar.test(n2); + return r2 && i2 && (n2 = n2.substring(1, n2.length - 1)), { type: "codespan", raw: t2[0], text: n2 }; + } + } + br(e2) { + let t2 = this.rules.inline.br.exec(e2); + if (t2) return { type: "br", raw: t2[0] }; + } + del(e2) { + let t2 = this.rules.inline.del.exec(e2); + if (t2) return { type: "del", raw: t2[0], text: t2[2], tokens: this.lexer.inlineTokens(t2[2]) }; + } + autolink(e2) { + let t2 = this.rules.inline.autolink.exec(e2); + if (t2) { + let n2, r2; + return t2[2] === "@" ? (n2 = t2[1], r2 = "mailto:" + n2) : (n2 = t2[1], r2 = n2), { type: "link", raw: t2[0], text: n2, href: r2, tokens: [{ type: "text", raw: n2, text: n2 }] }; + } + } + url(e2) { + let t2; + if (t2 = this.rules.inline.url.exec(e2)) { + let n2, r2; + if (t2[2] === "@") n2 = t2[0], r2 = "mailto:" + n2; + else { + let i2; + do + i2 = t2[0], t2[0] = this.rules.inline._backpedal.exec(t2[0])?.[0] ?? ""; + while (i2 !== t2[0]); + n2 = t2[0], t2[1] === "www." ? r2 = "http://" + t2[0] : r2 = t2[0]; + } + return { type: "link", raw: t2[0], text: n2, href: r2, tokens: [{ type: "text", raw: n2, text: n2 }] }; + } + } + inlineText(e2) { + let t2 = this.rules.inline.text.exec(e2); + if (t2) { + let n2 = this.lexer.state.inRawBlock; + return { type: "text", raw: t2[0], text: t2[0], escaped: n2 }; + } + } + }; + var x = class u { + tokens; + options; + state; + inlineQueue; + tokenizer; + constructor(e2) { + this.tokens = [], this.tokens.links = /* @__PURE__ */ Object.create(null), this.options = e2 || T, this.options.tokenizer = this.options.tokenizer || new y(), this.tokenizer = this.options.tokenizer, this.tokenizer.options = this.options, this.tokenizer.lexer = this, this.inlineQueue = [], this.state = { inLink: false, inRawBlock: false, top: true }; + let t2 = { other: m, block: E.normal, inline: M.normal }; + this.options.pedantic ? (t2.block = E.pedantic, t2.inline = M.pedantic) : this.options.gfm && (t2.block = E.gfm, this.options.breaks ? t2.inline = M.breaks : t2.inline = M.gfm), this.tokenizer.rules = t2; + } + static get rules() { + return { block: E, inline: M }; + } + static lex(e2, t2) { + return new u(t2).lex(e2); + } + static lexInline(e2, t2) { + return new u(t2).inlineTokens(e2); + } + lex(e2) { + e2 = e2.replace(m.carriageReturn, ` +`), this.blockTokens(e2, this.tokens); + for (let t2 = 0; t2 < this.inlineQueue.length; t2++) { + let n2 = this.inlineQueue[t2]; + this.inlineTokens(n2.src, n2.tokens); + } + return this.inlineQueue = [], this.tokens; + } + blockTokens(e2, t2 = [], n2 = false) { + for (this.options.pedantic && (e2 = e2.replace(m.tabCharGlobal, " ").replace(m.spaceLine, "")); e2; ) { + let r2; + if (this.options.extensions?.block?.some((s2) => (r2 = s2.call({ lexer: this }, e2, t2)) ? (e2 = e2.substring(r2.raw.length), t2.push(r2), true) : false)) continue; + if (r2 = this.tokenizer.space(e2)) { + e2 = e2.substring(r2.raw.length); + let s2 = t2.at(-1); + r2.raw.length === 1 && s2 !== void 0 ? s2.raw += ` +` : t2.push(r2); + continue; + } + if (r2 = this.tokenizer.code(e2)) { + e2 = e2.substring(r2.raw.length); + let s2 = t2.at(-1); + s2?.type === "paragraph" || s2?.type === "text" ? (s2.raw += (s2.raw.endsWith(` +`) ? "" : ` +`) + r2.raw, s2.text += ` +` + r2.text, this.inlineQueue.at(-1).src = s2.text) : t2.push(r2); + continue; + } + if (r2 = this.tokenizer.fences(e2)) { + e2 = e2.substring(r2.raw.length), t2.push(r2); + continue; + } + if (r2 = this.tokenizer.heading(e2)) { + e2 = e2.substring(r2.raw.length), t2.push(r2); + continue; + } + if (r2 = this.tokenizer.hr(e2)) { + e2 = e2.substring(r2.raw.length), t2.push(r2); + continue; + } + if (r2 = this.tokenizer.blockquote(e2)) { + e2 = e2.substring(r2.raw.length), t2.push(r2); + continue; + } + if (r2 = this.tokenizer.list(e2)) { + e2 = e2.substring(r2.raw.length), t2.push(r2); + continue; + } + if (r2 = this.tokenizer.html(e2)) { + e2 = e2.substring(r2.raw.length), t2.push(r2); + continue; + } + if (r2 = this.tokenizer.def(e2)) { + e2 = e2.substring(r2.raw.length); + let s2 = t2.at(-1); + s2?.type === "paragraph" || s2?.type === "text" ? (s2.raw += (s2.raw.endsWith(` +`) ? "" : ` +`) + r2.raw, s2.text += ` +` + r2.raw, this.inlineQueue.at(-1).src = s2.text) : this.tokens.links[r2.tag] || (this.tokens.links[r2.tag] = { href: r2.href, title: r2.title }, t2.push(r2)); + continue; + } + if (r2 = this.tokenizer.table(e2)) { + e2 = e2.substring(r2.raw.length), t2.push(r2); + continue; + } + if (r2 = this.tokenizer.lheading(e2)) { + e2 = e2.substring(r2.raw.length), t2.push(r2); + continue; + } + let i2 = e2; + if (this.options.extensions?.startBlock) { + let s2 = 1 / 0, a2 = e2.slice(1), o2; + this.options.extensions.startBlock.forEach((l2) => { + o2 = l2.call({ lexer: this }, a2), typeof o2 == "number" && o2 >= 0 && (s2 = Math.min(s2, o2)); + }), s2 < 1 / 0 && s2 >= 0 && (i2 = e2.substring(0, s2 + 1)); + } + if (this.state.top && (r2 = this.tokenizer.paragraph(i2))) { + let s2 = t2.at(-1); + n2 && s2?.type === "paragraph" ? (s2.raw += (s2.raw.endsWith(` +`) ? "" : ` +`) + r2.raw, s2.text += ` +` + r2.text, this.inlineQueue.pop(), this.inlineQueue.at(-1).src = s2.text) : t2.push(r2), n2 = i2.length !== e2.length, e2 = e2.substring(r2.raw.length); + continue; + } + if (r2 = this.tokenizer.text(e2)) { + e2 = e2.substring(r2.raw.length); + let s2 = t2.at(-1); + s2?.type === "text" ? (s2.raw += (s2.raw.endsWith(` +`) ? "" : ` +`) + r2.raw, s2.text += ` +` + r2.text, this.inlineQueue.pop(), this.inlineQueue.at(-1).src = s2.text) : t2.push(r2); + continue; + } + if (e2) { + let s2 = "Infinite loop on byte: " + e2.charCodeAt(0); + if (this.options.silent) { + console.error(s2); + break; + } else throw new Error(s2); + } + } + return this.state.top = true, t2; + } + inline(e2, t2 = []) { + return this.inlineQueue.push({ src: e2, tokens: t2 }), t2; + } + inlineTokens(e2, t2 = []) { + let n2 = e2, r2 = null; + if (this.tokens.links) { + let o2 = Object.keys(this.tokens.links); + if (o2.length > 0) for (; (r2 = this.tokenizer.rules.inline.reflinkSearch.exec(n2)) != null; ) o2.includes(r2[0].slice(r2[0].lastIndexOf("[") + 1, -1)) && (n2 = n2.slice(0, r2.index) + "[" + "a".repeat(r2[0].length - 2) + "]" + n2.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex)); + } + for (; (r2 = this.tokenizer.rules.inline.anyPunctuation.exec(n2)) != null; ) n2 = n2.slice(0, r2.index) + "++" + n2.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex); + let i2; + for (; (r2 = this.tokenizer.rules.inline.blockSkip.exec(n2)) != null; ) i2 = r2[2] ? r2[2].length : 0, n2 = n2.slice(0, r2.index + i2) + "[" + "a".repeat(r2[0].length - i2 - 2) + "]" + n2.slice(this.tokenizer.rules.inline.blockSkip.lastIndex); + n2 = this.options.hooks?.emStrongMask?.call({ lexer: this }, n2) ?? n2; + let s2 = false, a2 = ""; + for (; e2; ) { + s2 || (a2 = ""), s2 = false; + let o2; + if (this.options.extensions?.inline?.some((p2) => (o2 = p2.call({ lexer: this }, e2, t2)) ? (e2 = e2.substring(o2.raw.length), t2.push(o2), true) : false)) continue; + if (o2 = this.tokenizer.escape(e2)) { + e2 = e2.substring(o2.raw.length), t2.push(o2); + continue; + } + if (o2 = this.tokenizer.tag(e2)) { + e2 = e2.substring(o2.raw.length), t2.push(o2); + continue; + } + if (o2 = this.tokenizer.link(e2)) { + e2 = e2.substring(o2.raw.length), t2.push(o2); + continue; + } + if (o2 = this.tokenizer.reflink(e2, this.tokens.links)) { + e2 = e2.substring(o2.raw.length); + let p2 = t2.at(-1); + o2.type === "text" && p2?.type === "text" ? (p2.raw += o2.raw, p2.text += o2.text) : t2.push(o2); + continue; + } + if (o2 = this.tokenizer.emStrong(e2, n2, a2)) { + e2 = e2.substring(o2.raw.length), t2.push(o2); + continue; + } + if (o2 = this.tokenizer.codespan(e2)) { + e2 = e2.substring(o2.raw.length), t2.push(o2); + continue; + } + if (o2 = this.tokenizer.br(e2)) { + e2 = e2.substring(o2.raw.length), t2.push(o2); + continue; + } + if (o2 = this.tokenizer.del(e2)) { + e2 = e2.substring(o2.raw.length), t2.push(o2); + continue; + } + if (o2 = this.tokenizer.autolink(e2)) { + e2 = e2.substring(o2.raw.length), t2.push(o2); + continue; + } + if (!this.state.inLink && (o2 = this.tokenizer.url(e2))) { + e2 = e2.substring(o2.raw.length), t2.push(o2); + continue; + } + let l2 = e2; + if (this.options.extensions?.startInline) { + let p2 = 1 / 0, c3 = e2.slice(1), g2; + this.options.extensions.startInline.forEach((h2) => { + g2 = h2.call({ lexer: this }, c3), typeof g2 == "number" && g2 >= 0 && (p2 = Math.min(p2, g2)); + }), p2 < 1 / 0 && p2 >= 0 && (l2 = e2.substring(0, p2 + 1)); + } + if (o2 = this.tokenizer.inlineText(l2)) { + e2 = e2.substring(o2.raw.length), o2.raw.slice(-1) !== "_" && (a2 = o2.raw.slice(-1)), s2 = true; + let p2 = t2.at(-1); + p2?.type === "text" ? (p2.raw += o2.raw, p2.text += o2.text) : t2.push(o2); + continue; + } + if (e2) { + let p2 = "Infinite loop on byte: " + e2.charCodeAt(0); + if (this.options.silent) { + console.error(p2); + break; + } else throw new Error(p2); + } + } + return t2; + } + }; + var P = class { + options; + parser; + constructor(e2) { + this.options = e2 || T; + } + space(e2) { + return ""; + } + code({ text: e2, lang: t2, escaped: n2 }) { + let r2 = (t2 || "").match(m.notSpaceStart)?.[0], i2 = e2.replace(m.endingNewline, "") + ` +`; + return r2 ? '
' + (n2 ? i2 : w(i2, true)) + `
+` : "
" + (n2 ? i2 : w(i2, true)) + `
+`; + } + blockquote({ tokens: e2 }) { + return `
+${this.parser.parse(e2)}
+`; + } + html({ text: e2 }) { + return e2; + } + def(e2) { + return ""; + } + heading({ tokens: e2, depth: t2 }) { + return `${this.parser.parseInline(e2)} +`; + } + hr(e2) { + return `
+`; + } + list(e2) { + let t2 = e2.ordered, n2 = e2.start, r2 = ""; + for (let a2 = 0; a2 < e2.items.length; a2++) { + let o2 = e2.items[a2]; + r2 += this.listitem(o2); + } + let i2 = t2 ? "ol" : "ul", s2 = t2 && n2 !== 1 ? ' start="' + n2 + '"' : ""; + return "<" + i2 + s2 + `> +` + r2 + " +`; + } + listitem(e2) { + return `
  • ${this.parser.parse(e2.tokens)}
  • +`; + } + checkbox({ checked: e2 }) { + return " '; + } + paragraph({ tokens: e2 }) { + return `

    ${this.parser.parseInline(e2)}

    +`; + } + table(e2) { + let t2 = "", n2 = ""; + for (let i2 = 0; i2 < e2.header.length; i2++) n2 += this.tablecell(e2.header[i2]); + t2 += this.tablerow({ text: n2 }); + let r2 = ""; + for (let i2 = 0; i2 < e2.rows.length; i2++) { + let s2 = e2.rows[i2]; + n2 = ""; + for (let a2 = 0; a2 < s2.length; a2++) n2 += this.tablecell(s2[a2]); + r2 += this.tablerow({ text: n2 }); + } + return r2 && (r2 = `${r2}`), ` + +` + t2 + ` +` + r2 + `
    +`; + } + tablerow({ text: e2 }) { + return ` +${e2} +`; + } + tablecell(e2) { + let t2 = this.parser.parseInline(e2.tokens), n2 = e2.header ? "th" : "td"; + return (e2.align ? `<${n2} align="${e2.align}">` : `<${n2}>`) + t2 + ` +`; + } + strong({ tokens: e2 }) { + return `${this.parser.parseInline(e2)}`; + } + em({ tokens: e2 }) { + return `${this.parser.parseInline(e2)}`; + } + codespan({ text: e2 }) { + return `${w(e2, true)}`; + } + br(e2) { + return "
    "; + } + del({ tokens: e2 }) { + return `${this.parser.parseInline(e2)}`; + } + link({ href: e2, title: t2, tokens: n2 }) { + let r2 = this.parser.parseInline(n2), i2 = X(e2); + if (i2 === null) return r2; + e2 = i2; + let s2 = '
    ", s2; + } + image({ href: e2, title: t2, text: n2, tokens: r2 }) { + r2 && (n2 = this.parser.parseInline(r2, this.parser.textRenderer)); + let i2 = X(e2); + if (i2 === null) return w(n2); + e2 = i2; + let s2 = `${n2} { + let a2 = i2[s2].flat(1 / 0); + n2 = n2.concat(this.walkTokens(a2, t2)); + }) : i2.tokens && (n2 = n2.concat(this.walkTokens(i2.tokens, t2))); + } + } + return n2; + } + use(...e2) { + let t2 = this.defaults.extensions || { renderers: {}, childTokens: {} }; + return e2.forEach((n2) => { + let r2 = { ...n2 }; + if (r2.async = this.defaults.async || r2.async || false, n2.extensions && (n2.extensions.forEach((i2) => { + if (!i2.name) throw new Error("extension name required"); + if ("renderer" in i2) { + let s2 = t2.renderers[i2.name]; + s2 ? t2.renderers[i2.name] = function(...a2) { + let o2 = i2.renderer.apply(this, a2); + return o2 === false && (o2 = s2.apply(this, a2)), o2; + } : t2.renderers[i2.name] = i2.renderer; + } + if ("tokenizer" in i2) { + if (!i2.level || i2.level !== "block" && i2.level !== "inline") throw new Error("extension level must be 'block' or 'inline'"); + let s2 = t2[i2.level]; + s2 ? s2.unshift(i2.tokenizer) : t2[i2.level] = [i2.tokenizer], i2.start && (i2.level === "block" ? t2.startBlock ? t2.startBlock.push(i2.start) : t2.startBlock = [i2.start] : i2.level === "inline" && (t2.startInline ? t2.startInline.push(i2.start) : t2.startInline = [i2.start])); + } + "childTokens" in i2 && i2.childTokens && (t2.childTokens[i2.name] = i2.childTokens); + }), r2.extensions = t2), n2.renderer) { + let i2 = this.defaults.renderer || new P(this.defaults); + for (let s2 in n2.renderer) { + if (!(s2 in i2)) throw new Error(`renderer '${s2}' does not exist`); + if (["options", "parser"].includes(s2)) continue; + let a2 = s2, o2 = n2.renderer[a2], l2 = i2[a2]; + i2[a2] = (...p2) => { + let c3 = o2.apply(i2, p2); + return c3 === false && (c3 = l2.apply(i2, p2)), c3 || ""; + }; + } + r2.renderer = i2; + } + if (n2.tokenizer) { + let i2 = this.defaults.tokenizer || new y(this.defaults); + for (let s2 in n2.tokenizer) { + if (!(s2 in i2)) throw new Error(`tokenizer '${s2}' does not exist`); + if (["options", "rules", "lexer"].includes(s2)) continue; + let a2 = s2, o2 = n2.tokenizer[a2], l2 = i2[a2]; + i2[a2] = (...p2) => { + let c3 = o2.apply(i2, p2); + return c3 === false && (c3 = l2.apply(i2, p2)), c3; + }; + } + r2.tokenizer = i2; + } + if (n2.hooks) { + let i2 = this.defaults.hooks || new S(); + for (let s2 in n2.hooks) { + if (!(s2 in i2)) throw new Error(`hook '${s2}' does not exist`); + if (["options", "block"].includes(s2)) continue; + let a2 = s2, o2 = n2.hooks[a2], l2 = i2[a2]; + S.passThroughHooks.has(s2) ? i2[a2] = (p2) => { + if (this.defaults.async && S.passThroughHooksRespectAsync.has(s2)) return (async () => { + let g2 = await o2.call(i2, p2); + return l2.call(i2, g2); + })(); + let c3 = o2.call(i2, p2); + return l2.call(i2, c3); + } : i2[a2] = (...p2) => { + if (this.defaults.async) return (async () => { + let g2 = await o2.apply(i2, p2); + return g2 === false && (g2 = await l2.apply(i2, p2)), g2; + })(); + let c3 = o2.apply(i2, p2); + return c3 === false && (c3 = l2.apply(i2, p2)), c3; + }; + } + r2.hooks = i2; + } + if (n2.walkTokens) { + let i2 = this.defaults.walkTokens, s2 = n2.walkTokens; + r2.walkTokens = function(a2) { + let o2 = []; + return o2.push(s2.call(this, a2)), i2 && (o2 = o2.concat(i2.call(this, a2))), o2; + }; + } + this.defaults = { ...this.defaults, ...r2 }; + }), this; + } + setOptions(e2) { + return this.defaults = { ...this.defaults, ...e2 }, this; + } + lexer(e2, t2) { + return x.lex(e2, t2 ?? this.defaults); + } + parser(e2, t2) { + return b.parse(e2, t2 ?? this.defaults); + } + parseMarkdown(e2) { + return (n2, r2) => { + let i2 = { ...r2 }, s2 = { ...this.defaults, ...i2 }, a2 = this.onError(!!s2.silent, !!s2.async); + if (this.defaults.async === true && i2.async === false) return a2(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.")); + if (typeof n2 > "u" || n2 === null) return a2(new Error("marked(): input parameter is undefined or null")); + if (typeof n2 != "string") return a2(new Error("marked(): input parameter is of type " + Object.prototype.toString.call(n2) + ", string expected")); + if (s2.hooks && (s2.hooks.options = s2, s2.hooks.block = e2), s2.async) return (async () => { + let o2 = s2.hooks ? await s2.hooks.preprocess(n2) : n2, p2 = await (s2.hooks ? await s2.hooks.provideLexer() : e2 ? x.lex : x.lexInline)(o2, s2), c3 = s2.hooks ? await s2.hooks.processAllTokens(p2) : p2; + s2.walkTokens && await Promise.all(this.walkTokens(c3, s2.walkTokens)); + let h2 = await (s2.hooks ? await s2.hooks.provideParser() : e2 ? b.parse : b.parseInline)(c3, s2); + return s2.hooks ? await s2.hooks.postprocess(h2) : h2; + })().catch(a2); + try { + s2.hooks && (n2 = s2.hooks.preprocess(n2)); + let l2 = (s2.hooks ? s2.hooks.provideLexer() : e2 ? x.lex : x.lexInline)(n2, s2); + s2.hooks && (l2 = s2.hooks.processAllTokens(l2)), s2.walkTokens && this.walkTokens(l2, s2.walkTokens); + let c3 = (s2.hooks ? s2.hooks.provideParser() : e2 ? b.parse : b.parseInline)(l2, s2); + return s2.hooks && (c3 = s2.hooks.postprocess(c3)), c3; + } catch (o2) { + return a2(o2); + } + }; + } + onError(e2, t2) { + return (n2) => { + if (n2.message += ` +Please report this to https://github.com/markedjs/marked.`, e2) { + let r2 = "

    An error occurred:

    " + w(n2.message + "", true) + "
    "; + return t2 ? Promise.resolve(r2) : r2; + } + if (t2) return Promise.reject(n2); + throw n2; + }; + } + }; + var _ = new B(); + function d(u4, e2) { + return _.parse(u4, e2); + } + d.options = d.setOptions = function(u4) { + return _.setOptions(u4), d.defaults = _.defaults, Z(d.defaults), d; + }; + d.getDefaults = L; + d.defaults = T; + d.use = function(...u4) { + return _.use(...u4), d.defaults = _.defaults, Z(d.defaults), d; + }; + d.walkTokens = function(u4, e2) { + return _.walkTokens(u4, e2); + }; + d.parseInline = _.parseInline; + d.Parser = b; + d.parser = b.parse; + d.Renderer = P; + d.TextRenderer = $; + d.Lexer = x; + d.lexer = x.lex; + d.Tokenizer = y; + d.Hooks = S; + d.parse = d; + var Dt = d.options; + var Ht = d.setOptions; + var Zt = d.use; + var Gt = d.walkTokens; + var Nt = d.parseInline; + var Ft = b.parse; + var jt = x.lex; + + // ../../../../../toolkit/content/vendor/dompurify/dompurify.mjs + var { + entries, + setPrototypeOf, + isFrozen, + getPrototypeOf, + getOwnPropertyDescriptor + } = Object; + var { + freeze, + seal, + create + } = Object; + var { + apply, + construct + } = typeof Reflect !== "undefined" && Reflect; + if (!freeze) { + freeze = function freeze2(x3) { + return x3; + }; + } + if (!seal) { + seal = function seal2(x3) { + return x3; + }; + } + if (!apply) { + apply = function apply2(func, thisArg) { + for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { + args[_key - 2] = arguments[_key]; + } + return func.apply(thisArg, args); + }; + } + if (!construct) { + construct = function construct2(Func) { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + return new Func(...args); + }; + } + var arrayForEach = unapply(Array.prototype.forEach); + var arrayLastIndexOf = unapply(Array.prototype.lastIndexOf); + var arrayPop = unapply(Array.prototype.pop); + var arrayPush = unapply(Array.prototype.push); + var arraySplice = unapply(Array.prototype.splice); + var stringToLowerCase = unapply(String.prototype.toLowerCase); + var stringToString = unapply(String.prototype.toString); + var stringMatch = unapply(String.prototype.match); + var stringReplace = unapply(String.prototype.replace); + var stringIndexOf = unapply(String.prototype.indexOf); + var stringTrim = unapply(String.prototype.trim); + var objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty); + var regExpTest = unapply(RegExp.prototype.test); + var typeErrorCreate = unconstruct(TypeError); + function unapply(func) { + return function(thisArg) { + if (thisArg instanceof RegExp) { + thisArg.lastIndex = 0; + } + for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + args[_key3 - 1] = arguments[_key3]; + } + return apply(func, thisArg, args); + }; + } + function unconstruct(Func) { + return function() { + for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + return construct(Func, args); + }; + } + function addToSet(set2, array) { + let transformCaseFunc = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : stringToLowerCase; + if (setPrototypeOf) { + setPrototypeOf(set2, null); + } + let l2 = array.length; + while (l2--) { + let element = array[l2]; + if (typeof element === "string") { + const lcElement = transformCaseFunc(element); + if (lcElement !== element) { + if (!isFrozen(array)) { + array[l2] = lcElement; + } + element = lcElement; + } + } + set2[element] = true; + } + return set2; + } + function cleanArray(array) { + for (let index2 = 0; index2 < array.length; index2++) { + const isPropertyExist = objectHasOwnProperty(array, index2); + if (!isPropertyExist) { + array[index2] = null; + } + } + return array; + } + function clone(object) { + const newObject = create(null); + for (const [property, value] of entries(object)) { + const isPropertyExist = objectHasOwnProperty(object, property); + if (isPropertyExist) { + if (Array.isArray(value)) { + newObject[property] = cleanArray(value); + } else if (value && typeof value === "object" && value.constructor === Object) { + newObject[property] = clone(value); + } else { + newObject[property] = value; + } + } + } + return newObject; + } + function lookupGetter(object, prop) { + while (object !== null) { + const desc = getOwnPropertyDescriptor(object, prop); + if (desc) { + if (desc.get) { + return unapply(desc.get); + } + if (typeof desc.value === "function") { + return unapply(desc.value); + } + } + object = getPrototypeOf(object); + } + function fallbackValue() { + return null; + } + return fallbackValue; + } + var html$1 = freeze(["a", "abbr", "acronym", "address", "area", "article", "aside", "audio", "b", "bdi", "bdo", "big", "blink", "blockquote", "body", "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "content", "data", "datalist", "dd", "decorator", "del", "details", "dfn", "dialog", "dir", "div", "dl", "dt", "element", "em", "fieldset", "figcaption", "figure", "font", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "img", "input", "ins", "kbd", "label", "legend", "li", "main", "map", "mark", "marquee", "menu", "menuitem", "meter", "nav", "nobr", "ol", "optgroup", "option", "output", "p", "picture", "pre", "progress", "q", "rp", "rt", "ruby", "s", "samp", "search", "section", "select", "shadow", "slot", "small", "source", "spacer", "span", "strike", "strong", "style", "sub", "summary", "sup", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "tr", "track", "tt", "u", "ul", "var", "video", "wbr"]); + var svg$1 = freeze(["svg", "a", "altglyph", "altglyphdef", "altglyphitem", "animatecolor", "animatemotion", "animatetransform", "circle", "clippath", "defs", "desc", "ellipse", "enterkeyhint", "exportparts", "filter", "font", "g", "glyph", "glyphref", "hkern", "image", "inputmode", "line", "lineargradient", "marker", "mask", "metadata", "mpath", "part", "path", "pattern", "polygon", "polyline", "radialgradient", "rect", "stop", "style", "switch", "symbol", "text", "textpath", "title", "tref", "tspan", "view", "vkern"]); + var svgFilters = freeze(["feBlend", "feColorMatrix", "feComponentTransfer", "feComposite", "feConvolveMatrix", "feDiffuseLighting", "feDisplacementMap", "feDistantLight", "feDropShadow", "feFlood", "feFuncA", "feFuncB", "feFuncG", "feFuncR", "feGaussianBlur", "feImage", "feMerge", "feMergeNode", "feMorphology", "feOffset", "fePointLight", "feSpecularLighting", "feSpotLight", "feTile", "feTurbulence"]); + var svgDisallowed = freeze(["animate", "color-profile", "cursor", "discard", "font-face", "font-face-format", "font-face-name", "font-face-src", "font-face-uri", "foreignobject", "hatch", "hatchpath", "mesh", "meshgradient", "meshpatch", "meshrow", "missing-glyph", "script", "set", "solidcolor", "unknown", "use"]); + var mathMl$1 = freeze(["math", "menclose", "merror", "mfenced", "mfrac", "mglyph", "mi", "mlabeledtr", "mmultiscripts", "mn", "mo", "mover", "mpadded", "mphantom", "mroot", "mrow", "ms", "mspace", "msqrt", "mstyle", "msub", "msup", "msubsup", "mtable", "mtd", "mtext", "mtr", "munder", "munderover", "mprescripts"]); + var mathMlDisallowed = freeze(["maction", "maligngroup", "malignmark", "mlongdiv", "mscarries", "mscarry", "msgroup", "mstack", "msline", "msrow", "semantics", "annotation", "annotation-xml", "mprescripts", "none"]); + var text = freeze(["#text"]); + var html = freeze(["accept", "action", "align", "alt", "autocapitalize", "autocomplete", "autopictureinpicture", "autoplay", "background", "bgcolor", "border", "capture", "cellpadding", "cellspacing", "checked", "cite", "class", "clear", "color", "cols", "colspan", "controls", "controlslist", "coords", "crossorigin", "datetime", "decoding", "default", "dir", "disabled", "disablepictureinpicture", "disableremoteplayback", "download", "draggable", "enctype", "enterkeyhint", "exportparts", "face", "for", "headers", "height", "hidden", "high", "href", "hreflang", "id", "inert", "inputmode", "integrity", "ismap", "kind", "label", "lang", "list", "loading", "loop", "low", "max", "maxlength", "media", "method", "min", "minlength", "multiple", "muted", "name", "nonce", "noshade", "novalidate", "nowrap", "open", "optimum", "part", "pattern", "placeholder", "playsinline", "popover", "popovertarget", "popovertargetaction", "poster", "preload", "pubdate", "radiogroup", "readonly", "rel", "required", "rev", "reversed", "role", "rows", "rowspan", "spellcheck", "scope", "selected", "shape", "size", "sizes", "slot", "span", "srclang", "start", "src", "srcset", "step", "style", "summary", "tabindex", "title", "translate", "type", "usemap", "valign", "value", "width", "wrap", "xmlns", "slot"]); + var svg = freeze(["accent-height", "accumulate", "additive", "alignment-baseline", "amplitude", "ascent", "attributename", "attributetype", "azimuth", "basefrequency", "baseline-shift", "begin", "bias", "by", "class", "clip", "clippathunits", "clip-path", "clip-rule", "color", "color-interpolation", "color-interpolation-filters", "color-profile", "color-rendering", "cx", "cy", "d", "dx", "dy", "diffuseconstant", "direction", "display", "divisor", "dur", "edgemode", "elevation", "end", "exponent", "fill", "fill-opacity", "fill-rule", "filter", "filterunits", "flood-color", "flood-opacity", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "fx", "fy", "g1", "g2", "glyph-name", "glyphref", "gradientunits", "gradienttransform", "height", "href", "id", "image-rendering", "in", "in2", "intercept", "k", "k1", "k2", "k3", "k4", "kerning", "keypoints", "keysplines", "keytimes", "lang", "lengthadjust", "letter-spacing", "kernelmatrix", "kernelunitlength", "lighting-color", "local", "marker-end", "marker-mid", "marker-start", "markerheight", "markerunits", "markerwidth", "maskcontentunits", "maskunits", "max", "mask", "mask-type", "media", "method", "mode", "min", "name", "numoctaves", "offset", "operator", "opacity", "order", "orient", "orientation", "origin", "overflow", "paint-order", "path", "pathlength", "patterncontentunits", "patterntransform", "patternunits", "points", "preservealpha", "preserveaspectratio", "primitiveunits", "r", "rx", "ry", "radius", "refx", "refy", "repeatcount", "repeatdur", "restart", "result", "rotate", "scale", "seed", "shape-rendering", "slope", "specularconstant", "specularexponent", "spreadmethod", "startoffset", "stddeviation", "stitchtiles", "stop-color", "stop-opacity", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke", "stroke-width", "style", "surfacescale", "systemlanguage", "tabindex", "tablevalues", "targetx", "targety", "transform", "transform-origin", "text-anchor", "text-decoration", "text-rendering", "textlength", "type", "u1", "u2", "unicode", "values", "viewbox", "visibility", "version", "vert-adv-y", "vert-origin-x", "vert-origin-y", "width", "word-spacing", "wrap", "writing-mode", "xchannelselector", "ychannelselector", "x", "x1", "x2", "xmlns", "y", "y1", "y2", "z", "zoomandpan"]); + var mathMl = freeze(["accent", "accentunder", "align", "bevelled", "close", "columnsalign", "columnlines", "columnspan", "denomalign", "depth", "dir", "display", "displaystyle", "encoding", "fence", "frame", "height", "href", "id", "largeop", "length", "linethickness", "lspace", "lquote", "mathbackground", "mathcolor", "mathsize", "mathvariant", "maxsize", "minsize", "movablelimits", "notation", "numalign", "open", "rowalign", "rowlines", "rowspacing", "rowspan", "rspace", "rquote", "scriptlevel", "scriptminsize", "scriptsizemultiplier", "selection", "separator", "separators", "stretchy", "subscriptshift", "supscriptshift", "symmetric", "voffset", "width", "xmlns"]); + var xml = freeze(["xlink:href", "xml:id", "xlink:title", "xml:space", "xmlns:xlink"]); + var MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); + var ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm); + var TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm); + var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); + var ARIA_ATTR = seal(/^aria-[\-\w]+$/); + var IS_ALLOWED_URI = seal( + /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i + // eslint-disable-line no-useless-escape + ); + var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i); + var ATTR_WHITESPACE = seal( + /[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g + // eslint-disable-line no-control-regex + ); + var DOCTYPE_NAME = seal(/^html$/i); + var CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i); + var EXPRESSIONS = /* @__PURE__ */ Object.freeze({ + __proto__: null, + ARIA_ATTR, + ATTR_WHITESPACE, + CUSTOM_ELEMENT, + DATA_ATTR, + DOCTYPE_NAME, + ERB_EXPR, + IS_ALLOWED_URI, + IS_SCRIPT_OR_DATA, + MUSTACHE_EXPR, + TMPLIT_EXPR + }); + var NODE_TYPE = { + element: 1, + attribute: 2, + text: 3, + cdataSection: 4, + entityReference: 5, + // Deprecated + entityNode: 6, + // Deprecated + progressingInstruction: 7, + comment: 8, + document: 9, + documentType: 10, + documentFragment: 11, + notation: 12 + // Deprecated + }; + var getGlobal = function getGlobal2() { + return typeof window === "undefined" ? null : window; + }; + var _createTrustedTypesPolicy = function _createTrustedTypesPolicy2(trustedTypes, purifyHostElement) { + if (typeof trustedTypes !== "object" || typeof trustedTypes.createPolicy !== "function") { + return null; + } + let suffix = null; + const ATTR_NAME = "data-tt-policy-suffix"; + if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) { + suffix = purifyHostElement.getAttribute(ATTR_NAME); + } + const policyName = "dompurify" + (suffix ? "#" + suffix : ""); + try { + return trustedTypes.createPolicy(policyName, { + createHTML(html2) { + return html2; + }, + createScriptURL(scriptUrl) { + return scriptUrl; + } + }); + } catch (_2) { + console.warn("TrustedTypes policy " + policyName + " could not be created."); + return null; + } + }; + var _createHooksMap = function _createHooksMap2() { + return { + afterSanitizeAttributes: [], + afterSanitizeElements: [], + afterSanitizeShadowDOM: [], + beforeSanitizeAttributes: [], + beforeSanitizeElements: [], + beforeSanitizeShadowDOM: [], + uponSanitizeAttribute: [], + uponSanitizeElement: [], + uponSanitizeShadowNode: [] + }; + }; + function createDOMPurify() { + let window2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : getGlobal(); + const DOMPurify = (root) => createDOMPurify(root); + DOMPurify.version = "3.3.1"; + DOMPurify.removed = []; + if (!window2 || !window2.document || window2.document.nodeType !== NODE_TYPE.document || !window2.Element) { + DOMPurify.isSupported = false; + return DOMPurify; + } + let { + document: document2 + } = window2; + const originalDocument = document2; + const currentScript = originalDocument.currentScript; + const { + DocumentFragment, + HTMLTemplateElement, + Node, + Element, + NodeFilter, + NamedNodeMap = window2.NamedNodeMap || window2.MozNamedAttrMap, + HTMLFormElement, + DOMParser, + trustedTypes + } = window2; + const ElementPrototype = Element.prototype; + const cloneNode = lookupGetter(ElementPrototype, "cloneNode"); + const remove6 = lookupGetter(ElementPrototype, "remove"); + const getNextSibling = lookupGetter(ElementPrototype, "nextSibling"); + const getChildNodes = lookupGetter(ElementPrototype, "childNodes"); + const getParentNode = lookupGetter(ElementPrototype, "parentNode"); + if (typeof HTMLTemplateElement === "function") { + const template = document2.createElement("template"); + if (template.content && template.content.ownerDocument) { + document2 = template.content.ownerDocument; + } + } + let trustedTypesPolicy; + let emptyHTML = ""; + const { + implementation, + createNodeIterator, + createDocumentFragment, + getElementsByTagName + } = document2; + const { + importNode + } = originalDocument; + let hooks = _createHooksMap(); + DOMPurify.isSupported = typeof entries === "function" && typeof getParentNode === "function" && implementation && implementation.createHTMLDocument !== void 0; + const { + MUSTACHE_EXPR: MUSTACHE_EXPR2, + ERB_EXPR: ERB_EXPR2, + TMPLIT_EXPR: TMPLIT_EXPR2, + DATA_ATTR: DATA_ATTR2, + ARIA_ATTR: ARIA_ATTR2, + IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA2, + ATTR_WHITESPACE: ATTR_WHITESPACE2, + CUSTOM_ELEMENT: CUSTOM_ELEMENT2 + } = EXPRESSIONS; + let { + IS_ALLOWED_URI: IS_ALLOWED_URI$1 + } = EXPRESSIONS; + let ALLOWED_TAGS = null; + const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]); + let ALLOWED_ATTR = null; + const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]); + let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, { + tagNameCheck: { + writable: true, + configurable: false, + enumerable: true, + value: null + }, + attributeNameCheck: { + writable: true, + configurable: false, + enumerable: true, + value: null + }, + allowCustomizedBuiltInElements: { + writable: true, + configurable: false, + enumerable: true, + value: false + } + })); + let FORBID_TAGS = null; + let FORBID_ATTR = null; + const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, { + tagCheck: { + writable: true, + configurable: false, + enumerable: true, + value: null + }, + attributeCheck: { + writable: true, + configurable: false, + enumerable: true, + value: null + } + })); + let ALLOW_ARIA_ATTR = true; + let ALLOW_DATA_ATTR = true; + let ALLOW_UNKNOWN_PROTOCOLS = false; + let ALLOW_SELF_CLOSE_IN_ATTR = true; + let SAFE_FOR_TEMPLATES = false; + let SAFE_FOR_XML = true; + let WHOLE_DOCUMENT = false; + let SET_CONFIG = false; + let FORCE_BODY = false; + let RETURN_DOM = false; + let RETURN_DOM_FRAGMENT = false; + let RETURN_TRUSTED_TYPE = false; + let SANITIZE_DOM = true; + let SANITIZE_NAMED_PROPS = false; + const SANITIZE_NAMED_PROPS_PREFIX = "user-content-"; + let KEEP_CONTENT = true; + let IN_PLACE = false; + let USE_PROFILES = {}; + let FORBID_CONTENTS = null; + const DEFAULT_FORBID_CONTENTS = addToSet({}, ["annotation-xml", "audio", "colgroup", "desc", "foreignobject", "head", "iframe", "math", "mi", "mn", "mo", "ms", "mtext", "noembed", "noframes", "noscript", "plaintext", "script", "style", "svg", "template", "thead", "title", "video", "xmp"]); + let DATA_URI_TAGS = null; + const DEFAULT_DATA_URI_TAGS = addToSet({}, ["audio", "video", "img", "source", "image", "track"]); + let URI_SAFE_ATTRIBUTES = null; + const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ["alt", "class", "for", "id", "label", "name", "pattern", "placeholder", "role", "summary", "title", "value", "style", "xmlns"]); + const MATHML_NAMESPACE = "http://www.w3.org/1998/Math/MathML"; + const SVG_NAMESPACE = "http://www.w3.org/2000/svg"; + const HTML_NAMESPACE = "http://www.w3.org/1999/xhtml"; + let NAMESPACE = HTML_NAMESPACE; + let IS_EMPTY_INPUT = false; + let ALLOWED_NAMESPACES = null; + const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString); + let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ["mi", "mo", "mn", "ms", "mtext"]); + let HTML_INTEGRATION_POINTS = addToSet({}, ["annotation-xml"]); + const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ["title", "style", "font", "a", "script"]); + let PARSER_MEDIA_TYPE = null; + const SUPPORTED_PARSER_MEDIA_TYPES = ["application/xhtml+xml", "text/html"]; + const DEFAULT_PARSER_MEDIA_TYPE = "text/html"; + let transformCaseFunc = null; + let CONFIG = null; + const formElement = document2.createElement("form"); + const isRegexOrFunction = function isRegexOrFunction2(testValue) { + return testValue instanceof RegExp || testValue instanceof Function; + }; + const _parseConfig = function _parseConfig2() { + let cfg = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; + if (CONFIG && CONFIG === cfg) { + return; + } + if (!cfg || typeof cfg !== "object") { + cfg = {}; + } + cfg = clone(cfg); + PARSER_MEDIA_TYPE = // eslint-disable-next-line unicorn/prefer-includes + SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE; + transformCaseFunc = PARSER_MEDIA_TYPE === "application/xhtml+xml" ? stringToString : stringToLowerCase; + ALLOWED_TAGS = objectHasOwnProperty(cfg, "ALLOWED_TAGS") ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS; + ALLOWED_ATTR = objectHasOwnProperty(cfg, "ALLOWED_ATTR") ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR; + ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, "ALLOWED_NAMESPACES") ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES; + URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, "ADD_URI_SAFE_ATTR") ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES; + DATA_URI_TAGS = objectHasOwnProperty(cfg, "ADD_DATA_URI_TAGS") ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS; + FORBID_CONTENTS = objectHasOwnProperty(cfg, "FORBID_CONTENTS") ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS; + FORBID_TAGS = objectHasOwnProperty(cfg, "FORBID_TAGS") ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({}); + FORBID_ATTR = objectHasOwnProperty(cfg, "FORBID_ATTR") ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({}); + USE_PROFILES = objectHasOwnProperty(cfg, "USE_PROFILES") ? cfg.USE_PROFILES : false; + ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; + ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; + ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; + ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; + SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; + SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; + WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; + RETURN_DOM = cfg.RETURN_DOM || false; + RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; + RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; + FORCE_BODY = cfg.FORCE_BODY || false; + SANITIZE_DOM = cfg.SANITIZE_DOM !== false; + SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; + KEEP_CONTENT = cfg.KEEP_CONTENT !== false; + IN_PLACE = cfg.IN_PLACE || false; + IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI; + NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE; + MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS; + HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS; + CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {}; + if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) { + CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck; + } + if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) { + CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck; + } + if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === "boolean") { + CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements; + } + if (SAFE_FOR_TEMPLATES) { + ALLOW_DATA_ATTR = false; + } + if (RETURN_DOM_FRAGMENT) { + RETURN_DOM = true; + } + if (USE_PROFILES) { + ALLOWED_TAGS = addToSet({}, text); + ALLOWED_ATTR = []; + if (USE_PROFILES.html === true) { + addToSet(ALLOWED_TAGS, html$1); + addToSet(ALLOWED_ATTR, html); + } + if (USE_PROFILES.svg === true) { + addToSet(ALLOWED_TAGS, svg$1); + addToSet(ALLOWED_ATTR, svg); + addToSet(ALLOWED_ATTR, xml); + } + if (USE_PROFILES.svgFilters === true) { + addToSet(ALLOWED_TAGS, svgFilters); + addToSet(ALLOWED_ATTR, svg); + addToSet(ALLOWED_ATTR, xml); + } + if (USE_PROFILES.mathMl === true) { + addToSet(ALLOWED_TAGS, mathMl$1); + addToSet(ALLOWED_ATTR, mathMl); + addToSet(ALLOWED_ATTR, xml); + } + } + if (cfg.ADD_TAGS) { + if (typeof cfg.ADD_TAGS === "function") { + EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS; + } else { + if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) { + ALLOWED_TAGS = clone(ALLOWED_TAGS); + } + addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc); + } + } + if (cfg.ADD_ATTR) { + if (typeof cfg.ADD_ATTR === "function") { + EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR; + } else { + if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) { + ALLOWED_ATTR = clone(ALLOWED_ATTR); + } + addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc); + } + } + if (cfg.ADD_URI_SAFE_ATTR) { + addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc); + } + if (cfg.FORBID_CONTENTS) { + if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) { + FORBID_CONTENTS = clone(FORBID_CONTENTS); + } + addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc); + } + if (cfg.ADD_FORBID_CONTENTS) { + if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) { + FORBID_CONTENTS = clone(FORBID_CONTENTS); + } + addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc); + } + if (KEEP_CONTENT) { + ALLOWED_TAGS["#text"] = true; + } + if (WHOLE_DOCUMENT) { + addToSet(ALLOWED_TAGS, ["html", "head", "body"]); + } + if (ALLOWED_TAGS.table) { + addToSet(ALLOWED_TAGS, ["tbody"]); + delete FORBID_TAGS.tbody; + } + if (cfg.TRUSTED_TYPES_POLICY) { + if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== "function") { + throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.'); + } + if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== "function") { + throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.'); + } + trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY; + emptyHTML = trustedTypesPolicy.createHTML(""); + } else { + if (trustedTypesPolicy === void 0) { + trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript); + } + if (trustedTypesPolicy !== null && typeof emptyHTML === "string") { + emptyHTML = trustedTypesPolicy.createHTML(""); + } + } + if (freeze) { + freeze(cfg); + } + CONFIG = cfg; + }; + const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]); + const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]); + const _checkValidNamespace = function _checkValidNamespace2(element) { + let parent = getParentNode(element); + if (!parent || !parent.tagName) { + parent = { + namespaceURI: NAMESPACE, + tagName: "template" + }; + } + const tagName = stringToLowerCase(element.tagName); + const parentTagName = stringToLowerCase(parent.tagName); + if (!ALLOWED_NAMESPACES[element.namespaceURI]) { + return false; + } + if (element.namespaceURI === SVG_NAMESPACE) { + if (parent.namespaceURI === HTML_NAMESPACE) { + return tagName === "svg"; + } + if (parent.namespaceURI === MATHML_NAMESPACE) { + return tagName === "svg" && (parentTagName === "annotation-xml" || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]); + } + return Boolean(ALL_SVG_TAGS[tagName]); + } + if (element.namespaceURI === MATHML_NAMESPACE) { + if (parent.namespaceURI === HTML_NAMESPACE) { + return tagName === "math"; + } + if (parent.namespaceURI === SVG_NAMESPACE) { + return tagName === "math" && HTML_INTEGRATION_POINTS[parentTagName]; + } + return Boolean(ALL_MATHML_TAGS[tagName]); + } + if (element.namespaceURI === HTML_NAMESPACE) { + if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) { + return false; + } + if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) { + return false; + } + return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]); + } + if (PARSER_MEDIA_TYPE === "application/xhtml+xml" && ALLOWED_NAMESPACES[element.namespaceURI]) { + return true; + } + return false; + }; + const _forceRemove = function _forceRemove2(node) { + arrayPush(DOMPurify.removed, { + element: node + }); + try { + getParentNode(node).removeChild(node); + } catch (_2) { + remove6(node); + } + }; + const _removeAttribute = function _removeAttribute2(name, element) { + try { + arrayPush(DOMPurify.removed, { + attribute: element.getAttributeNode(name), + from: element + }); + } catch (_2) { + arrayPush(DOMPurify.removed, { + attribute: null, + from: element + }); + } + element.removeAttribute(name); + if (name === "is") { + if (RETURN_DOM || RETURN_DOM_FRAGMENT) { + try { + _forceRemove(element); + } catch (_2) { + } + } else { + try { + element.setAttribute(name, ""); + } catch (_2) { + } + } + } + }; + const _initDocument = function _initDocument2(dirty) { + let doc = null; + let leadingWhitespace = null; + if (FORCE_BODY) { + dirty = "" + dirty; + } else { + const matches = stringMatch(dirty, /^[\r\n\t ]+/); + leadingWhitespace = matches && matches[0]; + } + if (PARSER_MEDIA_TYPE === "application/xhtml+xml" && NAMESPACE === HTML_NAMESPACE) { + dirty = '' + dirty + ""; + } + const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty; + if (NAMESPACE === HTML_NAMESPACE) { + try { + doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE); + } catch (_2) { + } + } + if (!doc || !doc.documentElement) { + doc = implementation.createDocument(NAMESPACE, "template", null); + try { + doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload; + } catch (_2) { + } + } + const body = doc.body || doc.documentElement; + if (dirty && leadingWhitespace) { + body.insertBefore(document2.createTextNode(leadingWhitespace), body.childNodes[0] || null); + } + if (NAMESPACE === HTML_NAMESPACE) { + return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? "html" : "body")[0]; + } + return WHOLE_DOCUMENT ? doc.documentElement : body; + }; + const _createNodeIterator = function _createNodeIterator2(root) { + return createNodeIterator.call( + root.ownerDocument || root, + root, + // eslint-disable-next-line no-bitwise + NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, + null + ); + }; + const _isClobbered = function _isClobbered2(element) { + return element instanceof HTMLFormElement && (typeof element.nodeName !== "string" || typeof element.textContent !== "string" || typeof element.removeChild !== "function" || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== "function" || typeof element.setAttribute !== "function" || typeof element.namespaceURI !== "string" || typeof element.insertBefore !== "function" || typeof element.hasChildNodes !== "function"); + }; + const _isNode = function _isNode2(value) { + return typeof Node === "function" && value instanceof Node; + }; + function _executeHooks(hooks2, currentNode, data) { + arrayForEach(hooks2, (hook) => { + hook.call(DOMPurify, currentNode, data, CONFIG); + }); + } + const _sanitizeElements = function _sanitizeElements2(currentNode) { + let content = null; + _executeHooks(hooks.beforeSanitizeElements, currentNode, null); + if (_isClobbered(currentNode)) { + _forceRemove(currentNode); + return true; + } + const tagName = transformCaseFunc(currentNode.nodeName); + _executeHooks(hooks.uponSanitizeElement, currentNode, { + tagName, + allowedTags: ALLOWED_TAGS + }); + if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) { + _forceRemove(currentNode); + return true; + } + if (currentNode.nodeType === NODE_TYPE.progressingInstruction) { + _forceRemove(currentNode); + return true; + } + if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) { + _forceRemove(currentNode); + return true; + } + if (!(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName])) { + if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) { + if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) { + return false; + } + if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) { + return false; + } + } + if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) { + const parentNode = getParentNode(currentNode) || currentNode.parentNode; + const childNodes = getChildNodes(currentNode) || currentNode.childNodes; + if (childNodes && parentNode) { + const childCount = childNodes.length; + for (let i2 = childCount - 1; i2 >= 0; --i2) { + const childClone = cloneNode(childNodes[i2], true); + childClone.__removalCount = (currentNode.__removalCount || 0) + 1; + parentNode.insertBefore(childClone, getNextSibling(currentNode)); + } + } + } + _forceRemove(currentNode); + return true; + } + if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) { + _forceRemove(currentNode); + return true; + } + if ((tagName === "noscript" || tagName === "noembed" || tagName === "noframes") && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) { + _forceRemove(currentNode); + return true; + } + if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) { + content = currentNode.textContent; + arrayForEach([MUSTACHE_EXPR2, ERB_EXPR2, TMPLIT_EXPR2], (expr) => { + content = stringReplace(content, expr, " "); + }); + if (currentNode.textContent !== content) { + arrayPush(DOMPurify.removed, { + element: currentNode.cloneNode() + }); + currentNode.textContent = content; + } + } + _executeHooks(hooks.afterSanitizeElements, currentNode, null); + return false; + }; + const _isValidAttribute = function _isValidAttribute2(lcTag, lcName, value) { + if (SANITIZE_DOM && (lcName === "id" || lcName === "name") && (value in document2 || value in formElement)) { + return false; + } + if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR2, lcName)) ; + else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR2, lcName)) ; + else if (EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag)) ; + else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) { + if ( + // First condition does a very basic check if a) it's basically a valid custom element tagname AND + // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck + // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck + _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)) || // Alternative, second condition checks if it's an `is`-attribute, AND + // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck + lcName === "is" && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value)) + ) ; + else { + return false; + } + } else if (URI_SAFE_ATTRIBUTES[lcName]) ; + else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE2, ""))) ; + else if ((lcName === "src" || lcName === "xlink:href" || lcName === "href") && lcTag !== "script" && stringIndexOf(value, "data:") === 0 && DATA_URI_TAGS[lcTag]) ; + else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA2, stringReplace(value, ATTR_WHITESPACE2, ""))) ; + else if (value) { + return false; + } else ; + return true; + }; + const _isBasicCustomElement = function _isBasicCustomElement2(tagName) { + return tagName !== "annotation-xml" && stringMatch(tagName, CUSTOM_ELEMENT2); + }; + const _sanitizeAttributes = function _sanitizeAttributes2(currentNode) { + _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null); + const { + attributes + } = currentNode; + if (!attributes || _isClobbered(currentNode)) { + return; + } + const hookEvent = { + attrName: "", + attrValue: "", + keepAttr: true, + allowedAttributes: ALLOWED_ATTR, + forceKeepAttr: void 0 + }; + let l2 = attributes.length; + while (l2--) { + const attr = attributes[l2]; + const { + name, + namespaceURI, + value: attrValue + } = attr; + const lcName = transformCaseFunc(name); + const initValue = attrValue; + let value = name === "value" ? initValue : stringTrim(initValue); + hookEvent.attrName = lcName; + hookEvent.attrValue = value; + hookEvent.keepAttr = true; + hookEvent.forceKeepAttr = void 0; + _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent); + value = hookEvent.attrValue; + if (SANITIZE_NAMED_PROPS && (lcName === "id" || lcName === "name")) { + _removeAttribute(name, currentNode); + value = SANITIZE_NAMED_PROPS_PREFIX + value; + } + if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|title|textarea)/i, value)) { + _removeAttribute(name, currentNode); + continue; + } + if (lcName === "attributename" && stringMatch(value, "href")) { + _removeAttribute(name, currentNode); + continue; + } + if (hookEvent.forceKeepAttr) { + continue; + } + if (!hookEvent.keepAttr) { + _removeAttribute(name, currentNode); + continue; + } + if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) { + _removeAttribute(name, currentNode); + continue; + } + if (SAFE_FOR_TEMPLATES) { + arrayForEach([MUSTACHE_EXPR2, ERB_EXPR2, TMPLIT_EXPR2], (expr) => { + value = stringReplace(value, expr, " "); + }); + } + const lcTag = transformCaseFunc(currentNode.nodeName); + if (!_isValidAttribute(lcTag, lcName, value)) { + _removeAttribute(name, currentNode); + continue; + } + if (trustedTypesPolicy && typeof trustedTypes === "object" && typeof trustedTypes.getAttributeType === "function") { + if (namespaceURI) ; + else { + switch (trustedTypes.getAttributeType(lcTag, lcName)) { + case "TrustedHTML": { + value = trustedTypesPolicy.createHTML(value); + break; + } + case "TrustedScriptURL": { + value = trustedTypesPolicy.createScriptURL(value); + break; + } + } + } + } + if (value !== initValue) { + try { + if (namespaceURI) { + currentNode.setAttributeNS(namespaceURI, name, value); + } else { + currentNode.setAttribute(name, value); + } + if (_isClobbered(currentNode)) { + _forceRemove(currentNode); + } else { + arrayPop(DOMPurify.removed); + } + } catch (_2) { + _removeAttribute(name, currentNode); + } + } + } + _executeHooks(hooks.afterSanitizeAttributes, currentNode, null); + }; + const _sanitizeShadowDOM = function _sanitizeShadowDOM2(fragment) { + let shadowNode = null; + const shadowIterator = _createNodeIterator(fragment); + _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null); + while (shadowNode = shadowIterator.nextNode()) { + _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null); + _sanitizeElements(shadowNode); + _sanitizeAttributes(shadowNode); + if (shadowNode.content instanceof DocumentFragment) { + _sanitizeShadowDOM2(shadowNode.content); + } + } + _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null); + }; + DOMPurify.sanitize = function(dirty) { + let cfg = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; + let body = null; + let importedNode = null; + let currentNode = null; + let returnNode = null; + IS_EMPTY_INPUT = !dirty; + if (IS_EMPTY_INPUT) { + dirty = ""; + } + if (typeof dirty !== "string" && !_isNode(dirty)) { + if (typeof dirty.toString === "function") { + dirty = dirty.toString(); + if (typeof dirty !== "string") { + throw typeErrorCreate("dirty is not a string, aborting"); + } + } else { + throw typeErrorCreate("toString is not a function"); + } + } + if (!DOMPurify.isSupported) { + return dirty; + } + if (!SET_CONFIG) { + _parseConfig(cfg); + } + DOMPurify.removed = []; + if (typeof dirty === "string") { + IN_PLACE = false; + } + if (IN_PLACE) { + if (dirty.nodeName) { + const tagName = transformCaseFunc(dirty.nodeName); + if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) { + throw typeErrorCreate("root node is forbidden and cannot be sanitized in-place"); + } + } + } else if (dirty instanceof Node) { + body = _initDocument(""); + importedNode = body.ownerDocument.importNode(dirty, true); + if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === "BODY") { + body = importedNode; + } else if (importedNode.nodeName === "HTML") { + body = importedNode; + } else { + body.appendChild(importedNode); + } + } else { + if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && // eslint-disable-next-line unicorn/prefer-includes + dirty.indexOf("<") === -1) { + return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty; + } + body = _initDocument(dirty); + if (!body) { + return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : ""; + } + } + if (body && FORCE_BODY) { + _forceRemove(body.firstChild); + } + const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body); + while (currentNode = nodeIterator.nextNode()) { + _sanitizeElements(currentNode); + _sanitizeAttributes(currentNode); + if (currentNode.content instanceof DocumentFragment) { + _sanitizeShadowDOM(currentNode.content); + } + } + if (IN_PLACE) { + return dirty; + } + if (RETURN_DOM) { + if (RETURN_DOM_FRAGMENT) { + returnNode = createDocumentFragment.call(body.ownerDocument); + while (body.firstChild) { + returnNode.appendChild(body.firstChild); + } + } else { + returnNode = body; + } + if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) { + returnNode = importNode.call(originalDocument, returnNode, true); + } + return returnNode; + } + let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML; + if (WHOLE_DOCUMENT && ALLOWED_TAGS["!doctype"] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) { + serializedHTML = "\n" + serializedHTML; + } + if (SAFE_FOR_TEMPLATES) { + arrayForEach([MUSTACHE_EXPR2, ERB_EXPR2, TMPLIT_EXPR2], (expr) => { + serializedHTML = stringReplace(serializedHTML, expr, " "); + }); + } + return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML; + }; + DOMPurify.setConfig = function() { + let cfg = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; + _parseConfig(cfg); + SET_CONFIG = true; + }; + DOMPurify.clearConfig = function() { + CONFIG = null; + SET_CONFIG = false; + }; + DOMPurify.isValidAttribute = function(tag, attr, value) { + if (!CONFIG) { + _parseConfig({}); + } + const lcTag = transformCaseFunc(tag); + const lcName = transformCaseFunc(attr); + return _isValidAttribute(lcTag, lcName, value); + }; + DOMPurify.addHook = function(entryPoint, hookFunction) { + if (typeof hookFunction !== "function") { + return; + } + arrayPush(hooks[entryPoint], hookFunction); + }; + DOMPurify.removeHook = function(entryPoint, hookFunction) { + if (hookFunction !== void 0) { + const index2 = arrayLastIndexOf(hooks[entryPoint], hookFunction); + return index2 === -1 ? void 0 : arraySplice(hooks[entryPoint], index2, 1)[0]; + } + return arrayPop(hooks[entryPoint]); + }; + DOMPurify.removeHooks = function(entryPoint) { + hooks[entryPoint] = []; + }; + DOMPurify.removeAllHooks = function() { + hooks = _createHooksMap(); + }; + return DOMPurify; + } + var purify = createDOMPurify(); + + // node_modules/@langchain/core/dist/load/map_keys.js + var import_decamelize = __toESM(require_decamelize(), 1); + var import_camelcase = __toESM(require_camelcase(), 1); + function keyToJson(key, map2) { + return map2?.[key] || (0, import_decamelize.default)(key); + } + function mapKeys(fields, mapper, map2) { + const mapped = {}; + for (const key in fields) { + if (Object.hasOwn(fields, key)) { + mapped[mapper(key, map2)] = fields[key]; + } + } + return mapped; + } + + // node_modules/@langchain/core/dist/load/serializable.js + function shallowCopy(obj) { + return Array.isArray(obj) ? [...obj] : { ...obj }; + } + function replaceSecrets(root, secretsMap) { + const result = shallowCopy(root); + for (const [path, secretId] of Object.entries(secretsMap)) { + const [last2, ...partsReverse] = path.split(".").reverse(); + let current = result; + for (const part of partsReverse.reverse()) { + if (current[part] === void 0) { + break; + } + current[part] = shallowCopy(current[part]); + current = current[part]; + } + if (current[last2] !== void 0) { + current[last2] = { + lc: 1, + type: "secret", + id: [secretId] + }; + } + } + return result; + } + function get_lc_unique_name(serializableClass) { + const parentClass = Object.getPrototypeOf(serializableClass); + const lcNameIsSubclassed = typeof serializableClass.lc_name === "function" && (typeof parentClass.lc_name !== "function" || serializableClass.lc_name() !== parentClass.lc_name()); + if (lcNameIsSubclassed) { + return serializableClass.lc_name(); + } else { + return serializableClass.name; + } + } + var Serializable = class _Serializable { + /** + * The name of the serializable. Override to provide an alias or + * to preserve the serialized module name in minified environments. + * + * Implemented as a static method to support loading logic. + */ + static lc_name() { + return this.name; + } + /** + * The final serialized identifier for the module. + */ + get lc_id() { + return [ + ...this.lc_namespace, + get_lc_unique_name(this.constructor) + ]; + } + /** + * A map of secrets, which will be omitted from serialization. + * Keys are paths to the secret in constructor args, e.g. "foo.bar.baz". + * Values are the secret ids, which will be used when deserializing. + */ + get lc_secrets() { + return void 0; + } + /** + * A map of additional attributes to merge with constructor args. + * Keys are the attribute names, e.g. "foo". + * Values are the attribute values, which will be serialized. + * These attributes need to be accepted by the constructor as arguments. + */ + get lc_attributes() { + return void 0; + } + /** + * A map of aliases for constructor args. + * Keys are the attribute names, e.g. "foo". + * Values are the alias that will replace the key in serialization. + * This is used to eg. make argument names match Python. + */ + get lc_aliases() { + return void 0; + } + /** + * A manual list of keys that should be serialized. + * If not overridden, all fields passed into the constructor will be serialized. + */ + get lc_serializable_keys() { + return void 0; + } + constructor(kwargs, ..._args) { + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "lc_kwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + if (this.lc_serializable_keys !== void 0) { + this.lc_kwargs = Object.fromEntries(Object.entries(kwargs || {}).filter(([key]) => this.lc_serializable_keys?.includes(key))); + } else { + this.lc_kwargs = kwargs ?? {}; + } + } + toJSON() { + if (!this.lc_serializable) { + return this.toJSONNotImplemented(); + } + if ( + // eslint-disable-next-line no-instanceof/no-instanceof + this.lc_kwargs instanceof _Serializable || typeof this.lc_kwargs !== "object" || Array.isArray(this.lc_kwargs) + ) { + return this.toJSONNotImplemented(); + } + const aliases = {}; + const secrets = {}; + const kwargs = Object.keys(this.lc_kwargs).reduce((acc, key) => { + acc[key] = key in this ? this[key] : this.lc_kwargs[key]; + return acc; + }, {}); + for (let current = Object.getPrototypeOf(this); current; current = Object.getPrototypeOf(current)) { + Object.assign(aliases, Reflect.get(current, "lc_aliases", this)); + Object.assign(secrets, Reflect.get(current, "lc_secrets", this)); + Object.assign(kwargs, Reflect.get(current, "lc_attributes", this)); + } + Object.keys(secrets).forEach((keyPath) => { + let read = this; + let write2 = kwargs; + const [last2, ...partsReverse] = keyPath.split(".").reverse(); + for (const key of partsReverse.reverse()) { + if (!(key in read) || read[key] === void 0) + return; + if (!(key in write2) || write2[key] === void 0) { + if (typeof read[key] === "object" && read[key] != null) { + write2[key] = {}; + } else if (Array.isArray(read[key])) { + write2[key] = []; + } + } + read = read[key]; + write2 = write2[key]; + } + if (last2 in read && read[last2] !== void 0) { + write2[last2] = write2[last2] || read[last2]; + } + }); + return { + lc: 1, + type: "constructor", + id: this.lc_id, + kwargs: mapKeys(Object.keys(secrets).length ? replaceSecrets(kwargs, secrets) : kwargs, keyToJson, aliases) + }; + } + toJSONNotImplemented() { + return { + lc: 1, + type: "not_implemented", + id: this.lc_id + }; + } + }; + + // node_modules/@langchain/core/dist/messages/base.js + function stringifyWithDepthLimit(obj, depthLimit) { + function helper(obj2, currentDepth) { + if (typeof obj2 !== "object" || obj2 === null || obj2 === void 0) { + return obj2; + } + if (currentDepth >= depthLimit) { + if (Array.isArray(obj2)) { + return "[Array]"; + } + return "[Object]"; + } + if (Array.isArray(obj2)) { + return obj2.map((item) => helper(item, currentDepth + 1)); + } + const result = {}; + for (const key of Object.keys(obj2)) { + result[key] = helper(obj2[key], currentDepth + 1); + } + return result; + } + return JSON.stringify(helper(obj, 0), null, 2); + } + var BaseMessage = class extends Serializable { + get lc_aliases() { + return { + additional_kwargs: "additional_kwargs", + response_metadata: "response_metadata" + }; + } + /** + * Get text content of the message. + */ + get text() { + if (typeof this.content === "string") { + return this.content; + } + if (!Array.isArray(this.content)) + return ""; + return this.content.map((c3) => { + if (typeof c3 === "string") + return c3; + if (c3.type === "text") + return c3.text; + return ""; + }).join(""); + } + /** The type of the message. */ + getType() { + return this._getType(); + } + constructor(fields, kwargs) { + if (typeof fields === "string") { + fields = { + content: fields, + additional_kwargs: kwargs, + response_metadata: {} + }; + } + if (!fields.additional_kwargs) { + fields.additional_kwargs = {}; + } + if (!fields.response_metadata) { + fields.response_metadata = {}; + } + super(fields); + Object.defineProperty(this, "lc_namespace", { + enumerable: true, + configurable: true, + writable: true, + value: ["langchain_core", "messages"] + }); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "content", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "additional_kwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "response_metadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.name = fields.name; + this.content = fields.content; + this.additional_kwargs = fields.additional_kwargs; + this.response_metadata = fields.response_metadata; + this.id = fields.id; + } + toDict() { + return { + type: this._getType(), + data: this.toJSON().kwargs + }; + } + static lc_name() { + return "BaseMessage"; + } + // Can't be protected for silly reasons + get _printableFields() { + return { + id: this.id, + content: this.content, + name: this.name, + additional_kwargs: this.additional_kwargs, + response_metadata: this.response_metadata + }; + } + // this private method is used to update the ID for the runtime + // value as well as in lc_kwargs for serialisation + _updateId(value) { + this.id = value; + this.lc_kwargs.id = value; + } + get [Symbol.toStringTag]() { + return this.constructor.lc_name(); + } + // Override the default behavior of console.log + [Symbol.for("nodejs.util.inspect.custom")](depth) { + if (depth === null) { + return this; + } + const printable = stringifyWithDepthLimit(this._printableFields, Math.max(4, depth)); + return `${this.constructor.lc_name()} ${printable}`; + } + }; + + // node_modules/@langchain/core/dist/messages/tool.js + function defaultToolCallParser(rawToolCalls) { + const toolCalls = []; + const invalidToolCalls = []; + for (const toolCall of rawToolCalls) { + if (!toolCall.function) { + continue; + } else { + const functionName = toolCall.function.name; + try { + const functionArgs = JSON.parse(toolCall.function.arguments); + const parsed = { + name: functionName || "", + args: functionArgs || {}, + id: toolCall.id + }; + toolCalls.push(parsed); + } catch (error) { + invalidToolCalls.push({ + name: functionName, + args: toolCall.function.arguments, + id: toolCall.id, + error: "Malformed args." + }); + } + } + } + return [toolCalls, invalidToolCalls]; + } + + // node_modules/@langchain/core/dist/messages/ai.js + var AIMessage = class extends BaseMessage { + get lc_aliases() { + return { + ...super.lc_aliases, + tool_calls: "tool_calls", + invalid_tool_calls: "invalid_tool_calls" + }; + } + constructor(fields, kwargs) { + let initParams; + if (typeof fields === "string") { + initParams = { + content: fields, + tool_calls: [], + invalid_tool_calls: [], + additional_kwargs: kwargs ?? {} + }; + } else { + initParams = fields; + const rawToolCalls = initParams.additional_kwargs?.tool_calls; + const toolCalls = initParams.tool_calls; + if (!(rawToolCalls == null) && rawToolCalls.length > 0 && (toolCalls === void 0 || toolCalls.length === 0)) { + console.warn([ + "New LangChain packages are available that more efficiently handle", + "tool calling.\n\nPlease upgrade your packages to versions that set", + "message tool calls. e.g., `yarn add @langchain/anthropic`,", + "yarn add @langchain/openai`, etc." + ].join(" ")); + } + try { + if (!(rawToolCalls == null) && toolCalls === void 0) { + const [toolCalls2, invalidToolCalls] = defaultToolCallParser(rawToolCalls); + initParams.tool_calls = toolCalls2 ?? []; + initParams.invalid_tool_calls = invalidToolCalls ?? []; + } else { + initParams.tool_calls = initParams.tool_calls ?? []; + initParams.invalid_tool_calls = initParams.invalid_tool_calls ?? []; + } + } catch (e2) { + initParams.tool_calls = []; + initParams.invalid_tool_calls = []; + } + } + super(initParams); + Object.defineProperty(this, "tool_calls", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "invalid_tool_calls", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "usage_metadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + if (typeof initParams !== "string") { + this.tool_calls = initParams.tool_calls ?? this.tool_calls; + this.invalid_tool_calls = initParams.invalid_tool_calls ?? this.invalid_tool_calls; + } + this.usage_metadata = initParams.usage_metadata; + } + static lc_name() { + return "AIMessage"; + } + _getType() { + return "ai"; + } + get _printableFields() { + return { + ...super._printableFields, + tool_calls: this.tool_calls, + invalid_tool_calls: this.invalid_tool_calls, + usage_metadata: this.usage_metadata + }; + } + }; + + // node_modules/@langchain/core/dist/messages/human.js + var HumanMessage = class extends BaseMessage { + static lc_name() { + return "HumanMessage"; + } + _getType() { + return "human"; + } + constructor(fields, kwargs) { + super(fields, kwargs); + } + }; + + // node_modules/@langchain/core/dist/messages/system.js + var SystemMessage = class extends BaseMessage { + static lc_name() { + return "SystemMessage"; + } + _getType() { + return "system"; + } + constructor(fields, kwargs) { + super(fields, kwargs); + } + }; + + // node_modules/@langchain/core/dist/messages/utils.js + function getBufferString(messages, humanPrefix = "Human", aiPrefix = "AI") { + const string_messages = []; + for (const m3 of messages) { + let role; + if (m3._getType() === "human") { + role = humanPrefix; + } else if (m3._getType() === "ai") { + role = aiPrefix; + } else if (m3._getType() === "system") { + role = "System"; + } else if (m3._getType() === "function") { + role = "Function"; + } else if (m3._getType() === "tool") { + role = "Tool"; + } else if (m3._getType() === "generic") { + role = m3.role; + } else { + throw new Error(`Got unsupported message type: ${m3._getType()}`); + } + const nameStr = m3.name ? `${m3.name}, ` : ""; + const readableContent = typeof m3.content === "string" ? m3.content : JSON.stringify(m3.content, null, 2); + string_messages.push(`${role}: ${nameStr}${readableContent}`); + } + return string_messages.join("\n"); + } + + // node_modules/@langchain/core/dist/runnables/base.js + var import_p_retry3 = __toESM(require_p_retry(), 1); + + // node_modules/uuid/dist/esm-browser/regex.js + var regex_default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i; + + // node_modules/uuid/dist/esm-browser/validate.js + function validate(uuid) { + return typeof uuid === "string" && regex_default.test(uuid); + } + var validate_default = validate; + + // node_modules/uuid/dist/esm-browser/parse.js + function parse(uuid) { + if (!validate_default(uuid)) { + throw TypeError("Invalid UUID"); + } + var v6; + var arr2 = new Uint8Array(16); + arr2[0] = (v6 = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr2[1] = v6 >>> 16 & 255; + arr2[2] = v6 >>> 8 & 255; + arr2[3] = v6 & 255; + arr2[4] = (v6 = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr2[5] = v6 & 255; + arr2[6] = (v6 = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr2[7] = v6 & 255; + arr2[8] = (v6 = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr2[9] = v6 & 255; + arr2[10] = (v6 = parseInt(uuid.slice(24, 36), 16)) / 1099511627776 & 255; + arr2[11] = v6 / 4294967296 & 255; + arr2[12] = v6 >>> 24 & 255; + arr2[13] = v6 >>> 16 & 255; + arr2[14] = v6 >>> 8 & 255; + arr2[15] = v6 & 255; + return arr2; + } + var parse_default = parse; + + // node_modules/uuid/dist/esm-browser/stringify.js + var byteToHex = []; + for (i2 = 0; i2 < 256; ++i2) { + byteToHex.push((i2 + 256).toString(16).slice(1)); + } + var i2; + function unsafeStringify(arr2, offset = 0) { + return (byteToHex[arr2[offset + 0]] + byteToHex[arr2[offset + 1]] + byteToHex[arr2[offset + 2]] + byteToHex[arr2[offset + 3]] + "-" + byteToHex[arr2[offset + 4]] + byteToHex[arr2[offset + 5]] + "-" + byteToHex[arr2[offset + 6]] + byteToHex[arr2[offset + 7]] + "-" + byteToHex[arr2[offset + 8]] + byteToHex[arr2[offset + 9]] + "-" + byteToHex[arr2[offset + 10]] + byteToHex[arr2[offset + 11]] + byteToHex[arr2[offset + 12]] + byteToHex[arr2[offset + 13]] + byteToHex[arr2[offset + 14]] + byteToHex[arr2[offset + 15]]).toLowerCase(); + } + + // node_modules/uuid/dist/esm-browser/rng.js + var getRandomValues; + var rnds8 = new Uint8Array(16); + function rng() { + if (!getRandomValues) { + getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto); + if (!getRandomValues) { + throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported"); + } + } + return getRandomValues(rnds8); + } + + // node_modules/uuid/dist/esm-browser/v35.js + function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); + var bytes = []; + for (var i2 = 0; i2 < str.length; ++i2) { + bytes.push(str.charCodeAt(i2)); + } + return bytes; + } + var DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; + var URL2 = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; + function v35(name, version, hashfunc) { + function generateUUID(value, namespace, buf, offset) { + var _namespace; + if (typeof value === "string") { + value = stringToBytes(value); + } + if (typeof namespace === "string") { + namespace = parse_default(namespace); + } + if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { + throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)"); + } + var bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 15 | version; + bytes[8] = bytes[8] & 63 | 128; + if (buf) { + offset = offset || 0; + for (var i2 = 0; i2 < 16; ++i2) { + buf[offset + i2] = bytes[i2]; + } + return buf; + } + return unsafeStringify(bytes); + } + try { + generateUUID.name = name; + } catch (err) { + } + generateUUID.DNS = DNS; + generateUUID.URL = URL2; + return generateUUID; + } + + // node_modules/uuid/dist/esm-browser/native.js + var randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto); + var native_default = { + randomUUID + }; + + // node_modules/uuid/dist/esm-browser/v4.js + function v4(options, buf, offset) { + if (native_default.randomUUID && !buf && !options) { + return native_default.randomUUID(); + } + options = options || {}; + var rnds = options.random || (options.rng || rng)(); + rnds[6] = rnds[6] & 15 | 64; + rnds[8] = rnds[8] & 63 | 128; + if (buf) { + offset = offset || 0; + for (var i2 = 0; i2 < 16; ++i2) { + buf[offset + i2] = rnds[i2]; + } + return buf; + } + return unsafeStringify(rnds); + } + var v4_default = v4; + + // node_modules/uuid/dist/esm-browser/sha1.js + function f(s2, x3, y3, z3) { + switch (s2) { + case 0: + return x3 & y3 ^ ~x3 & z3; + case 1: + return x3 ^ y3 ^ z3; + case 2: + return x3 & y3 ^ x3 & z3 ^ y3 & z3; + case 3: + return x3 ^ y3 ^ z3; + } + } + function ROTL(x3, n2) { + return x3 << n2 | x3 >>> 32 - n2; + } + function sha1(bytes) { + var K3 = [1518500249, 1859775393, 2400959708, 3395469782]; + var H = [1732584193, 4023233417, 2562383102, 271733878, 3285377520]; + if (typeof bytes === "string") { + var msg = unescape(encodeURIComponent(bytes)); + bytes = []; + for (var i2 = 0; i2 < msg.length; ++i2) { + bytes.push(msg.charCodeAt(i2)); + } + } else if (!Array.isArray(bytes)) { + bytes = Array.prototype.slice.call(bytes); + } + bytes.push(128); + var l2 = bytes.length / 4 + 2; + var N2 = Math.ceil(l2 / 16); + var M2 = new Array(N2); + for (var _i = 0; _i < N2; ++_i) { + var arr2 = new Uint32Array(16); + for (var j3 = 0; j3 < 16; ++j3) { + arr2[j3] = bytes[_i * 64 + j3 * 4] << 24 | bytes[_i * 64 + j3 * 4 + 1] << 16 | bytes[_i * 64 + j3 * 4 + 2] << 8 | bytes[_i * 64 + j3 * 4 + 3]; + } + M2[_i] = arr2; + } + M2[N2 - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M2[N2 - 1][14] = Math.floor(M2[N2 - 1][14]); + M2[N2 - 1][15] = (bytes.length - 1) * 8 & 4294967295; + for (var _i2 = 0; _i2 < N2; ++_i2) { + var W2 = new Uint32Array(80); + for (var t2 = 0; t2 < 16; ++t2) { + W2[t2] = M2[_i2][t2]; + } + for (var _t = 16; _t < 80; ++_t) { + W2[_t] = ROTL(W2[_t - 3] ^ W2[_t - 8] ^ W2[_t - 14] ^ W2[_t - 16], 1); + } + var a2 = H[0]; + var b3 = H[1]; + var c3 = H[2]; + var d3 = H[3]; + var e2 = H[4]; + for (var _t2 = 0; _t2 < 80; ++_t2) { + var s2 = Math.floor(_t2 / 20); + var T2 = ROTL(a2, 5) + f(s2, b3, c3, d3) + e2 + K3[s2] + W2[_t2] >>> 0; + e2 = d3; + d3 = c3; + c3 = ROTL(b3, 30) >>> 0; + b3 = a2; + a2 = T2; + } + H[0] = H[0] + a2 >>> 0; + H[1] = H[1] + b3 >>> 0; + H[2] = H[2] + c3 >>> 0; + H[3] = H[3] + d3 >>> 0; + H[4] = H[4] + e2 >>> 0; + } + return [H[0] >> 24 & 255, H[0] >> 16 & 255, H[0] >> 8 & 255, H[0] & 255, H[1] >> 24 & 255, H[1] >> 16 & 255, H[1] >> 8 & 255, H[1] & 255, H[2] >> 24 & 255, H[2] >> 16 & 255, H[2] >> 8 & 255, H[2] & 255, H[3] >> 24 & 255, H[3] >> 16 & 255, H[3] >> 8 & 255, H[3] & 255, H[4] >> 24 & 255, H[4] >> 16 & 255, H[4] >> 8 & 255, H[4] & 255]; + } + var sha1_default = sha1; + + // node_modules/uuid/dist/esm-browser/v5.js + var v5 = v35("v5", 80, sha1_default); + var v5_default = v5; + + // node_modules/langsmith/dist/singletons/traceable.js + var MockAsyncLocalStorage = class { + getStore() { + return void 0; + } + run(_2, callback) { + return callback(); + } + }; + var TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage"); + var mockAsyncLocalStorage = new MockAsyncLocalStorage(); + var AsyncLocalStorageProvider = class { + getInstance() { + return globalThis[TRACING_ALS_KEY] ?? mockAsyncLocalStorage; + } + initializeGlobalInstance(instance) { + if (globalThis[TRACING_ALS_KEY] === void 0) { + globalThis[TRACING_ALS_KEY] = instance; + } + } + }; + var AsyncLocalStorageProviderSingleton = new AsyncLocalStorageProvider(); + function getCurrentRunTree(permitAbsentRunTree = false) { + const runTree = AsyncLocalStorageProviderSingleton.getInstance().getStore(); + if (!permitAbsentRunTree && runTree === void 0) { + throw new Error("Could not get the current run tree.\n\nPlease make sure you are calling this method within a traceable function and that tracing is enabled."); + } + return runTree; + } + var ROOT = Symbol.for("langsmith:traceable:root"); + + // node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js + var core_exports = {}; + __export(core_exports, { + JsonPatchError: () => JsonPatchError, + _areEquals: () => _areEquals, + applyOperation: () => applyOperation, + applyPatch: () => applyPatch, + applyReducer: () => applyReducer, + deepClone: () => deepClone, + getValueByPointer: () => getValueByPointer, + validate: () => validate2, + validator: () => validator + }); + + // node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js + var _hasOwnProperty = Object.prototype.hasOwnProperty; + function hasOwnProperty(obj, key) { + return _hasOwnProperty.call(obj, key); + } + function _objectKeys(obj) { + if (Array.isArray(obj)) { + const keys2 = new Array(obj.length); + for (let k3 = 0; k3 < keys2.length; k3++) { + keys2[k3] = "" + k3; + } + return keys2; + } + if (Object.keys) { + return Object.keys(obj); + } + let keys = []; + for (let i2 in obj) { + if (hasOwnProperty(obj, i2)) { + keys.push(i2); + } + } + return keys; + } + function _deepClone(obj) { + switch (typeof obj) { + case "object": + return JSON.parse(JSON.stringify(obj)); + //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5 + case "undefined": + return null; + //this is how JSON.stringify behaves for array items + default: + return obj; + } + } + function isInteger(str) { + let i2 = 0; + const len = str.length; + let charCode; + while (i2 < len) { + charCode = str.charCodeAt(i2); + if (charCode >= 48 && charCode <= 57) { + i2++; + continue; + } + return false; + } + return true; + } + function escapePathComponent(path) { + if (path.indexOf("/") === -1 && path.indexOf("~") === -1) + return path; + return path.replace(/~/g, "~0").replace(/\//g, "~1"); + } + function unescapePathComponent(path) { + return path.replace(/~1/g, "/").replace(/~0/g, "~"); + } + function hasUndefined(obj) { + if (obj === void 0) { + return true; + } + if (obj) { + if (Array.isArray(obj)) { + for (let i3 = 0, len = obj.length; i3 < len; i3++) { + if (hasUndefined(obj[i3])) { + return true; + } + } + } else if (typeof obj === "object") { + const objKeys = _objectKeys(obj); + const objKeysLength = objKeys.length; + for (var i2 = 0; i2 < objKeysLength; i2++) { + if (hasUndefined(obj[objKeys[i2]])) { + return true; + } + } + } + } + return false; + } + function patchErrorMessageFormatter(message, args) { + const messageParts = [message]; + for (const key in args) { + const value = typeof args[key] === "object" ? JSON.stringify(args[key], null, 2) : args[key]; + if (typeof value !== "undefined") { + messageParts.push(`${key}: ${value}`); + } + } + return messageParts.join("\n"); + } + var PatchError = class extends Error { + constructor(message, name, index2, operation, tree) { + super(patchErrorMessageFormatter(message, { name, index: index2, operation, tree })); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: name + }); + Object.defineProperty(this, "index", { + enumerable: true, + configurable: true, + writable: true, + value: index2 + }); + Object.defineProperty(this, "operation", { + enumerable: true, + configurable: true, + writable: true, + value: operation + }); + Object.defineProperty(this, "tree", { + enumerable: true, + configurable: true, + writable: true, + value: tree + }); + Object.setPrototypeOf(this, new.target.prototype); + this.message = patchErrorMessageFormatter(message, { + name, + index: index2, + operation, + tree + }); + } + }; + + // node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js + var JsonPatchError = PatchError; + var deepClone = _deepClone; + var objOps = { + add: function(obj, key, document2) { + obj[key] = this.value; + return { newDocument: document2 }; + }, + remove: function(obj, key, document2) { + var removed = obj[key]; + delete obj[key]; + return { newDocument: document2, removed }; + }, + replace: function(obj, key, document2) { + var removed = obj[key]; + obj[key] = this.value; + return { newDocument: document2, removed }; + }, + move: function(obj, key, document2) { + let removed = getValueByPointer(document2, this.path); + if (removed) { + removed = _deepClone(removed); + } + const originalValue = applyOperation(document2, { + op: "remove", + path: this.from + }).removed; + applyOperation(document2, { + op: "add", + path: this.path, + value: originalValue + }); + return { newDocument: document2, removed }; + }, + copy: function(obj, key, document2) { + const valueToCopy = getValueByPointer(document2, this.from); + applyOperation(document2, { + op: "add", + path: this.path, + value: _deepClone(valueToCopy) + }); + return { newDocument: document2 }; + }, + test: function(obj, key, document2) { + return { newDocument: document2, test: _areEquals(obj[key], this.value) }; + }, + _get: function(obj, key, document2) { + this.value = obj[key]; + return { newDocument: document2 }; + } + }; + var arrOps = { + add: function(arr2, i2, document2) { + if (isInteger(i2)) { + arr2.splice(i2, 0, this.value); + } else { + arr2[i2] = this.value; + } + return { newDocument: document2, index: i2 }; + }, + remove: function(arr2, i2, document2) { + var removedList = arr2.splice(i2, 1); + return { newDocument: document2, removed: removedList[0] }; + }, + replace: function(arr2, i2, document2) { + var removed = arr2[i2]; + arr2[i2] = this.value; + return { newDocument: document2, removed }; + }, + move: objOps.move, + copy: objOps.copy, + test: objOps.test, + _get: objOps._get + }; + function getValueByPointer(document2, pointer) { + if (pointer == "") { + return document2; + } + var getOriginalDestination = { op: "_get", path: pointer }; + applyOperation(document2, getOriginalDestination); + return getOriginalDestination.value; + } + function applyOperation(document2, operation, validateOperation = false, mutateDocument = true, banPrototypeModifications = true, index2 = 0) { + if (validateOperation) { + if (typeof validateOperation == "function") { + validateOperation(operation, 0, document2, operation.path); + } else { + validator(operation, 0); + } + } + if (operation.path === "") { + let returnValue = { newDocument: document2 }; + if (operation.op === "add") { + returnValue.newDocument = operation.value; + return returnValue; + } else if (operation.op === "replace") { + returnValue.newDocument = operation.value; + returnValue.removed = document2; + return returnValue; + } else if (operation.op === "move" || operation.op === "copy") { + returnValue.newDocument = getValueByPointer(document2, operation.from); + if (operation.op === "move") { + returnValue.removed = document2; + } + return returnValue; + } else if (operation.op === "test") { + returnValue.test = _areEquals(document2, operation.value); + if (returnValue.test === false) { + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index2, operation, document2); + } + returnValue.newDocument = document2; + return returnValue; + } else if (operation.op === "remove") { + returnValue.removed = document2; + returnValue.newDocument = null; + return returnValue; + } else if (operation.op === "_get") { + operation.value = document2; + return returnValue; + } else { + if (validateOperation) { + throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index2, operation, document2); + } else { + return returnValue; + } + } + } else { + if (!mutateDocument) { + document2 = _deepClone(document2); + } + const path = operation.path || ""; + const keys = path.split("/"); + let obj = document2; + let t2 = 1; + let len = keys.length; + let existingPathFragment = void 0; + let key; + let validateFunction; + if (typeof validateOperation == "function") { + validateFunction = validateOperation; + } else { + validateFunction = validator; + } + while (true) { + key = keys[t2]; + if (key && key.indexOf("~") != -1) { + key = unescapePathComponent(key); + } + if (banPrototypeModifications && (key == "__proto__" || key == "prototype" && t2 > 0 && keys[t2 - 1] == "constructor")) { + throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README"); + } + if (validateOperation) { + if (existingPathFragment === void 0) { + if (obj[key] === void 0) { + existingPathFragment = keys.slice(0, t2).join("/"); + } else if (t2 == len - 1) { + existingPathFragment = operation.path; + } + if (existingPathFragment !== void 0) { + validateFunction(operation, 0, document2, existingPathFragment); + } + } + } + t2++; + if (Array.isArray(obj)) { + if (key === "-") { + key = obj.length; + } else { + if (validateOperation && !isInteger(key)) { + throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index2, operation, document2); + } else if (isInteger(key)) { + key = ~~key; + } + } + if (t2 >= len) { + if (validateOperation && operation.op === "add" && key > obj.length) { + throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index2, operation, document2); + } + const returnValue = arrOps[operation.op].call(operation, obj, key, document2); + if (returnValue.test === false) { + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index2, operation, document2); + } + return returnValue; + } + } else { + if (t2 >= len) { + const returnValue = objOps[operation.op].call(operation, obj, key, document2); + if (returnValue.test === false) { + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index2, operation, document2); + } + return returnValue; + } + } + obj = obj[key]; + if (validateOperation && t2 < len && (!obj || typeof obj !== "object")) { + throw new JsonPatchError("Cannot perform operation at the desired path", "OPERATION_PATH_UNRESOLVABLE", index2, operation, document2); + } + } + } + } + function applyPatch(document2, patch, validateOperation, mutateDocument = true, banPrototypeModifications = true) { + if (validateOperation) { + if (!Array.isArray(patch)) { + throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); + } + } + if (!mutateDocument) { + document2 = _deepClone(document2); + } + const results = new Array(patch.length); + for (let i2 = 0, length = patch.length; i2 < length; i2++) { + results[i2] = applyOperation(document2, patch[i2], validateOperation, true, banPrototypeModifications, i2); + document2 = results[i2].newDocument; + } + results.newDocument = document2; + return results; + } + function applyReducer(document2, operation, index2) { + const operationResult = applyOperation(document2, operation); + if (operationResult.test === false) { + throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index2, operation, document2); + } + return operationResult.newDocument; + } + function validator(operation, index2, document2, existingPathFragment) { + if (typeof operation !== "object" || operation === null || Array.isArray(operation)) { + throw new JsonPatchError("Operation is not an object", "OPERATION_NOT_AN_OBJECT", index2, operation, document2); + } else if (!objOps[operation.op]) { + throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index2, operation, document2); + } else if (typeof operation.path !== "string") { + throw new JsonPatchError("Operation `path` property is not a string", "OPERATION_PATH_INVALID", index2, operation, document2); + } else if (operation.path.indexOf("/") !== 0 && operation.path.length > 0) { + throw new JsonPatchError('Operation `path` property must start with "/"', "OPERATION_PATH_INVALID", index2, operation, document2); + } else if ((operation.op === "move" || operation.op === "copy") && typeof operation.from !== "string") { + throw new JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)", "OPERATION_FROM_REQUIRED", index2, operation, document2); + } else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && operation.value === void 0) { + throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_REQUIRED", index2, operation, document2); + } else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && hasUndefined(operation.value)) { + throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED", index2, operation, document2); + } else if (document2) { + if (operation.op == "add") { + var pathLen = operation.path.split("/").length; + var existingPathLen = existingPathFragment.split("/").length; + if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) { + throw new JsonPatchError("Cannot perform an `add` operation at the desired path", "OPERATION_PATH_CANNOT_ADD", index2, operation, document2); + } + } else if (operation.op === "replace" || operation.op === "remove" || operation.op === "_get") { + if (operation.path !== existingPathFragment) { + throw new JsonPatchError("Cannot perform the operation at a path that does not exist", "OPERATION_PATH_UNRESOLVABLE", index2, operation, document2); + } + } else if (operation.op === "move" || operation.op === "copy") { + var existingValue = { + op: "_get", + path: operation.from, + value: void 0 + }; + var error = validate2([existingValue], document2); + if (error && error.name === "OPERATION_PATH_UNRESOLVABLE") { + throw new JsonPatchError("Cannot perform the operation from a path that does not exist", "OPERATION_FROM_UNRESOLVABLE", index2, operation, document2); + } + } + } + } + function validate2(sequence, document2, externalValidator) { + try { + if (!Array.isArray(sequence)) { + throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); + } + if (document2) { + applyPatch(_deepClone(document2), _deepClone(sequence), externalValidator || true); + } else { + externalValidator = externalValidator || validator; + for (var i2 = 0; i2 < sequence.length; i2++) { + externalValidator(sequence[i2], i2, document2, void 0); + } + } + } catch (e2) { + if (e2 instanceof JsonPatchError) { + return e2; + } else { + throw e2; + } + } + } + function _areEquals(a2, b3) { + if (a2 === b3) + return true; + if (a2 && b3 && typeof a2 == "object" && typeof b3 == "object") { + var arrA = Array.isArray(a2), arrB = Array.isArray(b3), i2, length, key; + if (arrA && arrB) { + length = a2.length; + if (length != b3.length) + return false; + for (i2 = length; i2-- !== 0; ) + if (!_areEquals(a2[i2], b3[i2])) + return false; + return true; + } + if (arrA != arrB) + return false; + var keys = Object.keys(a2); + length = keys.length; + if (length !== Object.keys(b3).length) + return false; + for (i2 = length; i2-- !== 0; ) + if (!b3.hasOwnProperty(keys[i2])) + return false; + for (i2 = length; i2-- !== 0; ) { + key = keys[i2]; + if (!_areEquals(a2[key], b3[key])) + return false; + } + return true; + } + return a2 !== a2 && b3 !== b3; + } + + // node_modules/@langchain/core/dist/utils/fast-json-patch/index.js + var fast_json_patch_default = { + ...core_exports, + // ...duplex, + JsonPatchError: PatchError, + deepClone: _deepClone, + escapePathComponent, + unescapePathComponent + }; + + // node_modules/langsmith/dist/experimental/otel/constants.js + var GEN_AI_OPERATION_NAME = "gen_ai.operation.name"; + var GEN_AI_SYSTEM = "gen_ai.system"; + var GEN_AI_REQUEST_MODEL = "gen_ai.request.model"; + var GEN_AI_RESPONSE_MODEL = "gen_ai.response.model"; + var GEN_AI_USAGE_INPUT_TOKENS = "gen_ai.usage.input_tokens"; + var GEN_AI_USAGE_OUTPUT_TOKENS = "gen_ai.usage.output_tokens"; + var GEN_AI_USAGE_TOTAL_TOKENS = "gen_ai.usage.total_tokens"; + var GEN_AI_REQUEST_MAX_TOKENS = "gen_ai.request.max_tokens"; + var GEN_AI_REQUEST_TEMPERATURE = "gen_ai.request.temperature"; + var GEN_AI_REQUEST_TOP_P = "gen_ai.request.top_p"; + var GEN_AI_REQUEST_FREQUENCY_PENALTY = "gen_ai.request.frequency_penalty"; + var GEN_AI_REQUEST_PRESENCE_PENALTY = "gen_ai.request.presence_penalty"; + var GEN_AI_RESPONSE_FINISH_REASONS = "gen_ai.response.finish_reasons"; + var GENAI_PROMPT = "gen_ai.prompt"; + var GENAI_COMPLETION = "gen_ai.completion"; + var GEN_AI_REQUEST_EXTRA_QUERY = "gen_ai.request.extra_query"; + var GEN_AI_REQUEST_EXTRA_BODY = "gen_ai.request.extra_body"; + var GEN_AI_SERIALIZED_NAME = "gen_ai.serialized.name"; + var GEN_AI_SERIALIZED_SIGNATURE = "gen_ai.serialized.signature"; + var GEN_AI_SERIALIZED_DOC = "gen_ai.serialized.doc"; + var GEN_AI_RESPONSE_ID = "gen_ai.response.id"; + var GEN_AI_RESPONSE_SERVICE_TIER = "gen_ai.response.service_tier"; + var GEN_AI_RESPONSE_SYSTEM_FINGERPRINT = "gen_ai.response.system_fingerprint"; + var GEN_AI_USAGE_INPUT_TOKEN_DETAILS = "gen_ai.usage.input_token_details"; + var GEN_AI_USAGE_OUTPUT_TOKEN_DETAILS = "gen_ai.usage.output_token_details"; + var LANGSMITH_SESSION_ID = "langsmith.trace.session_id"; + var LANGSMITH_SESSION_NAME = "langsmith.trace.session_name"; + var LANGSMITH_RUN_TYPE = "langsmith.span.kind"; + var LANGSMITH_NAME = "langsmith.trace.name"; + var LANGSMITH_METADATA = "langsmith.metadata"; + var LANGSMITH_TAGS = "langsmith.span.tags"; + var LANGSMITH_REQUEST_STREAMING = "langsmith.request.streaming"; + var LANGSMITH_REQUEST_HEADERS = "langsmith.request.headers"; + + // node_modules/langsmith/dist/singletons/fetch.js + var DEFAULT_FETCH_IMPLEMENTATION = (...args) => fetch(...args); + var LANGSMITH_FETCH_IMPLEMENTATION_KEY = Symbol.for("ls:fetch_implementation"); + var _globalFetchImplementationIsNodeFetch = () => { + const fetchImpl = globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY]; + if (!fetchImpl) + return false; + return typeof fetchImpl === "function" && "Headers" in fetchImpl && "Request" in fetchImpl && "Response" in fetchImpl; + }; + var _getFetchImplementation = (debug) => { + return async (...args) => { + if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") { + const [url, options] = args; + console.log(`\u2192 ${options?.method || "GET"} ${url}`); + } + const res = await (globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] ?? DEFAULT_FETCH_IMPLEMENTATION)(...args); + if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") { + console.log(`\u2190 ${res.status} ${res.statusText} ${res.url}`); + } + return res; + }; + }; + + // node_modules/langsmith/dist/utils/project.js + var getDefaultProjectName = () => { + return getLangSmithEnvironmentVariable("PROJECT") ?? getEnvironmentVariable("LANGCHAIN_SESSION") ?? // TODO: Deprecate + "default"; + }; + + // node_modules/langsmith/dist/index.js + var __version__ = "0.3.62"; + + // node_modules/langsmith/dist/utils/env.js + var globalEnv; + var isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; + var isWebWorker = () => typeof globalThis === "object" && globalThis.constructor && globalThis.constructor.name === "DedicatedWorkerGlobalScope"; + var isJsDom = () => typeof window !== "undefined" && window.name === "nodejs" || typeof navigator !== "undefined" && navigator.userAgent.includes("jsdom"); + var isDeno = () => typeof Deno !== "undefined"; + var isNode = () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && !isDeno(); + var getEnv = () => { + if (globalEnv) { + return globalEnv; + } + if (isBrowser()) { + globalEnv = "browser"; + } else if (isNode()) { + globalEnv = "node"; + } else if (isWebWorker()) { + globalEnv = "webworker"; + } else if (isJsDom()) { + globalEnv = "jsdom"; + } else if (isDeno()) { + globalEnv = "deno"; + } else { + globalEnv = "other"; + } + return globalEnv; + }; + var runtimeEnvironment; + function getRuntimeEnvironment() { + if (runtimeEnvironment === void 0) { + const env = getEnv(); + const releaseEnv = getShas(); + runtimeEnvironment = { + library: "langsmith", + runtime: env, + sdk: "langsmith-js", + sdk_version: __version__, + ...releaseEnv + }; + } + return runtimeEnvironment; + } + function getLangChainEnvVarsMetadata() { + const allEnvVars = getEnvironmentVariables() || {}; + const envVars = {}; + const excluded = [ + "LANGCHAIN_API_KEY", + "LANGCHAIN_ENDPOINT", + "LANGCHAIN_TRACING_V2", + "LANGCHAIN_PROJECT", + "LANGCHAIN_SESSION", + "LANGSMITH_API_KEY", + "LANGSMITH_ENDPOINT", + "LANGSMITH_TRACING_V2", + "LANGSMITH_PROJECT", + "LANGSMITH_SESSION" + ]; + for (const [key, value] of Object.entries(allEnvVars)) { + if ((key.startsWith("LANGCHAIN_") || key.startsWith("LANGSMITH_")) && typeof value === "string" && !excluded.includes(key) && !key.toLowerCase().includes("key") && !key.toLowerCase().includes("secret") && !key.toLowerCase().includes("token")) { + if (key === "LANGCHAIN_REVISION_ID") { + envVars["revision_id"] = value; + } else { + envVars[key] = value; + } + } + } + return envVars; + } + function getEnvironmentVariables() { + try { + if (typeof process !== "undefined" && process.env) { + return Object.entries(process.env).reduce((acc, [key, value]) => { + acc[key] = String(value); + return acc; + }, {}); + } + return void 0; + } catch (e2) { + return void 0; + } + } + function getEnvironmentVariable(name) { + try { + return typeof process !== "undefined" ? ( + // eslint-disable-next-line no-process-env + process.env?.[name] + ) : void 0; + } catch (e2) { + return void 0; + } + } + function getLangSmithEnvironmentVariable(name) { + return getEnvironmentVariable(`LANGSMITH_${name}`) || getEnvironmentVariable(`LANGCHAIN_${name}`); + } + var cachedCommitSHAs; + function getShas() { + if (cachedCommitSHAs !== void 0) { + return cachedCommitSHAs; + } + const common_release_envs = [ + "VERCEL_GIT_COMMIT_SHA", + "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA", + "COMMIT_REF", + "RENDER_GIT_COMMIT", + "CI_COMMIT_SHA", + "CIRCLE_SHA1", + "CF_PAGES_COMMIT_SHA", + "REACT_APP_GIT_SHA", + "SOURCE_VERSION", + "GITHUB_SHA", + "TRAVIS_COMMIT", + "GIT_COMMIT", + "BUILD_VCS_NUMBER", + "bamboo_planRepository_revision", + "Build.SourceVersion", + "BITBUCKET_COMMIT", + "DRONE_COMMIT_SHA", + "SEMAPHORE_GIT_SHA", + "BUILDKITE_COMMIT" + ]; + const shas = {}; + for (const env of common_release_envs) { + const envVar = getEnvironmentVariable(env); + if (envVar !== void 0) { + shas[env] = envVar; + } + } + cachedCommitSHAs = shas; + return shas; + } + function getOtelEnabled() { + return getEnvironmentVariable("OTEL_ENABLED") === "true" || getLangSmithEnvironmentVariable("OTEL_ENABLED") === "true"; + } + + // node_modules/langsmith/dist/singletons/otel.js + var MockTracer = class { + constructor() { + Object.defineProperty(this, "hasWarned", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + } + startActiveSpan(_name, ...args) { + if (!this.hasWarned && getOtelEnabled()) { + console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'); + this.hasWarned = true; + } + let fn; + if (args.length === 1 && typeof args[0] === "function") { + fn = args[0]; + } else if (args.length === 2 && typeof args[1] === "function") { + fn = args[1]; + } else if (args.length === 3 && typeof args[2] === "function") { + fn = args[2]; + } + if (typeof fn === "function") { + return fn(); + } + return void 0; + } + }; + var MockOTELTrace = class { + constructor() { + Object.defineProperty(this, "mockTracer", { + enumerable: true, + configurable: true, + writable: true, + value: new MockTracer() + }); + } + getTracer(_name, _version) { + return this.mockTracer; + } + getActiveSpan() { + return void 0; + } + setSpan(context, _span) { + return context; + } + getSpan(_context) { + return void 0; + } + setSpanContext(context, _spanContext) { + return context; + } + getTracerProvider() { + return void 0; + } + setGlobalTracerProvider(_tracerProvider) { + return false; + } + }; + var MockOTELContext = class { + active() { + return {}; + } + with(_context, fn) { + return fn(); + } + }; + var OTEL_TRACE_KEY = Symbol.for("ls:otel_trace"); + var OTEL_CONTEXT_KEY = Symbol.for("ls:otel_context"); + var OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY = Symbol.for("ls:otel_get_default_otlp_tracer_provider"); + var mockOTELTrace = new MockOTELTrace(); + var mockOTELContext = new MockOTELContext(); + var OTELProvider = class { + getTraceInstance() { + return globalThis[OTEL_TRACE_KEY] ?? mockOTELTrace; + } + getContextInstance() { + return globalThis[OTEL_CONTEXT_KEY] ?? mockOTELContext; + } + initializeGlobalInstances(otel) { + if (globalThis[OTEL_TRACE_KEY] === void 0) { + globalThis[OTEL_TRACE_KEY] = otel.trace; + } + if (globalThis[OTEL_CONTEXT_KEY] === void 0) { + globalThis[OTEL_CONTEXT_KEY] = otel.context; + } + } + setDefaultOTLPTracerComponents(components) { + globalThis[OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY] = components; + } + getDefaultOTLPTracerComponents() { + return globalThis[OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY] ?? void 0; + } + }; + var OTELProviderSingleton = new OTELProvider(); + function getOTELTrace() { + return OTELProviderSingleton.getTraceInstance(); + } + function getOTELContext() { + return OTELProviderSingleton.getContextInstance(); + } + function getDefaultOTLPTracerComponents() { + return OTELProviderSingleton.getDefaultOTLPTracerComponents(); + } + + // node_modules/langsmith/dist/experimental/otel/translator.js + var WELL_KNOWN_OPERATION_NAMES = { + llm: "chat", + tool: "execute_tool", + retriever: "embeddings", + embedding: "embeddings", + prompt: "chat" + }; + function getOperationName(runType) { + return WELL_KNOWN_OPERATION_NAMES[runType] || runType; + } + var LangSmithToOTELTranslator = class { + constructor() { + Object.defineProperty(this, "spans", { + enumerable: true, + configurable: true, + writable: true, + value: /* @__PURE__ */ new Map() + }); + } + exportBatch(operations, otelContextMap) { + for (const op of operations) { + try { + if (!op.run) { + continue; + } + if (op.operation === "post") { + const span = this.createSpanForRun(op, op.run, otelContextMap.get(op.id)); + if (span && !op.run.end_time) { + this.spans.set(op.id, span); + } + } else { + this.updateSpanForRun(op, op.run); + } + } catch (e2) { + console.error(`Error processing operation ${op.id}:`, e2); + } + } + } + createSpanForRun(op, runInfo, otelContext) { + const activeSpan = otelContext && getOTELTrace().getSpan(otelContext); + if (!activeSpan) { + return; + } + try { + return this.finishSpanSetup(activeSpan, runInfo, op); + } catch (e2) { + console.error(`Failed to create span for run ${op.id}:`, e2); + return void 0; + } + } + finishSpanSetup(span, runInfo, op) { + this.setSpanAttributes(span, runInfo, op); + if (runInfo.error) { + span.setStatus({ code: 2 }); + span.recordException(new Error(runInfo.error)); + } else { + span.setStatus({ code: 1 }); + } + if (runInfo.end_time) { + span.end(new Date(runInfo.end_time)); + } + return span; + } + updateSpanForRun(op, runInfo) { + try { + const span = this.spans.get(op.id); + if (!span) { + console.debug(`No span found for run ${op.id} during update`); + return; + } + this.setSpanAttributes(span, runInfo, op); + if (runInfo.error) { + span.setStatus({ code: 2 }); + span.recordException(new Error(runInfo.error)); + } else { + span.setStatus({ code: 1 }); + } + const endTime = runInfo.end_time; + if (endTime) { + span.end(new Date(endTime)); + this.spans.delete(op.id); + } + } catch (e2) { + console.error(`Failed to update span for run ${op.id}:`, e2); + } + } + extractModelName(runInfo) { + if (runInfo.extra?.metadata) { + const metadata = runInfo.extra.metadata; + if (metadata.ls_model_name) { + return metadata.ls_model_name; + } + if (metadata.invocation_params) { + const invocationParams = metadata.invocation_params; + if (invocationParams.model) { + return invocationParams.model; + } else if (invocationParams.model_name) { + return invocationParams.model_name; + } + } + } + return; + } + setSpanAttributes(span, runInfo, op) { + if ("run_type" in runInfo && runInfo.run_type) { + span.setAttribute(LANGSMITH_RUN_TYPE, runInfo.run_type); + const operationName = getOperationName(runInfo.run_type || "chain"); + span.setAttribute(GEN_AI_OPERATION_NAME, operationName); + } + if ("name" in runInfo && runInfo.name) { + span.setAttribute(LANGSMITH_NAME, runInfo.name); + } + if ("session_id" in runInfo && runInfo.session_id) { + span.setAttribute(LANGSMITH_SESSION_ID, runInfo.session_id); + } + if ("session_name" in runInfo && runInfo.session_name) { + span.setAttribute(LANGSMITH_SESSION_NAME, runInfo.session_name); + } + this.setGenAiSystem(span, runInfo); + const modelName = this.extractModelName(runInfo); + if (modelName) { + span.setAttribute(GEN_AI_REQUEST_MODEL, modelName); + } + if ("prompt_tokens" in runInfo && typeof runInfo.prompt_tokens === "number") { + span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, runInfo.prompt_tokens); + } + if ("completion_tokens" in runInfo && typeof runInfo.completion_tokens === "number") { + span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, runInfo.completion_tokens); + } + if ("total_tokens" in runInfo && typeof runInfo.total_tokens === "number") { + span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, runInfo.total_tokens); + } + this.setInvocationParameters(span, runInfo); + const metadata = runInfo.extra?.metadata || {}; + for (const [key, value] of Object.entries(metadata)) { + if (value !== null && value !== void 0) { + span.setAttribute(`${LANGSMITH_METADATA}.${key}`, String(value)); + } + } + const tags = runInfo.tags; + if (tags && Array.isArray(tags)) { + span.setAttribute(LANGSMITH_TAGS, tags.join(", ")); + } else if (tags) { + span.setAttribute(LANGSMITH_TAGS, String(tags)); + } + if ("serialized" in runInfo && typeof runInfo.serialized === "object") { + const serialized = runInfo.serialized; + if (serialized.name) { + span.setAttribute(GEN_AI_SERIALIZED_NAME, String(serialized.name)); + } + if (serialized.signature) { + span.setAttribute(GEN_AI_SERIALIZED_SIGNATURE, String(serialized.signature)); + } + if (serialized.doc) { + span.setAttribute(GEN_AI_SERIALIZED_DOC, String(serialized.doc)); + } + } + this.setIOAttributes(span, op); + } + setGenAiSystem(span, runInfo) { + let system = "langchain"; + const modelName = this.extractModelName(runInfo); + if (modelName) { + const modelLower = modelName.toLowerCase(); + if (modelLower.includes("anthropic") || modelLower.startsWith("claude")) { + system = "anthropic"; + } else if (modelLower.includes("bedrock")) { + system = "aws.bedrock"; + } else if (modelLower.includes("azure") && modelLower.includes("openai")) { + system = "az.ai.openai"; + } else if (modelLower.includes("azure") && modelLower.includes("inference")) { + system = "az.ai.inference"; + } else if (modelLower.includes("cohere")) { + system = "cohere"; + } else if (modelLower.includes("deepseek")) { + system = "deepseek"; + } else if (modelLower.includes("gemini")) { + system = "gemini"; + } else if (modelLower.includes("groq")) { + system = "groq"; + } else if (modelLower.includes("watson") || modelLower.includes("ibm")) { + system = "ibm.watsonx.ai"; + } else if (modelLower.includes("mistral")) { + system = "mistral_ai"; + } else if (modelLower.includes("gpt") || modelLower.includes("openai")) { + system = "openai"; + } else if (modelLower.includes("perplexity") || modelLower.includes("sonar")) { + system = "perplexity"; + } else if (modelLower.includes("vertex")) { + system = "vertex_ai"; + } else if (modelLower.includes("xai") || modelLower.includes("grok")) { + system = "xai"; + } + } + span.setAttribute(GEN_AI_SYSTEM, system); + } + setInvocationParameters(span, runInfo) { + if (!runInfo.extra?.metadata?.invocation_params) { + return; + } + const invocationParams = runInfo.extra.metadata.invocation_params; + if (invocationParams.max_tokens !== void 0) { + span.setAttribute(GEN_AI_REQUEST_MAX_TOKENS, invocationParams.max_tokens); + } + if (invocationParams.temperature !== void 0) { + span.setAttribute(GEN_AI_REQUEST_TEMPERATURE, invocationParams.temperature); + } + if (invocationParams.top_p !== void 0) { + span.setAttribute(GEN_AI_REQUEST_TOP_P, invocationParams.top_p); + } + if (invocationParams.frequency_penalty !== void 0) { + span.setAttribute(GEN_AI_REQUEST_FREQUENCY_PENALTY, invocationParams.frequency_penalty); + } + if (invocationParams.presence_penalty !== void 0) { + span.setAttribute(GEN_AI_REQUEST_PRESENCE_PENALTY, invocationParams.presence_penalty); + } + } + setIOAttributes(span, op) { + if (op.run.inputs) { + try { + const inputs = op.run.inputs; + if (typeof inputs === "object" && inputs !== null) { + if (inputs.model && Array.isArray(inputs.messages)) { + span.setAttribute(GEN_AI_REQUEST_MODEL, inputs.model); + } + if (inputs.stream !== void 0) { + span.setAttribute(LANGSMITH_REQUEST_STREAMING, inputs.stream); + } + if (inputs.extra_headers) { + span.setAttribute(LANGSMITH_REQUEST_HEADERS, JSON.stringify(inputs.extra_headers)); + } + if (inputs.extra_query) { + span.setAttribute(GEN_AI_REQUEST_EXTRA_QUERY, JSON.stringify(inputs.extra_query)); + } + if (inputs.extra_body) { + span.setAttribute(GEN_AI_REQUEST_EXTRA_BODY, JSON.stringify(inputs.extra_body)); + } + } + span.setAttribute(GENAI_PROMPT, JSON.stringify(inputs)); + } catch (e2) { + console.debug(`Failed to process inputs for run ${op.id}`, e2); + } + } + if (op.run.outputs) { + try { + const outputs = op.run.outputs; + const tokenUsage = this.getUnifiedRunTokens(outputs); + if (tokenUsage) { + span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, tokenUsage[0]); + span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, tokenUsage[1]); + span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, tokenUsage[0] + tokenUsage[1]); + } + if (outputs && typeof outputs === "object") { + if (outputs.model) { + span.setAttribute(GEN_AI_RESPONSE_MODEL, String(outputs.model)); + } + if (outputs.id) { + span.setAttribute(GEN_AI_RESPONSE_ID, outputs.id); + } + if (outputs.choices && Array.isArray(outputs.choices)) { + const finishReasons = outputs.choices.map((choice) => choice.finish_reason).filter((reason) => reason).map(String); + if (finishReasons.length > 0) { + span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, finishReasons.join(", ")); + } + } + if (outputs.service_tier) { + span.setAttribute(GEN_AI_RESPONSE_SERVICE_TIER, outputs.service_tier); + } + if (outputs.system_fingerprint) { + span.setAttribute(GEN_AI_RESPONSE_SYSTEM_FINGERPRINT, outputs.system_fingerprint); + } + if (outputs.usage_metadata && typeof outputs.usage_metadata === "object") { + const usageMetadata = outputs.usage_metadata; + if (usageMetadata.input_token_details) { + span.setAttribute(GEN_AI_USAGE_INPUT_TOKEN_DETAILS, JSON.stringify(usageMetadata.input_token_details)); + } + if (usageMetadata.output_token_details) { + span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKEN_DETAILS, JSON.stringify(usageMetadata.output_token_details)); + } + } + } + span.setAttribute(GENAI_COMPLETION, JSON.stringify(outputs)); + } catch (e2) { + console.debug(`Failed to process outputs for run ${op.id}`, e2); + } + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + getUnifiedRunTokens(outputs) { + if (!outputs) { + return null; + } + let tokenUsage = this.extractUnifiedRunTokens(outputs.usage_metadata); + if (tokenUsage) { + return tokenUsage; + } + const keys = Object.keys(outputs); + for (const key of keys) { + const haystack = outputs[key]; + if (!haystack || typeof haystack !== "object") { + continue; + } + tokenUsage = this.extractUnifiedRunTokens(haystack.usage_metadata); + if (tokenUsage) { + return tokenUsage; + } + if (haystack.lc === 1 && haystack.kwargs && typeof haystack.kwargs === "object") { + tokenUsage = this.extractUnifiedRunTokens(haystack.kwargs.usage_metadata); + if (tokenUsage) { + return tokenUsage; + } + } + } + const generations = outputs.generations || []; + if (!Array.isArray(generations)) { + return null; + } + const flatGenerations = Array.isArray(generations[0]) ? generations.flat() : generations; + for (const generation of flatGenerations) { + if (typeof generation === "object" && generation.message && typeof generation.message === "object" && generation.message.kwargs && typeof generation.message.kwargs === "object") { + tokenUsage = this.extractUnifiedRunTokens(generation.message.kwargs.usage_metadata); + if (tokenUsage) { + return tokenUsage; + } + } + } + return null; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + extractUnifiedRunTokens(outputs) { + if (!outputs || typeof outputs !== "object") { + return null; + } + if (typeof outputs.input_tokens !== "number" || typeof outputs.output_tokens !== "number") { + return null; + } + return [outputs.input_tokens, outputs.output_tokens]; + } + }; + + // node_modules/langsmith/dist/utils/async_caller.js + var import_p_retry = __toESM(require_p_retry(), 1); + var import_p_queue = __toESM(require_dist(), 1); + var STATUS_NO_RETRY = [ + 400, + // Bad Request + 401, + // Unauthorized + 403, + // Forbidden + 404, + // Not Found + 405, + // Method Not Allowed + 406, + // Not Acceptable + 407, + // Proxy Authentication Required + 408 + // Request Timeout + ]; + var STATUS_IGNORE = [ + 409 + // Conflict + ]; + var AsyncCaller = class { + constructor(params) { + Object.defineProperty(this, "maxConcurrency", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "maxRetries", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "queue", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "onFailedResponseHook", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "debug", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.maxConcurrency = params.maxConcurrency ?? Infinity; + this.maxRetries = params.maxRetries ?? 6; + this.debug = params.debug; + if ("default" in import_p_queue.default) { + this.queue = new import_p_queue.default.default({ + concurrency: this.maxConcurrency + }); + } else { + this.queue = new import_p_queue.default({ concurrency: this.maxConcurrency }); + } + this.onFailedResponseHook = params?.onFailedResponseHook; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + call(callable, ...args) { + const onFailedResponseHook = this.onFailedResponseHook; + return this.queue.add(() => (0, import_p_retry.default)(() => callable(...args).catch((error) => { + if (error instanceof Error) { + throw error; + } else { + throw new Error(error); + } + }), { + async onFailedAttempt(error) { + if (error.message.startsWith("Cancel") || error.message.startsWith("TimeoutError") || error.name === "TimeoutError" || error.message.startsWith("AbortError")) { + throw error; + } + if (error?.code === "ECONNABORTED") { + throw error; + } + const response = error?.response; + const status = response?.status; + if (status) { + if (STATUS_NO_RETRY.includes(+status)) { + throw error; + } else if (STATUS_IGNORE.includes(+status)) { + return; + } + if (onFailedResponseHook) { + await onFailedResponseHook(response); + } + } + }, + // If needed we can change some of the defaults here, + // but they're quite sensible. + retries: this.maxRetries, + randomize: true + }), { throwOnTimeout: true }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callWithOptions(options, callable, ...args) { + if (options.signal) { + return Promise.race([ + this.call(callable, ...args), + new Promise((_2, reject) => { + options.signal?.addEventListener("abort", () => { + reject(new Error("AbortError")); + }); + }) + ]); + } + return this.call(callable, ...args); + } + fetch(...args) { + return this.call(() => _getFetchImplementation(this.debug)(...args).then((res) => res.ok ? res : Promise.reject(res))); + } + }; + + // node_modules/langsmith/dist/utils/messages.js + function isLangChainMessage(message) { + return typeof message?._getType === "function"; + } + function convertLangChainMessageToExample(message) { + const converted = { + type: message._getType(), + data: { content: message.content } + }; + if (message?.additional_kwargs && Object.keys(message.additional_kwargs).length > 0) { + converted.data.additional_kwargs = { ...message.additional_kwargs }; + } + return converted; + } + + // node_modules/langsmith/dist/utils/_uuid.js + var UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + function assertUuid(str, which) { + if (!UUID_REGEX.test(str)) { + const msg = which !== void 0 ? `Invalid UUID for ${which}: ${str}` : `Invalid UUID: ${str}`; + throw new Error(msg); + } + return str; + } + + // node_modules/langsmith/dist/utils/warn.js + var warnedMessages = {}; + function warnOnce(message) { + if (!warnedMessages[message]) { + console.warn(message); + warnedMessages[message] = true; + } + } + + // node_modules/langsmith/dist/utils/prompts.js + var import_semver = __toESM(require_semver2(), 1); + function parsePromptIdentifier(identifier) { + if (!identifier || identifier.split("/").length > 2 || identifier.startsWith("/") || identifier.endsWith("/") || identifier.split(":").length > 2) { + throw new Error(`Invalid identifier format: ${identifier}`); + } + const [ownerNamePart, commitPart] = identifier.split(":"); + const commit = commitPart || "latest"; + if (ownerNamePart.includes("/")) { + const [owner, name] = ownerNamePart.split("/", 2); + if (!owner || !name) { + throw new Error(`Invalid identifier format: ${identifier}`); + } + return [owner, name, commit]; + } else { + if (!ownerNamePart) { + throw new Error(`Invalid identifier format: ${identifier}`); + } + return ["-", ownerNamePart, commit]; + } + } + + // node_modules/langsmith/dist/utils/error.js + var LangSmithConflictError = class extends Error { + constructor(message) { + super(message); + Object.defineProperty(this, "status", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.name = "LangSmithConflictError"; + this.status = 409; + } + }; + async function raiseForStatus(response, context, consume) { + let errorBody; + if (response.ok) { + if (consume) { + errorBody = await response.text(); + } + return; + } + errorBody = await response.text(); + const fullMessage = `Failed to ${context}. Received status [${response.status}]: ${response.statusText}. Server response: ${errorBody}`; + if (response.status === 409) { + throw new LangSmithConflictError(fullMessage); + } + const err = new Error(fullMessage); + err.status = response.status; + throw err; + } + var ERR_CONFLICTING_ENDPOINTS = "ERR_CONFLICTING_ENDPOINTS"; + var ConflictingEndpointsError = class extends Error { + constructor() { + super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."); + Object.defineProperty(this, "code", { + enumerable: true, + configurable: true, + writable: true, + value: ERR_CONFLICTING_ENDPOINTS + }); + this.name = "ConflictingEndpointsError"; + } + }; + function isConflictingEndpointsError(err) { + return typeof err === "object" && err !== null && err.code === ERR_CONFLICTING_ENDPOINTS; + } + + // node_modules/langsmith/dist/utils/fast-safe-stringify/index.js + var LIMIT_REPLACE_NODE = "[...]"; + var CIRCULAR_REPLACE_NODE = { result: "[Circular]" }; + var arr = []; + var replacerStack = []; + var encoder = new TextEncoder(); + function defaultOptions() { + return { + depthLimit: Number.MAX_SAFE_INTEGER, + edgesLimit: Number.MAX_SAFE_INTEGER + }; + } + function encodeString(str) { + return encoder.encode(str); + } + function serializeWellKnownTypes(val) { + if (val && typeof val === "object" && val !== null) { + if (val instanceof Map) { + return Object.fromEntries(val); + } else if (val instanceof Set) { + return Array.from(val); + } else if (val instanceof Date) { + return val.toISOString(); + } else if (val instanceof RegExp) { + return val.toString(); + } else if (val instanceof Error) { + return { + name: val.name, + message: val.message + }; + } + } else if (typeof val === "bigint") { + return val.toString(); + } + return val; + } + function createDefaultReplacer(userReplacer) { + return function(key, val) { + if (userReplacer) { + const userResult = userReplacer.call(this, key, val); + if (userResult !== void 0) { + return userResult; + } + } + return serializeWellKnownTypes(val); + }; + } + function serialize(obj, errorContext, replacer, spacer, options) { + try { + const str = JSON.stringify(obj, createDefaultReplacer(replacer), spacer); + return encodeString(str); + } catch (e2) { + if (!e2.message?.includes("Converting circular structure to JSON")) { + console.warn(`[WARNING]: LangSmith received unserializable value.${errorContext ? ` +Context: ${errorContext}` : ""}`); + return encodeString("[Unserializable]"); + } + getLangSmithEnvironmentVariable("SUPPRESS_CIRCULAR_JSON_WARNINGS") !== "true" && console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${errorContext ? ` +Context: ${errorContext}` : ""}`); + if (typeof options === "undefined") { + options = defaultOptions(); + } + decirc(obj, "", 0, [], void 0, 0, options); + let res; + try { + if (replacerStack.length === 0) { + res = JSON.stringify(obj, replacer, spacer); + } else { + res = JSON.stringify(obj, replaceGetterValues(replacer), spacer); + } + } catch (_2) { + return encodeString("[unable to serialize, circular reference is too complex to analyze]"); + } finally { + while (arr.length !== 0) { + const part = arr.pop(); + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]); + } else { + part[0][part[1]] = part[2]; + } + } + } + return encodeString(res); + } + } + function setReplace(replace, val, k3, parent) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k3); + if (propertyDescriptor.get !== void 0) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k3, { value: replace }); + arr.push([parent, k3, val, propertyDescriptor]); + } else { + replacerStack.push([val, k3, replace]); + } + } else { + parent[k3] = replace; + arr.push([parent, k3, val]); + } + } + function decirc(val, k3, edgeIndex, stack, parent, depth, options) { + depth += 1; + var i2; + if (typeof val === "object" && val !== null) { + for (i2 = 0; i2 < stack.length; i2++) { + if (stack[i2] === val) { + setReplace(CIRCULAR_REPLACE_NODE, val, k3, parent); + return; + } + } + if (typeof options.depthLimit !== "undefined" && depth > options.depthLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k3, parent); + return; + } + if (typeof options.edgesLimit !== "undefined" && edgeIndex + 1 > options.edgesLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k3, parent); + return; + } + stack.push(val); + if (Array.isArray(val)) { + for (i2 = 0; i2 < val.length; i2++) { + decirc(val[i2], i2, i2, stack, val, depth, options); + } + } else { + val = serializeWellKnownTypes(val); + var keys = Object.keys(val); + for (i2 = 0; i2 < keys.length; i2++) { + var key = keys[i2]; + decirc(val[key], key, i2, stack, val, depth, options); + } + } + stack.pop(); + } + } + function replaceGetterValues(replacer) { + replacer = typeof replacer !== "undefined" ? replacer : function(k3, v6) { + return v6; + }; + return function(key, val) { + if (replacerStack.length > 0) { + for (var i2 = 0; i2 < replacerStack.length; i2++) { + var part = replacerStack[i2]; + if (part[1] === key && part[0] === val) { + val = part[2]; + replacerStack.splice(i2, 1); + break; + } + } + } + return replacer.call(this, key, val); + }; + } + + // node_modules/langsmith/dist/client.js + function mergeRuntimeEnvIntoRun(run) { + const runtimeEnv = getRuntimeEnvironment(); + const envVars = getLangChainEnvVarsMetadata(); + const extra = run.extra ?? {}; + const metadata = extra.metadata; + run.extra = { + ...extra, + runtime: { + ...runtimeEnv, + ...extra?.runtime + }, + metadata: { + ...envVars, + ...envVars.revision_id || "revision_id" in run && run.revision_id ? { + revision_id: ("revision_id" in run ? run.revision_id : void 0) ?? envVars.revision_id + } : {}, + ...metadata + } + }; + return run; + } + var getTracingSamplingRate = (configRate) => { + const samplingRateStr = configRate?.toString() ?? getLangSmithEnvironmentVariable("TRACING_SAMPLING_RATE"); + if (samplingRateStr === void 0) { + return void 0; + } + const samplingRate = parseFloat(samplingRateStr); + if (samplingRate < 0 || samplingRate > 1) { + throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${samplingRate}`); + } + return samplingRate; + }; + var isLocalhost = (url) => { + const strippedUrl = url.replace("http://", "").replace("https://", ""); + const hostname = strippedUrl.split("/")[0].split(":")[0]; + return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1"; + }; + async function toArray(iterable) { + const result = []; + for await (const item of iterable) { + result.push(item); + } + return result; + } + function trimQuotes(str) { + if (str === void 0) { + return void 0; + } + return str.trim().replace(/^"(.*)"$/, "$1").replace(/^'(.*)'$/, "$1"); + } + var handle429 = async (response) => { + if (response?.status === 429) { + const retryAfter = parseInt(response.headers.get("retry-after") ?? "10", 10) * 1e3; + if (retryAfter > 0) { + await new Promise((resolve) => setTimeout(resolve, retryAfter)); + return true; + } + } + return false; + }; + function _formatFeedbackScore(score) { + if (typeof score === "number") { + return Number(score.toFixed(4)); + } + return score; + } + var AutoBatchQueue = class { + constructor() { + Object.defineProperty(this, "items", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "sizeBytes", { + enumerable: true, + configurable: true, + writable: true, + value: 0 + }); + } + peek() { + return this.items[0]; + } + push(item) { + let itemPromiseResolve; + const itemPromise = new Promise((resolve) => { + itemPromiseResolve = resolve; + }); + const size = serialize(item.item, `Serializing run with id: ${item.item.id}`).length; + this.items.push({ + action: item.action, + payload: item.item, + otelContext: item.otelContext, + apiKey: item.apiKey, + apiUrl: item.apiUrl, + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + itemPromiseResolve, + itemPromise, + size + }); + this.sizeBytes += size; + return itemPromise; + } + pop(upToSizeBytes) { + if (upToSizeBytes < 1) { + throw new Error("Number of bytes to pop off may not be less than 1."); + } + const popped = []; + let poppedSizeBytes = 0; + while (poppedSizeBytes + (this.peek()?.size ?? 0) < upToSizeBytes && this.items.length > 0) { + const item = this.items.shift(); + if (item) { + popped.push(item); + poppedSizeBytes += item.size; + this.sizeBytes -= item.size; + } + } + if (popped.length === 0 && this.items.length > 0) { + const item = this.items.shift(); + popped.push(item); + poppedSizeBytes += item.size; + this.sizeBytes -= item.size; + } + return [ + popped.map((it) => ({ + action: it.action, + item: it.payload, + otelContext: it.otelContext, + apiKey: it.apiKey, + apiUrl: it.apiUrl + })), + () => popped.forEach((it) => it.itemPromiseResolve()) + ]; + } + }; + var DEFAULT_UNCOMPRESSED_BATCH_SIZE_LIMIT_BYTES = 32 * 1024 * 1024; + var SERVER_INFO_REQUEST_TIMEOUT_MS = 1e4; + var DEFAULT_API_URL = "https://api.smith.langchain.com"; + var Client = class _Client { + constructor(config = {}) { + Object.defineProperty(this, "apiKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "apiUrl", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "webUrl", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "caller", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "batchIngestCaller", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "timeout_ms", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_tenantId", { + enumerable: true, + configurable: true, + writable: true, + value: null + }); + Object.defineProperty(this, "hideInputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "hideOutputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tracingSampleRate", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "filteredPostUuids", { + enumerable: true, + configurable: true, + writable: true, + value: /* @__PURE__ */ new Set() + }); + Object.defineProperty(this, "autoBatchTracing", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "autoBatchQueue", { + enumerable: true, + configurable: true, + writable: true, + value: new AutoBatchQueue() + }); + Object.defineProperty(this, "autoBatchTimeout", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "autoBatchAggregationDelayMs", { + enumerable: true, + configurable: true, + writable: true, + value: 250 + }); + Object.defineProperty(this, "batchSizeBytesLimit", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "fetchOptions", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "settings", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "blockOnRootRunFinalization", { + enumerable: true, + configurable: true, + writable: true, + value: getEnvironmentVariable("LANGSMITH_TRACING_BACKGROUND") === "false" + }); + Object.defineProperty(this, "traceBatchConcurrency", { + enumerable: true, + configurable: true, + writable: true, + value: 5 + }); + Object.defineProperty(this, "_serverInfo", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_getServerInfoPromise", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "manualFlushMode", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "langSmithToOTELTranslator", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "multipartStreamingDisabled", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "debug", { + enumerable: true, + configurable: true, + writable: true, + value: getEnvironmentVariable("LANGSMITH_DEBUG") === "true" + }); + const defaultConfig = _Client.getDefaultClientConfig(); + this.tracingSampleRate = getTracingSamplingRate(config.tracingSamplingRate); + this.apiUrl = trimQuotes(config.apiUrl ?? defaultConfig.apiUrl) ?? ""; + if (this.apiUrl.endsWith("/")) { + this.apiUrl = this.apiUrl.slice(0, -1); + } + this.apiKey = trimQuotes(config.apiKey ?? defaultConfig.apiKey); + this.webUrl = trimQuotes(config.webUrl ?? defaultConfig.webUrl); + if (this.webUrl?.endsWith("/")) { + this.webUrl = this.webUrl.slice(0, -1); + } + this.timeout_ms = config.timeout_ms ?? 9e4; + this.caller = new AsyncCaller({ + ...config.callerOptions ?? {}, + debug: config.debug ?? this.debug + }); + this.traceBatchConcurrency = config.traceBatchConcurrency ?? this.traceBatchConcurrency; + if (this.traceBatchConcurrency < 1) { + throw new Error("Trace batch concurrency must be positive."); + } + this.debug = config.debug ?? this.debug; + this.batchIngestCaller = new AsyncCaller({ + maxRetries: 2, + maxConcurrency: this.traceBatchConcurrency, + ...config.callerOptions ?? {}, + onFailedResponseHook: handle429, + debug: config.debug ?? this.debug + }); + this.hideInputs = config.hideInputs ?? config.anonymizer ?? defaultConfig.hideInputs; + this.hideOutputs = config.hideOutputs ?? config.anonymizer ?? defaultConfig.hideOutputs; + this.autoBatchTracing = config.autoBatchTracing ?? this.autoBatchTracing; + this.blockOnRootRunFinalization = config.blockOnRootRunFinalization ?? this.blockOnRootRunFinalization; + this.batchSizeBytesLimit = config.batchSizeBytesLimit; + this.fetchOptions = config.fetchOptions || {}; + this.manualFlushMode = config.manualFlushMode ?? this.manualFlushMode; + if (getOtelEnabled()) { + this.langSmithToOTELTranslator = new LangSmithToOTELTranslator(); + } + } + static getDefaultClientConfig() { + const apiKey = getLangSmithEnvironmentVariable("API_KEY"); + const apiUrl = getLangSmithEnvironmentVariable("ENDPOINT") ?? DEFAULT_API_URL; + const hideInputs = getLangSmithEnvironmentVariable("HIDE_INPUTS") === "true"; + const hideOutputs = getLangSmithEnvironmentVariable("HIDE_OUTPUTS") === "true"; + return { + apiUrl, + apiKey, + webUrl: void 0, + hideInputs, + hideOutputs + }; + } + getHostUrl() { + if (this.webUrl) { + return this.webUrl; + } else if (isLocalhost(this.apiUrl)) { + this.webUrl = "http://localhost:3000"; + return this.webUrl; + } else if (this.apiUrl.endsWith("/api/v1")) { + this.webUrl = this.apiUrl.replace("/api/v1", ""); + return this.webUrl; + } else if (this.apiUrl.includes("/api") && !this.apiUrl.split(".", 1)[0].endsWith("api")) { + this.webUrl = this.apiUrl.replace("/api", ""); + return this.webUrl; + } else if (this.apiUrl.split(".", 1)[0].includes("dev")) { + this.webUrl = "https://dev.smith.langchain.com"; + return this.webUrl; + } else if (this.apiUrl.split(".", 1)[0].includes("eu")) { + this.webUrl = "https://eu.smith.langchain.com"; + return this.webUrl; + } else if (this.apiUrl.split(".", 1)[0].includes("beta")) { + this.webUrl = "https://beta.smith.langchain.com"; + return this.webUrl; + } else { + this.webUrl = "https://smith.langchain.com"; + return this.webUrl; + } + } + get headers() { + const headers = { + "User-Agent": `langsmith-js/${__version__}` + }; + if (this.apiKey) { + headers["x-api-key"] = `${this.apiKey}`; + } + return headers; + } + _getPlatformEndpointPath(path) { + const needsV1Prefix = this.apiUrl.slice(-3) !== "/v1" && this.apiUrl.slice(-4) !== "/v1/"; + return needsV1Prefix ? `/v1/platform/${path}` : `/platform/${path}`; + } + async processInputs(inputs) { + if (this.hideInputs === false) { + return inputs; + } + if (this.hideInputs === true) { + return {}; + } + if (typeof this.hideInputs === "function") { + return this.hideInputs(inputs); + } + return inputs; + } + async processOutputs(outputs) { + if (this.hideOutputs === false) { + return outputs; + } + if (this.hideOutputs === true) { + return {}; + } + if (typeof this.hideOutputs === "function") { + return this.hideOutputs(outputs); + } + return outputs; + } + async prepareRunCreateOrUpdateInputs(run) { + const runParams = { ...run }; + if (runParams.inputs !== void 0) { + runParams.inputs = await this.processInputs(runParams.inputs); + } + if (runParams.outputs !== void 0) { + runParams.outputs = await this.processOutputs(runParams.outputs); + } + return runParams; + } + async _getResponse(path, queryParams) { + const paramsString = queryParams?.toString() ?? ""; + const url = `${this.apiUrl}${path}?${paramsString}`; + const response = await this.caller.call(_getFetchImplementation(this.debug), url, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, `Failed to fetch ${path}`); + return response; + } + async _get(path, queryParams) { + const response = await this._getResponse(path, queryParams); + return response.json(); + } + async *_getPaginated(path, queryParams = new URLSearchParams(), transform) { + let offset = Number(queryParams.get("offset")) || 0; + const limit = Number(queryParams.get("limit")) || 100; + while (true) { + queryParams.set("offset", String(offset)); + queryParams.set("limit", String(limit)); + const url = `${this.apiUrl}${path}?${queryParams}`; + const response = await this.caller.call(_getFetchImplementation(this.debug), url, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, `Failed to fetch ${path}`); + const items = transform ? transform(await response.json()) : await response.json(); + if (items.length === 0) { + break; + } + yield items; + if (items.length < limit) { + break; + } + offset += items.length; + } + } + async *_getCursorPaginatedList(path, body = null, requestMethod = "POST", dataKey = "runs") { + const bodyParams = body ? { ...body } : {}; + while (true) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${path}`, { + method: requestMethod, + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: JSON.stringify(bodyParams) + }); + const responseBody = await response.json(); + if (!responseBody) { + break; + } + if (!responseBody[dataKey]) { + break; + } + yield responseBody[dataKey]; + const cursors = responseBody.cursors; + if (!cursors) { + break; + } + if (!cursors.next) { + break; + } + bodyParams.cursor = cursors.next; + } + } + // Allows mocking for tests + _shouldSample() { + if (this.tracingSampleRate === void 0) { + return true; + } + return Math.random() < this.tracingSampleRate; + } + _filterForSampling(runs, patch = false) { + if (this.tracingSampleRate === void 0) { + return runs; + } + if (patch) { + const sampled = []; + for (const run of runs) { + if (!this.filteredPostUuids.has(run.trace_id)) { + sampled.push(run); + } else if (run.id === run.trace_id) { + this.filteredPostUuids.delete(run.trace_id); + } + } + return sampled; + } else { + const sampled = []; + for (const run of runs) { + const traceId = run.trace_id ?? run.id; + if (this.filteredPostUuids.has(traceId)) { + continue; + } + if (run.id === traceId) { + if (this._shouldSample()) { + sampled.push(run); + } else { + this.filteredPostUuids.add(traceId); + } + } else { + sampled.push(run); + } + } + return sampled; + } + } + async _getBatchSizeLimitBytes() { + const serverInfo = await this._ensureServerInfo(); + return this.batchSizeBytesLimit ?? serverInfo.batch_ingest_config?.size_limit_bytes ?? DEFAULT_UNCOMPRESSED_BATCH_SIZE_LIMIT_BYTES; + } + async _getDatasetExamplesMultiPartSupport() { + const serverInfo = await this._ensureServerInfo(); + return serverInfo.instance_flags?.dataset_examples_multipart_enabled ?? false; + } + drainAutoBatchQueue(batchSizeLimit) { + const promises = []; + while (this.autoBatchQueue.items.length > 0) { + const [batch, done] = this.autoBatchQueue.pop(batchSizeLimit); + if (!batch.length) { + done(); + break; + } + const batchesByDestination = batch.reduce((acc, item) => { + const apiUrl = item.apiUrl ?? this.apiUrl; + const apiKey = item.apiKey ?? this.apiKey; + const isDefault = item.apiKey === this.apiKey && item.apiUrl === this.apiUrl; + const batchKey = isDefault ? "default" : `${apiUrl}|${apiKey}`; + if (!acc[batchKey]) { + acc[batchKey] = []; + } + acc[batchKey].push(item); + return acc; + }, {}); + const batchPromises = []; + for (const [batchKey, batch2] of Object.entries(batchesByDestination)) { + const batchPromise = this._processBatch(batch2, { + apiUrl: batchKey === "default" ? void 0 : batchKey.split("|")[0], + apiKey: batchKey === "default" ? void 0 : batchKey.split("|")[1] + }); + batchPromises.push(batchPromise); + } + const allBatchesPromise = Promise.all(batchPromises).finally(done); + promises.push(allBatchesPromise); + } + return Promise.all(promises); + } + async _processBatch(batch, options) { + if (!batch.length) { + return; + } + try { + if (this.langSmithToOTELTranslator !== void 0) { + this._sendBatchToOTELTranslator(batch); + } else { + const ingestParams = { + runCreates: batch.filter((item) => item.action === "create").map((item) => item.item), + runUpdates: batch.filter((item) => item.action === "update").map((item) => item.item) + }; + const serverInfo = await this._ensureServerInfo(); + if (serverInfo?.batch_ingest_config?.use_multipart_endpoint) { + const useGzip = serverInfo?.instance_flags?.gzip_body_enabled; + await this.multipartIngestRuns(ingestParams, { ...options, useGzip }); + } else { + await this.batchIngestRuns(ingestParams, options); + } + } + } catch (e2) { + console.error("Error exporting batch:", e2); + } + } + _sendBatchToOTELTranslator(batch) { + if (this.langSmithToOTELTranslator !== void 0) { + const otelContextMap = /* @__PURE__ */ new Map(); + const operations = []; + for (const item of batch) { + if (item.item.id && item.otelContext) { + otelContextMap.set(item.item.id, item.otelContext); + if (item.action === "create") { + operations.push({ + operation: "post", + id: item.item.id, + trace_id: item.item.trace_id ?? item.item.id, + run: item.item + }); + } else { + operations.push({ + operation: "patch", + id: item.item.id, + trace_id: item.item.trace_id ?? item.item.id, + run: item.item + }); + } + } + } + this.langSmithToOTELTranslator.exportBatch(operations, otelContextMap); + } + } + async processRunOperation(item) { + clearTimeout(this.autoBatchTimeout); + this.autoBatchTimeout = void 0; + item.item = mergeRuntimeEnvIntoRun(item.item); + const itemPromise = this.autoBatchQueue.push(item); + if (this.manualFlushMode) { + return itemPromise; + } + const sizeLimitBytes = await this._getBatchSizeLimitBytes(); + if (this.autoBatchQueue.sizeBytes > sizeLimitBytes) { + void this.drainAutoBatchQueue(sizeLimitBytes); + } + if (this.autoBatchQueue.items.length > 0) { + this.autoBatchTimeout = setTimeout(() => { + this.autoBatchTimeout = void 0; + void this.drainAutoBatchQueue(sizeLimitBytes); + }, this.autoBatchAggregationDelayMs); + } + return itemPromise; + } + async _getServerInfo() { + const response = await this.caller.call(async () => { + const res = await _getFetchImplementation(this.debug)(`${this.apiUrl}/info`, { + method: "GET", + headers: { Accept: "application/json" }, + signal: AbortSignal.timeout(SERVER_INFO_REQUEST_TIMEOUT_MS), + ...this.fetchOptions + }); + await raiseForStatus(res, "get server info"); + return res; + }); + const json = await response.json(); + if (this.debug) { + console.log("\n=== LangSmith Server Configuration ===\n" + JSON.stringify(json, null, 2) + "\n"); + } + return json; + } + async _ensureServerInfo() { + if (this._getServerInfoPromise === void 0) { + this._getServerInfoPromise = (async () => { + if (this._serverInfo === void 0) { + try { + this._serverInfo = await this._getServerInfo(); + } catch (e2) { + console.warn(`[WARNING]: LangSmith failed to fetch info on supported operations with status code ${e2.status}. Falling back to batch operations and default limits.`); + } + } + return this._serverInfo ?? {}; + })(); + } + return this._getServerInfoPromise.then((serverInfo) => { + if (this._serverInfo === void 0) { + this._getServerInfoPromise = void 0; + } + return serverInfo; + }); + } + async _getSettings() { + if (!this.settings) { + this.settings = this._get("/settings"); + } + return await this.settings; + } + /** + * Flushes current queued traces. + */ + async flush() { + const sizeLimitBytes = await this._getBatchSizeLimitBytes(); + await this.drainAutoBatchQueue(sizeLimitBytes); + } + _cloneCurrentOTELContext() { + const otel_trace = getOTELTrace(); + const otel_context = getOTELContext(); + if (this.langSmithToOTELTranslator !== void 0) { + const currentSpan = otel_trace.getActiveSpan(); + if (currentSpan) { + return otel_trace.setSpan(otel_context.active(), currentSpan); + } + } + return void 0; + } + async createRun(run, options) { + if (!this._filterForSampling([run]).length) { + return; + } + const headers = { + ...this.headers, + "Content-Type": "application/json" + }; + const session_name = run.project_name; + delete run.project_name; + const runCreate = await this.prepareRunCreateOrUpdateInputs({ + session_name, + ...run, + start_time: run.start_time ?? Date.now() + }); + if (this.autoBatchTracing && runCreate.trace_id !== void 0 && runCreate.dotted_order !== void 0) { + const otelContext = this._cloneCurrentOTELContext(); + void this.processRunOperation({ + action: "create", + item: runCreate, + otelContext, + apiKey: options?.apiKey, + apiUrl: options?.apiUrl + }).catch(console.error); + return; + } + const mergedRunCreateParam = mergeRuntimeEnvIntoRun(runCreate); + if (options?.apiKey !== void 0) { + headers["x-api-key"] = options.apiKey; + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${options?.apiUrl ?? this.apiUrl}/runs`, { + method: "POST", + headers, + body: serialize(mergedRunCreateParam, `Creating run with id: ${mergedRunCreateParam.id}`), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "create run", true); + } + /** + * Batch ingest/upsert multiple runs in the Langsmith system. + * @param runs + */ + async batchIngestRuns({ runCreates, runUpdates }, options) { + if (runCreates === void 0 && runUpdates === void 0) { + return; + } + let preparedCreateParams = await Promise.all(runCreates?.map((create7) => this.prepareRunCreateOrUpdateInputs(create7)) ?? []); + let preparedUpdateParams = await Promise.all(runUpdates?.map((update2) => this.prepareRunCreateOrUpdateInputs(update2)) ?? []); + if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { + const createById = preparedCreateParams.reduce((params, run) => { + if (!run.id) { + return params; + } + params[run.id] = run; + return params; + }, {}); + const standaloneUpdates = []; + for (const updateParam of preparedUpdateParams) { + if (updateParam.id !== void 0 && createById[updateParam.id]) { + createById[updateParam.id] = { + ...createById[updateParam.id], + ...updateParam + }; + } else { + standaloneUpdates.push(updateParam); + } + } + preparedCreateParams = Object.values(createById); + preparedUpdateParams = standaloneUpdates; + } + const rawBatch = { + post: preparedCreateParams, + patch: preparedUpdateParams + }; + if (!rawBatch.post.length && !rawBatch.patch.length) { + return; + } + const batchChunks = { + post: [], + patch: [] + }; + for (const k3 of ["post", "patch"]) { + const key = k3; + const batchItems = rawBatch[key].reverse(); + let batchItem = batchItems.pop(); + while (batchItem !== void 0) { + batchChunks[key].push(batchItem); + batchItem = batchItems.pop(); + } + } + if (batchChunks.post.length > 0 || batchChunks.patch.length > 0) { + const runIds = batchChunks.post.map((item) => item.id).concat(batchChunks.patch.map((item) => item.id)).join(","); + await this._postBatchIngestRuns(serialize(batchChunks, `Ingesting runs with ids: ${runIds}`), options); + } + } + async _postBatchIngestRuns(body, options) { + const headers = { + ...this.headers, + "Content-Type": "application/json", + Accept: "application/json" + }; + if (options?.apiKey !== void 0) { + headers["x-api-key"] = options.apiKey; + } + const response = await this.batchIngestCaller.call(_getFetchImplementation(this.debug), `${options?.apiUrl ?? this.apiUrl}/runs/batch`, { + method: "POST", + headers, + body, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "batch create run", true); + } + /** + * Batch ingest/upsert multiple runs in the Langsmith system. + * @param runs + */ + async multipartIngestRuns({ runCreates, runUpdates }, options) { + if (runCreates === void 0 && runUpdates === void 0) { + return; + } + const allAttachments = {}; + let preparedCreateParams = []; + for (const create7 of runCreates ?? []) { + const preparedCreate = await this.prepareRunCreateOrUpdateInputs(create7); + if (preparedCreate.id !== void 0 && preparedCreate.attachments !== void 0) { + allAttachments[preparedCreate.id] = preparedCreate.attachments; + } + delete preparedCreate.attachments; + preparedCreateParams.push(preparedCreate); + } + let preparedUpdateParams = []; + for (const update2 of runUpdates ?? []) { + preparedUpdateParams.push(await this.prepareRunCreateOrUpdateInputs(update2)); + } + const invalidRunCreate = preparedCreateParams.find((runCreate) => { + return runCreate.trace_id === void 0 || runCreate.dotted_order === void 0; + }); + if (invalidRunCreate !== void 0) { + throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run`); + } + const invalidRunUpdate = preparedUpdateParams.find((runUpdate) => { + return runUpdate.trace_id === void 0 || runUpdate.dotted_order === void 0; + }); + if (invalidRunUpdate !== void 0) { + throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run`); + } + if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { + const createById = preparedCreateParams.reduce((params, run) => { + if (!run.id) { + return params; + } + params[run.id] = run; + return params; + }, {}); + const standaloneUpdates = []; + for (const updateParam of preparedUpdateParams) { + if (updateParam.id !== void 0 && createById[updateParam.id]) { + createById[updateParam.id] = { + ...createById[updateParam.id], + ...updateParam + }; + } else { + standaloneUpdates.push(updateParam); + } + } + preparedCreateParams = Object.values(createById); + preparedUpdateParams = standaloneUpdates; + } + if (preparedCreateParams.length === 0 && preparedUpdateParams.length === 0) { + return; + } + const accumulatedContext = []; + const accumulatedParts = []; + for (const [method, payloads] of [ + ["post", preparedCreateParams], + ["patch", preparedUpdateParams] + ]) { + for (const originalPayload of payloads) { + const { inputs, outputs, events, extra, error, serialized, attachments, ...payload } = originalPayload; + const fields = { inputs, outputs, events, extra, error, serialized }; + const stringifiedPayload = serialize(payload, `Serializing for multipart ingestion of run with id: ${payload.id}`); + accumulatedParts.push({ + name: `${method}.${payload.id}`, + payload: new Blob([stringifiedPayload], { + type: `application/json; length=${stringifiedPayload.length}` + // encoding=gzip + }) + }); + for (const [key, value] of Object.entries(fields)) { + if (value === void 0) { + continue; + } + const stringifiedValue = serialize(value, `Serializing ${key} for multipart ingestion of run with id: ${payload.id}`); + accumulatedParts.push({ + name: `${method}.${payload.id}.${key}`, + payload: new Blob([stringifiedValue], { + type: `application/json; length=${stringifiedValue.length}` + }) + }); + } + if (payload.id !== void 0) { + const attachments2 = allAttachments[payload.id]; + if (attachments2) { + delete allAttachments[payload.id]; + for (const [name, attachment] of Object.entries(attachments2)) { + let contentType; + let content; + if (Array.isArray(attachment)) { + [contentType, content] = attachment; + } else { + contentType = attachment.mimeType; + content = attachment.data; + } + if (name.includes(".")) { + console.warn(`Skipping attachment '${name}' for run ${payload.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`); + continue; + } + accumulatedParts.push({ + name: `attachment.${payload.id}.${name}`, + payload: new Blob([content], { + type: `${contentType}; length=${content.byteLength}` + }) + }); + } + } + } + accumulatedContext.push(`trace=${payload.trace_id},id=${payload.id}`); + } + } + await this._sendMultipartRequest(accumulatedParts, accumulatedContext.join("; "), options); + } + async _createNodeFetchBody(parts, boundary) { + const chunks = []; + for (const part of parts) { + chunks.push(new Blob([`--${boundary}\r +`])); + chunks.push(new Blob([ + `Content-Disposition: form-data; name="${part.name}"\r +`, + `Content-Type: ${part.payload.type}\r +\r +` + ])); + chunks.push(part.payload); + chunks.push(new Blob(["\r\n"])); + } + chunks.push(new Blob([`--${boundary}--\r +`])); + const body = new Blob(chunks); + const arrayBuffer = await body.arrayBuffer(); + return arrayBuffer; + } + async _createMultipartStream(parts, boundary) { + const encoder2 = new TextEncoder(); + const stream = new ReadableStream({ + async start(controller) { + const writeChunk = async (chunk) => { + if (typeof chunk === "string") { + controller.enqueue(encoder2.encode(chunk)); + } else { + controller.enqueue(chunk); + } + }; + for (const part of parts) { + await writeChunk(`--${boundary}\r +`); + await writeChunk(`Content-Disposition: form-data; name="${part.name}"\r +`); + await writeChunk(`Content-Type: ${part.payload.type}\r +\r +`); + const payloadStream = part.payload.stream(); + const reader = payloadStream.getReader(); + try { + let result; + while (!(result = await reader.read()).done) { + controller.enqueue(result.value); + } + } finally { + reader.releaseLock(); + } + await writeChunk("\r\n"); + } + await writeChunk(`--${boundary}--\r +`); + controller.close(); + } + }); + return stream; + } + async _sendMultipartRequest(parts, context, options) { + const boundary = "----LangSmithFormBoundary" + Math.random().toString(36).slice(2); + const isNodeFetch = _globalFetchImplementationIsNodeFetch(); + const buildBuffered = () => this._createNodeFetchBody(parts, boundary); + const buildStream = () => this._createMultipartStream(parts, boundary); + const send = async (body) => { + const headers = { + ...this.headers, + "Content-Type": `multipart/form-data; boundary=${boundary}` + }; + if (options?.apiKey !== void 0) { + headers["x-api-key"] = options.apiKey; + } + let transformedBody = body; + if (options?.useGzip && typeof body === "object" && "pipeThrough" in body) { + transformedBody = body.pipeThrough(new CompressionStream("gzip")); + headers["Content-Encoding"] = "gzip"; + } + return this.batchIngestCaller.call(_getFetchImplementation(this.debug), `${options?.apiUrl ?? this.apiUrl}/runs/multipart`, { + method: "POST", + headers, + body: transformedBody, + duplex: "half", + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + }; + try { + let res; + let streamedAttempt = false; + if (!isNodeFetch && !this.multipartStreamingDisabled) { + streamedAttempt = true; + res = await send(await buildStream()); + } else { + res = await send(await buildBuffered()); + } + if ((!this.multipartStreamingDisabled || streamedAttempt) && res.status === 422 && (options?.apiUrl ?? this.apiUrl) !== DEFAULT_API_URL) { + console.warn(`Streaming multipart upload to ${options?.apiUrl ?? this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${context}".`); + this.multipartStreamingDisabled = true; + res = await send(await buildBuffered()); + } + await raiseForStatus(res, "ingest multipart runs", true); + } catch (e2) { + console.warn(`${e2.message.trim()} + +Context: ${context}`); + } + } + async updateRun(runId, run, options) { + assertUuid(runId); + if (run.inputs) { + run.inputs = await this.processInputs(run.inputs); + } + if (run.outputs) { + run.outputs = await this.processOutputs(run.outputs); + } + const data = { ...run, id: runId }; + if (!this._filterForSampling([data], true).length) { + return; + } + if (this.autoBatchTracing && data.trace_id !== void 0 && data.dotted_order !== void 0) { + const otelContext = this._cloneCurrentOTELContext(); + if (run.end_time !== void 0 && data.parent_run_id === void 0 && this.blockOnRootRunFinalization && !this.manualFlushMode) { + await this.processRunOperation({ + action: "update", + item: data, + otelContext, + apiKey: options?.apiKey, + apiUrl: options?.apiUrl + }).catch(console.error); + return; + } else { + void this.processRunOperation({ + action: "update", + item: data, + otelContext, + apiKey: options?.apiKey, + apiUrl: options?.apiUrl + }).catch(console.error); + } + return; + } + const headers = { + ...this.headers, + "Content-Type": "application/json" + }; + if (options?.apiKey !== void 0) { + headers["x-api-key"] = options.apiKey; + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${options?.apiUrl ?? this.apiUrl}/runs/${runId}`, { + method: "PATCH", + headers, + body: serialize(run, `Serializing payload to update run with id: ${runId}`), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "update run", true); + } + async readRun(runId, { loadChildRuns } = { loadChildRuns: false }) { + assertUuid(runId); + let run = await this._get(`/runs/${runId}`); + if (loadChildRuns) { + run = await this._loadChildRuns(run); + } + return run; + } + async getRunUrl({ runId, run, projectOpts }) { + if (run !== void 0) { + let sessionId; + if (run.session_id) { + sessionId = run.session_id; + } else if (projectOpts?.projectName) { + sessionId = (await this.readProject({ projectName: projectOpts?.projectName })).id; + } else if (projectOpts?.projectId) { + sessionId = projectOpts?.projectId; + } else { + const project = await this.readProject({ + projectName: getLangSmithEnvironmentVariable("PROJECT") || "default" + }); + sessionId = project.id; + } + const tenantId = await this._getTenantId(); + return `${this.getHostUrl()}/o/${tenantId}/projects/p/${sessionId}/r/${run.id}?poll=true`; + } else if (runId !== void 0) { + const run_ = await this.readRun(runId); + if (!run_.app_path) { + throw new Error(`Run ${runId} has no app_path`); + } + const baseUrl = this.getHostUrl(); + return `${baseUrl}${run_.app_path}`; + } else { + throw new Error("Must provide either runId or run"); + } + } + async _loadChildRuns(run) { + const childRuns = await toArray(this.listRuns({ + isRoot: false, + projectId: run.session_id, + traceId: run.trace_id + })); + const treemap = {}; + const runs = {}; + childRuns.sort((a2, b3) => (a2?.dotted_order ?? "").localeCompare(b3?.dotted_order ?? "")); + for (const childRun of childRuns) { + if (childRun.parent_run_id === null || childRun.parent_run_id === void 0) { + throw new Error(`Child run ${childRun.id} has no parent`); + } + if (childRun.dotted_order?.startsWith(run.dotted_order ?? "") && childRun.id !== run.id) { + if (!(childRun.parent_run_id in treemap)) { + treemap[childRun.parent_run_id] = []; + } + treemap[childRun.parent_run_id].push(childRun); + runs[childRun.id] = childRun; + } + } + run.child_runs = treemap[run.id] || []; + for (const runId in treemap) { + if (runId !== run.id) { + runs[runId].child_runs = treemap[runId]; + } + } + return run; + } + /** + * List runs from the LangSmith server. + * @param projectId - The ID of the project to filter by. + * @param projectName - The name of the project to filter by. + * @param parentRunId - The ID of the parent run to filter by. + * @param traceId - The ID of the trace to filter by. + * @param referenceExampleId - The ID of the reference example to filter by. + * @param startTime - The start time to filter by. + * @param isRoot - Indicates whether to only return root runs. + * @param runType - The run type to filter by. + * @param error - Indicates whether to filter by error runs. + * @param id - The ID of the run to filter by. + * @param query - The query string to filter by. + * @param filter - The filter string to apply to the run spans. + * @param traceFilter - The filter string to apply on the root run of the trace. + * @param treeFilter - The filter string to apply on other runs in the trace. + * @param limit - The maximum number of runs to retrieve. + * @returns {AsyncIterable} - The runs. + * + * @example + * // List all runs in a project + * const projectRuns = client.listRuns({ projectName: "" }); + * + * @example + * // List LLM and Chat runs in the last 24 hours + * const todaysLLMRuns = client.listRuns({ + * projectName: "", + * start_time: new Date(Date.now() - 24 * 60 * 60 * 1000), + * run_type: "llm", + * }); + * + * @example + * // List traces in a project + * const rootRuns = client.listRuns({ + * projectName: "", + * execution_order: 1, + * }); + * + * @example + * // List runs without errors + * const correctRuns = client.listRuns({ + * projectName: "", + * error: false, + * }); + * + * @example + * // List runs by run ID + * const runIds = [ + * "a36092d2-4ad5-4fb4-9c0d-0dba9a2ed836", + * "9398e6be-964f-4aa4-8ae9-ad78cd4b7074", + * ]; + * const selectedRuns = client.listRuns({ run_ids: runIds }); + * + * @example + * // List all "chain" type runs that took more than 10 seconds and had `total_tokens` greater than 5000 + * const chainRuns = client.listRuns({ + * projectName: "", + * filter: 'and(eq(run_type, "chain"), gt(latency, 10), gt(total_tokens, 5000))', + * }); + * + * @example + * // List all runs called "extractor" whose root of the trace was assigned feedback "user_score" score of 1 + * const goodExtractorRuns = client.listRuns({ + * projectName: "", + * filter: 'eq(name, "extractor")', + * traceFilter: 'and(eq(feedback_key, "user_score"), eq(feedback_score, 1))', + * }); + * + * @example + * // List all runs that started after a specific timestamp and either have "error" not equal to null or a "Correctness" feedback score equal to 0 + * const complexRuns = client.listRuns({ + * projectName: "", + * filter: 'and(gt(start_time, "2023-07-15T12:34:56Z"), or(neq(error, null), and(eq(feedback_key, "Correctness"), eq(feedback_score, 0.0))))', + * }); + * + * @example + * // List all runs where `tags` include "experimental" or "beta" and `latency` is greater than 2 seconds + * const taggedRuns = client.listRuns({ + * projectName: "", + * filter: 'and(or(has(tags, "experimental"), has(tags, "beta")), gt(latency, 2))', + * }); + */ + async *listRuns(props) { + const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, isRoot, runType, error, id, query, filter, traceFilter, treeFilter, limit, select, order } = props; + let projectIds = []; + if (projectId) { + projectIds = Array.isArray(projectId) ? projectId : [projectId]; + } + if (projectName) { + const projectNames = Array.isArray(projectName) ? projectName : [projectName]; + const projectIds_ = await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id))); + projectIds.push(...projectIds_); + } + const default_select = [ + "app_path", + "completion_cost", + "completion_tokens", + "dotted_order", + "end_time", + "error", + "events", + "extra", + "feedback_stats", + "first_token_time", + "id", + "inputs", + "name", + "outputs", + "parent_run_id", + "parent_run_ids", + "prompt_cost", + "prompt_tokens", + "reference_example_id", + "run_type", + "session_id", + "start_time", + "status", + "tags", + "total_cost", + "total_tokens", + "trace_id" + ]; + const body = { + session: projectIds.length ? projectIds : null, + run_type: runType, + reference_example: referenceExampleId, + query, + filter, + trace_filter: traceFilter, + tree_filter: treeFilter, + execution_order: executionOrder, + parent_run: parentRunId, + start_time: startTime ? startTime.toISOString() : null, + error, + id, + limit, + trace: traceId, + select: select ? select : default_select, + is_root: isRoot, + order + }; + let runsYielded = 0; + for await (const runs of this._getCursorPaginatedList("/runs/query", body)) { + if (limit) { + if (runsYielded >= limit) { + break; + } + if (runs.length + runsYielded > limit) { + const newRuns = runs.slice(0, limit - runsYielded); + yield* newRuns; + break; + } + runsYielded += runs.length; + yield* runs; + } else { + yield* runs; + } + } + } + async *listGroupRuns(props) { + const { projectId, projectName, groupBy, filter, startTime, endTime, limit, offset } = props; + const sessionId = projectId || (await this.readProject({ projectName })).id; + const baseBody = { + session_id: sessionId, + group_by: groupBy, + filter, + start_time: startTime ? startTime.toISOString() : null, + end_time: endTime ? endTime.toISOString() : null, + limit: Number(limit) || 100 + }; + let currentOffset = Number(offset) || 0; + const path = "/runs/group"; + const url = `${this.apiUrl}${path}`; + while (true) { + const currentBody = { + ...baseBody, + offset: currentOffset + }; + const filteredPayload = Object.fromEntries(Object.entries(currentBody).filter(([_2, value]) => value !== void 0)); + const response = await this.caller.call(_getFetchImplementation(), url, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(filteredPayload), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, `Failed to fetch ${path}`); + const items = await response.json(); + const { groups, total } = items; + if (groups.length === 0) { + break; + } + for (const thread of groups) { + yield thread; + } + currentOffset += groups.length; + if (currentOffset >= total) { + break; + } + } + } + async getRunStats({ id, trace, parentRun, runType, projectNames, projectIds, referenceExampleIds, startTime, endTime, error, query, filter, traceFilter, treeFilter, isRoot, dataSourceType }) { + let projectIds_ = projectIds || []; + if (projectNames) { + projectIds_ = [ + ...projectIds || [], + ...await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id))) + ]; + } + const payload = { + id, + trace, + parent_run: parentRun, + run_type: runType, + session: projectIds_, + reference_example: referenceExampleIds, + start_time: startTime, + end_time: endTime, + error, + query, + filter, + trace_filter: traceFilter, + tree_filter: treeFilter, + is_root: isRoot, + data_source_type: dataSourceType + }; + const filteredPayload = Object.fromEntries(Object.entries(payload).filter(([_2, value]) => value !== void 0)); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/stats`, { + method: "POST", + headers: this.headers, + body: JSON.stringify(filteredPayload), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + const result = await response.json(); + return result; + } + async shareRun(runId, { shareId } = {}) { + const data = { + run_id: runId, + share_token: shareId || v4_default() + }; + assertUuid(runId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { + method: "PUT", + headers: this.headers, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + const result = await response.json(); + if (result === null || !("share_token" in result)) { + throw new Error("Invalid response from server"); + } + return `${this.getHostUrl()}/public/${result["share_token"]}/r`; + } + async unshareRun(runId) { + assertUuid(runId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "unshare run", true); + } + async readRunSharedLink(runId) { + assertUuid(runId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/runs/${runId}/share`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + const result = await response.json(); + if (result === null || !("share_token" in result)) { + return void 0; + } + return `${this.getHostUrl()}/public/${result["share_token"]}/r`; + } + async listSharedRuns(shareToken, { runIds } = {}) { + const queryParams = new URLSearchParams({ + share_token: shareToken + }); + if (runIds !== void 0) { + for (const runId of runIds) { + queryParams.append("id", runId); + } + } + assertUuid(shareToken); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/runs${queryParams}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + const runs = await response.json(); + return runs; + } + async readDatasetSharedSchema(datasetId, datasetName) { + if (!datasetId && !datasetName) { + throw new Error("Either datasetId or datasetName must be given"); + } + if (!datasetId) { + const dataset = await this.readDataset({ datasetName }); + datasetId = dataset.id; + } + assertUuid(datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + const shareSchema = await response.json(); + shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; + return shareSchema; + } + async shareDataset(datasetId, datasetName) { + if (!datasetId && !datasetName) { + throw new Error("Either datasetId or datasetName must be given"); + } + if (!datasetId) { + const dataset = await this.readDataset({ datasetName }); + datasetId = dataset.id; + } + const data = { + dataset_id: datasetId + }; + assertUuid(datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { + method: "PUT", + headers: this.headers, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + const shareSchema = await response.json(); + shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; + return shareSchema; + } + async unshareDataset(datasetId) { + assertUuid(datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/share`, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "unshare dataset", true); + } + async readSharedDataset(shareToken) { + assertUuid(shareToken); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/datasets`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + const dataset = await response.json(); + return dataset; + } + /** + * Get shared examples. + * + * @param {string} shareToken The share token to get examples for. A share token is the UUID (or LangSmith URL, including UUID) generated when explicitly marking an example as public. + * @param {Object} [options] Additional options for listing the examples. + * @param {string[] | undefined} [options.exampleIds] A list of example IDs to filter by. + * @returns {Promise} The shared examples. + */ + async listSharedExamples(shareToken, options) { + const params = {}; + if (options?.exampleIds) { + params.id = options.exampleIds; + } + const urlParams = new URLSearchParams(); + Object.entries(params).forEach(([key, value]) => { + if (Array.isArray(value)) { + value.forEach((v6) => urlParams.append(key, v6)); + } else { + urlParams.append(key, value); + } + }); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/public/${shareToken}/examples?${urlParams.toString()}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + const result = await response.json(); + if (!response.ok) { + if ("detail" in result) { + throw new Error(`Failed to list shared examples. +Status: ${response.status} +Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecified error"}`); + } + throw new Error(`Failed to list shared examples: ${response.status} ${response.statusText}`); + } + return result.map((example) => ({ + ...example, + _hostUrl: this.getHostUrl() + })); + } + async createProject({ projectName, description = null, metadata = null, upsert: upsert2 = false, projectExtra = null, referenceDatasetId = null }) { + const upsert_ = upsert2 ? `?upsert=true` : ""; + const endpoint = `${this.apiUrl}/sessions${upsert_}`; + const extra = projectExtra || {}; + if (metadata) { + extra["metadata"] = metadata; + } + const body = { + name: projectName, + extra, + description + }; + if (referenceDatasetId !== null) { + body["reference_dataset_id"] = referenceDatasetId; + } + const response = await this.caller.call(_getFetchImplementation(this.debug), endpoint, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "create project"); + const result = await response.json(); + return result; + } + async updateProject(projectId, { name = null, description = null, metadata = null, projectExtra = null, endTime = null }) { + const endpoint = `${this.apiUrl}/sessions/${projectId}`; + let extra = projectExtra; + if (metadata) { + extra = { ...extra || {}, metadata }; + } + const body = { + name, + extra, + description, + end_time: endTime ? new Date(endTime).toISOString() : null + }; + const response = await this.caller.call(_getFetchImplementation(this.debug), endpoint, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "update project"); + const result = await response.json(); + return result; + } + async hasProject({ projectId, projectName }) { + let path = "/sessions"; + const params = new URLSearchParams(); + if (projectId !== void 0 && projectName !== void 0) { + throw new Error("Must provide either projectName or projectId, not both"); + } else if (projectId !== void 0) { + assertUuid(projectId); + path += `/${projectId}`; + } else if (projectName !== void 0) { + params.append("name", projectName); + } else { + throw new Error("Must provide projectName or projectId"); + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${path}?${params}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + try { + const result = await response.json(); + if (!response.ok) { + return false; + } + if (Array.isArray(result)) { + return result.length > 0; + } + return true; + } catch (e2) { + return false; + } + } + async readProject({ projectId, projectName, includeStats }) { + let path = "/sessions"; + const params = new URLSearchParams(); + if (projectId !== void 0 && projectName !== void 0) { + throw new Error("Must provide either projectName or projectId, not both"); + } else if (projectId !== void 0) { + assertUuid(projectId); + path += `/${projectId}`; + } else if (projectName !== void 0) { + params.append("name", projectName); + } else { + throw new Error("Must provide projectName or projectId"); + } + if (includeStats !== void 0) { + params.append("include_stats", includeStats.toString()); + } + const response = await this._get(path, params); + let result; + if (Array.isArray(response)) { + if (response.length === 0) { + throw new Error(`Project[id=${projectId}, name=${projectName}] not found`); + } + result = response[0]; + } else { + result = response; + } + return result; + } + async getProjectUrl({ projectId, projectName }) { + if (projectId === void 0 && projectName === void 0) { + throw new Error("Must provide either projectName or projectId"); + } + const project = await this.readProject({ projectId, projectName }); + const tenantId = await this._getTenantId(); + return `${this.getHostUrl()}/o/${tenantId}/projects/p/${project.id}`; + } + async getDatasetUrl({ datasetId, datasetName }) { + if (datasetId === void 0 && datasetName === void 0) { + throw new Error("Must provide either datasetName or datasetId"); + } + const dataset = await this.readDataset({ datasetId, datasetName }); + const tenantId = await this._getTenantId(); + return `${this.getHostUrl()}/o/${tenantId}/datasets/${dataset.id}`; + } + async _getTenantId() { + if (this._tenantId !== null) { + return this._tenantId; + } + const queryParams = new URLSearchParams({ limit: "1" }); + for await (const projects of this._getPaginated("/sessions", queryParams)) { + this._tenantId = projects[0].tenant_id; + return projects[0].tenant_id; + } + throw new Error("No projects found to resolve tenant."); + } + async *listProjects({ projectIds, name, nameContains, referenceDatasetId, referenceDatasetName, referenceFree, metadata } = {}) { + const params = new URLSearchParams(); + if (projectIds !== void 0) { + for (const projectId of projectIds) { + params.append("id", projectId); + } + } + if (name !== void 0) { + params.append("name", name); + } + if (nameContains !== void 0) { + params.append("name_contains", nameContains); + } + if (referenceDatasetId !== void 0) { + params.append("reference_dataset", referenceDatasetId); + } else if (referenceDatasetName !== void 0) { + const dataset = await this.readDataset({ + datasetName: referenceDatasetName + }); + params.append("reference_dataset", dataset.id); + } + if (referenceFree !== void 0) { + params.append("reference_free", referenceFree.toString()); + } + if (metadata !== void 0) { + params.append("metadata", JSON.stringify(metadata)); + } + for await (const projects of this._getPaginated("/sessions", params)) { + yield* projects; + } + } + async deleteProject({ projectId, projectName }) { + let projectId_; + if (projectId === void 0 && projectName === void 0) { + throw new Error("Must provide projectName or projectId"); + } else if (projectId !== void 0 && projectName !== void 0) { + throw new Error("Must provide either projectName or projectId, not both"); + } else if (projectId === void 0) { + projectId_ = (await this.readProject({ projectName })).id; + } else { + projectId_ = projectId; + } + assertUuid(projectId_); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/sessions/${projectId_}`, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, `delete session ${projectId_} (${projectName})`, true); + } + async uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description, dataType, name }) { + const url = `${this.apiUrl}/datasets/upload`; + const formData = new FormData(); + formData.append("file", csvFile, fileName); + inputKeys.forEach((key) => { + formData.append("input_keys", key); + }); + outputKeys.forEach((key) => { + formData.append("output_keys", key); + }); + if (description) { + formData.append("description", description); + } + if (dataType) { + formData.append("data_type", dataType); + } + if (name) { + formData.append("name", name); + } + const response = await this.caller.call(_getFetchImplementation(this.debug), url, { + method: "POST", + headers: this.headers, + body: formData, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "upload CSV"); + const result = await response.json(); + return result; + } + async createDataset(name, { description, dataType, inputsSchema, outputsSchema, metadata } = {}) { + const body = { + name, + description, + extra: metadata ? { metadata } : void 0 + }; + if (dataType) { + body.data_type = dataType; + } + if (inputsSchema) { + body.inputs_schema_definition = inputsSchema; + } + if (outputsSchema) { + body.outputs_schema_definition = outputsSchema; + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "create dataset"); + const result = await response.json(); + return result; + } + async readDataset({ datasetId, datasetName }) { + let path = "/datasets"; + const params = new URLSearchParams({ limit: "1" }); + if (datasetId && datasetName) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } else if (datasetId) { + assertUuid(datasetId); + path += `/${datasetId}`; + } else if (datasetName) { + params.append("name", datasetName); + } else { + throw new Error("Must provide datasetName or datasetId"); + } + const response = await this._get(path, params); + let result; + if (Array.isArray(response)) { + if (response.length === 0) { + throw new Error(`Dataset[id=${datasetId}, name=${datasetName}] not found`); + } + result = response[0]; + } else { + result = response; + } + return result; + } + async hasDataset({ datasetId, datasetName }) { + try { + await this.readDataset({ datasetId, datasetName }); + return true; + } catch (e2) { + if ( + // eslint-disable-next-line no-instanceof/no-instanceof + e2 instanceof Error && e2.message.toLocaleLowerCase().includes("not found") + ) { + return false; + } + throw e2; + } + } + async diffDatasetVersions({ datasetId, datasetName, fromVersion, toVersion }) { + let datasetId_ = datasetId; + if (datasetId_ === void 0 && datasetName === void 0) { + throw new Error("Must provide either datasetName or datasetId"); + } else if (datasetId_ !== void 0 && datasetName !== void 0) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } else if (datasetId_ === void 0) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + const urlParams = new URLSearchParams({ + from_version: typeof fromVersion === "string" ? fromVersion : fromVersion.toISOString(), + to_version: typeof toVersion === "string" ? toVersion : toVersion.toISOString() + }); + const response = await this._get(`/datasets/${datasetId_}/versions/diff`, urlParams); + return response; + } + async readDatasetOpenaiFinetuning({ datasetId, datasetName }) { + const path = "/datasets"; + if (datasetId !== void 0) { + } else if (datasetName !== void 0) { + datasetId = (await this.readDataset({ datasetName })).id; + } else { + throw new Error("Must provide either datasetName or datasetId"); + } + const response = await this._getResponse(`${path}/${datasetId}/openai_ft`); + const datasetText = await response.text(); + const dataset = datasetText.trim().split("\n").map((line) => JSON.parse(line)); + return dataset; + } + async *listDatasets({ limit = 100, offset = 0, datasetIds, datasetName, datasetNameContains, metadata } = {}) { + const path = "/datasets"; + const params = new URLSearchParams({ + limit: limit.toString(), + offset: offset.toString() + }); + if (datasetIds !== void 0) { + for (const id_ of datasetIds) { + params.append("id", id_); + } + } + if (datasetName !== void 0) { + params.append("name", datasetName); + } + if (datasetNameContains !== void 0) { + params.append("name_contains", datasetNameContains); + } + if (metadata !== void 0) { + params.append("metadata", JSON.stringify(metadata)); + } + for await (const datasets of this._getPaginated(path, params)) { + yield* datasets; + } + } + /** + * Update a dataset + * @param props The dataset details to update + * @returns The updated dataset + */ + async updateDataset(props) { + const { datasetId, datasetName, ...update2 } = props; + if (!datasetId && !datasetName) { + throw new Error("Must provide either datasetName or datasetId"); + } + const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; + assertUuid(_datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${_datasetId}`, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(update2), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "update dataset"); + return await response.json(); + } + /** + * Updates a tag on a dataset. + * + * If the tag is already assigned to a different version of this dataset, + * the tag will be moved to the new version. The as_of parameter is used to + * determine which version of the dataset to apply the new tags to. + * + * It must be an exact version of the dataset to succeed. You can + * use the "readDatasetVersion" method to find the exact version + * to apply the tags to. + * @param params.datasetId The ID of the dataset to update. Must be provided if "datasetName" is not provided. + * @param params.datasetName The name of the dataset to update. Must be provided if "datasetId" is not provided. + * @param params.asOf The timestamp of the dataset to apply the new tags to. + * @param params.tag The new tag to apply to the dataset. + */ + async updateDatasetTag(props) { + const { datasetId, datasetName, asOf, tag } = props; + if (!datasetId && !datasetName) { + throw new Error("Must provide either datasetName or datasetId"); + } + const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; + assertUuid(_datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${_datasetId}/tags`, { + method: "PUT", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify({ + as_of: typeof asOf === "string" ? asOf : asOf.toISOString(), + tag + }), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "update dataset tags"); + } + async deleteDataset({ datasetId, datasetName }) { + let path = "/datasets"; + let datasetId_ = datasetId; + if (datasetId !== void 0 && datasetName !== void 0) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } else if (datasetName !== void 0) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + if (datasetId_ !== void 0) { + assertUuid(datasetId_); + path += `/${datasetId_}`; + } else { + throw new Error("Must provide datasetName or datasetId"); + } + const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, `delete ${path}`); + await response.json(); + } + async indexDataset({ datasetId, datasetName, tag }) { + let datasetId_ = datasetId; + if (!datasetId_ && !datasetName) { + throw new Error("Must provide either datasetName or datasetId"); + } else if (datasetId_ && datasetName) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } else if (!datasetId_) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + assertUuid(datasetId_); + const data = { + tag + }; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId_}/index`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "index dataset"); + await response.json(); + } + /** + * Lets you run a similarity search query on a dataset. + * + * Requires the dataset to be indexed. Please see the `indexDataset` method to set up indexing. + * + * @param inputs The input on which to run the similarity search. Must have the + * same schema as the dataset. + * + * @param datasetId The dataset to search for similar examples. + * + * @param limit The maximum number of examples to return. Will return the top `limit` most + * similar examples in order of most similar to least similar. If no similar + * examples are found, random examples will be returned. + * + * @param filter A filter string to apply to the search. Only examples will be returned that + * match the filter string. Some examples of filters + * + * - eq(metadata.mykey, "value") + * - and(neq(metadata.my.nested.key, "value"), neq(metadata.mykey, "value")) + * - or(eq(metadata.mykey, "value"), eq(metadata.mykey, "othervalue")) + * + * @returns A list of similar examples. + * + * + * @example + * dataset_id = "123e4567-e89b-12d3-a456-426614174000" + * inputs = {"text": "How many people live in Berlin?"} + * limit = 5 + * examples = await client.similarExamples(inputs, dataset_id, limit) + */ + async similarExamples(inputs, datasetId, limit, { filter } = {}) { + const data = { + limit, + inputs + }; + if (filter !== void 0) { + data["filter"] = filter; + } + assertUuid(datasetId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId}/search`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "fetch similar examples"); + const result = await response.json(); + return result["examples"]; + } + async createExample(inputsOrUpdate, outputs, options) { + if (isExampleCreate(inputsOrUpdate)) { + if (outputs !== void 0 || options !== void 0) { + throw new Error("Cannot provide outputs or options when using ExampleCreate object"); + } + } + let datasetId_ = outputs ? options?.datasetId : inputsOrUpdate.dataset_id; + const datasetName_ = outputs ? options?.datasetName : inputsOrUpdate.dataset_name; + if (datasetId_ === void 0 && datasetName_ === void 0) { + throw new Error("Must provide either datasetName or datasetId"); + } else if (datasetId_ !== void 0 && datasetName_ !== void 0) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } else if (datasetId_ === void 0) { + const dataset = await this.readDataset({ datasetName: datasetName_ }); + datasetId_ = dataset.id; + } + const createdAt_ = (outputs ? options?.createdAt : inputsOrUpdate.created_at) || /* @__PURE__ */ new Date(); + let data; + if (!isExampleCreate(inputsOrUpdate)) { + data = { + inputs: inputsOrUpdate, + outputs, + created_at: createdAt_?.toISOString(), + id: options?.exampleId, + metadata: options?.metadata, + split: options?.split, + source_run_id: options?.sourceRunId, + use_source_run_io: options?.useSourceRunIO, + use_source_run_attachments: options?.useSourceRunAttachments, + attachments: options?.attachments + }; + } else { + data = inputsOrUpdate; + } + const response = await this._uploadExamplesMultipart(datasetId_, [data]); + const example = await this.readExample(response.example_ids?.[0] ?? v4_default()); + return example; + } + async createExamples(propsOrUploads) { + if (Array.isArray(propsOrUploads)) { + if (propsOrUploads.length === 0) { + return []; + } + const uploads = propsOrUploads; + let datasetId_2 = uploads[0].dataset_id; + const datasetName_2 = uploads[0].dataset_name; + if (datasetId_2 === void 0 && datasetName_2 === void 0) { + throw new Error("Must provide either datasetName or datasetId"); + } else if (datasetId_2 !== void 0 && datasetName_2 !== void 0) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } else if (datasetId_2 === void 0) { + const dataset = await this.readDataset({ datasetName: datasetName_2 }); + datasetId_2 = dataset.id; + } + const response2 = await this._uploadExamplesMultipart(datasetId_2, uploads); + const examples2 = await Promise.all(response2.example_ids.map((id) => this.readExample(id))); + return examples2; + } + const { inputs, outputs, metadata, splits, sourceRunIds, useSourceRunIOs, useSourceRunAttachments, attachments, exampleIds, datasetId, datasetName } = propsOrUploads; + if (inputs === void 0) { + throw new Error("Must provide inputs when using legacy parameters"); + } + let datasetId_ = datasetId; + const datasetName_ = datasetName; + if (datasetId_ === void 0 && datasetName_ === void 0) { + throw new Error("Must provide either datasetName or datasetId"); + } else if (datasetId_ !== void 0 && datasetName_ !== void 0) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } else if (datasetId_ === void 0) { + const dataset = await this.readDataset({ datasetName: datasetName_ }); + datasetId_ = dataset.id; + } + const formattedExamples = inputs.map((input, idx) => { + return { + dataset_id: datasetId_, + inputs: input, + outputs: outputs?.[idx], + metadata: metadata?.[idx], + split: splits?.[idx], + id: exampleIds?.[idx], + attachments: attachments?.[idx], + source_run_id: sourceRunIds?.[idx], + use_source_run_io: useSourceRunIOs?.[idx], + use_source_run_attachments: useSourceRunAttachments?.[idx] + }; + }); + const response = await this._uploadExamplesMultipart(datasetId_, formattedExamples); + const examples = await Promise.all(response.example_ids.map((id) => this.readExample(id))); + return examples; + } + async createLLMExample(input, generation, options) { + return this.createExample({ input }, { output: generation }, options); + } + async createChatExample(input, generations, options) { + const finalInput = input.map((message) => { + if (isLangChainMessage(message)) { + return convertLangChainMessageToExample(message); + } + return message; + }); + const finalOutput = isLangChainMessage(generations) ? convertLangChainMessageToExample(generations) : generations; + return this.createExample({ input: finalInput }, { output: finalOutput }, options); + } + async readExample(exampleId) { + assertUuid(exampleId); + const path = `/examples/${exampleId}`; + const rawExample = await this._get(path); + const { attachment_urls, ...rest } = rawExample; + const example = rest; + if (attachment_urls) { + example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { + acc[key.slice("attachment.".length)] = { + presigned_url: value.presigned_url, + mime_type: value.mime_type + }; + return acc; + }, {}); + } + return example; + } + async *listExamples({ datasetId, datasetName, exampleIds, asOf, splits, inlineS3Urls, metadata, limit, offset, filter, includeAttachments } = {}) { + let datasetId_; + if (datasetId !== void 0 && datasetName !== void 0) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } else if (datasetId !== void 0) { + datasetId_ = datasetId; + } else if (datasetName !== void 0) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } else { + throw new Error("Must provide a datasetName or datasetId"); + } + const params = new URLSearchParams({ dataset: datasetId_ }); + const dataset_version = asOf ? typeof asOf === "string" ? asOf : asOf?.toISOString() : void 0; + if (dataset_version) { + params.append("as_of", dataset_version); + } + const inlineS3Urls_ = inlineS3Urls ?? true; + params.append("inline_s3_urls", inlineS3Urls_.toString()); + if (exampleIds !== void 0) { + for (const id_ of exampleIds) { + params.append("id", id_); + } + } + if (splits !== void 0) { + for (const split of splits) { + params.append("splits", split); + } + } + if (metadata !== void 0) { + const serializedMetadata = JSON.stringify(metadata); + params.append("metadata", serializedMetadata); + } + if (limit !== void 0) { + params.append("limit", limit.toString()); + } + if (offset !== void 0) { + params.append("offset", offset.toString()); + } + if (filter !== void 0) { + params.append("filter", filter); + } + if (includeAttachments === true) { + ["attachment_urls", "outputs", "metadata"].forEach((field) => params.append("select", field)); + } + let i2 = 0; + for await (const rawExamples of this._getPaginated("/examples", params)) { + for (const rawExample of rawExamples) { + const { attachment_urls, ...rest } = rawExample; + const example = rest; + if (attachment_urls) { + example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { + acc[key.slice("attachment.".length)] = { + presigned_url: value.presigned_url, + mime_type: value.mime_type || void 0 + }; + return acc; + }, {}); + } + yield example; + i2++; + } + if (limit !== void 0 && i2 >= limit) { + break; + } + } + } + async deleteExample(exampleId) { + assertUuid(exampleId); + const path = `/examples/${exampleId}`; + const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, `delete ${path}`); + await response.json(); + } + async updateExample(exampleIdOrUpdate, update2) { + let exampleId; + if (update2) { + exampleId = exampleIdOrUpdate; + } else { + exampleId = exampleIdOrUpdate.id; + } + assertUuid(exampleId); + let updateToUse; + if (update2) { + updateToUse = { id: exampleId, ...update2 }; + } else { + updateToUse = exampleIdOrUpdate; + } + let datasetId; + if (updateToUse.dataset_id !== void 0) { + datasetId = updateToUse.dataset_id; + } else { + const example = await this.readExample(exampleId); + datasetId = example.dataset_id; + } + return this._updateExamplesMultipart(datasetId, [updateToUse]); + } + async updateExamples(update2) { + let datasetId; + if (update2[0].dataset_id === void 0) { + const example = await this.readExample(update2[0].id); + datasetId = example.dataset_id; + } else { + datasetId = update2[0].dataset_id; + } + return this._updateExamplesMultipart(datasetId, update2); + } + /** + * Get dataset version by closest date or exact tag. + * + * Use this to resolve the nearest version to a given timestamp or for a given tag. + * + * @param options The options for getting the dataset version + * @param options.datasetId The ID of the dataset + * @param options.datasetName The name of the dataset + * @param options.asOf The timestamp of the dataset to retrieve + * @param options.tag The tag of the dataset to retrieve + * @returns The dataset version + */ + async readDatasetVersion({ datasetId, datasetName, asOf, tag }) { + let resolvedDatasetId; + if (!datasetId) { + const dataset = await this.readDataset({ datasetName }); + resolvedDatasetId = dataset.id; + } else { + resolvedDatasetId = datasetId; + } + assertUuid(resolvedDatasetId); + if (asOf && tag || !asOf && !tag) { + throw new Error("Exactly one of asOf and tag must be specified."); + } + const params = new URLSearchParams(); + if (asOf !== void 0) { + params.append("as_of", typeof asOf === "string" ? asOf : asOf.toISOString()); + } + if (tag !== void 0) { + params.append("tag", tag); + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${resolvedDatasetId}/version?${params.toString()}`, { + method: "GET", + headers: { ...this.headers }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "read dataset version"); + return await response.json(); + } + async listDatasetSplits({ datasetId, datasetName, asOf }) { + let datasetId_; + if (datasetId === void 0 && datasetName === void 0) { + throw new Error("Must provide dataset name or ID"); + } else if (datasetId !== void 0 && datasetName !== void 0) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } else if (datasetId === void 0) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } else { + datasetId_ = datasetId; + } + assertUuid(datasetId_); + const params = new URLSearchParams(); + const dataset_version = asOf ? typeof asOf === "string" ? asOf : asOf?.toISOString() : void 0; + if (dataset_version) { + params.append("as_of", dataset_version); + } + const response = await this._get(`/datasets/${datasetId_}/splits`, params); + return response; + } + async updateDatasetSplits({ datasetId, datasetName, splitName, exampleIds, remove: remove6 = false }) { + let datasetId_; + if (datasetId === void 0 && datasetName === void 0) { + throw new Error("Must provide dataset name or ID"); + } else if (datasetId !== void 0 && datasetName !== void 0) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } else if (datasetId === void 0) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } else { + datasetId_ = datasetId; + } + assertUuid(datasetId_); + const data = { + split_name: splitName, + examples: exampleIds.map((id) => { + assertUuid(id); + return id; + }), + remove: remove6 + }; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/${datasetId_}/splits`, { + method: "PUT", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "update dataset splits", true); + } + /** + * @deprecated This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead. + */ + async evaluateRun(run, evaluator, { sourceInfo, loadChildRuns, referenceExample } = { loadChildRuns: false }) { + warnOnce("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead."); + let run_; + if (typeof run === "string") { + run_ = await this.readRun(run, { loadChildRuns }); + } else if (typeof run === "object" && "id" in run) { + run_ = run; + } else { + throw new Error(`Invalid run type: ${typeof run}`); + } + if (run_.reference_example_id !== null && run_.reference_example_id !== void 0) { + referenceExample = await this.readExample(run_.reference_example_id); + } + const feedbackResult = await evaluator.evaluateRun(run_, referenceExample); + const [_2, feedbacks] = await this._logEvaluationFeedback(feedbackResult, run_, sourceInfo); + return feedbacks[0]; + } + async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "api", sourceRunId, feedbackId, feedbackConfig, projectId, comparativeExperimentId }) { + if (!runId && !projectId) { + throw new Error("One of runId or projectId must be provided"); + } + if (runId && projectId) { + throw new Error("Only one of runId or projectId can be provided"); + } + const feedback_source = { + type: feedbackSourceType ?? "api", + metadata: sourceInfo ?? {} + }; + if (sourceRunId !== void 0 && feedback_source?.metadata !== void 0 && !feedback_source.metadata["__run"]) { + feedback_source.metadata["__run"] = { run_id: sourceRunId }; + } + if (feedback_source?.metadata !== void 0 && feedback_source.metadata["__run"]?.run_id !== void 0) { + assertUuid(feedback_source.metadata["__run"].run_id); + } + const feedback = { + id: feedbackId ?? v4_default(), + run_id: runId, + key, + score: _formatFeedbackScore(score), + value, + correction, + comment, + feedback_source, + comparative_experiment_id: comparativeExperimentId, + feedbackConfig, + session_id: projectId + }; + const url = `${this.apiUrl}/feedback`; + const response = await this.caller.call(_getFetchImplementation(this.debug), url, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(feedback), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "create feedback", true); + return feedback; + } + async updateFeedback(feedbackId, { score, value, correction, comment }) { + const feedbackUpdate = {}; + if (score !== void 0 && score !== null) { + feedbackUpdate["score"] = _formatFeedbackScore(score); + } + if (value !== void 0 && value !== null) { + feedbackUpdate["value"] = value; + } + if (correction !== void 0 && correction !== null) { + feedbackUpdate["correction"] = correction; + } + if (comment !== void 0 && comment !== null) { + feedbackUpdate["comment"] = comment; + } + assertUuid(feedbackId); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/feedback/${feedbackId}`, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(feedbackUpdate), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "update feedback", true); + } + async readFeedback(feedbackId) { + assertUuid(feedbackId); + const path = `/feedback/${feedbackId}`; + const response = await this._get(path); + return response; + } + async deleteFeedback(feedbackId) { + assertUuid(feedbackId); + const path = `/feedback/${feedbackId}`; + const response = await this.caller.call(_getFetchImplementation(this.debug), this.apiUrl + path, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, `delete ${path}`); + await response.json(); + } + async *listFeedback({ runIds, feedbackKeys, feedbackSourceTypes } = {}) { + const queryParams = new URLSearchParams(); + if (runIds) { + queryParams.append("run", runIds.join(",")); + } + if (feedbackKeys) { + for (const key of feedbackKeys) { + queryParams.append("key", key); + } + } + if (feedbackSourceTypes) { + for (const type of feedbackSourceTypes) { + queryParams.append("source", type); + } + } + for await (const feedbacks of this._getPaginated("/feedback", queryParams)) { + yield* feedbacks; + } + } + /** + * Creates a presigned feedback token and URL. + * + * The token can be used to authorize feedback metrics without + * needing an API key. This is useful for giving browser-based + * applications the ability to submit feedback without needing + * to expose an API key. + * + * @param runId The ID of the run. + * @param feedbackKey The feedback key. + * @param options Additional options for the token. + * @param options.expiration The expiration time for the token. + * + * @returns A promise that resolves to a FeedbackIngestToken. + */ + async createPresignedFeedbackToken(runId, feedbackKey, { expiration, feedbackConfig } = {}) { + const body = { + run_id: runId, + feedback_key: feedbackKey, + feedback_config: feedbackConfig + }; + if (expiration) { + if (typeof expiration === "string") { + body["expires_at"] = expiration; + } else if (expiration?.hours || expiration?.minutes || expiration?.days) { + body["expires_in"] = expiration; + } + } else { + body["expires_in"] = { + hours: 3 + }; + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/feedback/tokens`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + const result = await response.json(); + return result; + } + async createComparativeExperiment({ name, experimentIds, referenceDatasetId, createdAt, description, metadata, id }) { + if (experimentIds.length === 0) { + throw new Error("At least one experiment is required"); + } + if (!referenceDatasetId) { + referenceDatasetId = (await this.readProject({ + projectId: experimentIds[0] + })).reference_dataset_id; + } + if (!referenceDatasetId == null) { + throw new Error("A reference dataset is required"); + } + const body = { + id, + name, + experiment_ids: experimentIds, + reference_dataset_id: referenceDatasetId, + description, + created_at: (createdAt ?? /* @__PURE__ */ new Date())?.toISOString(), + extra: {} + }; + if (metadata) + body.extra["metadata"] = metadata; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/datasets/comparative`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + return await response.json(); + } + /** + * Retrieves a list of presigned feedback tokens for a given run ID. + * @param runId The ID of the run. + * @returns An async iterable of FeedbackIngestToken objects. + */ + async *listPresignedFeedbackTokens(runId) { + assertUuid(runId); + const params = new URLSearchParams({ run_id: runId }); + for await (const tokens of this._getPaginated("/feedback/tokens", params)) { + yield* tokens; + } + } + _selectEvalResults(results) { + let results_; + if ("results" in results) { + results_ = results.results; + } else if (Array.isArray(results)) { + results_ = results; + } else { + results_ = [results]; + } + return results_; + } + async _logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { + const evalResults = this._selectEvalResults(evaluatorResponse); + const feedbacks = []; + for (const res of evalResults) { + let sourceInfo_ = sourceInfo || {}; + if (res.evaluatorInfo) { + sourceInfo_ = { ...res.evaluatorInfo, ...sourceInfo_ }; + } + let runId_ = null; + if (res.targetRunId) { + runId_ = res.targetRunId; + } else if (run) { + runId_ = run.id; + } + feedbacks.push(await this.createFeedback(runId_, res.key, { + score: res.score, + value: res.value, + comment: res.comment, + correction: res.correction, + sourceInfo: sourceInfo_, + sourceRunId: res.sourceRunId, + feedbackConfig: res.feedbackConfig, + feedbackSourceType: "model" + })); + } + return [evalResults, feedbacks]; + } + async logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { + const [results] = await this._logEvaluationFeedback(evaluatorResponse, run, sourceInfo); + return results; + } + /** + * API for managing annotation queues + */ + /** + * List the annotation queues on the LangSmith API. + * @param options - The options for listing annotation queues + * @param options.queueIds - The IDs of the queues to filter by + * @param options.name - The name of the queue to filter by + * @param options.nameContains - The substring that the queue name should contain + * @param options.limit - The maximum number of queues to return + * @returns An iterator of AnnotationQueue objects + */ + async *listAnnotationQueues(options = {}) { + const { queueIds, name, nameContains, limit } = options; + const params = new URLSearchParams(); + if (queueIds) { + queueIds.forEach((id, i2) => { + assertUuid(id, `queueIds[${i2}]`); + params.append("ids", id); + }); + } + if (name) + params.append("name", name); + if (nameContains) + params.append("name_contains", nameContains); + params.append("limit", (limit !== void 0 ? Math.min(limit, 100) : 100).toString()); + let count3 = 0; + for await (const queues of this._getPaginated("/annotation-queues", params)) { + yield* queues; + count3++; + if (limit !== void 0 && count3 >= limit) + break; + } + } + /** + * Create an annotation queue on the LangSmith API. + * @param options - The options for creating an annotation queue + * @param options.name - The name of the annotation queue + * @param options.description - The description of the annotation queue + * @param options.queueId - The ID of the annotation queue + * @returns The created AnnotationQueue object + */ + async createAnnotationQueue(options) { + const { name, description, queueId, rubricInstructions } = options; + const body = { + name, + description, + id: queueId || v4_default(), + rubric_instructions: rubricInstructions + }; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(Object.fromEntries(Object.entries(body).filter(([_2, v6]) => v6 !== void 0))), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "create annotation queue"); + const data = await response.json(); + return data; + } + /** + * Read an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue to read + * @returns The AnnotationQueueWithDetails object + */ + async readAnnotationQueue(queueId) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "read annotation queue"); + const data = await response.json(); + return data; + } + /** + * Update an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue to update + * @param options - The options for updating the annotation queue + * @param options.name - The new name for the annotation queue + * @param options.description - The new description for the annotation queue + */ + async updateAnnotationQueue(queueId, options) { + const { name, description, rubricInstructions } = options; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify({ + name, + description, + rubric_instructions: rubricInstructions + }), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "update annotation queue"); + } + /** + * Delete an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue to delete + */ + async deleteAnnotationQueue(queueId) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { + method: "DELETE", + headers: { ...this.headers, Accept: "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "delete annotation queue"); + } + /** + * Add runs to an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue + * @param runIds - The IDs of the runs to be added to the annotation queue + */ + async addRunsToAnnotationQueue(queueId, runIds) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(runIds.map((id, i2) => assertUuid(id, `runIds[${i2}]`).toString())), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "add runs to annotation queue"); + } + /** + * Get a run from an annotation queue at the specified index. + * @param queueId - The ID of the annotation queue + * @param index - The index of the run to retrieve + * @returns A Promise that resolves to a RunWithAnnotationQueueInfo object + * @throws {Error} If the run is not found at the given index or for other API-related errors + */ + async getRunFromAnnotationQueue(queueId, index2) { + const baseUrl = `/annotation-queues/${assertUuid(queueId, "queueId")}/run`; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${baseUrl}/${index2}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "get run from annotation queue"); + return await response.json(); + } + /** + * Delete a run from an an annotation queue. + * @param queueId - The ID of the annotation queue to delete the run from + * @param queueRunId - The ID of the run to delete from the annotation queue + */ + async deleteRunFromAnnotationQueue(queueId, queueRunId) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs/${assertUuid(queueRunId, "queueRunId")}`, { + method: "DELETE", + headers: { ...this.headers, Accept: "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "delete run from annotation queue"); + } + /** + * Get the size of an annotation queue. + * @param queueId - The ID of the annotation queue + */ + async getSizeFromAnnotationQueue(queueId) { + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/size`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "get size from annotation queue"); + return await response.json(); + } + async _currentTenantIsOwner(owner) { + const settings = await this._getSettings(); + return owner == "-" || settings.tenant_handle === owner; + } + async _ownerConflictError(action, owner) { + const settings = await this._getSettings(); + return new Error(`Cannot ${action} for another tenant. + + Current tenant: ${settings.tenant_handle} + + Requested tenant: ${owner}`); + } + async _getLatestCommitHash(promptOwnerAndName) { + const res = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${promptOwnerAndName}/?limit=${1}&offset=${0}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + const json = await res.json(); + if (!res.ok) { + const detail = typeof json.detail === "string" ? json.detail : JSON.stringify(json.detail); + const error = new Error(`Error ${res.status}: ${res.statusText} +${detail}`); + error.statusCode = res.status; + throw error; + } + if (json.commits.length === 0) { + return void 0; + } + return json.commits[0].commit_hash; + } + async _likeOrUnlikePrompt(promptIdentifier, like) { + const [owner, promptName, _2] = parsePromptIdentifier(promptIdentifier); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/likes/${owner}/${promptName}`, { + method: "POST", + body: JSON.stringify({ like }), + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, `${like ? "like" : "unlike"} prompt`); + return await response.json(); + } + async _getPromptUrl(promptIdentifier) { + const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier); + if (!await this._currentTenantIsOwner(owner)) { + if (commitHash !== "latest") { + return `${this.getHostUrl()}/hub/${owner}/${promptName}/${commitHash.substring(0, 8)}`; + } else { + return `${this.getHostUrl()}/hub/${owner}/${promptName}`; + } + } else { + const settings = await this._getSettings(); + if (commitHash !== "latest") { + return `${this.getHostUrl()}/prompts/${promptName}/${commitHash.substring(0, 8)}?organizationId=${settings.id}`; + } else { + return `${this.getHostUrl()}/prompts/${promptName}?organizationId=${settings.id}`; + } + } + } + async promptExists(promptIdentifier) { + const prompt = await this.getPrompt(promptIdentifier); + return !!prompt; + } + async likePrompt(promptIdentifier) { + return this._likeOrUnlikePrompt(promptIdentifier, true); + } + async unlikePrompt(promptIdentifier) { + return this._likeOrUnlikePrompt(promptIdentifier, false); + } + async *listCommits(promptOwnerAndName) { + for await (const commits of this._getPaginated(`/commits/${promptOwnerAndName}/`, new URLSearchParams(), (res) => res.commits)) { + yield* commits; + } + } + async *listPrompts(options) { + const params = new URLSearchParams(); + params.append("sort_field", options?.sortField ?? "updated_at"); + params.append("sort_direction", "desc"); + params.append("is_archived", (!!options?.isArchived).toString()); + if (options?.isPublic !== void 0) { + params.append("is_public", options.isPublic.toString()); + } + if (options?.query) { + params.append("query", options.query); + } + for await (const prompts of this._getPaginated("/repos", params, (res) => res.repos)) { + yield* prompts; + } + } + async getPrompt(promptIdentifier) { + const [owner, promptName, _2] = parsePromptIdentifier(promptIdentifier); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + if (response.status === 404) { + return null; + } + await raiseForStatus(response, "get prompt"); + const result = await response.json(); + if (result.repo) { + return result.repo; + } else { + return null; + } + } + async createPrompt(promptIdentifier, options) { + const settings = await this._getSettings(); + if (options?.isPublic && !settings.tenant_handle) { + throw new Error(`Cannot create a public prompt without first + + creating a LangChain Hub handle. + You can add a handle by creating a public prompt at: + + https://smith.langchain.com/prompts`); + } + const [owner, promptName, _2] = parsePromptIdentifier(promptIdentifier); + if (!await this._currentTenantIsOwner(owner)) { + throw await this._ownerConflictError("create a prompt", owner); + } + const data = { + repo_handle: promptName, + ...options?.description && { description: options.description }, + ...options?.readme && { readme: options.readme }, + ...options?.tags && { tags: options.tags }, + is_public: !!options?.isPublic + }; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(data), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "create prompt"); + const { repo } = await response.json(); + return repo; + } + async createCommit(promptIdentifier, object, options) { + if (!await this.promptExists(promptIdentifier)) { + throw new Error("Prompt does not exist, you must create it first."); + } + const [owner, promptName, _2] = parsePromptIdentifier(promptIdentifier); + const resolvedParentCommitHash = options?.parentCommitHash === "latest" || !options?.parentCommitHash ? await this._getLatestCommitHash(`${owner}/${promptName}`) : options?.parentCommitHash; + const payload = { + manifest: JSON.parse(JSON.stringify(object)), + parent_commit: resolvedParentCommitHash + }; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${owner}/${promptName}`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify(payload), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "create commit"); + const result = await response.json(); + return this._getPromptUrl(`${owner}/${promptName}${result.commit_hash ? `:${result.commit_hash}` : ""}`); + } + /** + * Update examples with attachments using multipart form data. + * @param updates List of ExampleUpdateWithAttachments objects to upsert + * @returns Promise with the update response + */ + async updateExamplesMultipart(datasetId, updates = []) { + return this._updateExamplesMultipart(datasetId, updates); + } + async _updateExamplesMultipart(datasetId, updates = []) { + if (!await this._getDatasetExamplesMultiPartSupport()) { + throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); + } + const formData = new FormData(); + for (const example of updates) { + const exampleId = example.id; + const exampleBody = { + ...example.metadata && { metadata: example.metadata }, + ...example.split && { split: example.split } + }; + const stringifiedExample = serialize(exampleBody, `Serializing body for example with id: ${exampleId}`); + const exampleBlob = new Blob([stringifiedExample], { + type: "application/json" + }); + formData.append(exampleId, exampleBlob); + if (example.inputs) { + const stringifiedInputs = serialize(example.inputs, `Serializing inputs for example with id: ${exampleId}`); + const inputsBlob = new Blob([stringifiedInputs], { + type: "application/json" + }); + formData.append(`${exampleId}.inputs`, inputsBlob); + } + if (example.outputs) { + const stringifiedOutputs = serialize(example.outputs, `Serializing outputs whle updating example with id: ${exampleId}`); + const outputsBlob = new Blob([stringifiedOutputs], { + type: "application/json" + }); + formData.append(`${exampleId}.outputs`, outputsBlob); + } + if (example.attachments) { + for (const [name, attachment] of Object.entries(example.attachments)) { + let mimeType; + let data; + if (Array.isArray(attachment)) { + [mimeType, data] = attachment; + } else { + mimeType = attachment.mimeType; + data = attachment.data; + } + const attachmentBlob = new Blob([data], { + type: `${mimeType}; length=${data.byteLength}` + }); + formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); + } + } + if (example.attachments_operations) { + const stringifiedAttachmentsOperations = serialize(example.attachments_operations, `Serializing attachments while updating example with id: ${exampleId}`); + const attachmentsOperationsBlob = new Blob([stringifiedAttachmentsOperations], { + type: "application/json" + }); + formData.append(`${exampleId}.attachments_operations`, attachmentsOperationsBlob); + } + } + const datasetIdToUse = datasetId ?? updates[0]?.dataset_id; + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${datasetIdToUse}/examples`)}`, { + method: "PATCH", + headers: this.headers, + body: formData + }); + const result = await response.json(); + return result; + } + /** + * Upload examples with attachments using multipart form data. + * @param uploads List of ExampleUploadWithAttachments objects to upload + * @returns Promise with the upload response + * @deprecated This method is deprecated and will be removed in future LangSmith versions, please use `createExamples` instead + */ + async uploadExamplesMultipart(datasetId, uploads = []) { + return this._uploadExamplesMultipart(datasetId, uploads); + } + async _uploadExamplesMultipart(datasetId, uploads = []) { + if (!await this._getDatasetExamplesMultiPartSupport()) { + throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); + } + const formData = new FormData(); + for (const example of uploads) { + const exampleId = (example.id ?? v4_default()).toString(); + const exampleBody = { + created_at: example.created_at, + ...example.metadata && { metadata: example.metadata }, + ...example.split && { split: example.split }, + ...example.source_run_id && { source_run_id: example.source_run_id }, + ...example.use_source_run_io && { + use_source_run_io: example.use_source_run_io + }, + ...example.use_source_run_attachments && { + use_source_run_attachments: example.use_source_run_attachments + } + }; + const stringifiedExample = serialize(exampleBody, `Serializing body for uploaded example with id: ${exampleId}`); + const exampleBlob = new Blob([stringifiedExample], { + type: "application/json" + }); + formData.append(exampleId, exampleBlob); + if (example.inputs) { + const stringifiedInputs = serialize(example.inputs, `Serializing inputs for uploaded example with id: ${exampleId}`); + const inputsBlob = new Blob([stringifiedInputs], { + type: "application/json" + }); + formData.append(`${exampleId}.inputs`, inputsBlob); + } + if (example.outputs) { + const stringifiedOutputs = serialize(example.outputs, `Serializing outputs for uploaded example with id: ${exampleId}`); + const outputsBlob = new Blob([stringifiedOutputs], { + type: "application/json" + }); + formData.append(`${exampleId}.outputs`, outputsBlob); + } + if (example.attachments) { + for (const [name, attachment] of Object.entries(example.attachments)) { + let mimeType; + let data; + if (Array.isArray(attachment)) { + [mimeType, data] = attachment; + } else { + mimeType = attachment.mimeType; + data = attachment.data; + } + const attachmentBlob = new Blob([data], { + type: `${mimeType}; length=${data.byteLength}` + }); + formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); + } + } + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${datasetId}/examples`)}`, { + method: "POST", + headers: this.headers, + body: formData + }); + await raiseForStatus(response, "upload examples"); + const result = await response.json(); + return result; + } + async updatePrompt(promptIdentifier, options) { + if (!await this.promptExists(promptIdentifier)) { + throw new Error("Prompt does not exist, you must create it first."); + } + const [owner, promptName] = parsePromptIdentifier(promptIdentifier); + if (!await this._currentTenantIsOwner(owner)) { + throw await this._ownerConflictError("update a prompt", owner); + } + const payload = {}; + if (options?.description !== void 0) + payload.description = options.description; + if (options?.readme !== void 0) + payload.readme = options.readme; + if (options?.tags !== void 0) + payload.tags = options.tags; + if (options?.isPublic !== void 0) + payload.is_public = options.isPublic; + if (options?.isArchived !== void 0) + payload.is_archived = options.isArchived; + if (Object.keys(payload).length === 0) { + throw new Error("No valid update options provided"); + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { + method: "PATCH", + body: JSON.stringify(payload), + headers: { + ...this.headers, + "Content-Type": "application/json" + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "update prompt"); + return response.json(); + } + async deletePrompt(promptIdentifier) { + if (!await this.promptExists(promptIdentifier)) { + throw new Error("Prompt does not exist, you must create it first."); + } + const [owner, promptName, _2] = parsePromptIdentifier(promptIdentifier); + if (!await this._currentTenantIsOwner(owner)) { + throw await this._ownerConflictError("delete a prompt", owner); + } + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/repos/${owner}/${promptName}`, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + return await response.json(); + } + async pullPromptCommit(promptIdentifier, options) { + const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier); + const response = await this.caller.call(_getFetchImplementation(this.debug), `${this.apiUrl}/commits/${owner}/${promptName}/${commitHash}${options?.includeModel ? "?include_model=true" : ""}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions + }); + await raiseForStatus(response, "pull prompt commit"); + const result = await response.json(); + return { + owner, + repo: promptName, + commit_hash: result.commit_hash, + manifest: result.manifest, + examples: result.examples + }; + } + /** + * This method should not be used directly, use `import { pull } from "langchain/hub"` instead. + * Using this method directly returns the JSON string of the prompt rather than a LangChain object. + * @private + */ + async _pullPrompt(promptIdentifier, options) { + const promptObject = await this.pullPromptCommit(promptIdentifier, { + includeModel: options?.includeModel + }); + const prompt = JSON.stringify(promptObject.manifest); + return prompt; + } + async pushPrompt(promptIdentifier, options) { + if (await this.promptExists(promptIdentifier)) { + if (options && Object.keys(options).some((key) => key !== "object")) { + await this.updatePrompt(promptIdentifier, { + description: options?.description, + readme: options?.readme, + tags: options?.tags, + isPublic: options?.isPublic + }); + } + } else { + await this.createPrompt(promptIdentifier, { + description: options?.description, + readme: options?.readme, + tags: options?.tags, + isPublic: options?.isPublic + }); + } + if (!options?.object) { + return await this._getPromptUrl(promptIdentifier); + } + const url = await this.createCommit(promptIdentifier, options?.object, { + parentCommitHash: options?.parentCommitHash + }); + return url; + } + /** + * Clone a public dataset to your own langsmith tenant. + * This operation is idempotent. If you already have a dataset with the given name, + * this function will do nothing. + + * @param {string} tokenOrUrl The token of the public dataset to clone. + * @param {Object} [options] Additional options for cloning the dataset. + * @param {string} [options.sourceApiUrl] The URL of the langsmith server where the data is hosted. Defaults to the API URL of your current client. + * @param {string} [options.datasetName] The name of the dataset to create in your tenant. Defaults to the name of the public dataset. + * @returns {Promise} + */ + async clonePublicDataset(tokenOrUrl, options = {}) { + const { sourceApiUrl = this.apiUrl, datasetName } = options; + const [parsedApiUrl, tokenUuid] = this.parseTokenOrUrl(tokenOrUrl, sourceApiUrl); + const sourceClient = new _Client({ + apiUrl: parsedApiUrl, + // Placeholder API key not needed anymore in most cases, but + // some private deployments may have API key-based rate limiting + // that would cause this to fail if we provide no value. + apiKey: "placeholder" + }); + const ds = await sourceClient.readSharedDataset(tokenUuid); + const finalDatasetName = datasetName || ds.name; + try { + if (await this.hasDataset({ datasetId: finalDatasetName })) { + console.log(`Dataset ${finalDatasetName} already exists in your tenant. Skipping.`); + return; + } + } catch (_2) { + } + const examples = await sourceClient.listSharedExamples(tokenUuid); + const dataset = await this.createDataset(finalDatasetName, { + description: ds.description, + dataType: ds.data_type || "kv", + inputsSchema: ds.inputs_schema_definition ?? void 0, + outputsSchema: ds.outputs_schema_definition ?? void 0 + }); + try { + await this.createExamples({ + inputs: examples.map((e2) => e2.inputs), + outputs: examples.flatMap((e2) => e2.outputs ? [e2.outputs] : []), + datasetId: dataset.id + }); + } catch (e2) { + console.error(`An error occurred while creating dataset ${finalDatasetName}. You should delete it manually.`); + throw e2; + } + } + parseTokenOrUrl(urlOrToken, apiUrl, numParts = 2, kind = "dataset") { + try { + assertUuid(urlOrToken); + return [apiUrl, urlOrToken]; + } catch (_2) { + } + try { + const parsedUrl = new URL(urlOrToken); + const pathParts = parsedUrl.pathname.split("/").filter((part) => part !== ""); + if (pathParts.length >= numParts) { + const tokenUuid = pathParts[pathParts.length - numParts]; + return [apiUrl, tokenUuid]; + } else { + throw new Error(`Invalid public ${kind} URL: ${urlOrToken}`); + } + } catch (error) { + throw new Error(`Invalid public ${kind} URL or token: ${urlOrToken}`); + } + } + /** + * Awaits all pending trace batches. Useful for environments where + * you need to be sure that all tracing requests finish before execution ends, + * such as serverless environments. + * + * @example + * ``` + * import { Client } from "langsmith"; + * + * const client = new Client(); + * + * try { + * // Tracing happens here + * ... + * } finally { + * await client.awaitPendingTraceBatches(); + * } + * ``` + * + * @returns A promise that resolves once all currently pending traces have sent. + */ + async awaitPendingTraceBatches() { + if (this.manualFlushMode) { + console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."); + return Promise.resolve(); + } + await Promise.all([ + ...this.autoBatchQueue.items.map(({ itemPromise }) => itemPromise), + this.batchIngestCaller.queue.onIdle() + ]); + if (this.langSmithToOTELTranslator !== void 0) { + await getDefaultOTLPTracerComponents()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush(); + } + } + }; + function isExampleCreate(input) { + return "dataset_id" in input || "dataset_name" in input; + } + + // node_modules/langsmith/dist/env.js + var isTracingEnabled = (tracingEnabled) => { + if (tracingEnabled !== void 0) { + return tracingEnabled; + } + const envVars = ["TRACING_V2", "TRACING"]; + return !!envVars.find((envVar) => getLangSmithEnvironmentVariable(envVar) === "true"); + }; + + // node_modules/langsmith/dist/singletons/constants.js + var _LC_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); + + // node_modules/langsmith/dist/run_trees.js + function stripNonAlphanumeric(input) { + return input.replace(/[-:.]/g, ""); + } + function convertToDottedOrderFormat(epoch, runId, executionOrder = 1) { + const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0"); + const microsecondPrecisionDatestring = `${new Date(epoch).toISOString().slice(0, -1)}${paddedOrder}Z`; + return { + dottedOrder: stripNonAlphanumeric(microsecondPrecisionDatestring) + runId, + microsecondPrecisionDatestring + }; + } + var Baggage = class _Baggage { + constructor(metadata, tags, project_name, replicas) { + Object.defineProperty(this, "metadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "project_name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "replicas", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.metadata = metadata; + this.tags = tags; + this.project_name = project_name; + this.replicas = replicas; + } + static fromHeader(value) { + const items = value.split(","); + let metadata = {}; + let tags = []; + let project_name; + let replicas; + for (const item of items) { + const [key, uriValue] = item.split("="); + const value2 = decodeURIComponent(uriValue); + if (key === "langsmith-metadata") { + metadata = JSON.parse(value2); + } else if (key === "langsmith-tags") { + tags = value2.split(","); + } else if (key === "langsmith-project") { + project_name = value2; + } else if (key === "langsmith-replicas") { + replicas = JSON.parse(value2); + } + } + return new _Baggage(metadata, tags, project_name, replicas); + } + toHeader() { + const items = []; + if (this.metadata && Object.keys(this.metadata).length > 0) { + items.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`); + } + if (this.tags && this.tags.length > 0) { + items.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`); + } + if (this.project_name) { + items.push(`langsmith-project=${encodeURIComponent(this.project_name)}`); + } + return items.join(","); + } + }; + var RunTree = class _RunTree { + constructor(originalConfig) { + Object.defineProperty(this, "id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "run_type", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "project_name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "parent_run", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "parent_run_id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "child_runs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "start_time", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "end_time", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "extra", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "error", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "serialized", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "outputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "reference_example_id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "client", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "events", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "trace_id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "dotted_order", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tracingEnabled", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "execution_order", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "child_execution_order", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "attachments", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "replicas", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_serialized_start_time", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + if (isRunTree(originalConfig)) { + Object.assign(this, { ...originalConfig }); + return; + } + const defaultConfig = _RunTree.getDefaultConfig(); + const { metadata, ...config } = originalConfig; + const client2 = config.client ?? _RunTree.getSharedClient(); + const dedupedMetadata = { + ...metadata, + ...config?.extra?.metadata + }; + config.extra = { ...config.extra, metadata: dedupedMetadata }; + Object.assign(this, { ...defaultConfig, ...config, client: client2 }); + if (!this.trace_id) { + if (this.parent_run) { + this.trace_id = this.parent_run.trace_id ?? this.id; + } else { + this.trace_id = this.id; + } + } + this.replicas = _ensureWriteReplicas(this.replicas); + this.execution_order ??= 1; + this.child_execution_order ??= 1; + if (!this.dotted_order) { + const { dottedOrder, microsecondPrecisionDatestring } = convertToDottedOrderFormat(this.start_time, this.id, this.execution_order); + if (this.parent_run) { + this.dotted_order = this.parent_run.dotted_order + "." + dottedOrder; + } else { + this.dotted_order = dottedOrder; + } + this._serialized_start_time = microsecondPrecisionDatestring; + } + } + set metadata(metadata) { + this.extra = { + ...this.extra, + metadata: { + ...this.extra?.metadata, + ...metadata + } + }; + } + get metadata() { + return this.extra?.metadata; + } + static getDefaultConfig() { + return { + id: v4_default(), + run_type: "chain", + project_name: getDefaultProjectName(), + child_runs: [], + api_url: getEnvironmentVariable("LANGCHAIN_ENDPOINT") ?? "http://localhost:1984", + api_key: getEnvironmentVariable("LANGCHAIN_API_KEY"), + caller_options: {}, + start_time: Date.now(), + serialized: {}, + inputs: {}, + extra: {} + }; + } + static getSharedClient() { + if (!_RunTree.sharedClient) { + _RunTree.sharedClient = new Client(); + } + return _RunTree.sharedClient; + } + createChild(config) { + const child_execution_order = this.child_execution_order + 1; + const child = new _RunTree({ + ...config, + parent_run: this, + project_name: this.project_name, + replicas: this.replicas, + client: this.client, + tracingEnabled: this.tracingEnabled, + execution_order: child_execution_order, + child_execution_order + }); + if (_LC_CONTEXT_VARIABLES_KEY in this) { + child[_LC_CONTEXT_VARIABLES_KEY] = this[_LC_CONTEXT_VARIABLES_KEY]; + } + const LC_CHILD = Symbol.for("lc:child_config"); + const presentConfig = config.extra?.[LC_CHILD] ?? this.extra[LC_CHILD]; + if (isRunnableConfigLike(presentConfig)) { + const newConfig = { ...presentConfig }; + const callbacks = isCallbackManagerLike(newConfig.callbacks) ? newConfig.callbacks.copy?.() : void 0; + if (callbacks) { + Object.assign(callbacks, { _parentRunId: child.id }); + callbacks.handlers?.find(isLangChainTracerLike)?.updateFromRunTree?.(child); + newConfig.callbacks = callbacks; + } + child.extra[LC_CHILD] = newConfig; + } + const visited = /* @__PURE__ */ new Set(); + let current = this; + while (current != null && !visited.has(current.id)) { + visited.add(current.id); + current.child_execution_order = Math.max(current.child_execution_order, child_execution_order); + current = current.parent_run; + } + this.child_runs.push(child); + return child; + } + async end(outputs, error, endTime = Date.now(), metadata) { + this.outputs = this.outputs ?? outputs; + this.error = this.error ?? error; + this.end_time = this.end_time ?? endTime; + if (metadata && Object.keys(metadata).length > 0) { + this.extra = this.extra ? { ...this.extra, metadata: { ...this.extra.metadata, ...metadata } } : { metadata }; + } + } + _convertToCreate(run, runtimeEnv, excludeChildRuns = true) { + const runExtra = run.extra ?? {}; + if (runExtra?.runtime?.library === void 0) { + if (!runExtra.runtime) { + runExtra.runtime = {}; + } + if (runtimeEnv) { + for (const [k3, v6] of Object.entries(runtimeEnv)) { + if (!runExtra.runtime[k3]) { + runExtra.runtime[k3] = v6; + } + } + } + } + let child_runs; + let parent_run_id; + if (!excludeChildRuns) { + child_runs = run.child_runs.map((child_run) => this._convertToCreate(child_run, runtimeEnv, excludeChildRuns)); + parent_run_id = void 0; + } else { + parent_run_id = run.parent_run?.id ?? run.parent_run_id; + child_runs = []; + } + return { + id: run.id, + name: run.name, + start_time: run._serialized_start_time ?? run.start_time, + end_time: run.end_time, + run_type: run.run_type, + reference_example_id: run.reference_example_id, + extra: runExtra, + serialized: run.serialized, + error: run.error, + inputs: run.inputs, + outputs: run.outputs, + session_name: run.project_name, + child_runs, + parent_run_id, + trace_id: run.trace_id, + dotted_order: run.dotted_order, + tags: run.tags, + attachments: run.attachments, + events: run.events + }; + } + _remapForProject(projectName, runtimeEnv, excludeChildRuns = true) { + const baseRun = this._convertToCreate(this, runtimeEnv, excludeChildRuns); + if (projectName === this.project_name) { + return baseRun; + } + const createRemappedId = (originalId) => { + return v5_default(`${originalId}:${projectName}`, v5_default.DNS); + }; + const newId = createRemappedId(baseRun.id); + const newTraceId = baseRun.trace_id ? createRemappedId(baseRun.trace_id) : void 0; + const newParentRunId = baseRun.parent_run_id ? createRemappedId(baseRun.parent_run_id) : void 0; + let newDottedOrder; + if (baseRun.dotted_order) { + const segments = _parseDottedOrder(baseRun.dotted_order); + const rebuilt = []; + for (let i2 = 0; i2 < segments.length - 1; i2++) { + const [timestamp2, segmentId] = segments[i2]; + const remappedId = createRemappedId(segmentId); + rebuilt.push(timestamp2.toISOString().replace(/[-:]/g, "").replace(".", "") + remappedId); + } + const [lastTimestamp] = segments[segments.length - 1]; + rebuilt.push(lastTimestamp.toISOString().replace(/[-:]/g, "").replace(".", "") + newId); + newDottedOrder = rebuilt.join("."); + } else { + newDottedOrder = void 0; + } + const remappedRun = { + ...baseRun, + id: newId, + trace_id: newTraceId, + parent_run_id: newParentRunId, + dotted_order: newDottedOrder, + session_name: projectName + }; + return remappedRun; + } + async postRun(excludeChildRuns = true) { + try { + const runtimeEnv = getRuntimeEnvironment(); + if (this.replicas && this.replicas.length > 0) { + for (const { projectName, apiKey, apiUrl } of this.replicas) { + const runCreate = this._remapForProject(projectName ?? this.project_name, runtimeEnv, true); + await this.client.createRun(runCreate, { + apiKey, + apiUrl + }); + } + } else { + const runCreate = this._convertToCreate(this, runtimeEnv, excludeChildRuns); + await this.client.createRun(runCreate); + } + if (!excludeChildRuns) { + warnOnce("Posting with excludeChildRuns=false is deprecated and will be removed in a future version."); + for (const childRun of this.child_runs) { + await childRun.postRun(false); + } + } + } catch (error) { + console.error(`Error in postRun for run ${this.id}:`, error); + } + } + async patchRun(options) { + if (this.replicas && this.replicas.length > 0) { + for (const { projectName, apiKey, apiUrl, updates } of this.replicas) { + const runData = this._remapForProject(projectName ?? this.project_name); + const updatePayload = { + id: runData.id, + outputs: runData.outputs, + error: runData.error, + parent_run_id: runData.parent_run_id, + session_name: runData.session_name, + reference_example_id: runData.reference_example_id, + end_time: runData.end_time, + dotted_order: runData.dotted_order, + trace_id: runData.trace_id, + events: runData.events, + tags: runData.tags, + extra: runData.extra, + attachments: this.attachments, + ...updates + }; + if (!options?.excludeInputs) { + updatePayload.inputs = runData.inputs; + } + await this.client.updateRun(runData.id, updatePayload, { + apiKey, + apiUrl + }); + } + } else { + try { + const runUpdate = { + end_time: this.end_time, + error: this.error, + outputs: this.outputs, + parent_run_id: this.parent_run?.id ?? this.parent_run_id, + reference_example_id: this.reference_example_id, + extra: this.extra, + events: this.events, + dotted_order: this.dotted_order, + trace_id: this.trace_id, + tags: this.tags, + attachments: this.attachments, + session_name: this.project_name + }; + if (!options?.excludeInputs) { + runUpdate.inputs = this.inputs; + } + await this.client.updateRun(this.id, runUpdate); + } catch (error) { + console.error(`Error in patchRun for run ${this.id}`, error); + } + } + } + toJSON() { + return this._convertToCreate(this, void 0, false); + } + /** + * Add an event to the run tree. + * @param event - A single event or string to add + */ + addEvent(event) { + if (!this.events) { + this.events = []; + } + if (typeof event === "string") { + this.events.push({ + name: "event", + time: (/* @__PURE__ */ new Date()).toISOString(), + message: event + }); + } else { + this.events.push({ + ...event, + time: event.time ?? (/* @__PURE__ */ new Date()).toISOString() + }); + } + } + static fromRunnableConfig(parentConfig, props) { + const callbackManager = parentConfig?.callbacks; + let parentRun; + let projectName; + let client2; + let tracingEnabled = isTracingEnabled(); + if (callbackManager) { + const parentRunId = callbackManager?.getParentRunId?.() ?? ""; + const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name == "langchain_tracer"); + parentRun = langChainTracer?.getRun?.(parentRunId); + projectName = langChainTracer?.projectName; + client2 = langChainTracer?.client; + tracingEnabled = tracingEnabled || !!langChainTracer; + } + if (!parentRun) { + return new _RunTree({ + ...props, + client: client2, + tracingEnabled, + project_name: projectName + }); + } + const parentRunTree = new _RunTree({ + name: parentRun.name, + id: parentRun.id, + trace_id: parentRun.trace_id, + dotted_order: parentRun.dotted_order, + client: client2, + tracingEnabled, + project_name: projectName, + tags: [ + ...new Set((parentRun?.tags ?? []).concat(parentConfig?.tags ?? [])) + ], + extra: { + metadata: { + ...parentRun?.extra?.metadata, + ...parentConfig?.metadata + } + } + }); + return parentRunTree.createChild(props); + } + static fromDottedOrder(dottedOrder) { + return this.fromHeaders({ "langsmith-trace": dottedOrder }); + } + static fromHeaders(headers, inheritArgs) { + const rawHeaders = "get" in headers && typeof headers.get === "function" ? { + "langsmith-trace": headers.get("langsmith-trace"), + baggage: headers.get("baggage") + } : headers; + const headerTrace = rawHeaders["langsmith-trace"]; + if (!headerTrace || typeof headerTrace !== "string") + return void 0; + const parentDottedOrder = headerTrace.trim(); + const parsedDottedOrder = parentDottedOrder.split(".").map((part) => { + const [strTime, uuid] = part.split("Z"); + return { strTime, time: Date.parse(strTime + "Z"), uuid }; + }); + const traceId = parsedDottedOrder[0].uuid; + const config = { + ...inheritArgs, + name: inheritArgs?.["name"] ?? "parent", + run_type: inheritArgs?.["run_type"] ?? "chain", + start_time: inheritArgs?.["start_time"] ?? Date.now(), + id: parsedDottedOrder.at(-1)?.uuid, + trace_id: traceId, + dotted_order: parentDottedOrder + }; + if (rawHeaders["baggage"] && typeof rawHeaders["baggage"] === "string") { + const baggage = Baggage.fromHeader(rawHeaders["baggage"]); + config.metadata = baggage.metadata; + config.tags = baggage.tags; + config.project_name = baggage.project_name; + config.replicas = baggage.replicas; + } + return new _RunTree(config); + } + toHeaders(headers) { + const result = { + "langsmith-trace": this.dotted_order, + baggage: new Baggage(this.extra?.metadata, this.tags, this.project_name, this.replicas).toHeader() + }; + if (headers) { + for (const [key, value] of Object.entries(result)) { + headers.set(key, value); + } + } + return result; + } + }; + Object.defineProperty(RunTree, "sharedClient", { + enumerable: true, + configurable: true, + writable: true, + value: null + }); + function isRunTree(x3) { + return x3 !== void 0 && typeof x3.createChild === "function" && typeof x3.postRun === "function"; + } + function isLangChainTracerLike(x3) { + return typeof x3 === "object" && x3 != null && typeof x3.name === "string" && x3.name === "langchain_tracer"; + } + function containsLangChainTracerLike(x3) { + return Array.isArray(x3) && x3.some((callback) => isLangChainTracerLike(callback)); + } + function isCallbackManagerLike(x3) { + return typeof x3 === "object" && x3 != null && Array.isArray(x3.handlers); + } + function isRunnableConfigLike(x3) { + return x3 !== void 0 && typeof x3.callbacks === "object" && // Callback manager with a langchain tracer + (containsLangChainTracerLike(x3.callbacks?.handlers) || // Or it's an array with a LangChainTracerLike object within it + containsLangChainTracerLike(x3.callbacks)); + } + function _parseDottedOrder(dottedOrder) { + const parts = dottedOrder.split("."); + return parts.map((part) => { + const timestampStr = part.slice(0, -36); + const uuidStr = part.slice(-36); + const year = parseInt(timestampStr.slice(0, 4)); + const month = parseInt(timestampStr.slice(4, 6)) - 1; + const day = parseInt(timestampStr.slice(6, 8)); + const hour = parseInt(timestampStr.slice(9, 11)); + const minute = parseInt(timestampStr.slice(11, 13)); + const second2 = parseInt(timestampStr.slice(13, 15)); + const microsecond = parseInt(timestampStr.slice(15, 21)); + const timestamp2 = new Date(year, month, day, hour, minute, second2, microsecond / 1e3); + return [timestamp2, uuidStr]; + }); + } + function _getWriteReplicasFromEnv() { + const envVar = getEnvironmentVariable("LANGSMITH_RUNS_ENDPOINTS"); + if (!envVar) + return []; + try { + const parsed = JSON.parse(envVar); + if (Array.isArray(parsed)) { + const replicas = []; + for (const item of parsed) { + if (typeof item !== "object" || item === null) { + console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof item}`); + continue; + } + if (typeof item.api_url !== "string") { + console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof item.api_url}`); + continue; + } + if (typeof item.api_key !== "string") { + console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof item.api_key}`); + continue; + } + replicas.push({ + apiUrl: item.api_url.replace(/\/$/, ""), + apiKey: item.api_key + }); + } + return replicas; + } else if (typeof parsed === "object" && parsed !== null) { + _checkEndpointEnvUnset(parsed); + const replicas = []; + for (const [url, key] of Object.entries(parsed)) { + const cleanUrl = url.replace(/\/$/, ""); + if (typeof key === "string") { + replicas.push({ + apiUrl: cleanUrl, + apiKey: key + }); + } else { + console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${url}: expected string, got ${typeof key}`); + continue; + } + } + return replicas; + } else { + console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof parsed}`); + return []; + } + } catch (e2) { + if (isConflictingEndpointsError(e2)) { + throw e2; + } + console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"); + return []; + } + } + function _ensureWriteReplicas(replicas) { + if (replicas) { + return replicas.map((replica) => { + if (Array.isArray(replica)) { + return { + projectName: replica[0], + updates: replica[1] + }; + } + return replica; + }); + } + return _getWriteReplicasFromEnv(); + } + function _checkEndpointEnvUnset(parsed) { + if (Object.keys(parsed).length > 0 && getLangSmithEnvironmentVariable("ENDPOINT")) { + throw new ConflictingEndpointsError(); + } + } + + // node_modules/@langchain/core/dist/utils/env.js + var isBrowser2 = () => typeof window !== "undefined" && typeof window.document !== "undefined"; + var isWebWorker2 = () => typeof globalThis === "object" && globalThis.constructor && globalThis.constructor.name === "DedicatedWorkerGlobalScope"; + var isJsDom2 = () => typeof window !== "undefined" && window.name === "nodejs" || typeof navigator !== "undefined" && navigator.userAgent.includes("jsdom"); + var isDeno2 = () => typeof Deno !== "undefined"; + var isNode2 = () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && !isDeno2(); + var getEnv2 = () => { + let env; + if (isBrowser2()) { + env = "browser"; + } else if (isNode2()) { + env = "node"; + } else if (isWebWorker2()) { + env = "webworker"; + } else if (isJsDom2()) { + env = "jsdom"; + } else if (isDeno2()) { + env = "deno"; + } else { + env = "other"; + } + return env; + }; + var runtimeEnvironment2; + function getRuntimeEnvironmentSync() { + if (runtimeEnvironment2 === void 0) { + const env = getEnv2(); + runtimeEnvironment2 = { + library: "langchain-js", + runtime: env + }; + } + return runtimeEnvironment2; + } + function getEnvironmentVariable2(name) { + try { + if (typeof process !== "undefined") { + return process.env?.[name]; + } else if (isDeno2()) { + return Deno?.env.get(name); + } else { + return void 0; + } + } catch (e2) { + return void 0; + } + } + + // node_modules/@langchain/core/dist/callbacks/base.js + var BaseCallbackHandlerMethodsClass = class { + }; + var BaseCallbackHandler = class _BaseCallbackHandler extends BaseCallbackHandlerMethodsClass { + get lc_namespace() { + return ["langchain_core", "callbacks", this.name]; + } + get lc_secrets() { + return void 0; + } + get lc_attributes() { + return void 0; + } + get lc_aliases() { + return void 0; + } + get lc_serializable_keys() { + return void 0; + } + /** + * The name of the serializable. Override to provide an alias or + * to preserve the serialized module name in minified environments. + * + * Implemented as a static method to support loading logic. + */ + static lc_name() { + return this.name; + } + /** + * The final serialized identifier for the module. + */ + get lc_id() { + return [ + ...this.lc_namespace, + get_lc_unique_name(this.constructor) + ]; + } + constructor(input) { + super(); + Object.defineProperty(this, "lc_serializable", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "lc_kwargs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "ignoreLLM", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "ignoreChain", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "ignoreAgent", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "ignoreRetriever", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "ignoreCustomEvent", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "raiseError", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "awaitHandlers", { + enumerable: true, + configurable: true, + writable: true, + value: getEnvironmentVariable2("LANGCHAIN_CALLBACKS_BACKGROUND") === "false" + }); + this.lc_kwargs = input || {}; + if (input) { + this.ignoreLLM = input.ignoreLLM ?? this.ignoreLLM; + this.ignoreChain = input.ignoreChain ?? this.ignoreChain; + this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent; + this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever; + this.ignoreCustomEvent = input.ignoreCustomEvent ?? this.ignoreCustomEvent; + this.raiseError = input.raiseError ?? this.raiseError; + this.awaitHandlers = this.raiseError || (input._awaitHandler ?? this.awaitHandlers); + } + } + copy() { + return new this.constructor(this); + } + toJSON() { + return Serializable.prototype.toJSON.call(this); + } + toJSONNotImplemented() { + return Serializable.prototype.toJSONNotImplemented.call(this); + } + static fromMethods(methods) { + class Handler extends _BaseCallbackHandler { + constructor() { + super(); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: v4_default() + }); + Object.assign(this, methods); + } + } + return new Handler(); + } + }; + var isBaseCallbackHandler = (x3) => { + const callbackHandler = x3; + return callbackHandler !== void 0 && typeof callbackHandler.copy === "function" && typeof callbackHandler.name === "string" && typeof callbackHandler.awaitHandlers === "boolean"; + }; + + // node_modules/@langchain/core/dist/tracers/base.js + var convertRunTreeToRun = (runTree) => { + if (!runTree) { + return void 0; + } + runTree.events = runTree.events ?? []; + runTree.child_runs = runTree.child_runs ?? []; + return runTree; + }; + function convertRunToRunTree(run, parentRun) { + if (!run) { + return void 0; + } + return new RunTree({ + ...run, + start_time: run._serialized_start_time ?? run.start_time, + parent_run: convertRunToRunTree(parentRun), + child_runs: run.child_runs.map((r2) => convertRunToRunTree(r2)).filter((r2) => r2 !== void 0), + extra: { + ...run.extra, + runtime: getRuntimeEnvironmentSync() + }, + tracingEnabled: false + }); + } + function _coerceToDict(value, defaultKey) { + return value && !Array.isArray(value) && typeof value === "object" ? value : { [defaultKey]: value }; + } + function isBaseTracer(x3) { + return typeof x3._addRunToRunMap === "function"; + } + var BaseTracer = class extends BaseCallbackHandler { + constructor(_fields) { + super(...arguments); + Object.defineProperty(this, "runMap", { + enumerable: true, + configurable: true, + writable: true, + value: /* @__PURE__ */ new Map() + }); + Object.defineProperty(this, "runTreeMap", { + enumerable: true, + configurable: true, + writable: true, + value: /* @__PURE__ */ new Map() + }); + Object.defineProperty(this, "usesRunTreeMap", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + } + copy() { + return this; + } + getRunById(runId) { + if (runId === void 0) { + return void 0; + } + return this.usesRunTreeMap ? convertRunTreeToRun(this.runTreeMap.get(runId)) : this.runMap.get(runId); + } + stringifyError(error) { + if (error instanceof Error) { + return error.message + (error?.stack ? ` + +${error.stack}` : ""); + } + if (typeof error === "string") { + return error; + } + return `${error}`; + } + _addChildRun(parentRun, childRun) { + parentRun.child_runs.push(childRun); + } + _addRunToRunMap(run) { + const { dottedOrder: currentDottedOrder, microsecondPrecisionDatestring } = convertToDottedOrderFormat(new Date(run.start_time).getTime(), run.id, run.execution_order); + const storedRun = { ...run }; + const parentRun = this.getRunById(storedRun.parent_run_id); + if (storedRun.parent_run_id !== void 0) { + if (parentRun) { + this._addChildRun(parentRun, storedRun); + parentRun.child_execution_order = Math.max(parentRun.child_execution_order, storedRun.child_execution_order); + storedRun.trace_id = parentRun.trace_id; + if (parentRun.dotted_order !== void 0) { + storedRun.dotted_order = [ + parentRun.dotted_order, + currentDottedOrder + ].join("."); + storedRun._serialized_start_time = microsecondPrecisionDatestring; + } else { + } + } else { + } + } else { + storedRun.trace_id = storedRun.id; + storedRun.dotted_order = currentDottedOrder; + storedRun._serialized_start_time = microsecondPrecisionDatestring; + } + if (this.usesRunTreeMap) { + const runTree = convertRunToRunTree(storedRun, parentRun); + if (runTree !== void 0) { + this.runTreeMap.set(storedRun.id, runTree); + } + } else { + this.runMap.set(storedRun.id, storedRun); + } + return storedRun; + } + async _endTrace(run) { + const parentRun = run.parent_run_id !== void 0 && this.getRunById(run.parent_run_id); + if (parentRun) { + parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order); + } else { + await this.persistRun(run); + } + await this.onRunUpdate?.(run); + if (this.usesRunTreeMap) { + this.runTreeMap.delete(run.id); + } else { + this.runMap.delete(run.id); + } + } + _getExecutionOrder(parentRunId) { + const parentRun = parentRunId !== void 0 && this.getRunById(parentRunId); + if (!parentRun) { + return 1; + } + return parentRun.child_execution_order + 1; + } + /** + * Create and add a run to the run map for LLM start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const finalExtraParams = metadata ? { ...extraParams, metadata } : extraParams; + const run = { + id: runId, + name: name ?? llm.id[llm.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: llm, + events: [ + { + name: "start", + time: new Date(start_time).toISOString() + } + ], + inputs: { prompts }, + execution_order, + child_runs: [], + child_execution_order: execution_order, + run_type: "llm", + extra: finalExtraParams ?? {}, + tags: tags || [] + }; + return this._addRunToRunMap(run); + } + async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { + const run = this.getRunById(runId) ?? this._createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onLLMStart?.(run); + return run; + } + /** + * Create and add a run to the run map for chat model start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const finalExtraParams = metadata ? { ...extraParams, metadata } : extraParams; + const run = { + id: runId, + name: name ?? llm.id[llm.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: llm, + events: [ + { + name: "start", + time: new Date(start_time).toISOString() + } + ], + inputs: { messages }, + execution_order, + child_runs: [], + child_execution_order: execution_order, + run_type: "llm", + extra: finalExtraParams ?? {}, + tags: tags || [] + }; + return this._addRunToRunMap(run); + } + async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { + const run = this.getRunById(runId) ?? this._createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onLLMStart?.(run); + return run; + } + async handleLLMEnd(output, runId, _parentRunId, _tags, extraParams) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "llm") { + throw new Error("No LLM run to end."); + } + run.end_time = Date.now(); + run.outputs = output; + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString() + }); + run.extra = { ...run.extra, ...extraParams }; + await this.onLLMEnd?.(run); + await this._endTrace(run); + return run; + } + async handleLLMError(error, runId, _parentRunId, _tags, extraParams) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "llm") { + throw new Error("No LLM run to end."); + } + run.end_time = Date.now(); + run.error = this.stringifyError(error); + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString() + }); + run.extra = { ...run.extra, ...extraParams }; + await this.onLLMError?.(run); + await this._endTrace(run); + return run; + } + /** + * Create and add a run to the run map for chain start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? chain.id[chain.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: chain, + events: [ + { + name: "start", + time: new Date(start_time).toISOString() + } + ], + inputs, + execution_order, + child_execution_order: execution_order, + run_type: runType ?? "chain", + child_runs: [], + extra: metadata ? { metadata } : {}, + tags: tags || [] + }; + return this._addRunToRunMap(run); + } + async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) { + const run = this.getRunById(runId) ?? this._createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name); + await this.onRunCreate?.(run); + await this.onChainStart?.(run); + return run; + } + async handleChainEnd(outputs, runId, _parentRunId, _tags, kwargs) { + const run = this.getRunById(runId); + if (!run) { + throw new Error("No chain run to end."); + } + run.end_time = Date.now(); + run.outputs = _coerceToDict(outputs, "output"); + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString() + }); + if (kwargs?.inputs !== void 0) { + run.inputs = _coerceToDict(kwargs.inputs, "input"); + } + await this.onChainEnd?.(run); + await this._endTrace(run); + return run; + } + async handleChainError(error, runId, _parentRunId, _tags, kwargs) { + const run = this.getRunById(runId); + if (!run) { + throw new Error("No chain run to end."); + } + run.end_time = Date.now(); + run.error = this.stringifyError(error); + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString() + }); + if (kwargs?.inputs !== void 0) { + run.inputs = _coerceToDict(kwargs.inputs, "input"); + } + await this.onChainError?.(run); + await this._endTrace(run); + return run; + } + /** + * Create and add a run to the run map for tool start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForToolStart(tool, input, runId, parentRunId, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? tool.id[tool.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: tool, + events: [ + { + name: "start", + time: new Date(start_time).toISOString() + } + ], + inputs: { input }, + execution_order, + child_execution_order: execution_order, + run_type: "tool", + child_runs: [], + extra: metadata ? { metadata } : {}, + tags: tags || [] + }; + return this._addRunToRunMap(run); + } + async handleToolStart(tool, input, runId, parentRunId, tags, metadata, name) { + const run = this.getRunById(runId) ?? this._createRunForToolStart(tool, input, runId, parentRunId, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onToolStart?.(run); + return run; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async handleToolEnd(output, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "tool") { + throw new Error("No tool run to end"); + } + run.end_time = Date.now(); + run.outputs = { output }; + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString() + }); + await this.onToolEnd?.(run); + await this._endTrace(run); + return run; + } + async handleToolError(error, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "tool") { + throw new Error("No tool run to end"); + } + run.end_time = Date.now(); + run.error = this.stringifyError(error); + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString() + }); + await this.onToolError?.(run); + await this._endTrace(run); + return run; + } + async handleAgentAction(action, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "chain") { + return; + } + const agentRun = run; + agentRun.actions = agentRun.actions || []; + agentRun.actions.push(action); + agentRun.events.push({ + name: "agent_action", + time: (/* @__PURE__ */ new Date()).toISOString(), + kwargs: { action } + }); + await this.onAgentAction?.(run); + } + async handleAgentEnd(action, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "chain") { + return; + } + run.events.push({ + name: "agent_end", + time: (/* @__PURE__ */ new Date()).toISOString(), + kwargs: { action } + }); + await this.onAgentEnd?.(run); + } + /** + * Create and add a run to the run map for retriever start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? retriever.id[retriever.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: retriever, + events: [ + { + name: "start", + time: new Date(start_time).toISOString() + } + ], + inputs: { query }, + execution_order, + child_execution_order: execution_order, + run_type: "retriever", + child_runs: [], + extra: metadata ? { metadata } : {}, + tags: tags || [] + }; + return this._addRunToRunMap(run); + } + async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { + const run = this.getRunById(runId) ?? this._createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onRetrieverStart?.(run); + return run; + } + async handleRetrieverEnd(documents, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "retriever") { + throw new Error("No retriever run to end"); + } + run.end_time = Date.now(); + run.outputs = { documents }; + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString() + }); + await this.onRetrieverEnd?.(run); + await this._endTrace(run); + return run; + } + async handleRetrieverError(error, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "retriever") { + throw new Error("No retriever run to end"); + } + run.end_time = Date.now(); + run.error = this.stringifyError(error); + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString() + }); + await this.onRetrieverError?.(run); + await this._endTrace(run); + return run; + } + async handleText(text2, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "chain") { + return; + } + run.events.push({ + name: "text", + time: (/* @__PURE__ */ new Date()).toISOString(), + kwargs: { text: text2 } + }); + await this.onText?.(run); + } + async handleLLMNewToken(token, idx, runId, _parentRunId, _tags, fields) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "llm") { + throw new Error(`Invalid "runId" provided to "handleLLMNewToken" callback.`); + } + run.events.push({ + name: "new_token", + time: (/* @__PURE__ */ new Date()).toISOString(), + kwargs: { token, idx, chunk: fields?.chunk } + }); + await this.onLLMNewToken?.(run, token, { chunk: fields?.chunk }); + return run; + } + }; + + // node_modules/@langchain/core/dist/tracers/console.js + var import_ansi_styles = __toESM(require_ansi_styles(), 1); + function wrap(style, text2) { + return `${style.open}${text2}${style.close}`; + } + function tryJsonStringify(obj, fallback) { + try { + return JSON.stringify(obj, null, 2); + } catch (err) { + return fallback; + } + } + function formatKVMapItem(value) { + if (typeof value === "string") { + return value.trim(); + } + if (value === null || value === void 0) { + return value; + } + return tryJsonStringify(value, value.toString()); + } + function elapsed(run) { + if (!run.end_time) + return ""; + const elapsed2 = run.end_time - run.start_time; + if (elapsed2 < 1e3) { + return `${elapsed2}ms`; + } + return `${(elapsed2 / 1e3).toFixed(2)}s`; + } + var { color } = import_ansi_styles.default; + var ConsoleCallbackHandler = class extends BaseTracer { + constructor() { + super(...arguments); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "console_callback_handler" + }); + } + /** + * Method used to persist the run. In this case, it simply returns a + * resolved promise as there's no persistence logic. + * @param _run The run to persist. + * @returns A resolved promise. + */ + persistRun(_run) { + return Promise.resolve(); + } + // utility methods + /** + * Method used to get all the parent runs of a given run. + * @param run The run whose parents are to be retrieved. + * @returns An array of parent runs. + */ + getParents(run) { + const parents = []; + let currentRun = run; + while (currentRun.parent_run_id) { + const parent = this.runMap.get(currentRun.parent_run_id); + if (parent) { + parents.push(parent); + currentRun = parent; + } else { + break; + } + } + return parents; + } + /** + * Method used to get a string representation of the run's lineage, which + * is used in logging. + * @param run The run whose lineage is to be retrieved. + * @returns A string representation of the run's lineage. + */ + getBreadcrumbs(run) { + const parents = this.getParents(run).reverse(); + const string2 = [...parents, run].map((parent, i2, arr2) => { + const name = `${parent.execution_order}:${parent.run_type}:${parent.name}`; + return i2 === arr2.length - 1 ? wrap(import_ansi_styles.default.bold, name) : name; + }).join(" > "); + return wrap(color.grey, string2); + } + // logging methods + /** + * Method used to log the start of a chain run. + * @param run The chain run that has started. + * @returns void + */ + onChainStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[chain/start]")} [${crumbs}] Entering Chain run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); + } + /** + * Method used to log the end of a chain run. + * @param run The chain run that has ended. + * @returns void + */ + onChainEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[chain/end]")} [${crumbs}] [${elapsed(run)}] Exiting Chain run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); + } + /** + * Method used to log any errors of a chain run. + * @param run The chain run that has errored. + * @returns void + */ + onChainError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[chain/error]")} [${crumbs}] [${elapsed(run)}] Chain run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the start of an LLM run. + * @param run The LLM run that has started. + * @returns void + */ + onLLMStart(run) { + const crumbs = this.getBreadcrumbs(run); + const inputs = "prompts" in run.inputs ? { prompts: run.inputs.prompts.map((p2) => p2.trim()) } : run.inputs; + console.log(`${wrap(color.green, "[llm/start]")} [${crumbs}] Entering LLM run with input: ${tryJsonStringify(inputs, "[inputs]")}`); + } + /** + * Method used to log the end of an LLM run. + * @param run The LLM run that has ended. + * @returns void + */ + onLLMEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[llm/end]")} [${crumbs}] [${elapsed(run)}] Exiting LLM run with output: ${tryJsonStringify(run.outputs, "[response]")}`); + } + /** + * Method used to log any errors of an LLM run. + * @param run The LLM run that has errored. + * @returns void + */ + onLLMError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[llm/error]")} [${crumbs}] [${elapsed(run)}] LLM run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the start of a tool run. + * @param run The tool run that has started. + * @returns void + */ + onToolStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[tool/start]")} [${crumbs}] Entering Tool run with input: "${formatKVMapItem(run.inputs.input)}"`); + } + /** + * Method used to log the end of a tool run. + * @param run The tool run that has ended. + * @returns void + */ + onToolEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[tool/end]")} [${crumbs}] [${elapsed(run)}] Exiting Tool run with output: "${formatKVMapItem(run.outputs?.output)}"`); + } + /** + * Method used to log any errors of a tool run. + * @param run The tool run that has errored. + * @returns void + */ + onToolError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[tool/error]")} [${crumbs}] [${elapsed(run)}] Tool run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the start of a retriever run. + * @param run The retriever run that has started. + * @returns void + */ + onRetrieverStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[retriever/start]")} [${crumbs}] Entering Retriever run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); + } + /** + * Method used to log the end of a retriever run. + * @param run The retriever run that has ended. + * @returns void + */ + onRetrieverEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[retriever/end]")} [${crumbs}] [${elapsed(run)}] Exiting Retriever run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); + } + /** + * Method used to log any errors of a retriever run. + * @param run The retriever run that has errored. + * @returns void + */ + onRetrieverError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[retriever/error]")} [${crumbs}] [${elapsed(run)}] Retriever run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the action selected by the agent. + * @param run The run in which the agent action occurred. + * @returns void + */ + onAgentAction(run) { + const agentRun = run; + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.blue, "[agent/action]")} [${crumbs}] Agent selected action: ${tryJsonStringify(agentRun.actions[agentRun.actions.length - 1], "[action]")}`); + } + }; + + // node_modules/@langchain/core/dist/singletons/tracer.js + var client; + var getDefaultLangChainClientSingleton = () => { + if (client === void 0) { + const clientParams = getEnvironmentVariable2("LANGCHAIN_CALLBACKS_BACKGROUND") === "false" ? { + // LangSmith has its own backgrounding system + blockOnRootRunFinalization: true + } : {}; + client = new Client(clientParams); + } + return client; + }; + + // node_modules/@langchain/core/dist/tracers/tracer_langchain.js + var LangChainTracer = class _LangChainTracer extends BaseTracer { + constructor(fields = {}) { + super(fields); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "langchain_tracer" + }); + Object.defineProperty(this, "projectName", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "exampleId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "client", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "replicas", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "usesRunTreeMap", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + const { exampleId, projectName, client: client2, replicas } = fields; + this.projectName = projectName ?? getDefaultProjectName(); + this.replicas = replicas; + this.exampleId = exampleId; + this.client = client2 ?? getDefaultLangChainClientSingleton(); + const traceableTree = _LangChainTracer.getTraceableRunTree(); + if (traceableTree) { + this.updateFromRunTree(traceableTree); + } + } + async persistRun(_run) { + } + async onRunCreate(run) { + const runTree = this.getRunTreeWithTracingConfig(run.id); + await runTree?.postRun(); + } + async onRunUpdate(run) { + const runTree = this.getRunTreeWithTracingConfig(run.id); + await runTree?.patchRun(); + } + getRun(id) { + return this.runTreeMap.get(id); + } + updateFromRunTree(runTree) { + this.runTreeMap.set(runTree.id, runTree); + let rootRun = runTree; + const visited = /* @__PURE__ */ new Set(); + while (rootRun.parent_run) { + if (visited.has(rootRun.id)) + break; + visited.add(rootRun.id); + if (!rootRun.parent_run) + break; + rootRun = rootRun.parent_run; + } + visited.clear(); + const queue2 = [rootRun]; + while (queue2.length > 0) { + const current = queue2.shift(); + if (!current || visited.has(current.id)) + continue; + visited.add(current.id); + this.runTreeMap.set(current.id, current); + if (current.child_runs) { + queue2.push(...current.child_runs); + } + } + this.client = runTree.client ?? this.client; + this.replicas = runTree.replicas ?? this.replicas; + this.projectName = runTree.project_name ?? this.projectName; + this.exampleId = runTree.reference_example_id ?? this.exampleId; + } + getRunTreeWithTracingConfig(id) { + const runTree = this.runTreeMap.get(id); + if (!runTree) + return void 0; + return new RunTree({ + ...runTree, + client: this.client, + project_name: this.projectName, + replicas: this.replicas, + reference_example_id: this.exampleId, + tracingEnabled: true + }); + } + static getTraceableRunTree() { + try { + return ( + // The type cast here provides forward compatibility. Old versions of LangSmith will just + // ignore the permitAbsentRunTree arg. + getCurrentRunTree(true) + ); + } catch { + return void 0; + } + } + }; + + // node_modules/@langchain/core/dist/singletons/callbacks.js + var import_p_queue2 = __toESM(require_dist(), 1); + + // node_modules/@langchain/core/dist/singletons/async_local_storage/globals.js + var TRACING_ALS_KEY2 = Symbol.for("ls:tracing_async_local_storage"); + var _CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); + var setGlobalAsyncLocalStorageInstance = (instance) => { + globalThis[TRACING_ALS_KEY2] = instance; + }; + var getGlobalAsyncLocalStorageInstance = () => { + return globalThis[TRACING_ALS_KEY2]; + }; + + // node_modules/@langchain/core/dist/singletons/callbacks.js + var queue; + function createQueue() { + const PQueue = "default" in import_p_queue2.default ? import_p_queue2.default.default : import_p_queue2.default; + return new PQueue({ + autoStart: true, + concurrency: 1 + }); + } + function getQueue() { + if (typeof queue === "undefined") { + queue = createQueue(); + } + return queue; + } + async function consumeCallback(promiseFn, wait2) { + if (wait2 === true) { + const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance(); + if (asyncLocalStorageInstance !== void 0) { + await asyncLocalStorageInstance.run(void 0, async () => promiseFn()); + } else { + await promiseFn(); + } + } else { + queue = getQueue(); + void queue.add(async () => { + const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance(); + if (asyncLocalStorageInstance !== void 0) { + await asyncLocalStorageInstance.run(void 0, async () => promiseFn()); + } else { + await promiseFn(); + } + }); + } + } + + // node_modules/@langchain/core/dist/utils/callbacks.js + var isTracingEnabled2 = (tracingEnabled) => { + if (tracingEnabled !== void 0) { + return tracingEnabled; + } + const envVars = [ + "LANGSMITH_TRACING_V2", + "LANGCHAIN_TRACING_V2", + "LANGSMITH_TRACING", + "LANGCHAIN_TRACING" + ]; + return !!envVars.find((envVar) => getEnvironmentVariable2(envVar) === "true"); + }; + + // node_modules/@langchain/core/dist/singletons/async_local_storage/context.js + function getContextVariable(name) { + const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance(); + if (asyncLocalStorageInstance === void 0) { + return void 0; + } + const runTree = asyncLocalStorageInstance.getStore(); + return runTree?.[_CONTEXT_VARIABLES_KEY]?.[name]; + } + var LC_CONFIGURE_HOOKS_KEY = Symbol("lc:configure_hooks"); + var _getConfigureHooks = () => getContextVariable(LC_CONFIGURE_HOOKS_KEY) || []; + + // node_modules/@langchain/core/dist/callbacks/manager.js + var BaseCallbackManager = class { + setHandler(handler) { + return this.setHandlers([handler]); + } + }; + var BaseRunManager = class { + constructor(runId, handlers, inheritableHandlers, tags, inheritableTags, metadata, inheritableMetadata, _parentRunId) { + Object.defineProperty(this, "runId", { + enumerable: true, + configurable: true, + writable: true, + value: runId + }); + Object.defineProperty(this, "handlers", { + enumerable: true, + configurable: true, + writable: true, + value: handlers + }); + Object.defineProperty(this, "inheritableHandlers", { + enumerable: true, + configurable: true, + writable: true, + value: inheritableHandlers + }); + Object.defineProperty(this, "tags", { + enumerable: true, + configurable: true, + writable: true, + value: tags + }); + Object.defineProperty(this, "inheritableTags", { + enumerable: true, + configurable: true, + writable: true, + value: inheritableTags + }); + Object.defineProperty(this, "metadata", { + enumerable: true, + configurable: true, + writable: true, + value: metadata + }); + Object.defineProperty(this, "inheritableMetadata", { + enumerable: true, + configurable: true, + writable: true, + value: inheritableMetadata + }); + Object.defineProperty(this, "_parentRunId", { + enumerable: true, + configurable: true, + writable: true, + value: _parentRunId + }); + } + get parentRunId() { + return this._parentRunId; + } + async handleText(text2) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + try { + await handler.handleText?.(text2, this.runId, this._parentRunId, this.tags); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleText: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers))); + } + async handleCustomEvent(eventName, data, _runId, _tags, _metadata) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + try { + await handler.handleCustomEvent?.(eventName, data, this.runId, this.tags, this.metadata); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers))); + } + }; + var CallbackManagerForRetrieverRun = class extends BaseRunManager { + getChild(tag) { + const manager = new CallbackManager(this.runId); + manager.setHandlers(this.inheritableHandlers); + manager.addTags(this.inheritableTags); + manager.addMetadata(this.inheritableMetadata); + if (tag) { + manager.addTags([tag], false); + } + return manager; + } + async handleRetrieverEnd(documents) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreRetriever) { + try { + await handler.handleRetrieverEnd?.(documents, this.runId, this._parentRunId, this.tags); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleRetriever`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + async handleRetrieverError(err) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreRetriever) { + try { + await handler.handleRetrieverError?.(err, this.runId, this._parentRunId, this.tags); + } catch (error) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleRetrieverError: ${error}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + }; + var CallbackManagerForLLMRun = class extends BaseRunManager { + async handleLLMNewToken(token, idx, _runId, _parentRunId, _tags, fields) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreLLM) { + try { + await handler.handleLLMNewToken?.(token, idx ?? { prompt: 0, completion: 0 }, this.runId, this._parentRunId, this.tags, fields); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMNewToken: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + async handleLLMError(err, _runId, _parentRunId, _tags, extraParams) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreLLM) { + try { + await handler.handleLLMError?.(err, this.runId, this._parentRunId, this.tags, extraParams); + } catch (err2) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMError: ${err2}`); + if (handler.raiseError) { + throw err2; + } + } + } + }, handler.awaitHandlers))); + } + async handleLLMEnd(output, _runId, _parentRunId, _tags, extraParams) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreLLM) { + try { + await handler.handleLLMEnd?.(output, this.runId, this._parentRunId, this.tags, extraParams); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMEnd: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + }; + var CallbackManagerForChainRun = class extends BaseRunManager { + getChild(tag) { + const manager = new CallbackManager(this.runId); + manager.setHandlers(this.inheritableHandlers); + manager.addTags(this.inheritableTags); + manager.addMetadata(this.inheritableMetadata); + if (tag) { + manager.addTags([tag], false); + } + return manager; + } + async handleChainError(err, _runId, _parentRunId, _tags, kwargs) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreChain) { + try { + await handler.handleChainError?.(err, this.runId, this._parentRunId, this.tags, kwargs); + } catch (err2) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleChainError: ${err2}`); + if (handler.raiseError) { + throw err2; + } + } + } + }, handler.awaitHandlers))); + } + async handleChainEnd(output, _runId, _parentRunId, _tags, kwargs) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreChain) { + try { + await handler.handleChainEnd?.(output, this.runId, this._parentRunId, this.tags, kwargs); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleChainEnd: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + async handleAgentAction(action) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleAgentAction?.(action, this.runId, this._parentRunId, this.tags); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleAgentAction: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + async handleAgentEnd(action) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleAgentEnd?.(action, this.runId, this._parentRunId, this.tags); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleAgentEnd: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + }; + var CallbackManagerForToolRun = class extends BaseRunManager { + getChild(tag) { + const manager = new CallbackManager(this.runId); + manager.setHandlers(this.inheritableHandlers); + manager.addTags(this.inheritableTags); + manager.addMetadata(this.inheritableMetadata); + if (tag) { + manager.addTags([tag], false); + } + return manager; + } + async handleToolError(err) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleToolError?.(err, this.runId, this._parentRunId, this.tags); + } catch (err2) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleToolError: ${err2}`); + if (handler.raiseError) { + throw err2; + } + } + } + }, handler.awaitHandlers))); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async handleToolEnd(output) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) { + try { + await handler.handleToolEnd?.(output, this.runId, this._parentRunId, this.tags); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleToolEnd: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + }; + var CallbackManager = class _CallbackManager extends BaseCallbackManager { + constructor(parentRunId, options) { + super(); + Object.defineProperty(this, "handlers", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "inheritableHandlers", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "tags", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "inheritableTags", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "metadata", { + enumerable: true, + configurable: true, + writable: true, + value: {} + }); + Object.defineProperty(this, "inheritableMetadata", { + enumerable: true, + configurable: true, + writable: true, + value: {} + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "callback_manager" + }); + Object.defineProperty(this, "_parentRunId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.handlers = options?.handlers ?? this.handlers; + this.inheritableHandlers = options?.inheritableHandlers ?? this.inheritableHandlers; + this.tags = options?.tags ?? this.tags; + this.inheritableTags = options?.inheritableTags ?? this.inheritableTags; + this.metadata = options?.metadata ?? this.metadata; + this.inheritableMetadata = options?.inheritableMetadata ?? this.inheritableMetadata; + this._parentRunId = parentRunId; + } + /** + * Gets the parent run ID, if any. + * + * @returns The parent run ID. + */ + getParentRunId() { + return this._parentRunId; + } + async handleLLMStart(llm, prompts, runId = void 0, _parentRunId = void 0, extraParams = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { + return Promise.all(prompts.map(async (prompt, idx) => { + const runId_ = idx === 0 && runId ? runId : v4_default(); + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreLLM) { + return; + } + if (isBaseTracer(handler)) { + handler._createRunForLLMStart(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + } + return consumeCallback(async () => { + try { + await handler.handleLLMStart?.(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + })); + } + async handleChatModelStart(llm, messages, runId = void 0, _parentRunId = void 0, extraParams = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { + return Promise.all(messages.map(async (messageGroup, idx) => { + const runId_ = idx === 0 && runId ? runId : v4_default(); + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreLLM) { + return; + } + if (isBaseTracer(handler)) { + handler._createRunForChatModelStart(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + } + return consumeCallback(async () => { + try { + if (handler.handleChatModelStart) { + await handler.handleChatModelStart?.(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + } else if (handler.handleLLMStart) { + const messageString = getBufferString(messageGroup); + await handler.handleLLMStart?.(llm, [messageString], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + } + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + })); + } + async handleChainStart(chain, inputs, runId = v4_default(), runType = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreChain) { + return; + } + if (isBaseTracer(handler)) { + handler._createRunForChainStart(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName); + } + return consumeCallback(async () => { + try { + await handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleChainStart: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForChainRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + } + async handleToolStart(tool, input, runId = v4_default(), _parentRunId = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreAgent) { + return; + } + if (isBaseTracer(handler)) { + handler._createRunForToolStart(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName); + } + return consumeCallback(async () => { + try { + await handler.handleToolStart?.(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleToolStart: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForToolRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + } + async handleRetrieverStart(retriever, query, runId = v4_default(), _parentRunId = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreRetriever) { + return; + } + if (isBaseTracer(handler)) { + handler._createRunForRetrieverStart(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName); + } + return consumeCallback(async () => { + try { + await handler.handleRetrieverStart?.(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleRetrieverStart: ${err}`); + if (handler.raiseError) { + throw err; + } + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForRetrieverRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + } + async handleCustomEvent(eventName, data, runId, _tags, _metadata) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreCustomEvent) { + try { + await handler.handleCustomEvent?.(eventName, data, runId, this.tags, this.metadata); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`); + if (handler.raiseError) { + throw err; + } + } + } + }, handler.awaitHandlers))); + } + addHandler(handler, inherit = true) { + this.handlers.push(handler); + if (inherit) { + this.inheritableHandlers.push(handler); + } + } + removeHandler(handler) { + this.handlers = this.handlers.filter((_handler) => _handler !== handler); + this.inheritableHandlers = this.inheritableHandlers.filter((_handler) => _handler !== handler); + } + setHandlers(handlers, inherit = true) { + this.handlers = []; + this.inheritableHandlers = []; + for (const handler of handlers) { + this.addHandler(handler, inherit); + } + } + addTags(tags, inherit = true) { + this.removeTags(tags); + this.tags.push(...tags); + if (inherit) { + this.inheritableTags.push(...tags); + } + } + removeTags(tags) { + this.tags = this.tags.filter((tag) => !tags.includes(tag)); + this.inheritableTags = this.inheritableTags.filter((tag) => !tags.includes(tag)); + } + addMetadata(metadata, inherit = true) { + this.metadata = { ...this.metadata, ...metadata }; + if (inherit) { + this.inheritableMetadata = { ...this.inheritableMetadata, ...metadata }; + } + } + removeMetadata(metadata) { + for (const key of Object.keys(metadata)) { + delete this.metadata[key]; + delete this.inheritableMetadata[key]; + } + } + copy(additionalHandlers = [], inherit = true) { + const manager = new _CallbackManager(this._parentRunId); + for (const handler of this.handlers) { + const inheritable = this.inheritableHandlers.includes(handler); + manager.addHandler(handler, inheritable); + } + for (const tag of this.tags) { + const inheritable = this.inheritableTags.includes(tag); + manager.addTags([tag], inheritable); + } + for (const key of Object.keys(this.metadata)) { + const inheritable = Object.keys(this.inheritableMetadata).includes(key); + manager.addMetadata({ [key]: this.metadata[key] }, inheritable); + } + for (const handler of additionalHandlers) { + if ( + // Prevent multiple copies of console_callback_handler + manager.handlers.filter((h2) => h2.name === "console_callback_handler").some((h2) => h2.name === handler.name) + ) { + continue; + } + manager.addHandler(handler, inherit); + } + return manager; + } + static fromHandlers(handlers) { + class Handler extends BaseCallbackHandler { + constructor() { + super(); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: v4_default() + }); + Object.assign(this, handlers); + } + } + const manager = new this(); + manager.addHandler(new Handler()); + return manager; + } + static configure(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { + return this._configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options); + } + // TODO: Deprecate async method in favor of this one. + static _configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { + let callbackManager; + if (inheritableHandlers || localHandlers) { + if (Array.isArray(inheritableHandlers) || !inheritableHandlers) { + callbackManager = new _CallbackManager(); + callbackManager.setHandlers(inheritableHandlers?.map(ensureHandler) ?? [], true); + } else { + callbackManager = inheritableHandlers; + } + callbackManager = callbackManager.copy(Array.isArray(localHandlers) ? localHandlers.map(ensureHandler) : localHandlers?.handlers, false); + } + const verboseEnabled = getEnvironmentVariable2("LANGCHAIN_VERBOSE") === "true" || options?.verbose; + const tracingV2Enabled = LangChainTracer.getTraceableRunTree()?.tracingEnabled || isTracingEnabled2(); + const tracingEnabled = tracingV2Enabled || (getEnvironmentVariable2("LANGCHAIN_TRACING") ?? false); + if (verboseEnabled || tracingEnabled) { + if (!callbackManager) { + callbackManager = new _CallbackManager(); + } + if (verboseEnabled && !callbackManager.handlers.some((handler) => handler.name === ConsoleCallbackHandler.prototype.name)) { + const consoleHandler = new ConsoleCallbackHandler(); + callbackManager.addHandler(consoleHandler, true); + } + if (tracingEnabled && !callbackManager.handlers.some((handler) => handler.name === "langchain_tracer")) { + if (tracingV2Enabled) { + const tracerV2 = new LangChainTracer(); + callbackManager.addHandler(tracerV2, true); + callbackManager._parentRunId = LangChainTracer.getTraceableRunTree()?.id ?? callbackManager._parentRunId; + } + } + } + for (const { contextVar, inheritable = true, handlerClass, envVar } of _getConfigureHooks()) { + const createIfNotInContext = envVar && getEnvironmentVariable2(envVar) === "true" && handlerClass; + let handler; + const contextVarValue = contextVar !== void 0 ? getContextVariable(contextVar) : void 0; + if (contextVarValue && isBaseCallbackHandler(contextVarValue)) { + handler = contextVarValue; + } else if (createIfNotInContext) { + handler = new handlerClass({}); + } + if (handler !== void 0) { + if (!callbackManager) { + callbackManager = new _CallbackManager(); + } + if (!callbackManager.handlers.some((h2) => h2.name === handler.name)) { + callbackManager.addHandler(handler, inheritable); + } + } + } + if (inheritableTags || localTags) { + if (callbackManager) { + callbackManager.addTags(inheritableTags ?? []); + callbackManager.addTags(localTags ?? [], false); + } + } + if (inheritableMetadata || localMetadata) { + if (callbackManager) { + callbackManager.addMetadata(inheritableMetadata ?? {}); + callbackManager.addMetadata(localMetadata ?? {}, false); + } + } + return callbackManager; + } + }; + function ensureHandler(handler) { + if ("name" in handler) { + return handler; + } + return BaseCallbackHandler.fromMethods(handler); + } + + // node_modules/@langchain/core/dist/singletons/async_local_storage/index.js + var MockAsyncLocalStorage2 = class { + getStore() { + return void 0; + } + run(_store, callback) { + return callback(); + } + enterWith(_store) { + return void 0; + } + }; + var mockAsyncLocalStorage2 = new MockAsyncLocalStorage2(); + var LC_CHILD_KEY = Symbol.for("lc:child_config"); + var AsyncLocalStorageProvider2 = class { + getInstance() { + return getGlobalAsyncLocalStorageInstance() ?? mockAsyncLocalStorage2; + } + getRunnableConfig() { + const storage = this.getInstance(); + return storage.getStore()?.extra?.[LC_CHILD_KEY]; + } + runWithConfig(config, callback, avoidCreatingRootRunTree) { + const callbackManager = CallbackManager._configureSync(config?.callbacks, void 0, config?.tags, void 0, config?.metadata); + const storage = this.getInstance(); + const previousValue = storage.getStore(); + const parentRunId = callbackManager?.getParentRunId(); + const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name === "langchain_tracer"); + let runTree; + if (langChainTracer && parentRunId) { + runTree = langChainTracer.getRunTreeWithTracingConfig(parentRunId); + } else if (!avoidCreatingRootRunTree) { + runTree = new RunTree({ + name: "", + tracingEnabled: false + }); + } + if (runTree) { + runTree.extra = { ...runTree.extra, [LC_CHILD_KEY]: config }; + } + if (previousValue !== void 0 && previousValue[_CONTEXT_VARIABLES_KEY] !== void 0) { + if (runTree === void 0) { + runTree = {}; + } + runTree[_CONTEXT_VARIABLES_KEY] = previousValue[_CONTEXT_VARIABLES_KEY]; + } + return storage.run(runTree, callback); + } + initializeGlobalInstance(instance) { + if (getGlobalAsyncLocalStorageInstance() === void 0) { + setGlobalAsyncLocalStorageInstance(instance); + } + } + }; + var AsyncLocalStorageProviderSingleton2 = new AsyncLocalStorageProvider2(); + + // node_modules/@langchain/core/dist/utils/async_caller.js + var import_p_retry2 = __toESM(require_p_retry(), 1); + var import_p_queue3 = __toESM(require_dist(), 1); + + // node_modules/zod-to-json-schema/dist/esm/Options.js + var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); + + // node_modules/zod-to-json-schema/dist/esm/parsers/string.js + var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); + + // node_modules/@cfworker/json-schema/dist/esm/dereference.js + var initialBaseURI = typeof self !== "undefined" && self.location && self.location.origin !== "null" ? new URL(self.location.origin + self.location.pathname + location.search) : new URL("https://github.com/cfworker"); + + // node_modules/@cfworker/json-schema/dist/esm/format.js + var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; + var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; + var HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i; + var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; + var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; + var URL_ = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; + var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; + var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; + var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; + var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; + var EMAIL = (input) => { + if (input[0] === '"') + return false; + const [name, host, ...rest] = input.split("@"); + if (!name || !host || rest.length !== 0 || name.length > 64 || host.length > 253) + return false; + if (name[0] === "." || name.endsWith(".") || name.includes("..")) + return false; + if (!/^[a-z0-9.-]+$/i.test(host) || !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(name)) + return false; + return host.split(".").every((part) => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(part)); + }; + var IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/; + var IPV6 = /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i; + var DURATION = (input) => input.length > 1 && input.length < 80 && (/^P\d+([.,]\d+)?W$/.test(input) || /^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(input) && /^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(input)); + function bind(r2) { + return r2.test.bind(r2); + } + var format = { + date, + time: time.bind(void 0, false), + "date-time": date_time, + duration: DURATION, + uri, + "uri-reference": bind(URIREF), + "uri-template": bind(URITEMPLATE), + url: bind(URL_), + email: EMAIL, + hostname: bind(HOSTNAME), + ipv4: bind(IPV4), + ipv6: bind(IPV6), + regex, + uuid: bind(UUID), + "json-pointer": bind(JSON_POINTER), + "json-pointer-uri-fragment": bind(JSON_POINTER_URI_FRAGMENT), + "relative-json-pointer": bind(RELATIVE_JSON_POINTER) + }; + function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); + } + function date(str) { + const matches = str.match(DATE); + if (!matches) + return false; + const year = +matches[1]; + const month = +matches[2]; + const day = +matches[3]; + return month >= 1 && month <= 12 && day >= 1 && day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); + } + function time(full, str) { + const matches = str.match(TIME); + if (!matches) + return false; + const hour = +matches[1]; + const minute = +matches[2]; + const second2 = +matches[3]; + const timeZone = !!matches[5]; + return (hour <= 23 && minute <= 59 && second2 <= 59 || hour == 23 && minute == 59 && second2 == 60) && (!full || timeZone); + } + var DATE_TIME_SEPARATOR = /t|\s/i; + function date_time(str) { + const dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length == 2 && date(dateTime[0]) && time(true, dateTime[1]); + } + var NOT_URI_FRAGMENT = /\/|:/; + var URI_PATTERN = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; + function uri(str) { + return NOT_URI_FRAGMENT.test(str) && URI_PATTERN.test(str); + } + var Z_ANCHOR = /[^\\]\\Z/; + function regex(str) { + if (Z_ANCHOR.test(str)) + return false; + try { + new RegExp(str, "u"); + return true; + } catch (e2) { + return false; + } + } + + // node_modules/@cfworker/json-schema/dist/esm/types.js + var OutputFormat; + (function(OutputFormat2) { + OutputFormat2[OutputFormat2["Flag"] = 1] = "Flag"; + OutputFormat2[OutputFormat2["Basic"] = 2] = "Basic"; + OutputFormat2[OutputFormat2["Detailed"] = 4] = "Detailed"; + })(OutputFormat || (OutputFormat = {})); + + // ../shared/capabilitiesOverviewConstants.ts + var CAPABILITIES_OVERVIEW_FIRST_LINE = "What Oasis can do in this build"; + var OASIS_CAPABILITIES_FEATURES_URL = "https://kahana.co/features/oasis-assistant"; + var OASIS_CAPABILITIES_LINK_LABEL = "Oasis assistant on Kahana"; + var OASIS_CAPABILITIES_FEEDBACK_URL = "https://tally.so/r/3jkNN6"; + var OASIS_CAPABILITIES_FEEDBACK_LINK_LABEL = "Send feedback"; + + // src/assistant/capabilitiesOverview.ts + var kahanaMd = `[${OASIS_CAPABILITIES_LINK_LABEL}](${OASIS_CAPABILITIES_FEATURES_URL})`; + var feedbackMd = `[${OASIS_CAPABILITIES_FEEDBACK_LINK_LABEL}](${OASIS_CAPABILITIES_FEEDBACK_URL})`; + var SUPPORT_AND_FEEDBACK_HEADING = "### Support and feedback"; + function buildCapabilitiesOverviewMarkdown(assistTools) { + if (!assistTools.length) { + return [ + `${CAPABILITIES_OVERVIEW_FIRST_LINE}`, + "", + "Oasis capabilities are not available in this build.", + "", + "You can still describe what you wanted in plain English. When something is wrong or missing, use the feedback link below or the thumbs up and thumbs down on assistant replies (training) so we can widen what Oasis supports.", + "", + SUPPORT_AND_FEEDBACK_HEADING, + "", + "Kahana lists commands in depth; the feedback form captures suggestions. Thumbs on each reply add training signal so we can expand supported behavior quickly.", + "", + `- ${kahanaMd}`, + `- ${feedbackMd}` + ].join("\n"); + } + const intro = [ + `${CAPABILITIES_OVERVIEW_FIRST_LINE}`, + "", + "Ask in plain English; Oasis picks the right browser action. Destructive steps may ask you to confirm first.", + "", + "Use your imagination: rephrase, combine ideas, and try requests that are not spelled out here. If something fails or is missing, use the feedback link in Support and feedback below or the thumbs up and thumbs down on that assistant reply (training). You help expand what Oasis supports, and we use that signal to improve quickly." + ].join("\n"); + const webSearch = [ + "### Web and search", + "", + "Open a site in a new tab or run a web search when you want something beyond the page you are on.", + "", + "- Open a link, e.g. `Open example.com in a new tab`", + "- Search the web, e.g. `Search the web for cheap flights to Lisbon`" + ].join("\n"); + const generalQuestions = [ + "### General questions", + "", + "Ask quick factual or how-to questions that are not about the browser; Oasis answers in chat and may use the web when that helps.", + "", + "- Example: `Who is the president of Djibouti?`", + "- Example: `What is the square root of 256?`" + ].join("\n"); + const summarize = [ + "### Summarization", + "", + "Ask for a concise readout of the page you are on (or a tab you point at).", + "", + "- Example: `Summarize this page`" + ].join("\n"); + const navigation = [ + "### Navigation", + "", + "Work with tabs and windows: list what is open, open new windows, move or reload tabs, pin, mute, and similar moves without digging through menus.", + "", + "- List or switch tabs, e.g. `What tabs do I have open?`", + "- New windows, e.g. `Open a new window`" + ].join("\n"); + const organization = [ + "### Organization", + "", + "Group tabs, split the view, and arrange how you work across tabs and panes.", + "", + "- Tab groups, e.g. `Create a tab group called Research`", + "- Split view shows two tabs side by side; you can choose which tabs. Try: `split view`" + ].join("\n"); + const memory = [ + "### Memory and history", + "", + "Search across open tabs, tab groups, browsing history, and saved memory. For cross-source recall, ask in your own words. For history only, start your request with `search history` (plain find is not wired to history yet).", + "", + "- Cross-source recall, e.g. `Find anything about budgets across my tabs and history`", + "- History-only search, e.g. `search history for pages I read about taxes last month`" + ].join("\n"); + const supportAndFeedback = [ + SUPPORT_AND_FEEDBACK_HEADING, + "", + "The first link opens Kahana for the full command list and roadmap. The second is the feedback form for broad suggestions. Thumbs on assistant replies feed training so we can grow what Oasis handles in step with real use.", + "", + `- ${kahanaMd}`, + `- ${feedbackMd}` + ].join("\n"); + return [ + intro, + webSearch, + generalQuestions, + summarize, + navigation, + organization, + memory, + supportAndFeedback + ].join("\n\n"); + } + + // node_modules/idb/build/index.js + var instanceOfAny = (object, constructors) => constructors.some((c3) => object instanceof c3); + var idbProxyableTypes; + var cursorAdvanceMethods; + function getIdbProxyableTypes() { + return idbProxyableTypes || (idbProxyableTypes = [ + IDBDatabase, + IDBObjectStore, + IDBIndex, + IDBCursor, + IDBTransaction + ]); + } + function getCursorAdvanceMethods() { + return cursorAdvanceMethods || (cursorAdvanceMethods = [ + IDBCursor.prototype.advance, + IDBCursor.prototype.continue, + IDBCursor.prototype.continuePrimaryKey + ]); + } + var transactionDoneMap = /* @__PURE__ */ new WeakMap(); + var transformCache = /* @__PURE__ */ new WeakMap(); + var reverseTransformCache = /* @__PURE__ */ new WeakMap(); + function promisifyRequest(request) { + const promise = new Promise((resolve, reject) => { + const unlisten = () => { + request.removeEventListener("success", success); + request.removeEventListener("error", error); + }; + const success = () => { + resolve(wrap2(request.result)); + unlisten(); + }; + const error = () => { + reject(request.error); + unlisten(); + }; + request.addEventListener("success", success); + request.addEventListener("error", error); + }); + reverseTransformCache.set(promise, request); + return promise; + } + function cacheDonePromiseForTransaction(tx) { + if (transactionDoneMap.has(tx)) + return; + const done = new Promise((resolve, reject) => { + const unlisten = () => { + tx.removeEventListener("complete", complete); + tx.removeEventListener("error", error); + tx.removeEventListener("abort", error); + }; + const complete = () => { + resolve(); + unlisten(); + }; + const error = () => { + reject(tx.error || new DOMException("AbortError", "AbortError")); + unlisten(); + }; + tx.addEventListener("complete", complete); + tx.addEventListener("error", error); + tx.addEventListener("abort", error); + }); + transactionDoneMap.set(tx, done); + } + var idbProxyTraps = { + get(target, prop, receiver) { + if (target instanceof IDBTransaction) { + if (prop === "done") + return transactionDoneMap.get(target); + if (prop === "store") { + return receiver.objectStoreNames[1] ? void 0 : receiver.objectStore(receiver.objectStoreNames[0]); + } + } + return wrap2(target[prop]); + }, + set(target, prop, value) { + target[prop] = value; + return true; + }, + has(target, prop) { + if (target instanceof IDBTransaction && (prop === "done" || prop === "store")) { + return true; + } + return prop in target; + } + }; + function replaceTraps(callback) { + idbProxyTraps = callback(idbProxyTraps); + } + function wrapFunction(func) { + if (getCursorAdvanceMethods().includes(func)) { + return function(...args) { + func.apply(unwrap(this), args); + return wrap2(this.request); + }; + } + return function(...args) { + return wrap2(func.apply(unwrap(this), args)); + }; + } + function transformCachableValue(value) { + if (typeof value === "function") + return wrapFunction(value); + if (value instanceof IDBTransaction) + cacheDonePromiseForTransaction(value); + if (instanceOfAny(value, getIdbProxyableTypes())) + return new Proxy(value, idbProxyTraps); + return value; + } + function wrap2(value) { + if (value instanceof IDBRequest) + return promisifyRequest(value); + if (transformCache.has(value)) + return transformCache.get(value); + const newValue = transformCachableValue(value); + if (newValue !== value) { + transformCache.set(value, newValue); + reverseTransformCache.set(newValue, value); + } + return newValue; + } + var unwrap = (value) => reverseTransformCache.get(value); + function openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) { + const request = indexedDB.open(name, version); + const openPromise = wrap2(request); + if (upgrade) { + request.addEventListener("upgradeneeded", (event) => { + upgrade(wrap2(request.result), event.oldVersion, event.newVersion, wrap2(request.transaction), event); + }); + } + if (blocked) { + request.addEventListener("blocked", (event) => blocked( + // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405 + event.oldVersion, + event.newVersion, + event + )); + } + openPromise.then((db) => { + if (terminated) + db.addEventListener("close", () => terminated()); + if (blocking) { + db.addEventListener("versionchange", (event) => blocking(event.oldVersion, event.newVersion, event)); + } + }).catch(() => { + }); + return openPromise; + } + var readMethods = ["get", "getKey", "getAll", "getAllKeys", "count"]; + var writeMethods = ["put", "add", "delete", "clear"]; + var cachedMethods = /* @__PURE__ */ new Map(); + function getMethod(target, prop) { + if (!(target instanceof IDBDatabase && !(prop in target) && typeof prop === "string")) { + return; + } + if (cachedMethods.get(prop)) + return cachedMethods.get(prop); + const targetFuncName = prop.replace(/FromIndex$/, ""); + const useIndex = prop !== targetFuncName; + const isWrite = writeMethods.includes(targetFuncName); + if ( + // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge. + !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || !(isWrite || readMethods.includes(targetFuncName)) + ) { + return; + } + const method = async function(storeName, ...args) { + const tx = this.transaction(storeName, isWrite ? "readwrite" : "readonly"); + let target2 = tx.store; + if (useIndex) + target2 = target2.index(args.shift()); + return (await Promise.all([ + target2[targetFuncName](...args), + isWrite && tx.done + ]))[0]; + }; + cachedMethods.set(prop, method); + return method; + } + replaceTraps((oldTraps) => ({ + ...oldTraps, + get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver), + has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop) + })); + var advanceMethodProps = ["continue", "continuePrimaryKey", "advance"]; + var methodMap = {}; + var advanceResults = /* @__PURE__ */ new WeakMap(); + var ittrProxiedCursorToOriginalProxy = /* @__PURE__ */ new WeakMap(); + var cursorIteratorTraps = { + get(target, prop) { + if (!advanceMethodProps.includes(prop)) + return target[prop]; + let cachedFunc = methodMap[prop]; + if (!cachedFunc) { + cachedFunc = methodMap[prop] = function(...args) { + advanceResults.set(this, ittrProxiedCursorToOriginalProxy.get(this)[prop](...args)); + }; + } + return cachedFunc; + } + }; + async function* iterate(...args) { + let cursor = this; + if (!(cursor instanceof IDBCursor)) { + cursor = await cursor.openCursor(...args); + } + if (!cursor) + return; + cursor = cursor; + const proxiedCursor = new Proxy(cursor, cursorIteratorTraps); + ittrProxiedCursorToOriginalProxy.set(proxiedCursor, cursor); + reverseTransformCache.set(proxiedCursor, unwrap(cursor)); + while (cursor) { + yield proxiedCursor; + cursor = await (advanceResults.get(proxiedCursor) || cursor.continue()); + advanceResults.delete(proxiedCursor); + } + } + function isIteratorProp(target, prop) { + return prop === Symbol.asyncIterator && instanceOfAny(target, [IDBIndex, IDBObjectStore, IDBCursor]) || prop === "iterate" && instanceOfAny(target, [IDBIndex, IDBObjectStore]); + } + replaceTraps((oldTraps) => ({ + ...oldTraps, + get(target, prop, receiver) { + if (isIteratorProp(target, prop)) + return iterate; + return oldTraps.get(target, prop, receiver); + }, + has(target, prop) { + return isIteratorProp(target, prop) || oldTraps.has(target, prop); + } + })); + + // node_modules/minisearch/dist/es/index.js + var ENTRIES = "ENTRIES"; + var KEYS = "KEYS"; + var VALUES = "VALUES"; + var LEAF = ""; + var TreeIterator = class { + constructor(set2, type) { + const node = set2._tree; + const keys = Array.from(node.keys()); + this.set = set2; + this._type = type; + this._path = keys.length > 0 ? [{ node, keys }] : []; + } + next() { + const value = this.dive(); + this.backtrack(); + return value; + } + dive() { + if (this._path.length === 0) { + return { done: true, value: void 0 }; + } + const { node, keys } = last$1(this._path); + if (last$1(keys) === LEAF) { + return { done: false, value: this.result() }; + } + const child = node.get(last$1(keys)); + this._path.push({ node: child, keys: Array.from(child.keys()) }); + return this.dive(); + } + backtrack() { + if (this._path.length === 0) { + return; + } + const keys = last$1(this._path).keys; + keys.pop(); + if (keys.length > 0) { + return; + } + this._path.pop(); + this.backtrack(); + } + key() { + return this.set._prefix + this._path.map(({ keys }) => last$1(keys)).filter((key) => key !== LEAF).join(""); + } + value() { + return last$1(this._path).node.get(LEAF); + } + result() { + switch (this._type) { + case VALUES: + return this.value(); + case KEYS: + return this.key(); + default: + return [this.key(), this.value()]; + } + } + [Symbol.iterator]() { + return this; + } + }; + var last$1 = (array) => { + return array[array.length - 1]; + }; + var fuzzySearch = (node, query, maxDistance) => { + const results = /* @__PURE__ */ new Map(); + if (query === void 0) + return results; + const n2 = query.length + 1; + const m3 = n2 + maxDistance; + const matrix = new Uint8Array(m3 * n2).fill(maxDistance + 1); + for (let j3 = 0; j3 < n2; ++j3) + matrix[j3] = j3; + for (let i2 = 1; i2 < m3; ++i2) + matrix[i2 * n2] = i2; + recurse(node, query, maxDistance, results, matrix, 1, n2, ""); + return results; + }; + var recurse = (node, query, maxDistance, results, matrix, m3, n2, prefix) => { + const offset = m3 * n2; + key: for (const key of node.keys()) { + if (key === LEAF) { + const distance = matrix[offset - 1]; + if (distance <= maxDistance) { + results.set(prefix, [node.get(key), distance]); + } + } else { + let i2 = m3; + for (let pos = 0; pos < key.length; ++pos, ++i2) { + const char = key[pos]; + const thisRowOffset = n2 * i2; + const prevRowOffset = thisRowOffset - n2; + let minDistance = matrix[thisRowOffset]; + const jmin = Math.max(0, i2 - maxDistance - 1); + const jmax = Math.min(n2 - 1, i2 + maxDistance); + for (let j3 = jmin; j3 < jmax; ++j3) { + const different = char !== query[j3]; + const rpl = matrix[prevRowOffset + j3] + +different; + const del = matrix[prevRowOffset + j3 + 1] + 1; + const ins = matrix[thisRowOffset + j3] + 1; + const dist = matrix[thisRowOffset + j3 + 1] = Math.min(rpl, del, ins); + if (dist < minDistance) + minDistance = dist; + } + if (minDistance > maxDistance) { + continue key; + } + } + recurse(node.get(key), query, maxDistance, results, matrix, i2, n2, prefix + key); + } + } + }; + var SearchableMap = class _SearchableMap { + /** + * The constructor is normally called without arguments, creating an empty + * map. In order to create a {@link SearchableMap} from an iterable or from an + * object, check {@link SearchableMap.from} and {@link + * SearchableMap.fromObject}. + * + * The constructor arguments are for internal use, when creating derived + * mutable views of a map at a prefix. + */ + constructor(tree = /* @__PURE__ */ new Map(), prefix = "") { + this._size = void 0; + this._tree = tree; + this._prefix = prefix; + } + /** + * Creates and returns a mutable view of this {@link SearchableMap}, + * containing only entries that share the given prefix. + * + * ### Usage: + * + * ```javascript + * let map = new SearchableMap() + * map.set("unicorn", 1) + * map.set("universe", 2) + * map.set("university", 3) + * map.set("unique", 4) + * map.set("hello", 5) + * + * let uni = map.atPrefix("uni") + * uni.get("unique") // => 4 + * uni.get("unicorn") // => 1 + * uni.get("hello") // => undefined + * + * let univer = map.atPrefix("univer") + * univer.get("unique") // => undefined + * univer.get("universe") // => 2 + * univer.get("university") // => 3 + * ``` + * + * @param prefix The prefix + * @return A {@link SearchableMap} representing a mutable view of the original + * Map at the given prefix + */ + atPrefix(prefix) { + if (!prefix.startsWith(this._prefix)) { + throw new Error("Mismatched prefix"); + } + const [node, path] = trackDown(this._tree, prefix.slice(this._prefix.length)); + if (node === void 0) { + const [parentNode, key] = last(path); + for (const k3 of parentNode.keys()) { + if (k3 !== LEAF && k3.startsWith(key)) { + const node2 = /* @__PURE__ */ new Map(); + node2.set(k3.slice(key.length), parentNode.get(k3)); + return new _SearchableMap(node2, prefix); + } + } + } + return new _SearchableMap(node, prefix); + } + /** + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/clear + */ + clear() { + this._size = void 0; + this._tree.clear(); + } + /** + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/delete + * @param key Key to delete + */ + delete(key) { + this._size = void 0; + return remove(this._tree, key); + } + /** + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries + * @return An iterator iterating through `[key, value]` entries. + */ + entries() { + return new TreeIterator(this, ENTRIES); + } + /** + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach + * @param fn Iteration function + */ + forEach(fn) { + for (const [key, value] of this) { + fn(key, value, this); + } + } + /** + * Returns a Map of all the entries that have a key within the given edit + * distance from the search key. The keys of the returned Map are the matching + * keys, while the values are two-element arrays where the first element is + * the value associated to the key, and the second is the edit distance of the + * key to the search key. + * + * ### Usage: + * + * ```javascript + * let map = new SearchableMap() + * map.set('hello', 'world') + * map.set('hell', 'yeah') + * map.set('ciao', 'mondo') + * + * // Get all entries that match the key 'hallo' with a maximum edit distance of 2 + * map.fuzzyGet('hallo', 2) + * // => Map(2) { 'hello' => ['world', 1], 'hell' => ['yeah', 2] } + * + * // In the example, the "hello" key has value "world" and edit distance of 1 + * // (change "e" to "a"), the key "hell" has value "yeah" and edit distance of 2 + * // (change "e" to "a", delete "o") + * ``` + * + * @param key The search key + * @param maxEditDistance The maximum edit distance (Levenshtein) + * @return A Map of the matching keys to their value and edit distance + */ + fuzzyGet(key, maxEditDistance) { + return fuzzySearch(this._tree, key, maxEditDistance); + } + /** + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get + * @param key Key to get + * @return Value associated to the key, or `undefined` if the key is not + * found. + */ + get(key) { + const node = lookup(this._tree, key); + return node !== void 0 ? node.get(LEAF) : void 0; + } + /** + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has + * @param key Key + * @return True if the key is in the map, false otherwise + */ + has(key) { + const node = lookup(this._tree, key); + return node !== void 0 && node.has(LEAF); + } + /** + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/keys + * @return An `Iterable` iterating through keys + */ + keys() { + return new TreeIterator(this, KEYS); + } + /** + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/set + * @param key Key to set + * @param value Value to associate to the key + * @return The {@link SearchableMap} itself, to allow chaining + */ + set(key, value) { + if (typeof key !== "string") { + throw new Error("key must be a string"); + } + this._size = void 0; + const node = createPath(this._tree, key); + node.set(LEAF, value); + return this; + } + /** + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/size + */ + get size() { + if (this._size) { + return this._size; + } + this._size = 0; + const iter = this.entries(); + while (!iter.next().done) + this._size += 1; + return this._size; + } + /** + * Updates the value at the given key using the provided function. The function + * is called with the current value at the key, and its return value is used as + * the new value to be set. + * + * ### Example: + * + * ```javascript + * // Increment the current value by one + * searchableMap.update('somekey', (currentValue) => currentValue == null ? 0 : currentValue + 1) + * ``` + * + * If the value at the given key is or will be an object, it might not require + * re-assignment. In that case it is better to use `fetch()`, because it is + * faster. + * + * @param key The key to update + * @param fn The function used to compute the new value from the current one + * @return The {@link SearchableMap} itself, to allow chaining + */ + update(key, fn) { + if (typeof key !== "string") { + throw new Error("key must be a string"); + } + this._size = void 0; + const node = createPath(this._tree, key); + node.set(LEAF, fn(node.get(LEAF))); + return this; + } + /** + * Fetches the value of the given key. If the value does not exist, calls the + * given function to create a new value, which is inserted at the given key + * and subsequently returned. + * + * ### Example: + * + * ```javascript + * const map = searchableMap.fetch('somekey', () => new Map()) + * map.set('foo', 'bar') + * ``` + * + * @param key The key to update + * @param initial A function that creates a new value if the key does not exist + * @return The existing or new value at the given key + */ + fetch(key, initial) { + if (typeof key !== "string") { + throw new Error("key must be a string"); + } + this._size = void 0; + const node = createPath(this._tree, key); + let value = node.get(LEAF); + if (value === void 0) { + node.set(LEAF, value = initial()); + } + return value; + } + /** + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/values + * @return An `Iterable` iterating through values. + */ + values() { + return new TreeIterator(this, VALUES); + } + /** + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/@@iterator + */ + [Symbol.iterator]() { + return this.entries(); + } + /** + * Creates a {@link SearchableMap} from an `Iterable` of entries + * + * @param entries Entries to be inserted in the {@link SearchableMap} + * @return A new {@link SearchableMap} with the given entries + */ + static from(entries2) { + const tree = new _SearchableMap(); + for (const [key, value] of entries2) { + tree.set(key, value); + } + return tree; + } + /** + * Creates a {@link SearchableMap} from the iterable properties of a JavaScript object + * + * @param object Object of entries for the {@link SearchableMap} + * @return A new {@link SearchableMap} with the given entries + */ + static fromObject(object) { + return _SearchableMap.from(Object.entries(object)); + } + }; + var trackDown = (tree, key, path = []) => { + if (key.length === 0 || tree == null) { + return [tree, path]; + } + for (const k3 of tree.keys()) { + if (k3 !== LEAF && key.startsWith(k3)) { + path.push([tree, k3]); + return trackDown(tree.get(k3), key.slice(k3.length), path); + } + } + path.push([tree, key]); + return trackDown(void 0, "", path); + }; + var lookup = (tree, key) => { + if (key.length === 0 || tree == null) { + return tree; + } + for (const k3 of tree.keys()) { + if (k3 !== LEAF && key.startsWith(k3)) { + return lookup(tree.get(k3), key.slice(k3.length)); + } + } + }; + var createPath = (node, key) => { + const keyLength = key.length; + outer: for (let pos = 0; node && pos < keyLength; ) { + for (const k3 of node.keys()) { + if (k3 !== LEAF && key[pos] === k3[0]) { + const len = Math.min(keyLength - pos, k3.length); + let offset = 1; + while (offset < len && key[pos + offset] === k3[offset]) + ++offset; + const child2 = node.get(k3); + if (offset === k3.length) { + node = child2; + } else { + const intermediate = /* @__PURE__ */ new Map(); + intermediate.set(k3.slice(offset), child2); + node.set(key.slice(pos, pos + offset), intermediate); + node.delete(k3); + node = intermediate; + } + pos += offset; + continue outer; + } + } + const child = /* @__PURE__ */ new Map(); + node.set(key.slice(pos), child); + return child; + } + return node; + }; + var remove = (tree, key) => { + const [node, path] = trackDown(tree, key); + if (node === void 0) { + return; + } + node.delete(LEAF); + if (node.size === 0) { + cleanup(path); + } else if (node.size === 1) { + const [key2, value] = node.entries().next().value; + merge(path, key2, value); + } + }; + var cleanup = (path) => { + if (path.length === 0) { + return; + } + const [node, key] = last(path); + node.delete(key); + if (node.size === 0) { + cleanup(path.slice(0, -1)); + } else if (node.size === 1) { + const [key2, value] = node.entries().next().value; + if (key2 !== LEAF) { + merge(path.slice(0, -1), key2, value); + } + } + }; + var merge = (path, key, value) => { + if (path.length === 0) { + return; + } + const [node, nodeKey] = last(path); + node.set(nodeKey + key, value); + node.delete(nodeKey); + }; + var last = (array) => { + return array[array.length - 1]; + }; + var OR = "or"; + var AND = "and"; + var AND_NOT = "and_not"; + var MiniSearch = class _MiniSearch { + /** + * @param options Configuration options + * + * ### Examples: + * + * ```javascript + * // Create a search engine that indexes the 'title' and 'text' fields of your + * // documents: + * const miniSearch = new MiniSearch({ fields: ['title', 'text'] }) + * ``` + * + * ### ID Field: + * + * ```javascript + * // Your documents are assumed to include a unique 'id' field, but if you want + * // to use a different field for document identification, you can set the + * // 'idField' option: + * const miniSearch = new MiniSearch({ idField: 'key', fields: ['title', 'text'] }) + * ``` + * + * ### Options and defaults: + * + * ```javascript + * // The full set of options (here with their default value) is: + * const miniSearch = new MiniSearch({ + * // idField: field that uniquely identifies a document + * idField: 'id', + * + * // extractField: function used to get the value of a field in a document. + * // By default, it assumes the document is a flat object with field names as + * // property keys and field values as string property values, but custom logic + * // can be implemented by setting this option to a custom extractor function. + * extractField: (document, fieldName) => document[fieldName], + * + * // tokenize: function used to split fields into individual terms. By + * // default, it is also used to tokenize search queries, unless a specific + * // `tokenize` search option is supplied. When tokenizing an indexed field, + * // the field name is passed as the second argument. + * tokenize: (string, _fieldName) => string.split(SPACE_OR_PUNCTUATION), + * + * // processTerm: function used to process each tokenized term before + * // indexing. It can be used for stemming and normalization. Return a falsy + * // value in order to discard a term. By default, it is also used to process + * // search queries, unless a specific `processTerm` option is supplied as a + * // search option. When processing a term from a indexed field, the field + * // name is passed as the second argument. + * processTerm: (term, _fieldName) => term.toLowerCase(), + * + * // searchOptions: default search options, see the `search` method for + * // details + * searchOptions: undefined, + * + * // fields: document fields to be indexed. Mandatory, but not set by default + * fields: undefined + * + * // storeFields: document fields to be stored and returned as part of the + * // search results. + * storeFields: [] + * }) + * ``` + */ + constructor(options) { + if ((options === null || options === void 0 ? void 0 : options.fields) == null) { + throw new Error('MiniSearch: option "fields" must be provided'); + } + const autoVacuum = options.autoVacuum == null || options.autoVacuum === true ? defaultAutoVacuumOptions : options.autoVacuum; + this._options = { + ...defaultOptions2, + ...options, + autoVacuum, + searchOptions: { ...defaultSearchOptions, ...options.searchOptions || {} }, + autoSuggestOptions: { ...defaultAutoSuggestOptions, ...options.autoSuggestOptions || {} } + }; + this._index = new SearchableMap(); + this._documentCount = 0; + this._documentIds = /* @__PURE__ */ new Map(); + this._idToShortId = /* @__PURE__ */ new Map(); + this._fieldIds = {}; + this._fieldLength = /* @__PURE__ */ new Map(); + this._avgFieldLength = []; + this._nextId = 0; + this._storedFields = /* @__PURE__ */ new Map(); + this._dirtCount = 0; + this._currentVacuum = null; + this._enqueuedVacuum = null; + this._enqueuedVacuumConditions = defaultVacuumConditions; + this.addFields(this._options.fields); + } + /** + * Adds a document to the index + * + * @param document The document to be indexed + */ + add(document2) { + const { extractField, stringifyField, tokenize: tokenize2, processTerm, fields, idField } = this._options; + const id = extractField(document2, idField); + if (id == null) { + throw new Error(`MiniSearch: document does not have ID field "${idField}"`); + } + if (this._idToShortId.has(id)) { + throw new Error(`MiniSearch: duplicate ID ${id}`); + } + const shortDocumentId = this.addDocumentId(id); + this.saveStoredFields(shortDocumentId, document2); + for (const field of fields) { + const fieldValue = extractField(document2, field); + if (fieldValue == null) + continue; + const tokens = tokenize2(stringifyField(fieldValue, field), field); + const fieldId = this._fieldIds[field]; + const uniqueTerms = new Set(tokens).size; + this.addFieldLength(shortDocumentId, fieldId, this._documentCount - 1, uniqueTerms); + for (const term of tokens) { + const processedTerm = processTerm(term, field); + if (Array.isArray(processedTerm)) { + for (const t2 of processedTerm) { + this.addTerm(fieldId, shortDocumentId, t2); + } + } else if (processedTerm) { + this.addTerm(fieldId, shortDocumentId, processedTerm); + } + } + } + } + /** + * Adds all the given documents to the index + * + * @param documents An array of documents to be indexed + */ + addAll(documents) { + for (const document2 of documents) + this.add(document2); + } + /** + * Adds all the given documents to the index asynchronously. + * + * Returns a promise that resolves (to `undefined`) when the indexing is done. + * This method is useful when index many documents, to avoid blocking the main + * thread. The indexing is performed asynchronously and in chunks. + * + * @param documents An array of documents to be indexed + * @param options Configuration options + * @return A promise resolving to `undefined` when the indexing is done + */ + addAllAsync(documents, options = {}) { + const { chunkSize = 10 } = options; + const acc = { chunk: [], promise: Promise.resolve() }; + const { chunk, promise } = documents.reduce(({ chunk: chunk2, promise: promise2 }, document2, i2) => { + chunk2.push(document2); + if ((i2 + 1) % chunkSize === 0) { + return { + chunk: [], + promise: promise2.then(() => new Promise((resolve) => setTimeout(resolve, 0))).then(() => this.addAll(chunk2)) + }; + } else { + return { chunk: chunk2, promise: promise2 }; + } + }, acc); + return promise.then(() => this.addAll(chunk)); + } + /** + * Removes the given document from the index. + * + * The document to remove must NOT have changed between indexing and removal, + * otherwise the index will be corrupted. + * + * This method requires passing the full document to be removed (not just the + * ID), and immediately removes the document from the inverted index, allowing + * memory to be released. A convenient alternative is {@link + * MiniSearch#discard}, which needs only the document ID, and has the same + * visible effect, but delays cleaning up the index until the next vacuuming. + * + * @param document The document to be removed + */ + remove(document2) { + const { tokenize: tokenize2, processTerm, extractField, stringifyField, fields, idField } = this._options; + const id = extractField(document2, idField); + if (id == null) { + throw new Error(`MiniSearch: document does not have ID field "${idField}"`); + } + const shortId = this._idToShortId.get(id); + if (shortId == null) { + throw new Error(`MiniSearch: cannot remove document with ID ${id}: it is not in the index`); + } + for (const field of fields) { + const fieldValue = extractField(document2, field); + if (fieldValue == null) + continue; + const tokens = tokenize2(stringifyField(fieldValue, field), field); + const fieldId = this._fieldIds[field]; + const uniqueTerms = new Set(tokens).size; + this.removeFieldLength(shortId, fieldId, this._documentCount, uniqueTerms); + for (const term of tokens) { + const processedTerm = processTerm(term, field); + if (Array.isArray(processedTerm)) { + for (const t2 of processedTerm) { + this.removeTerm(fieldId, shortId, t2); + } + } else if (processedTerm) { + this.removeTerm(fieldId, shortId, processedTerm); + } + } + } + this._storedFields.delete(shortId); + this._documentIds.delete(shortId); + this._idToShortId.delete(id); + this._fieldLength.delete(shortId); + this._documentCount -= 1; + } + /** + * Removes all the given documents from the index. If called with no arguments, + * it removes _all_ documents from the index. + * + * @param documents The documents to be removed. If this argument is omitted, + * all documents are removed. Note that, for removing all documents, it is + * more efficient to call this method with no arguments than to pass all + * documents. + */ + removeAll(documents) { + if (documents) { + for (const document2 of documents) + this.remove(document2); + } else if (arguments.length > 0) { + throw new Error("Expected documents to be present. Omit the argument to remove all documents."); + } else { + this._index = new SearchableMap(); + this._documentCount = 0; + this._documentIds = /* @__PURE__ */ new Map(); + this._idToShortId = /* @__PURE__ */ new Map(); + this._fieldLength = /* @__PURE__ */ new Map(); + this._avgFieldLength = []; + this._storedFields = /* @__PURE__ */ new Map(); + this._nextId = 0; + } + } + /** + * Discards the document with the given ID, so it won't appear in search results + * + * It has the same visible effect of {@link MiniSearch.remove} (both cause the + * document to stop appearing in searches), but a different effect on the + * internal data structures: + * + * - {@link MiniSearch#remove} requires passing the full document to be + * removed as argument, and removes it from the inverted index immediately. + * + * - {@link MiniSearch#discard} instead only needs the document ID, and + * works by marking the current version of the document as discarded, so it + * is immediately ignored by searches. This is faster and more convenient + * than {@link MiniSearch#remove}, but the index is not immediately + * modified. To take care of that, vacuuming is performed after a certain + * number of documents are discarded, cleaning up the index and allowing + * memory to be released. + * + * After discarding a document, it is possible to re-add a new version, and + * only the new version will appear in searches. In other words, discarding + * and re-adding a document works exactly like removing and re-adding it. The + * {@link MiniSearch.replace} method can also be used to replace a document + * with a new version. + * + * #### Details about vacuuming + * + * Repetite calls to this method would leave obsolete document references in + * the index, invisible to searches. Two mechanisms take care of cleaning up: + * clean up during search, and vacuuming. + * + * - Upon search, whenever a discarded ID is found (and ignored for the + * results), references to the discarded document are removed from the + * inverted index entries for the search terms. This ensures that subsequent + * searches for the same terms do not need to skip these obsolete references + * again. + * + * - In addition, vacuuming is performed automatically by default (see the + * `autoVacuum` field in {@link Options}) after a certain number of + * documents are discarded. Vacuuming traverses all terms in the index, + * cleaning up all references to discarded documents. Vacuuming can also be + * triggered manually by calling {@link MiniSearch#vacuum}. + * + * @param id The ID of the document to be discarded + */ + discard(id) { + const shortId = this._idToShortId.get(id); + if (shortId == null) { + throw new Error(`MiniSearch: cannot discard document with ID ${id}: it is not in the index`); + } + this._idToShortId.delete(id); + this._documentIds.delete(shortId); + this._storedFields.delete(shortId); + (this._fieldLength.get(shortId) || []).forEach((fieldLength, fieldId) => { + this.removeFieldLength(shortId, fieldId, this._documentCount, fieldLength); + }); + this._fieldLength.delete(shortId); + this._documentCount -= 1; + this._dirtCount += 1; + this.maybeAutoVacuum(); + } + maybeAutoVacuum() { + if (this._options.autoVacuum === false) { + return; + } + const { minDirtFactor, minDirtCount, batchSize, batchWait } = this._options.autoVacuum; + this.conditionalVacuum({ batchSize, batchWait }, { minDirtCount, minDirtFactor }); + } + /** + * Discards the documents with the given IDs, so they won't appear in search + * results + * + * It is equivalent to calling {@link MiniSearch#discard} for all the given + * IDs, but with the optimization of triggering at most one automatic + * vacuuming at the end. + * + * Note: to remove all documents from the index, it is faster and more + * convenient to call {@link MiniSearch.removeAll} with no argument, instead + * of passing all IDs to this method. + */ + discardAll(ids) { + const autoVacuum = this._options.autoVacuum; + try { + this._options.autoVacuum = false; + for (const id of ids) { + this.discard(id); + } + } finally { + this._options.autoVacuum = autoVacuum; + } + this.maybeAutoVacuum(); + } + /** + * It replaces an existing document with the given updated version + * + * It works by discarding the current version and adding the updated one, so + * it is functionally equivalent to calling {@link MiniSearch#discard} + * followed by {@link MiniSearch#add}. The ID of the updated document should + * be the same as the original one. + * + * Since it uses {@link MiniSearch#discard} internally, this method relies on + * vacuuming to clean up obsolete document references from the index, allowing + * memory to be released (see {@link MiniSearch#discard}). + * + * @param updatedDocument The updated document to replace the old version + * with + */ + replace(updatedDocument) { + const { idField, extractField } = this._options; + const id = extractField(updatedDocument, idField); + this.discard(id); + this.add(updatedDocument); + } + /** + * Triggers a manual vacuuming, cleaning up references to discarded documents + * from the inverted index + * + * Vacuuming is only useful for applications that use the {@link + * MiniSearch#discard} or {@link MiniSearch#replace} methods. + * + * By default, vacuuming is performed automatically when needed (controlled by + * the `autoVacuum` field in {@link Options}), so there is usually no need to + * call this method, unless one wants to make sure to perform vacuuming at a + * specific moment. + * + * Vacuuming traverses all terms in the inverted index in batches, and cleans + * up references to discarded documents from the posting list, allowing memory + * to be released. + * + * The method takes an optional object as argument with the following keys: + * + * - `batchSize`: the size of each batch (1000 by default) + * + * - `batchWait`: the number of milliseconds to wait between batches (10 by + * default) + * + * On large indexes, vacuuming could have a non-negligible cost: batching + * avoids blocking the thread for long, diluting this cost so that it is not + * negatively affecting the application. Nonetheless, this method should only + * be called when necessary, and relying on automatic vacuuming is usually + * better. + * + * It returns a promise that resolves (to undefined) when the clean up is + * completed. If vacuuming is already ongoing at the time this method is + * called, a new one is enqueued immediately after the ongoing one, and a + * corresponding promise is returned. However, no more than one vacuuming is + * enqueued on top of the ongoing one, even if this method is called more + * times (enqueuing multiple ones would be useless). + * + * @param options Configuration options for the batch size and delay. See + * {@link VacuumOptions}. + */ + vacuum(options = {}) { + return this.conditionalVacuum(options); + } + conditionalVacuum(options, conditions) { + if (this._currentVacuum) { + this._enqueuedVacuumConditions = this._enqueuedVacuumConditions && conditions; + if (this._enqueuedVacuum != null) { + return this._enqueuedVacuum; + } + this._enqueuedVacuum = this._currentVacuum.then(() => { + const conditions2 = this._enqueuedVacuumConditions; + this._enqueuedVacuumConditions = defaultVacuumConditions; + return this.performVacuuming(options, conditions2); + }); + return this._enqueuedVacuum; + } + if (this.vacuumConditionsMet(conditions) === false) { + return Promise.resolve(); + } + this._currentVacuum = this.performVacuuming(options); + return this._currentVacuum; + } + async performVacuuming(options, conditions) { + const initialDirtCount = this._dirtCount; + if (this.vacuumConditionsMet(conditions)) { + const batchSize = options.batchSize || defaultVacuumOptions.batchSize; + const batchWait = options.batchWait || defaultVacuumOptions.batchWait; + let i2 = 1; + for (const [term, fieldsData] of this._index) { + for (const [fieldId, fieldIndex] of fieldsData) { + for (const [shortId] of fieldIndex) { + if (this._documentIds.has(shortId)) { + continue; + } + if (fieldIndex.size <= 1) { + fieldsData.delete(fieldId); + } else { + fieldIndex.delete(shortId); + } + } + } + if (this._index.get(term).size === 0) { + this._index.delete(term); + } + if (i2 % batchSize === 0) { + await new Promise((resolve) => setTimeout(resolve, batchWait)); + } + i2 += 1; + } + this._dirtCount -= initialDirtCount; + } + await null; + this._currentVacuum = this._enqueuedVacuum; + this._enqueuedVacuum = null; + } + vacuumConditionsMet(conditions) { + if (conditions == null) { + return true; + } + let { minDirtCount, minDirtFactor } = conditions; + minDirtCount = minDirtCount || defaultAutoVacuumOptions.minDirtCount; + minDirtFactor = minDirtFactor || defaultAutoVacuumOptions.minDirtFactor; + return this.dirtCount >= minDirtCount && this.dirtFactor >= minDirtFactor; + } + /** + * Is `true` if a vacuuming operation is ongoing, `false` otherwise + */ + get isVacuuming() { + return this._currentVacuum != null; + } + /** + * The number of documents discarded since the most recent vacuuming + */ + get dirtCount() { + return this._dirtCount; + } + /** + * A number between 0 and 1 giving an indication about the proportion of + * documents that are discarded, and can therefore be cleaned up by vacuuming. + * A value close to 0 means that the index is relatively clean, while a higher + * value means that the index is relatively dirty, and vacuuming could release + * memory. + */ + get dirtFactor() { + return this._dirtCount / (1 + this._documentCount + this._dirtCount); + } + /** + * Returns `true` if a document with the given ID is present in the index and + * available for search, `false` otherwise + * + * @param id The document ID + */ + has(id) { + return this._idToShortId.has(id); + } + /** + * Returns the stored fields (as configured in the `storeFields` constructor + * option) for the given document ID. Returns `undefined` if the document is + * not present in the index. + * + * @param id The document ID + */ + getStoredFields(id) { + const shortId = this._idToShortId.get(id); + if (shortId == null) { + return void 0; + } + return this._storedFields.get(shortId); + } + /** + * Search for documents matching the given search query. + * + * The result is a list of scored document IDs matching the query, sorted by + * descending score, and each including data about which terms were matched and + * in which fields. + * + * ### Basic usage: + * + * ```javascript + * // Search for "zen art motorcycle" with default options: terms have to match + * // exactly, and individual terms are joined with OR + * miniSearch.search('zen art motorcycle') + * // => [ { id: 2, score: 2.77258, match: { ... } }, { id: 4, score: 1.38629, match: { ... } } ] + * ``` + * + * ### Restrict search to specific fields: + * + * ```javascript + * // Search only in the 'title' field + * miniSearch.search('zen', { fields: ['title'] }) + * ``` + * + * ### Field boosting: + * + * ```javascript + * // Boost a field + * miniSearch.search('zen', { boost: { title: 2 } }) + * ``` + * + * ### Prefix search: + * + * ```javascript + * // Search for "moto" with prefix search (it will match documents + * // containing terms that start with "moto" or "neuro") + * miniSearch.search('moto neuro', { prefix: true }) + * ``` + * + * ### Fuzzy search: + * + * ```javascript + * // Search for "ismael" with fuzzy search (it will match documents containing + * // terms similar to "ismael", with a maximum edit distance of 0.2 term.length + * // (rounded to nearest integer) + * miniSearch.search('ismael', { fuzzy: 0.2 }) + * ``` + * + * ### Combining strategies: + * + * ```javascript + * // Mix of exact match, prefix search, and fuzzy search + * miniSearch.search('ismael mob', { + * prefix: true, + * fuzzy: 0.2 + * }) + * ``` + * + * ### Advanced prefix and fuzzy search: + * + * ```javascript + * // Perform fuzzy and prefix search depending on the search term. Here + * // performing prefix and fuzzy search only on terms longer than 3 characters + * miniSearch.search('ismael mob', { + * prefix: term => term.length > 3 + * fuzzy: term => term.length > 3 ? 0.2 : null + * }) + * ``` + * + * ### Combine with AND: + * + * ```javascript + * // Combine search terms with AND (to match only documents that contain both + * // "motorcycle" and "art") + * miniSearch.search('motorcycle art', { combineWith: 'AND' }) + * ``` + * + * ### Combine with AND_NOT: + * + * There is also an AND_NOT combinator, that finds documents that match the + * first term, but do not match any of the other terms. This combinator is + * rarely useful with simple queries, and is meant to be used with advanced + * query combinations (see later for more details). + * + * ### Filtering results: + * + * ```javascript + * // Filter only results in the 'fiction' category (assuming that 'category' + * // is a stored field) + * miniSearch.search('motorcycle art', { + * filter: (result) => result.category === 'fiction' + * }) + * ``` + * + * ### Wildcard query + * + * Searching for an empty string (assuming the default tokenizer) returns no + * results. Sometimes though, one needs to match all documents, like in a + * "wildcard" search. This is possible by passing the special value + * {@link MiniSearch.wildcard} as the query: + * + * ```javascript + * // Return search results for all documents + * miniSearch.search(MiniSearch.wildcard) + * ``` + * + * Note that search options such as `filter` and `boostDocument` are still + * applied, influencing which results are returned, and their order: + * + * ```javascript + * // Return search results for all documents in the 'fiction' category + * miniSearch.search(MiniSearch.wildcard, { + * filter: (result) => result.category === 'fiction' + * }) + * ``` + * + * ### Advanced combination of queries: + * + * It is possible to combine different subqueries with OR, AND, and AND_NOT, + * and even with different search options, by passing a query expression + * tree object as the first argument, instead of a string. + * + * ```javascript + * // Search for documents that contain "zen" and ("motorcycle" or "archery") + * miniSearch.search({ + * combineWith: 'AND', + * queries: [ + * 'zen', + * { + * combineWith: 'OR', + * queries: ['motorcycle', 'archery'] + * } + * ] + * }) + * + * // Search for documents that contain ("apple" or "pear") but not "juice" and + * // not "tree" + * miniSearch.search({ + * combineWith: 'AND_NOT', + * queries: [ + * { + * combineWith: 'OR', + * queries: ['apple', 'pear'] + * }, + * 'juice', + * 'tree' + * ] + * }) + * ``` + * + * Each node in the expression tree can be either a string, or an object that + * supports all {@link SearchOptions} fields, plus a `queries` array field for + * subqueries. + * + * Note that, while this can become complicated to do by hand for complex or + * deeply nested queries, it provides a formalized expression tree API for + * external libraries that implement a parser for custom query languages. + * + * @param query Search query + * @param searchOptions Search options. Each option, if not given, defaults to the corresponding value of `searchOptions` given to the constructor, or to the library default. + */ + search(query, searchOptions = {}) { + const { searchOptions: globalSearchOptions } = this._options; + const searchOptionsWithDefaults = { ...globalSearchOptions, ...searchOptions }; + const rawResults = this.executeQuery(query, searchOptions); + const results = []; + for (const [docId, { score, terms, match }] of rawResults) { + const quality = terms.length || 1; + const result = { + id: this._documentIds.get(docId), + score: score * quality, + terms: Object.keys(match), + queryTerms: terms, + match + }; + Object.assign(result, this._storedFields.get(docId)); + if (searchOptionsWithDefaults.filter == null || searchOptionsWithDefaults.filter(result)) { + results.push(result); + } + } + if (query === _MiniSearch.wildcard && searchOptionsWithDefaults.boostDocument == null) { + return results; + } + results.sort(byScore); + return results; + } + /** + * Provide suggestions for the given search query + * + * The result is a list of suggested modified search queries, derived from the + * given search query, each with a relevance score, sorted by descending score. + * + * By default, it uses the same options used for search, except that by + * default it performs prefix search on the last term of the query, and + * combine terms with `'AND'` (requiring all query terms to match). Custom + * options can be passed as a second argument. Defaults can be changed upon + * calling the {@link MiniSearch} constructor, by passing a + * `autoSuggestOptions` option. + * + * ### Basic usage: + * + * ```javascript + * // Get suggestions for 'neuro': + * miniSearch.autoSuggest('neuro') + * // => [ { suggestion: 'neuromancer', terms: [ 'neuromancer' ], score: 0.46240 } ] + * ``` + * + * ### Multiple words: + * + * ```javascript + * // Get suggestions for 'zen ar': + * miniSearch.autoSuggest('zen ar') + * // => [ + * // { suggestion: 'zen archery art', terms: [ 'zen', 'archery', 'art' ], score: 1.73332 }, + * // { suggestion: 'zen art', terms: [ 'zen', 'art' ], score: 1.21313 } + * // ] + * ``` + * + * ### Fuzzy suggestions: + * + * ```javascript + * // Correct spelling mistakes using fuzzy search: + * miniSearch.autoSuggest('neromancer', { fuzzy: 0.2 }) + * // => [ { suggestion: 'neuromancer', terms: [ 'neuromancer' ], score: 1.03998 } ] + * ``` + * + * ### Filtering: + * + * ```javascript + * // Get suggestions for 'zen ar', but only within the 'fiction' category + * // (assuming that 'category' is a stored field): + * miniSearch.autoSuggest('zen ar', { + * filter: (result) => result.category === 'fiction' + * }) + * // => [ + * // { suggestion: 'zen archery art', terms: [ 'zen', 'archery', 'art' ], score: 1.73332 }, + * // { suggestion: 'zen art', terms: [ 'zen', 'art' ], score: 1.21313 } + * // ] + * ``` + * + * @param queryString Query string to be expanded into suggestions + * @param options Search options. The supported options and default values + * are the same as for the {@link MiniSearch#search} method, except that by + * default prefix search is performed on the last term in the query, and terms + * are combined with `'AND'`. + * @return A sorted array of suggestions sorted by relevance score. + */ + autoSuggest(queryString, options = {}) { + options = { ...this._options.autoSuggestOptions, ...options }; + const suggestions = /* @__PURE__ */ new Map(); + for (const { score, terms } of this.search(queryString, options)) { + const phrase = terms.join(" "); + const suggestion = suggestions.get(phrase); + if (suggestion != null) { + suggestion.score += score; + suggestion.count += 1; + } else { + suggestions.set(phrase, { score, terms, count: 1 }); + } + } + const results = []; + for (const [suggestion, { score, terms, count: count3 }] of suggestions) { + results.push({ suggestion, terms, score: score / count3 }); + } + results.sort(byScore); + return results; + } + /** + * Total number of documents available to search + */ + get documentCount() { + return this._documentCount; + } + /** + * Number of terms in the index + */ + get termCount() { + return this._index.size; + } + /** + * Deserializes a JSON index (serialized with `JSON.stringify(miniSearch)`) + * and instantiates a MiniSearch instance. It should be given the same options + * originally used when serializing the index. + * + * ### Usage: + * + * ```javascript + * // If the index was serialized with: + * let miniSearch = new MiniSearch({ fields: ['title', 'text'] }) + * miniSearch.addAll(documents) + * + * const json = JSON.stringify(miniSearch) + * // It can later be deserialized like this: + * miniSearch = MiniSearch.loadJSON(json, { fields: ['title', 'text'] }) + * ``` + * + * @param json JSON-serialized index + * @param options configuration options, same as the constructor + * @return An instance of MiniSearch deserialized from the given JSON. + */ + static loadJSON(json, options) { + if (options == null) { + throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index"); + } + return this.loadJS(JSON.parse(json), options); + } + /** + * Async equivalent of {@link MiniSearch.loadJSON} + * + * This function is an alternative to {@link MiniSearch.loadJSON} that returns + * a promise, and loads the index in batches, leaving pauses between them to avoid + * blocking the main thread. It tends to be slower than the synchronous + * version, but does not block the main thread, so it can be a better choice + * when deserializing very large indexes. + * + * @param json JSON-serialized index + * @param options configuration options, same as the constructor + * @return A Promise that will resolve to an instance of MiniSearch deserialized from the given JSON. + */ + static async loadJSONAsync(json, options) { + if (options == null) { + throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index"); + } + return this.loadJSAsync(JSON.parse(json), options); + } + /** + * Returns the default value of an option. It will throw an error if no option + * with the given name exists. + * + * @param optionName Name of the option + * @return The default value of the given option + * + * ### Usage: + * + * ```javascript + * // Get default tokenizer + * MiniSearch.getDefault('tokenize') + * + * // Get default term processor + * MiniSearch.getDefault('processTerm') + * + * // Unknown options will throw an error + * MiniSearch.getDefault('notExisting') + * // => throws 'MiniSearch: unknown option "notExisting"' + * ``` + */ + static getDefault(optionName) { + if (defaultOptions2.hasOwnProperty(optionName)) { + return getOwnProperty(defaultOptions2, optionName); + } else { + throw new Error(`MiniSearch: unknown option "${optionName}"`); + } + } + /** + * @ignore + */ + static loadJS(js, options) { + const { index: index2, documentIds, fieldLength, storedFields, serializationVersion } = js; + const miniSearch = this.instantiateMiniSearch(js, options); + miniSearch._documentIds = objectToNumericMap(documentIds); + miniSearch._fieldLength = objectToNumericMap(fieldLength); + miniSearch._storedFields = objectToNumericMap(storedFields); + for (const [shortId, id] of miniSearch._documentIds) { + miniSearch._idToShortId.set(id, shortId); + } + for (const [term, data] of index2) { + const dataMap = /* @__PURE__ */ new Map(); + for (const fieldId of Object.keys(data)) { + let indexEntry = data[fieldId]; + if (serializationVersion === 1) { + indexEntry = indexEntry.ds; + } + dataMap.set(parseInt(fieldId, 10), objectToNumericMap(indexEntry)); + } + miniSearch._index.set(term, dataMap); + } + return miniSearch; + } + /** + * @ignore + */ + static async loadJSAsync(js, options) { + const { index: index2, documentIds, fieldLength, storedFields, serializationVersion } = js; + const miniSearch = this.instantiateMiniSearch(js, options); + miniSearch._documentIds = await objectToNumericMapAsync(documentIds); + miniSearch._fieldLength = await objectToNumericMapAsync(fieldLength); + miniSearch._storedFields = await objectToNumericMapAsync(storedFields); + for (const [shortId, id] of miniSearch._documentIds) { + miniSearch._idToShortId.set(id, shortId); + } + let count3 = 0; + for (const [term, data] of index2) { + const dataMap = /* @__PURE__ */ new Map(); + for (const fieldId of Object.keys(data)) { + let indexEntry = data[fieldId]; + if (serializationVersion === 1) { + indexEntry = indexEntry.ds; + } + dataMap.set(parseInt(fieldId, 10), await objectToNumericMapAsync(indexEntry)); + } + if (++count3 % 1e3 === 0) + await wait(0); + miniSearch._index.set(term, dataMap); + } + return miniSearch; + } + /** + * @ignore + */ + static instantiateMiniSearch(js, options) { + const { documentCount, nextId, fieldIds, averageFieldLength, dirtCount, serializationVersion } = js; + if (serializationVersion !== 1 && serializationVersion !== 2) { + throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version"); + } + const miniSearch = new _MiniSearch(options); + miniSearch._documentCount = documentCount; + miniSearch._nextId = nextId; + miniSearch._idToShortId = /* @__PURE__ */ new Map(); + miniSearch._fieldIds = fieldIds; + miniSearch._avgFieldLength = averageFieldLength; + miniSearch._dirtCount = dirtCount || 0; + miniSearch._index = new SearchableMap(); + return miniSearch; + } + /** + * @ignore + */ + executeQuery(query, searchOptions = {}) { + if (query === _MiniSearch.wildcard) { + return this.executeWildcardQuery(searchOptions); + } + if (typeof query !== "string") { + const options2 = { ...searchOptions, ...query, queries: void 0 }; + const results2 = query.queries.map((subquery) => this.executeQuery(subquery, options2)); + return this.combineResults(results2, options2.combineWith); + } + const { tokenize: tokenize2, processTerm, searchOptions: globalSearchOptions } = this._options; + const options = { tokenize: tokenize2, processTerm, ...globalSearchOptions, ...searchOptions }; + const { tokenize: searchTokenize, processTerm: searchProcessTerm } = options; + const terms = searchTokenize(query).flatMap((term) => searchProcessTerm(term)).filter((term) => !!term); + const queries = terms.map(termToQuerySpec(options)); + const results = queries.map((query2) => this.executeQuerySpec(query2, options)); + return this.combineResults(results, options.combineWith); + } + /** + * @ignore + */ + executeQuerySpec(query, searchOptions) { + const options = { ...this._options.searchOptions, ...searchOptions }; + const boosts = (options.fields || this._options.fields).reduce((boosts2, field) => ({ ...boosts2, [field]: getOwnProperty(options.boost, field) || 1 }), {}); + const { boostDocument, weights, maxFuzzy, bm25: bm25params } = options; + const { fuzzy: fuzzyWeight, prefix: prefixWeight } = { ...defaultSearchOptions.weights, ...weights }; + const data = this._index.get(query.term); + const results = this.termResults(query.term, query.term, 1, query.termBoost, data, boosts, boostDocument, bm25params); + let prefixMatches; + let fuzzyMatches; + if (query.prefix) { + prefixMatches = this._index.atPrefix(query.term); + } + if (query.fuzzy) { + const fuzzy = query.fuzzy === true ? 0.2 : query.fuzzy; + const maxDistance = fuzzy < 1 ? Math.min(maxFuzzy, Math.round(query.term.length * fuzzy)) : fuzzy; + if (maxDistance) + fuzzyMatches = this._index.fuzzyGet(query.term, maxDistance); + } + if (prefixMatches) { + for (const [term, data2] of prefixMatches) { + const distance = term.length - query.term.length; + if (!distance) { + continue; + } + fuzzyMatches === null || fuzzyMatches === void 0 ? void 0 : fuzzyMatches.delete(term); + const weight = prefixWeight * term.length / (term.length + 0.3 * distance); + this.termResults(query.term, term, weight, query.termBoost, data2, boosts, boostDocument, bm25params, results); + } + } + if (fuzzyMatches) { + for (const term of fuzzyMatches.keys()) { + const [data2, distance] = fuzzyMatches.get(term); + if (!distance) { + continue; + } + const weight = fuzzyWeight * term.length / (term.length + distance); + this.termResults(query.term, term, weight, query.termBoost, data2, boosts, boostDocument, bm25params, results); + } + } + return results; + } + /** + * @ignore + */ + executeWildcardQuery(searchOptions) { + const results = /* @__PURE__ */ new Map(); + const options = { ...this._options.searchOptions, ...searchOptions }; + for (const [shortId, id] of this._documentIds) { + const score = options.boostDocument ? options.boostDocument(id, "", this._storedFields.get(shortId)) : 1; + results.set(shortId, { + score, + terms: [], + match: {} + }); + } + return results; + } + /** + * @ignore + */ + combineResults(results, combineWith = OR) { + if (results.length === 0) { + return /* @__PURE__ */ new Map(); + } + const operator = combineWith.toLowerCase(); + const combinator = combinators[operator]; + if (!combinator) { + throw new Error(`Invalid combination operator: ${combineWith}`); + } + return results.reduce(combinator) || /* @__PURE__ */ new Map(); + } + /** + * Allows serialization of the index to JSON, to possibly store it and later + * deserialize it with {@link MiniSearch.loadJSON}. + * + * Normally one does not directly call this method, but rather call the + * standard JavaScript `JSON.stringify()` passing the {@link MiniSearch} + * instance, and JavaScript will internally call this method. Upon + * deserialization, one must pass to {@link MiniSearch.loadJSON} the same + * options used to create the original instance that was serialized. + * + * ### Usage: + * + * ```javascript + * // Serialize the index: + * let miniSearch = new MiniSearch({ fields: ['title', 'text'] }) + * miniSearch.addAll(documents) + * const json = JSON.stringify(miniSearch) + * + * // Later, to deserialize it: + * miniSearch = MiniSearch.loadJSON(json, { fields: ['title', 'text'] }) + * ``` + * + * @return A plain-object serializable representation of the search index. + */ + toJSON() { + const index2 = []; + for (const [term, fieldIndex] of this._index) { + const data = {}; + for (const [fieldId, freqs] of fieldIndex) { + data[fieldId] = Object.fromEntries(freqs); + } + index2.push([term, data]); + } + return { + documentCount: this._documentCount, + nextId: this._nextId, + documentIds: Object.fromEntries(this._documentIds), + fieldIds: this._fieldIds, + fieldLength: Object.fromEntries(this._fieldLength), + averageFieldLength: this._avgFieldLength, + storedFields: Object.fromEntries(this._storedFields), + dirtCount: this._dirtCount, + index: index2, + serializationVersion: 2 + }; + } + /** + * @ignore + */ + termResults(sourceTerm, derivedTerm, termWeight, termBoost, fieldTermData, fieldBoosts, boostDocumentFn, bm25params, results = /* @__PURE__ */ new Map()) { + if (fieldTermData == null) + return results; + for (const field of Object.keys(fieldBoosts)) { + const fieldBoost = fieldBoosts[field]; + const fieldId = this._fieldIds[field]; + const fieldTermFreqs = fieldTermData.get(fieldId); + if (fieldTermFreqs == null) + continue; + let matchingFields = fieldTermFreqs.size; + const avgFieldLength = this._avgFieldLength[fieldId]; + for (const docId of fieldTermFreqs.keys()) { + if (!this._documentIds.has(docId)) { + this.removeTerm(fieldId, docId, derivedTerm); + matchingFields -= 1; + continue; + } + const docBoost = boostDocumentFn ? boostDocumentFn(this._documentIds.get(docId), derivedTerm, this._storedFields.get(docId)) : 1; + if (!docBoost) + continue; + const termFreq = fieldTermFreqs.get(docId); + const fieldLength = this._fieldLength.get(docId)[fieldId]; + const rawScore = calcBM25Score(termFreq, matchingFields, this._documentCount, fieldLength, avgFieldLength, bm25params); + const weightedScore = termWeight * termBoost * fieldBoost * docBoost * rawScore; + const result = results.get(docId); + if (result) { + result.score += weightedScore; + assignUniqueTerm(result.terms, sourceTerm); + const match = getOwnProperty(result.match, derivedTerm); + if (match) { + match.push(field); + } else { + result.match[derivedTerm] = [field]; + } + } else { + results.set(docId, { + score: weightedScore, + terms: [sourceTerm], + match: { [derivedTerm]: [field] } + }); + } + } + } + return results; + } + /** + * @ignore + */ + addTerm(fieldId, documentId, term) { + const indexData = this._index.fetch(term, createMap); + let fieldIndex = indexData.get(fieldId); + if (fieldIndex == null) { + fieldIndex = /* @__PURE__ */ new Map(); + fieldIndex.set(documentId, 1); + indexData.set(fieldId, fieldIndex); + } else { + const docs = fieldIndex.get(documentId); + fieldIndex.set(documentId, (docs || 0) + 1); + } + } + /** + * @ignore + */ + removeTerm(fieldId, documentId, term) { + if (!this._index.has(term)) { + this.warnDocumentChanged(documentId, fieldId, term); + return; + } + const indexData = this._index.fetch(term, createMap); + const fieldIndex = indexData.get(fieldId); + if (fieldIndex == null || fieldIndex.get(documentId) == null) { + this.warnDocumentChanged(documentId, fieldId, term); + } else if (fieldIndex.get(documentId) <= 1) { + if (fieldIndex.size <= 1) { + indexData.delete(fieldId); + } else { + fieldIndex.delete(documentId); + } + } else { + fieldIndex.set(documentId, fieldIndex.get(documentId) - 1); + } + if (this._index.get(term).size === 0) { + this._index.delete(term); + } + } + /** + * @ignore + */ + warnDocumentChanged(shortDocumentId, fieldId, term) { + for (const fieldName of Object.keys(this._fieldIds)) { + if (this._fieldIds[fieldName] === fieldId) { + this._options.logger("warn", `MiniSearch: document with ID ${this._documentIds.get(shortDocumentId)} has changed before removal: term "${term}" was not present in field "${fieldName}". Removing a document after it has changed can corrupt the index!`, "version_conflict"); + return; + } + } + } + /** + * @ignore + */ + addDocumentId(documentId) { + const shortDocumentId = this._nextId; + this._idToShortId.set(documentId, shortDocumentId); + this._documentIds.set(shortDocumentId, documentId); + this._documentCount += 1; + this._nextId += 1; + return shortDocumentId; + } + /** + * @ignore + */ + addFields(fields) { + for (let i2 = 0; i2 < fields.length; i2++) { + this._fieldIds[fields[i2]] = i2; + } + } + /** + * @ignore + */ + addFieldLength(documentId, fieldId, count3, length) { + let fieldLengths = this._fieldLength.get(documentId); + if (fieldLengths == null) + this._fieldLength.set(documentId, fieldLengths = []); + fieldLengths[fieldId] = length; + const averageFieldLength = this._avgFieldLength[fieldId] || 0; + const totalFieldLength = averageFieldLength * count3 + length; + this._avgFieldLength[fieldId] = totalFieldLength / (count3 + 1); + } + /** + * @ignore + */ + removeFieldLength(documentId, fieldId, count3, length) { + if (count3 === 1) { + this._avgFieldLength[fieldId] = 0; + return; + } + const totalFieldLength = this._avgFieldLength[fieldId] * count3 - length; + this._avgFieldLength[fieldId] = totalFieldLength / (count3 - 1); + } + /** + * @ignore + */ + saveStoredFields(documentId, doc) { + const { storeFields, extractField } = this._options; + if (storeFields == null || storeFields.length === 0) { + return; + } + let documentFields = this._storedFields.get(documentId); + if (documentFields == null) + this._storedFields.set(documentId, documentFields = {}); + for (const fieldName of storeFields) { + const fieldValue = extractField(doc, fieldName); + if (fieldValue !== void 0) + documentFields[fieldName] = fieldValue; + } + } + }; + MiniSearch.wildcard = Symbol("*"); + var getOwnProperty = (object, property) => Object.prototype.hasOwnProperty.call(object, property) ? object[property] : void 0; + var combinators = { + [OR]: (a2, b3) => { + for (const docId of b3.keys()) { + const existing = a2.get(docId); + if (existing == null) { + a2.set(docId, b3.get(docId)); + } else { + const { score, terms, match } = b3.get(docId); + existing.score = existing.score + score; + existing.match = Object.assign(existing.match, match); + assignUniqueTerms(existing.terms, terms); + } + } + return a2; + }, + [AND]: (a2, b3) => { + const combined = /* @__PURE__ */ new Map(); + for (const docId of b3.keys()) { + const existing = a2.get(docId); + if (existing == null) + continue; + const { score, terms, match } = b3.get(docId); + assignUniqueTerms(existing.terms, terms); + combined.set(docId, { + score: existing.score + score, + terms: existing.terms, + match: Object.assign(existing.match, match) + }); + } + return combined; + }, + [AND_NOT]: (a2, b3) => { + for (const docId of b3.keys()) + a2.delete(docId); + return a2; + } + }; + var defaultBM25params = { k: 1.2, b: 0.7, d: 0.5 }; + var calcBM25Score = (termFreq, matchingCount, totalCount, fieldLength, avgFieldLength, bm25params) => { + const { k: k3, b: b3, d: d3 } = bm25params; + const invDocFreq = Math.log(1 + (totalCount - matchingCount + 0.5) / (matchingCount + 0.5)); + return invDocFreq * (d3 + termFreq * (k3 + 1) / (termFreq + k3 * (1 - b3 + b3 * fieldLength / avgFieldLength))); + }; + var termToQuerySpec = (options) => (term, i2, terms) => { + const fuzzy = typeof options.fuzzy === "function" ? options.fuzzy(term, i2, terms) : options.fuzzy || false; + const prefix = typeof options.prefix === "function" ? options.prefix(term, i2, terms) : options.prefix === true; + const termBoost = typeof options.boostTerm === "function" ? options.boostTerm(term, i2, terms) : 1; + return { term, fuzzy, prefix, termBoost }; + }; + var defaultOptions2 = { + idField: "id", + extractField: (document2, fieldName) => document2[fieldName], + stringifyField: (fieldValue, fieldName) => fieldValue.toString(), + tokenize: (text2) => text2.split(SPACE_OR_PUNCTUATION), + processTerm: (term) => term.toLowerCase(), + fields: void 0, + searchOptions: void 0, + storeFields: [], + logger: (level, message) => { + if (typeof (console === null || console === void 0 ? void 0 : console[level]) === "function") + console[level](message); + }, + autoVacuum: true + }; + var defaultSearchOptions = { + combineWith: OR, + prefix: false, + fuzzy: false, + maxFuzzy: 6, + boost: {}, + weights: { fuzzy: 0.45, prefix: 0.375 }, + bm25: defaultBM25params + }; + var defaultAutoSuggestOptions = { + combineWith: AND, + prefix: (term, i2, terms) => i2 === terms.length - 1 + }; + var defaultVacuumOptions = { batchSize: 1e3, batchWait: 10 }; + var defaultVacuumConditions = { minDirtFactor: 0.1, minDirtCount: 20 }; + var defaultAutoVacuumOptions = { ...defaultVacuumOptions, ...defaultVacuumConditions }; + var assignUniqueTerm = (target, term) => { + if (!target.includes(term)) + target.push(term); + }; + var assignUniqueTerms = (target, source) => { + for (const term of source) { + if (!target.includes(term)) + target.push(term); + } + }; + var byScore = ({ score: a2 }, { score: b3 }) => b3 - a2; + var createMap = () => /* @__PURE__ */ new Map(); + var objectToNumericMap = (object) => { + const map2 = /* @__PURE__ */ new Map(); + for (const key of Object.keys(object)) { + map2.set(parseInt(key, 10), object[key]); + } + return map2; + }; + var objectToNumericMapAsync = async (object) => { + const map2 = /* @__PURE__ */ new Map(); + let count3 = 0; + for (const key of Object.keys(object)) { + map2.set(parseInt(key, 10), object[key]); + if (++count3 % 1e3 === 0) { + await wait(0); + } + } + return map2; + }; + var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + var SPACE_OR_PUNCTUATION = /[\n\r\p{Z}\p{P}]+/u; + + // src/utils/localMemoryUtils.ts + var BOOKMARK_FOLDER_TYPES = /* @__PURE__ */ new Set(["hub_item", "bookmark_folder_item"]); + function sanitizeKeyPart(value) { + return value.replace(/\|/g, "%7C"); + } + function normalizeTextForKey(text2) { + return text2.toLowerCase().replace(/\s+/g, " ").trim().slice(0, 256); + } + function normalizeMemoryName(value) { + return (value || "").trim().toLowerCase(); + } + function isBookmarkFolderType(rawType) { + return BOOKMARK_FOLDER_TYPES.has((rawType || "").toLowerCase()); + } + function getMemoryDocSource(doc) { + const rawType = String(doc?.metadata?.type || "memory").toLowerCase(); + if (isBookmarkFolderType(rawType)) { + return "bookmark-folder"; + } + return rawType; + } + function getMemoryDocFolderName(doc) { + return normalizeMemoryName( + String(doc?.metadata?.folderName || doc?.metadata?.hubName || "") + ); + } + function getMemoryDocUrl(doc) { + return String(doc?.url || doc?.metadata?.url || "").trim(); + } + function computeMemoryDedupeKey(doc) { + const source = getMemoryDocSource(doc); + const folder = getMemoryDocFolderName(doc); + const url = getMemoryDocUrl(doc); + const contentKey = url || `text:${normalizeTextForKey(String(doc?.text || ""))}`; + return `${sanitizeKeyPart(source)}|${sanitizeKeyPart(folder)}|${sanitizeKeyPart(contentKey)}`; + } + + // src/types/runtime.ts + function getBrowserWindow(globalRef = globalThis) { + const maybeWindow = globalRef.window; + const win = maybeWindow || globalRef; + const services = win.Services || win.top?.Services; + if (services?.wm) { + return services.wm.getMostRecentWindow("navigator:browser"); + } + return win.top || win; + } + + // src/utils/assistantLogger.ts + var DEBUG_PREF_NAME = "browser.oasis.assistant.debug"; + function isDebugEnabled(globalRef = globalThis) { + try { + const host = globalRef; + const prefs = host.window?.Services?.prefs || host.Services?.prefs; + if (!prefs?.getBoolPref) { + return false; + } + return !!prefs.getBoolPref(DEBUG_PREF_NAME, false); + } catch { + return false; + } + } + function formatPrefix(scope, message) { + return `[Assistant:${scope}] ${message}`; + } + function write(level, scope, message, meta) { + if ((level === "debug" || level === "info") && !isDebugEnabled()) { + return; + } + const text2 = formatPrefix(scope, message); + if (meta !== void 0) { + console[level](text2, meta); + return; + } + console[level](text2); + } + var assistantLogger = { + debug(scope, message, meta) { + write("debug", scope, message, meta); + }, + info(scope, message, meta) { + write("info", scope, message, meta); + }, + warn(scope, message, meta) { + write("warn", scope, message, meta); + }, + error(scope, message, meta) { + write("error", scope, message, meta); + }, + isDebugEnabled + }; + + // src/services/localMemory.ts + function getChrome() { + const topWin = getBrowserWindow(); + const gBrowser = topWin?.gBrowser; + const PlacesUtils = topWin?.PlacesUtils; + return { topWin, gBrowser, PlacesUtils }; + } + function toUrlString(value) { + if (!value) return ""; + if (typeof value === "string") return value.trim(); + const fromSpec = String(value.spec || "").trim(); + if (fromSpec) return fromSpec; + const fromHref = String(value.href || "").trim(); + if (fromHref) return fromHref; + return String(value.toString?.() || "").trim(); + } + var logDebug = (message, ...meta) => { + assistantLogger.debug( + "local-memory", + String(message ?? ""), + meta.length === 0 ? void 0 : meta.length === 1 ? meta[0] : meta + ); + }; + var logWarn = (message, ...meta) => { + assistantLogger.warn( + "local-memory", + String(message ?? ""), + meta.length === 0 ? void 0 : meta.length === 1 ? meta[0] : meta + ); + }; + var logError = (message, ...meta) => { + assistantLogger.error( + "local-memory", + String(message ?? ""), + meta.length === 0 ? void 0 : meta.length === 1 ? meta[0] : meta + ); + }; + var OASIS_MANAGED_BOOKMARK_ROOT = "Oasis Hubs"; + var LocalMemoryService = class { + dbPromise; + miniSearch; + isIndexDirty = true; + constructor() { + try { + this.dbPromise = openDB("oasis-memory", 3, { + upgrade(db, oldVersion, _newVersion, transaction) { + if (oldVersion < 1) { + const store2 = db.createObjectStore("documents", { + keyPath: "id", + autoIncrement: true + }); + store2.createIndex("by-timestamp", "timestamp"); + store2.createIndex("by-url", "url", { unique: false }); + } + if (oldVersion < 2) { + db.createObjectStore("usage", { keyPath: "userId" }); + } + if (oldVersion < 3) { + const docsStore = transaction.objectStore("documents"); + if (!docsStore.indexNames.contains("by-dedupe-key")) { + docsStore.createIndex("by-dedupe-key", "dedupeKey", { + unique: true + }); + } + } + } + }); + } catch (error) { + logError("[LocalMemory] IndexedDB unavailable in this context", error); + this.dbPromise = Promise.reject(error); + } + this.miniSearch = new MiniSearch({ + fields: ["text", "title", "description"], + storeFields: ["text", "metadata", "url", "timestamp", "dedupeKey"], + extractField: (doc, fieldName) => { + if (fieldName === "title") return doc.metadata?.title; + if (fieldName === "description") return doc.metadata?.description; + return doc[fieldName]; + }, + tokenize: (text2) => this.tokenize(text2), + searchOptions: { + boost: { title: 2 }, + fuzzy: 0.2, + prefix: true, + tokenize: (text2) => this.tokenize(text2) + } + }); + this.backfillDedupeKeys().then(() => this.ensureIndex()).then(() => { + setTimeout(() => this.indexAll(), 5e3); + }).catch((error) => { + logError("[LocalMemory] initialization failed", error); + }); + } + // Simple tokenizer: lowercase, replace punctuation with spaces, split by whitespace + tokenize(text2) { + return text2.toLowerCase().replace(/[^\w\s]/g, " ").split(/\s+/).filter((t2) => t2.length > 2); + } + async backfillDedupeKeys() { + const db = await this.dbPromise; + const tx = db.transaction("documents", "readwrite"); + const store2 = tx.store; + const winners = /* @__PURE__ */ new Map(); + let cursor = await store2.openCursor(); + let updated = 0; + let removed = 0; + while (cursor) { + const id = Number(cursor.primaryKey); + const doc = cursor.value; + const dedupeKey = computeMemoryDedupeKey(doc); + const timestamp2 = Number(doc.timestamp || 0); + const winner = winners.get(dedupeKey); + if (winner) { + if (timestamp2 > winner.timestamp) { + await store2.delete(winner.id); + winners.set(dedupeKey, { id, timestamp: timestamp2 }); + if (doc.dedupeKey !== dedupeKey) { + await cursor.update({ ...doc, dedupeKey }); + updated++; + } + } else { + await cursor.delete(); + } + removed++; + cursor = await cursor.continue(); + continue; + } + winners.set(dedupeKey, { id, timestamp: timestamp2 }); + if (doc.dedupeKey !== dedupeKey) { + await cursor.update({ ...doc, dedupeKey }); + updated++; + } + cursor = await cursor.continue(); + } + await tx.done; + if (updated > 0 || removed > 0) { + this.isIndexDirty = true; + logDebug( + `[LocalMemory] dedupe backfill updated=${updated} removed_duplicates=${removed}` + ); + } + } + async upsertDocumentByDedupeKey(doc) { + const db = await this.dbPromise; + const tx = db.transaction("documents", "readwrite"); + const docsStore = tx.store; + const index2 = docsStore.index("by-dedupe-key"); + const existing = doc.dedupeKey ? await index2.get(doc.dedupeKey) : null; + if (existing?.id != null) { + await docsStore.put({ ...doc, id: existing.id }); + await tx.done; + return "updated"; + } + await docsStore.add(doc); + await tx.done; + return "inserted"; + } + async mutateDocuments(mutator) { + const db = await this.dbPromise; + const tx = db.transaction("documents", "readwrite"); + let cursor = await tx.store.openCursor(); + let changed = 0; + while (cursor) { + const doc = cursor.value; + const nextDoc = mutator(doc); + if (nextDoc === null) { + await cursor.delete(); + changed++; + } else if (nextDoc !== doc) { + await cursor.update(nextDoc); + changed++; + } + cursor = await cursor.continue(); + } + await tx.done; + if (changed > 0) { + this.isIndexDirty = true; + } + return changed; + } + async ensureIndex() { + if (!this.isIndexDirty) return; + const db = await this.dbPromise; + const docs = await db.getAll("documents"); + this.miniSearch.removeAll(); + if (docs.length > 0) { + this.miniSearch.addAll( + docs.map((d3) => ({ + id: d3.id, + text: d3.text, + metadata: d3.metadata, + url: d3.url, + timestamp: d3.timestamp, + dedupeKey: d3.dedupeKey + })) + ); + } + this.isIndexDirty = false; + logDebug(`[LocalMemory] Index rebuilt with ${docs.length} documents`); + } + async addDocument(text2, metadata = {}, url) { + const tokens = this.tokenize(text2); + const doc = { + text: text2, + tokens, + metadata, + timestamp: Date.now(), + url, + dedupeKey: computeMemoryDedupeKey({ text: text2, metadata, url }) + }; + const upsertResult = await this.upsertDocumentByDedupeKey(doc); + this.isIndexDirty = true; + if (upsertResult === "updated") { + logDebug( + `[LocalMemory] dedupe hit source=${getMemoryDocSource(doc)} key=${doc.dedupeKey}` + ); + } + } + async removeDocumentByUrl(url) { + const db = await this.dbPromise; + const tx = db.transaction("documents", "readwrite"); + const index2 = tx.store.index("by-url"); + let cursor = await index2.openCursor(url); + while (cursor) { + await cursor.delete(); + cursor = await cursor.continue(); + } + await tx.done; + this.isIndexDirty = true; + logDebug(`Removed documents for URL: ${url}`); + } + async removeBookmarkFolderDocuments(folderName) { + const targetFolder = normalizeMemoryName(folderName); + if (!targetFolder) return 0; + const removed = await this.mutateDocuments((doc) => { + if (getMemoryDocSource(doc) !== "bookmark-folder") return doc; + if (getMemoryDocFolderName(doc) !== targetFolder) return doc; + return null; + }); + if (removed > 0) { + logDebug( + `[LocalMemory] Removed ${removed} documents for folder: ${folderName}` + ); + } + return removed; + } + async removeAllBookmarkFolderDocuments() { + const removed = await this.mutateDocuments((doc) => { + if (getMemoryDocSource(doc) !== "bookmark-folder") return doc; + return null; + }); + if (removed > 0) { + logDebug( + `[LocalMemory] Removed all bookmark-folder documents: ${removed}` + ); + } + return removed; + } + async removeBookmarkFolderDocumentByUrl(folderName, url) { + const targetFolder = normalizeMemoryName(folderName); + if (!targetFolder || !url) return 0; + const removed = await this.mutateDocuments((doc) => { + if (getMemoryDocSource(doc) !== "bookmark-folder") return doc; + if (getMemoryDocFolderName(doc) !== targetFolder) return doc; + const docUrl = getMemoryDocUrl(doc); + if (docUrl !== url) return doc; + return null; + }); + if (removed > 0) { + logDebug( + `[LocalMemory] Removed ${removed} folder documents for URL: ${url}` + ); + } + return removed; + } + async renameBookmarkFolderDocuments(oldName, newName) { + const from = normalizeMemoryName(oldName); + const to = (newName || "").trim(); + const toNorm = normalizeMemoryName(newName); + if (!from || !toNorm) return 0; + const updated = await this.mutateDocuments((doc) => { + if (getMemoryDocSource(doc) !== "bookmark-folder") return doc; + if (getMemoryDocFolderName(doc) !== from) return doc; + const metadata = { ...doc.metadata || {} }; + metadata.folderName = to; + metadata.hubName = to; + if (typeof metadata.context === "string" && metadata.context.toLowerCase().startsWith("bookmark folder:")) { + metadata.context = `Bookmark Folder: ${to}`; + } + return { + ...doc, + metadata, + dedupeKey: computeMemoryDedupeKey({ ...doc, metadata }) + }; + }); + if (updated > 0) { + logDebug( + `[LocalMemory] Renamed ${updated} folder documents: ${oldName} -> ${newName}` + ); + } + return updated; + } + async syncBookmarkFolderDocuments(entries2) { + const byGuid = /* @__PURE__ */ new Map(); + for (const entry of entries2) { + const guid = String(entry.bookmarkGuid || "").trim(); + const url = String(entry.url || "").trim(); + const folderName = String(entry.folderName || "").trim(); + if (!guid || !url || !folderName) continue; + byGuid.set(guid, { ...entry, bookmarkGuid: guid, url, folderName }); + } + const seen = /* @__PURE__ */ new Set(); + let updated = 0; + let removed = 0; + await this.mutateDocuments((doc) => { + if (getMemoryDocSource(doc) !== "bookmark-folder") return doc; + const bookmarkGuid = String(doc.metadata?.bookmarkGuid || "").trim(); + if (!bookmarkGuid) { + removed++; + return null; + } + const nextEntry = byGuid.get(bookmarkGuid); + if (!nextEntry) { + removed++; + return null; + } + seen.add(bookmarkGuid); + const previousMetadata = doc.metadata || {}; + const nextMetadata = { + ...previousMetadata, + type: "bookmark_folder_item", + title: nextEntry.title, + url: nextEntry.url, + hub: nextEntry.parentGuid, + hubName: nextEntry.folderName, + folderName: nextEntry.folderName, + bookmarkGuid: nextEntry.bookmarkGuid, + parentGuid: nextEntry.parentGuid, + context: `Bookmark Folder: ${nextEntry.folderName}`, + description: nextEntry.description ?? previousMetadata.description ?? "" + }; + const nextText = `Title: ${nextEntry.title} +URL: ${nextEntry.url} +Content: ${nextMetadata.description || ""}`; + const nextDoc = { + ...doc, + text: nextText, + metadata: nextMetadata, + url: nextEntry.url, + dedupeKey: computeMemoryDedupeKey({ + text: nextText, + metadata: nextMetadata, + url: nextEntry.url + }) + }; + const unchanged = doc.text === nextDoc.text && doc.url === nextDoc.url && doc.metadata?.title === nextMetadata.title && doc.metadata?.folderName === nextMetadata.folderName && doc.metadata?.bookmarkGuid === nextMetadata.bookmarkGuid && doc.metadata?.parentGuid === nextMetadata.parentGuid; + if (unchanged) return doc; + updated++; + return nextDoc; + }); + let added = 0; + for (const entry of byGuid.values()) { + if (seen.has(entry.bookmarkGuid)) continue; + const text2 = `Title: ${entry.title} +URL: ${entry.url} +Content: ${entry.description || ""}`; + await this.addDocument( + text2, + { + type: "bookmark_folder_item", + title: entry.title, + url: entry.url, + hub: entry.parentGuid, + hubName: entry.folderName, + folderName: entry.folderName, + bookmarkGuid: entry.bookmarkGuid, + parentGuid: entry.parentGuid, + context: `Bookmark Folder: ${entry.folderName}`, + description: entry.description || "" + }, + entry.url + ); + added++; + } + if (added > 0 || updated > 0 || removed > 0) { + logDebug( + `[LocalMemory] bookmark-folder sync added=${added} updated=${updated} removed=${removed}` + ); + } + return { added, updated, removed }; + } + async removeStaleBookmarkSourceDocuments(validDedupeKeys) { + const removed = await this.mutateDocuments((doc) => { + if (getMemoryDocSource(doc) !== "bookmark") return doc; + const key = String(doc.dedupeKey || computeMemoryDedupeKey(doc)); + if (validDedupeKeys.has(key)) return doc; + return null; + }); + if (removed > 0) { + logDebug( + `[LocalMemory] Removed stale bookmark-source documents: ${removed}` + ); + } + return removed; + } + async removeStaleLiveSourceDocuments(validDedupeKeys) { + const removed = await this.mutateDocuments((doc) => { + const source = getMemoryDocSource(doc); + if (source !== "tab" && source !== "tab-group") return doc; + const key = String(doc.dedupeKey || computeMemoryDedupeKey(doc)); + if (validDedupeKeys.has(key)) return doc; + return null; + }); + if (removed > 0) { + logDebug( + `[LocalMemory] Removed stale live tab/tab-group documents: ${removed}` + ); + } + return removed; + } + async search(query, limit = 5, filter) { + await this.ensureIndex(); + const folderFilter = filter?.folder || filter?.hub; + const results = this.miniSearch.search(query, { + filter: (result) => { + if (folderFilter) { + const name = normalizeMemoryName( + String( + result.metadata?.folderName || result.metadata?.hubName || "" + ) + ); + return name === normalizeMemoryName(folderFilter); + } + return true; + } + }); + const seenKeys = /* @__PURE__ */ new Set(); + const uniqueResults = []; + for (const r2 of results) { + const stored = r2; + const metadata = stored.metadata || {}; + const key = String( + stored.dedupeKey || computeMemoryDedupeKey({ + text: stored.text || "", + url: stored.url, + metadata + }) + ); + if (seenKeys.has(key)) continue; + seenKeys.add(key); + uniqueResults.push(stored); + if (uniqueResults.length >= limit) break; + } + return uniqueResults.map((r2) => ({ + text: r2.text || "", + score: r2.score, + metadata: r2.metadata || {}, + url: r2.url + })); + } + async getUsage(userId) { + const db = await this.dbPromise; + const record = await db.get("usage", userId); + return record?.count || 0; + } + async saveUsage(userId, count3) { + const db = await this.dbPromise; + await db.put("usage", { userId, count: count3, timestamp: Date.now() }); + logDebug(`[LocalMemory] Saved usage for ${userId}: ${count3}`); + } + // --- Indexing from Browser --- + async indexHistory(maxItems = 1e3) { + const win = window; + const PlacesUtils = getChrome().PlacesUtils ?? win.PlacesUtils; + if (!PlacesUtils?.history) return; + const options = PlacesUtils.history.getNewQueryOptions(); + options.sortingMode = options.SORT_BY_DATE_DESCENDING; + options.maxResults = maxItems; + options.includeHidden = false; + const query = PlacesUtils.history.getNewQuery(); + const result = PlacesUtils.history.executeQuery(query, options); + const root = result.root; + try { + root.containerOpen = true; + for (let i2 = 0; i2 < root.childCount; i2++) { + const node = root.getChild(i2); + const uri2 = node.uri ? String(node.uri) : ""; + if (!uri2) continue; + const title = node.title != null ? String(node.title) : ""; + const rawTime = typeof node.time === "number" ? node.time : Number(node.time) || 0; + const visitTimeMs = Math.floor(rawTime / 1e3); + await this.addDocument( + `${title} ${uri2}`, + { + type: "history", + title, + url: uri2, + timestamp: visitTimeMs, + context: "Browsing History" + }, + uri2 + ); + } + logDebug(`[LocalMemory] Indexed ${root.childCount} history items.`); + } catch (e2) { + logError("[LocalMemory] Failed to index history:", e2); + } finally { + root.containerOpen = false; + } + } + async indexBookmarks() { + const { PlacesUtils } = getChrome(); + const win = window; + const PM = win.PlacesUtils || win.top?.PlacesUtils; + if (!PlacesUtils?.bookmarks && !PM?.bookmarks) return; + const PU = PlacesUtils || PM; + if (!PU?.bookmarks) return; + const bookmarksApi = PU.bookmarks; + try { + const validBookmarkKeys = /* @__PURE__ */ new Set(); + const unfiledGuid = bookmarksApi.unfiledGuid; + let hadTraversalFailure = false; + const processFolder = async (folderGuid, folderName) => { + try { + const fetched = await bookmarksApi.fetch({ parentGuid: folderGuid }); + const children = Array.isArray(fetched) ? fetched : fetched ? [fetched] : []; + if (children.length === 0) return; + for (const child of children) { + if (child.type === bookmarksApi.TYPE_FOLDER) { + const childName = String(child.title || "Untitled"); + const isManagedRoot = folderGuid === unfiledGuid && normalizeMemoryName(childName) === normalizeMemoryName(OASIS_MANAGED_BOOKMARK_ROOT); + if (isManagedRoot) { + continue; + } + await processFolder(child.guid, childName); + } else if (child.type === bookmarksApi.TYPE_BOOKMARK && child.url) { + const url = toUrlString(child.url); + if (!url) continue; + const metadata = { + type: "bookmark", + title: child.title, + url, + timestamp: child.dateAdded, + context: `Bookmark Folder: ${folderName}`, + folderName, + hubName: folderName + }; + const text2 = (child.title || "") + " " + url; + validBookmarkKeys.add( + computeMemoryDedupeKey({ + text: text2, + metadata, + url + }) + ); + await this.addDocument(text2, metadata, url); + } + } + } catch (e2) { + hadTraversalFailure = true; + logWarn(`Failed to fetch bookmarks for ${folderGuid}:`, e2); + } + }; + await processFolder(bookmarksApi.menuGuid, "Bookmarks Menu"); + await processFolder(bookmarksApi.toolbarGuid, "Bookmarks Toolbar"); + await processFolder(bookmarksApi.unfiledGuid, "Other Bookmarks"); + if (!hadTraversalFailure) { + await this.removeStaleBookmarkSourceDocuments(validBookmarkKeys); + } else { + logWarn( + "[LocalMemory] Skipped stale bookmark cleanup due to traversal failures." + ); + } + logDebug("[LocalMemory] Bookmarks indexed."); + } catch (e2) { + logError("[LocalMemory] Failed to index bookmarks:", e2); + } + } + async indexTabGroups() { + const { gBrowser } = getChrome(); + if (!gBrowser) return; + try { + const validLiveKeys = /* @__PURE__ */ new Set(); + const groups = Array.from( + gBrowser.tabGroups || [] + ); + for (const group of groups) { + const groupName = group.label || "(unnamed group)"; + const groupMetadata = { + type: "tab-group", + title: groupName, + id: group.id + }; + const groupUrl = `about:tab-group?id=${group.id}`; + const groupText = `Tab Group: ${groupName}`; + validLiveKeys.add( + computeMemoryDedupeKey({ + text: groupText, + metadata: groupMetadata, + url: groupUrl + }) + ); + await this.addDocument(groupText, groupMetadata, groupUrl); + } + const tabs = Array.from(gBrowser.tabs || []); + for (const tab of tabs) { + const url = tab.linkedBrowser?.currentURI?.spec; + const title = tab.label || "(untitled)"; + let context = "Open Tab"; + if (tab.group) { + const gName = tab.group.label || "Unnamed Group"; + context = `Tab Group: ${gName}`; + } + if (url && !url.startsWith("about:")) { + const tabMetadata = { + type: "tab", + title, + url, + timestamp: Date.now(), + context + }; + const tabText = title + " " + url; + validLiveKeys.add( + computeMemoryDedupeKey({ + text: tabText, + metadata: tabMetadata, + url + }) + ); + await this.addDocument(tabText, tabMetadata, url); + } + } + await this.removeStaleLiveSourceDocuments(validLiveKeys); + logDebug(`[LocalMemory] Indexed tabs and groups.`); + } catch (e2) { + logError("[LocalMemory] Failed to index tab groups:", e2); + } + } + async indexAll() { + await this.indexTabGroups(); + await this.indexBookmarks(); + await this.indexHistory(); + } + }; + var localMemory = new LocalMemoryService(); + + // src/services/firefoxFacade.ts + function getAssistantWindow() { + return window; + } + function getChromeContext() { + const topWin = getBrowserWindow(); + const assistantWindow2 = getAssistantWindow(); + const Services = topWin?.Services || assistantWindow2.Services || assistantWindow2.top?.Services || null; + const PlacesUtils = topWin?.PlacesUtils || assistantWindow2.PlacesUtils || assistantWindow2.top?.PlacesUtils || null; + const gBrowser = topWin?.gBrowser || null; + return { topWin, gBrowser, PlacesUtils, Services }; + } + function toUrlString2(value) { + if (!value) return ""; + if (typeof value === "string") return value.trim(); + if (typeof value === "object") { + const uri2 = value; + const fromSpec = String(uri2.spec || "").trim(); + if (fromSpec) return fromSpec; + const fromHref = String(uri2.href || "").trim(); + if (fromHref) return fromHref; + const fromToString = String(uri2.toString?.() || "").trim(); + if (fromToString && fromToString !== "[object Object]") return fromToString; + } + return ""; + } + function normalizeName(value) { + return (value || "").trim().toLowerCase(); + } + function getTabs(gBrowser) { + if (!gBrowser?.tabs) return []; + return Array.from(gBrowser.tabs); + } + function getTabGroups(gBrowser) { + if (!gBrowser) return []; + const groups = gBrowser.getAllTabGroups ? gBrowser.getAllTabGroups() : gBrowser.tabGroups || []; + return Array.from(groups); + } + function tabUrl(tab) { + return toUrlString2(tab?.linkedBrowser?.currentURI); + } + function tabTitle(tab) { + return tab?.label || tab?.linkedBrowser?.contentTitle || tabUrl(tab) || "(untitled)"; + } + function findTabByIndex(gBrowser, index2) { + const tabs = getTabs(gBrowser); + if (!tabs.length) return null; + if (index2 == null) return gBrowser?.selectedTab || tabs[0] || null; + const i2 = Math.max(1, Math.floor(index2)); + if (i2 > tabs.length) return null; + return tabs[i2 - 1] || null; + } + function findTabsByQuery(gBrowser, query) { + const target = normalizeName(query); + if (!target) return []; + return getTabs(gBrowser).filter((tab) => { + const title = normalizeName(tabTitle(tab)); + const url = normalizeName(tabUrl(tab)); + return title.includes(target) || url.includes(target); + }); + } + function findGroupByName(gBrowser, name) { + const target = normalizeName(name); + if (!target) return null; + return getTabGroups(gBrowser).find((group) => normalizeName(group.label || "") === target) || null; + } + function withUriFixup(rawInput, services) { + let input = String(rawInput || "").trim(); + if (!input) return ""; + const info = services?.uriFixup?.getFixupURIInfo?.(input, 2 | 4); + const fixed = toUrlString2(info?.preferredURI); + return fixed || input; + } + function getSystemPrincipal(services) { + return services?.scriptSecurityManager?.getSystemPrincipal?.(); + } + async function fetchChildrenBookmarks(places, parentGuid) { + if (!places?.bookmarks?.fetch || !parentGuid) return []; + const collected = []; + const fetched = await places.bookmarks.fetch({ parentGuid }, (bookmark) => { + collected.push(bookmark); + }); + if (collected.length > 0) { + return collected; + } + if (Array.isArray(fetched)) { + return fetched; + } + return fetched ? [fetched] : []; + } + async function fetchBookmarkByGuid(places, guid) { + if (!places?.bookmarks?.fetch || !guid) return null; + const fetched = await places.bookmarks.fetch(guid); + if (!fetched) return null; + if (Array.isArray(fetched)) { + return fetched[0] || null; + } + return fetched; + } + + // ../shared/contracts.ts + var OASIS_EVENT_HISTORY_UPDATE = "oasis-history-update"; + var OASIS_EVENT_CONFIRMATION_UPDATE = "oasis-confirmation-update"; + var OASIS_EVENT_BOOKMARK_FOLDERS_CHANGED = "oasis-bookmark-folders-changed"; + + // src/bookmarkFolders.ts + var ROOT_FOLDER_NAME = "Oasis Hubs"; + function hostOf(url) { + try { + return new URL(url).host.toLowerCase(); + } catch { + return ""; + } + } + function bookmarkUri(bookmark) { + return toUrlString2(bookmark.url) || String(bookmark.uri || "").trim(); + } + function isFolderNode(places, bookmark) { + return bookmark.type === places?.bookmarks?.TYPE_FOLDER; + } + function isBookmarkNode(places, bookmark) { + return bookmark.type === places?.bookmarks?.TYPE_BOOKMARK; + } + async function findRootFolderId(places) { + if (!places?.bookmarks?.search || !places.bookmarks.unfiledGuid) return null; + const results = await places.bookmarks.search({ title: ROOT_FOLDER_NAME }); + const existing = results.find( + (bookmark) => isFolderNode(places, bookmark) && bookmark.parentGuid === places.bookmarks?.unfiledGuid + ); + return existing?.guid || null; + } + async function ensureRootFolderId(places) { + if (!places?.bookmarks) throw new Error("PlacesUtils.bookmarks not available"); + const existing = await findRootFolderId(places); + if (existing) return existing; + if (!places.bookmarks.insert) throw new Error("Bookmarks insert API not available"); + const root = await places.bookmarks.insert({ + title: ROOT_FOLDER_NAME, + type: places.bookmarks.TYPE_FOLDER, + parentGuid: places.bookmarks.unfiledGuid + }); + return root.guid; + } + async function getBookmarkChildren(places, guid) { + if (!places?.bookmarks?.fetch || !guid) return []; + const parent = await fetchBookmarkByGuid(places, guid); + if (!parent) return []; + const children = await fetchChildrenBookmarks(places, guid); + return children.map((child) => ({ + ...child, + uri: bookmarkUri(child) + })); + } + async function createBookmark(places, details) { + if (!places?.bookmarks?.insert) throw new Error("Bookmarks insert API not available"); + const created = await places.bookmarks.insert({ + parentGuid: details.parentGuid, + title: details.title, + url: details.url, + type: details.type || (details.url ? places.bookmarks.TYPE_BOOKMARK : places.bookmarks.TYPE_FOLDER) + }); + return { ...created, uri: bookmarkUri(created) }; + } + async function removeBookmark(places, guid) { + if (!places?.bookmarks?.remove) return; + await places.bookmarks.remove(guid); + } + async function updateBookmark(places, guid, changes) { + if (!places?.bookmarks?.update) throw new Error("Bookmarks update API not available"); + const updated = await places.bookmarks.update({ guid, ...changes }); + return { ...updated, uri: bookmarkUri(updated) }; + } + var BookmarkFolderManager = class { + rootFolderId = null; + placesObserverRegistered = false; + managedFolderGuids = /* @__PURE__ */ new Set(); + syncTimer = null; + syncInFlight = false; + constructor() { + this.ensurePlacesObserver(); + this.scheduleManagedFolderSync("startup"); + } + emitFoldersChanged(folderNames = []) { + try { + window.dispatchEvent( + new CustomEvent(OASIS_EVENT_BOOKMARK_FOLDERS_CHANGED, { + detail: { folderNames } + }) + ); + } catch (error) { + assistantLogger.warn("bookmark-folders", "failed to emit folder change event", error); + } + } + ensurePlacesObserver() { + if (this.placesObserverRegistered) return; + const { PlacesUtils } = getChromeContext(); + if (!PlacesUtils?.observers?.addListener) return; + PlacesUtils.observers.addListener( + [ + "bookmark-added", + "bookmark-removed", + "bookmark-moved", + "bookmark-title-changed", + "bookmark-url-changed" + ], + this.handlePlacesEvents + ); + this.placesObserverRegistered = true; + } + handlePlacesEvents = async (events) => { + try { + const rootId = await this.ensureExistingRootFolder(); + if (!rootId) return; + let isRelevant = false; + for (const rawEvent of events || []) { + const event = rawEvent || {}; + const guid = String(event.guid || ""); + const parentGuid = String(event.parentGuid || ""); + const oldParentGuid = String(event.oldParentGuid || ""); + if (guid === rootId || parentGuid === rootId || oldParentGuid === rootId || this.managedFolderGuids.has(guid) || this.managedFolderGuids.has(parentGuid) || this.managedFolderGuids.has(oldParentGuid)) { + isRelevant = true; + break; + } + } + if (!isRelevant) return; + this.scheduleManagedFolderSync("places-event"); + } catch (error) { + assistantLogger.warn("bookmark-folders", "places event processing failed", error); + } + }; + scheduleManagedFolderSync(reason) { + this.ensurePlacesObserver(); + if (this.syncTimer != null) return; + this.syncTimer = window.setTimeout(() => { + this.syncTimer = null; + void this.syncManagedFolderMemoryFromBookmarks(reason); + }, 250); + } + async ensureRootFolder() { + this.ensurePlacesObserver(); + if (this.rootFolderId) return this.rootFolderId; + const { PlacesUtils } = getChromeContext(); + this.rootFolderId = await ensureRootFolderId(PlacesUtils); + return this.rootFolderId; + } + async ensureExistingRootFolder() { + this.ensurePlacesObserver(); + const { PlacesUtils } = getChromeContext(); + if (!PlacesUtils?.bookmarks?.fetch) { + this.rootFolderId = null; + return null; + } + if (this.rootFolderId) { + const existing = await fetchBookmarkByGuid(PlacesUtils, this.rootFolderId); + if (existing) return this.rootFolderId; + this.rootFolderId = null; + } + const rootId = await findRootFolderId(PlacesUtils); + if (rootId) this.rootFolderId = rootId; + return rootId; + } + async getFolderNodes(rootId) { + const { PlacesUtils } = getChromeContext(); + const children = await getBookmarkChildren(PlacesUtils, rootId); + return children.filter((child) => isFolderNode(PlacesUtils, child)); + } + async findFolderNode(rootId, name) { + const target = normalizeName(name); + if (!target) return null; + const folders = await this.getFolderNodes(rootId); + return folders.find((folder) => normalizeName(folder.title || "") === target) || null; + } + async collectFolders(rootId) { + const { PlacesUtils } = getChromeContext(); + const folders = await this.getFolderNodes(rootId); + const result = []; + for (const folder of folders) { + const bookmarks = await getBookmarkChildren(PlacesUtils, folder.guid); + const items = bookmarks.filter((bookmark) => !!bookmark.uri).map((bookmark) => ({ + id: bookmark.guid, + url: String(bookmark.uri), + title: bookmark.title, + host: hostOf(String(bookmark.uri)) + })); + result.push({ name: folder.title || "Untitled", items }); + } + return result; + } + async syncManagedFolderMemoryFromBookmarks(reason) { + if (this.syncInFlight) return; + this.syncInFlight = true; + try { + const { PlacesUtils } = getChromeContext(); + const rootId = await this.ensureExistingRootFolder(); + if (!rootId) { + this.managedFolderGuids.clear(); + const removed = await localMemory.removeAllBookmarkFolderDocuments(); + if (removed > 0) { + assistantLogger.debug( + "bookmark-folders", + `managed folder root missing; removed ${removed} memory docs` + ); + } + this.emitFoldersChanged([]); + return; + } + const folders = await this.getFolderNodes(rootId); + this.managedFolderGuids = new Set(folders.map((folder) => folder.guid)); + const folderNames = []; + const entries2 = []; + for (const folder of folders) { + const folderName = folder.title || "Untitled"; + folderNames.push(folderName); + const bookmarks = await getBookmarkChildren(PlacesUtils, folder.guid); + for (const bookmark of bookmarks) { + if (!bookmark.uri || !isBookmarkNode(PlacesUtils, bookmark)) continue; + entries2.push({ + bookmarkGuid: bookmark.guid, + parentGuid: folder.guid, + folderName, + title: bookmark.title || bookmark.uri, + url: bookmark.uri + }); + } + } + const syncResult = await localMemory.syncBookmarkFolderDocuments(entries2); + this.emitFoldersChanged(folderNames); + assistantLogger.debug( + "bookmark-folders", + `sync complete reason=${reason} folders=${folderNames.length} added=${syncResult.added} updated=${syncResult.updated} removed=${syncResult.removed}` + ); + } catch (error) { + assistantLogger.warn("bookmark-folders", "managed folder sync failed", error); + } finally { + this.syncInFlight = false; + } + } + async list() { + try { + const { PlacesUtils } = getChromeContext(); + const rootId = await this.ensureRootFolder(); + const folders = await this.getFolderNodes(rootId); + const result = []; + for (const folder of folders) { + const items = await getBookmarkChildren(PlacesUtils, folder.guid); + result.push({ name: folder.title || "Untitled", count: items.length }); + } + return result; + } catch (error) { + assistantLogger.error("bookmark-folders", "Failed to list bookmark folders", error); + return []; + } + } + async getAll() { + try { + const rootId = await this.ensureRootFolder(); + return await this.collectFolders(rootId); + } catch (error) { + assistantLogger.error("bookmark-folders", "Failed to get all bookmark folders", error); + return []; + } + } + async getAllReadOnly() { + try { + const rootId = await this.ensureExistingRootFolder(); + if (!rootId) return { ok: true, folders: [] }; + const folders = await this.collectFolders(rootId); + return { ok: true, folders }; + } catch (error) { + assistantLogger.warn("bookmark-folders", "read-only folder lookup failed", error); + return { ok: false, folders: [] }; + } + } + async create(name, opts) { + const context = getChromeContext(); + const places = context.PlacesUtils; + const normalizedName = (name || "").trim() || this.suggestName(); + const rootId = await this.ensureRootFolder(); + let folder = await this.findFolderNode(rootId, normalizedName); + if (!folder) { + folder = await createBookmark(places, { + parentGuid: rootId, + title: normalizedName + }); + } + const include = opts?.include || "none"; + const tabs = getTabs(context.gBrowser); + let count3 = 0; + if (include === "current" && tabs.length > 0) { + const current = context.gBrowser?.selectedTab || tabs[0]; + if (current) { + await this.addTabs(folder.title || normalizedName, [current]); + count3 = 1; + } + } else if (include === "all" && tabs.length > 0) { + await this.addTabs(folder.title || normalizedName, tabs); + count3 = tabs.length; + } + this.scheduleManagedFolderSync("create-folder"); + return { name: folder.title || normalizedName, count: count3 }; + } + async delete(name, opts) { + const context = getChromeContext(); + const rootId = await this.ensureRootFolder(); + const folder = await this.findFolderNode(rootId, name); + if (!folder) return { name, removed: 0 }; + const items = await getBookmarkChildren(context.PlacesUtils, folder.guid); + const bookmarks = items.filter((bookmark) => !!bookmark.uri); + if (opts?.closeTabs) { + const hostSet = new Set(bookmarks.map((bookmark) => hostOf(String(bookmark.uri)))); + for (const tab of getTabs(context.gBrowser)) { + if (hostSet.has(hostOf(tabUrl(tab)))) { + context.gBrowser?.removeTab?.(tab); + } + } + } + await removeBookmark(context.PlacesUtils, folder.guid); + await localMemory.removeBookmarkFolderDocuments(folder.title || name); + this.scheduleManagedFolderSync("delete-folder"); + return { name: folder.title || name, removed: bookmarks.length }; + } + async rename(oldName, newName) { + const normalizedOld = (oldName || "").trim(); + const normalizedNew = (newName || "").trim(); + if (!normalizedOld || !normalizedNew) return { ok: false }; + const context = getChromeContext(); + const rootId = await this.ensureRootFolder(); + const folder = await this.findFolderNode(rootId, normalizedOld); + if (!folder) return { ok: false }; + const existing = await this.findFolderNode(rootId, normalizedNew); + if (existing) return { ok: false, msg: "Target exists" }; + await updateBookmark(context.PlacesUtils, folder.guid, { title: normalizedNew }); + await localMemory.renameBookmarkFolderDocuments(folder.title || normalizedOld, normalizedNew); + this.scheduleManagedFolderSync("rename-folder"); + return { ok: true }; + } + async addTabs(name, tabs) { + const context = getChromeContext(); + const rootId = await this.ensureRootFolder(); + let folder = await this.findFolderNode(rootId, name); + if (!folder) { + folder = await createBookmark(context.PlacesUtils, { + parentGuid: rootId, + title: name + }); + } + for (const tab of tabs) { + await this.addTabToFolder(folder.guid, tab, folder.title || name); + } + this.scheduleManagedFolderSync("add-tabs"); + return { ok: true }; + } + async removeUrl(name, url) { + const normalizedName = (name || "").trim(); + const rootId = await this.ensureRootFolder(); + const folder = await this.findFolderNode(rootId, normalizedName); + if (!folder) return { ok: false }; + const bookmarks = await getBookmarkChildren(getChromeContext().PlacesUtils, folder.guid); + const toRemove = bookmarks.filter((bookmark) => bookmark.uri === url); + for (const bookmark of toRemove) { + await removeBookmark(getChromeContext().PlacesUtils, bookmark.guid); + } + if (toRemove.length > 0) { + await localMemory.removeBookmarkFolderDocumentByUrl(folder.title || normalizedName, url); + this.scheduleManagedFolderSync("remove-url"); + } + return { ok: toRemove.length > 0 }; + } + async openFolder(name, where = "tabs") { + const normalizedName = (name || "").trim(); + const context = getChromeContext(); + const rootId = await this.ensureRootFolder(); + const folder = await this.findFolderNode(rootId, normalizedName); + if (!folder) return { ok: false }; + const bookmarks = await getBookmarkChildren(context.PlacesUtils, folder.guid); + const urls = bookmarks.filter((bookmark) => !!bookmark.uri).map((bookmark) => String(bookmark.uri)); + if (urls.length === 0) return { ok: true }; + let targetBrowser = context.gBrowser; + if (where === "window") { + const newWindow = context.topWin?.OpenBrowserWindow?.(); + if (!newWindow) return { ok: false }; + await new Promise((resolve) => setTimeout(resolve, 250)); + targetBrowser = newWindow.gBrowser || null; + } + if (!targetBrowser?.addTrustedTab) return { ok: false }; + const principal = getSystemPrincipal(context.Services); + const openedTabs = []; + for (const url of urls) { + try { + const tab = targetBrowser.addTrustedTab(url, { + triggeringPrincipal: principal, + relatedToCurrent: false + }); + if (tab) openedTabs.push(tab); + } catch (error) { + assistantLogger.error("bookmark-folders", `Failed to open tab for URL: ${url}`, error); + } + } + if (where === "tabgroup" && openedTabs.length > 0) { + try { + targetBrowser.addTabGroup?.(openedTabs, { label: normalizedName }); + } catch (error) { + assistantLogger.warn("bookmark-folders", "Failed to group opened tabs", error); + } + } + return { ok: true }; + } + async addTabToFolder(folderGuid, tab, folderName) { + const url = tabUrl(tab); + if (!url) return; + const title = tabTitle(tab); + const context = getChromeContext(); + const existing = await getBookmarkChildren(context.PlacesUtils, folderGuid); + const alreadyExists = existing.some((bookmark) => bookmark.uri === url); + if (alreadyExists) return; + const createdBookmark = await createBookmark(context.PlacesUtils, { + parentGuid: folderGuid, + title, + url + }); + let content = ""; + try { + const bodyText = tab.linkedBrowser?.contentDocument?.body?.innerText || ""; + content = String(bodyText).substring(0, 5e3); + } catch (error) { + assistantLogger.warn("bookmark-folders", "Failed to extract tab content", error); + } + const text2 = `Title: ${title} +URL: ${url} +Content: ${content}`; + await localMemory.addDocument( + text2, + { + title, + type: "bookmark_folder_item", + hub: folderGuid, + hubName: folderName, + folderName, + url, + bookmarkGuid: createdBookmark.guid, + parentGuid: folderGuid, + description: content.substring(0, 200) + }, + url + ); + } + suggestName() { + return "Folder 1"; + } + }; + var bookmarkFolders = new BookmarkFolderManager(); + + // node_modules/@supabase/supabase-js/dist/esm/wrapper.mjs + var index = __toESM(require_main5(), 1); + var { + PostgrestError, + FunctionsHttpError, + FunctionsFetchError, + FunctionsRelayError, + FunctionsError, + FunctionRegion, + SupabaseClient, + createClient, + GoTrueAdminApi, + GoTrueClient, + AuthAdminApi, + AuthClient, + navigatorLock, + NavigatorLockAcquireTimeoutError, + lockInternals, + processLock, + SIGN_OUT_SCOPES, + AuthError, + AuthApiError, + AuthUnknownError, + CustomAuthError, + AuthSessionMissingError, + AuthInvalidTokenResponseError, + AuthInvalidCredentialsError, + AuthImplicitGrantRedirectError, + AuthPKCEGrantCodeExchangeError, + AuthRetryableFetchError, + AuthWeakPasswordError, + AuthInvalidJwtError, + isAuthError, + isAuthApiError, + isAuthSessionMissingError, + isAuthImplicitGrantRedirectError, + isAuthRetryableFetchError, + isAuthWeakPasswordError, + RealtimePresence, + RealtimeChannel, + RealtimeClient, + REALTIME_LISTEN_TYPES, + REALTIME_POSTGRES_CHANGES_LISTEN_EVENT, + REALTIME_PRESENCE_LISTEN_EVENTS, + REALTIME_SUBSCRIBE_STATES, + REALTIME_CHANNEL_STATES + } = index.default || index; + + // src/config/env.ts + var ENV = { + SUPABASE_URL: "https://wvclepquxxczgrukfqyr.supabase.co", + SUPABASE_ANON_KEY: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Ind2Y2xlcHF1eHhjemdydWtmcXlyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTUwODU5OTksImV4cCI6MjA3MDY2MTk5OX0.T-hZ_8QxtVnOt0mtCY_Zch87SYEcsyQZwnvvFAtZiNY", + APP_VERSION: "1.0.0", + LOG_LEVEL: "info", + validate() { + if (!this.SUPABASE_URL) { + throw new Error("SUPABASE_URL is required"); + } + if (!this.SUPABASE_ANON_KEY) { + throw new Error("SUPABASE_ANON_KEY is required"); + } + } + }; + + // src/services/supabase.ts + var SupabaseAuth = class _SupabaseAuth { + static instance; + supabase; + currentSession = null; + authStateCallbacks = []; + lastTrackedSessionUserId = null; + sessionTrackInFlight = null; + oauthCallbackBaseUrl = null; + activeOAuthLaunch = null; + constructor() { + this.supabase = createClient(ENV.SUPABASE_URL, ENV.SUPABASE_ANON_KEY); + this.supabase.auth.onAuthStateChange((event, session) => { + console.log("Auth state changed:", event); + this.handleAuthStateChange(event, session); + }); + } + static getInstance() { + if (!_SupabaseAuth.instance) { + _SupabaseAuth.instance = new _SupabaseAuth(); + } + return _SupabaseAuth.instance; + } + setOAuthCallbackBaseUrl(url) { + const normalized = this.normalizeOAuthCallbackBaseUrl(url); + this.oauthCallbackBaseUrl = normalized; + if (typeof window !== "undefined") { + window.__oasisOAuthCallbackBaseUrl = normalized; + } + return this.getOAuthCallbackBaseUrl(); + } + getOAuthCallbackBaseUrl() { + if (this.oauthCallbackBaseUrl) { + return this.oauthCallbackBaseUrl; + } + if (typeof window !== "undefined") { + const runtimeOverride = window.__oasisOAuthCallbackBaseUrl; + const normalizedRuntime = this.normalizeOAuthCallbackBaseUrl(runtimeOverride); + if (normalizedRuntime) { + this.oauthCallbackBaseUrl = normalizedRuntime; + return normalizedRuntime; + } + try { + const override = window.localStorage?.getItem( + "oasis_oauth_callback_base_url" + ); + const normalizedStorage = this.normalizeOAuthCallbackBaseUrl(override); + if (normalizedStorage) { + this.oauthCallbackBaseUrl = normalizedStorage; + return normalizedStorage; + } + } catch (e2) { + } + } + return "https://kahana.co"; + } + normalizeOAuthCallbackBaseUrl(url) { + if (!url || !/^https?:\/\//i.test(url)) { + return null; + } + return url.replace(/\/+$/, ""); + } + createOAuthFlowId() { + return `oauth_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`; + } + getActiveOAuthLaunch(provider, target) { + if (!this.activeOAuthLaunch) { + return null; + } + if (Date.now() - this.activeOAuthLaunch.startedAt > 6e5) { + this.activeOAuthLaunch = null; + return null; + } + if (this.activeOAuthLaunch.provider === provider && this.activeOAuthLaunch.target === target) { + return this.activeOAuthLaunch; + } + return null; + } + beginOAuthLaunch(provider, target) { + const existingLaunch = this.getActiveOAuthLaunch(provider, target); + if (existingLaunch) { + console.warn( + `[Oasis OAuth][${existingLaunch.flowId}] Reusing active OAuth launcher URL` + ); + return existingLaunch; + } + const flowId = this.createOAuthFlowId(); + this.setFirefoxOAuthMarker(target, provider, flowId); + const launcherUrl = this.getOAuthLauncherUrl(provider, target, flowId); + const launch = { + provider, + target, + flowId, + launcherUrl, + startedAt: Date.now() + }; + this.activeOAuthLaunch = launch; + return launch; + } + clearActiveOAuthLaunch(flowId) { + if (!this.activeOAuthLaunch) { + return; + } + if (!flowId || this.activeOAuthLaunch.flowId === flowId) { + this.activeOAuthLaunch = null; + } + } + getOAuthRedirectUrl(target = "assistant", flowId) { + const params = new URLSearchParams({ + flow: "assistant", + handoff_target: target + }); + if (flowId) { + params.set("flow_id", flowId); + } + return `${this.getOAuthCallbackBaseUrl()}/oauth-callback?${params.toString()}`; + } + getOAuthLauncherUrl(provider, target = "assistant", flowId) { + const params = new URLSearchParams({ + flow: "assistant", + handoff_target: target, + provider + }); + if (flowId) { + params.set("flow_id", flowId); + } + return `${this.getOAuthCallbackBaseUrl()}/oasis-auth?${params.toString()}`; + } + setFirefoxOAuthMarker(target, provider, flowId) { + if (typeof window === "undefined") { + return; + } + const Services = window.Services || (globalThis.ChromeUtils ? globalThis.ChromeUtils.import( + "resource://gre/modules/Services.jsm" + ).Services : null); + const Ci = window.Ci || globalThis.Ci; + if (!Services?.cookies || !Ci?.nsICookie) { + return; + } + const payload = encodeURIComponent( + JSON.stringify({ + target, + provider, + flowId, + timestamp: Date.now(), + callbackBaseUrl: this.getOAuthCallbackBaseUrl() + }) + ); + const expiry = Date.now() + 3 * 60 * 1e3; + const writeCookie = (baseUrl) => { + try { + const parsed = new URL(baseUrl); + const schemeMap = parsed.protocol === "https:" ? Ci.nsICookie.SCHEME_HTTPS : Ci.nsICookie.SCHEME_HTTP; + Services.cookies.add( + parsed.hostname, + "/", + "oasis_firefox_oauth_target", + payload, + parsed.protocol === "https:", + false, + false, + expiry, + {}, + Ci.nsICookie.SAMESITE_LAX, + schemeMap + ); + } catch (e2) { + console.warn("Failed to set Firefox OAuth marker cookie:", e2); + } + }; + const callbackBaseUrl = this.getOAuthCallbackBaseUrl(); + writeCookie(callbackBaseUrl); + if (!callbackBaseUrl.includes("kahana.co")) { + writeCookie("https://kahana.co"); + } + } + // Google OAuth Authentication + async signInWithGoogle(target = "assistant") { + try { + const launch = this.beginOAuthLaunch("google", target); + const { flowId, launcherUrl } = launch; + console.log( + `[Oasis OAuth][${flowId}] Preparing Google OAuth launcher URL` + ); + const currentUser = await this.getCurrentUser(); + if (currentUser) { + console.log( + `[Oasis OAuth][${flowId}] User already authenticated:`, + currentUser.id + ); + return { user: currentUser, error: null }; + } + console.log( + `[Oasis OAuth][${flowId}] Generated launcher URL:`, + launcherUrl + ); + return { + user: null, + error: new Error(`GOOGLE_OAUTH_URL:${launcherUrl}`) + }; + } catch (error) { + console.error("Google sign in error:", error); + return { user: null, error }; + } + } + async signInWithAzure(target = "assistant") { + try { + const launch = this.beginOAuthLaunch("azure", target); + const { flowId, launcherUrl } = launch; + console.log( + `[Oasis OAuth][${flowId}] Preparing Azure OAuth launcher URL` + ); + const currentUser = await this.getCurrentUser(); + if (currentUser) { + console.log( + `[Oasis OAuth][${flowId}] User already authenticated:`, + currentUser.id + ); + return { user: currentUser, error: null }; + } + console.log( + `[Oasis OAuth][${flowId}] Generated launcher URL:`, + launcherUrl + ); + return { + user: null, + error: new Error(`AZURE_OAUTH_URL:${launcherUrl}`) + }; + } catch (error) { + console.error("Azure sign in error:", error); + return { user: null, error }; + } + } + async signInWithApple(target = "assistant") { + try { + const launch = this.beginOAuthLaunch("apple", target); + const { flowId, launcherUrl } = launch; + console.log( + `[Oasis OAuth][${flowId}] Preparing Apple OAuth launcher URL` + ); + const currentUser = await this.getCurrentUser(); + if (currentUser) { + console.log( + `[Oasis OAuth][${flowId}] User already authenticated:`, + currentUser.id + ); + return { user: currentUser, error: null }; + } + console.log( + `[Oasis OAuth][${flowId}] Generated launcher URL:`, + launcherUrl + ); + return { + user: null, + error: new Error(`APPLE_OAUTH_URL:${launcherUrl}`) + }; + } catch (error) { + console.error("Apple sign in error:", error); + return { user: null, error }; + } + } + // Email/Password Authentication + async signInWithEmail(email, password) { + try { + console.log("Attempting email sign in for:", email); + const { data, error } = await this.supabase.auth.signInWithPassword({ + email, + password + }); + if (error) { + console.error("Email sign in error:", error.message); + return { user: null, error }; + } + if (data.user) { + await this.updateLastLogin(data.user.id); + await this.createSession(data.user.id); + console.log("Email sign in successful for user:", data.user.id); + } + return { user: data.user, error: null }; + } catch (error) { + console.error("Sign in error:", error); + return { user: null, error }; + } + } + async signUp(email, password, name) { + try { + console.log("Attempting sign up for:", email); + const { data, error } = await this.supabase.auth.signUp({ + email, + password, + options: { + data: { + name: name || email.split("@")[0] + } + } + }); + if (error) { + console.error("Sign up error:", error.message); + return { user: null, error }; + } + if (data.user) { + await this.createUserProfile(data.user, name); + console.log("Sign up successful for user:", data.user.id); + } + return { user: data.user, error: null }; + } catch (error) { + console.error("Sign up error:", error); + return { user: null, error }; + } + } + async resetPasswordForEmail(email) { + try { + console.log("Attempting password reset for:", email); + const { error } = await this.supabase.auth.resetPasswordForEmail(email, { + redirectTo: "https://kahana.co/update-password" + }); + if (error) { + console.error("Password reset error:", error.message); + return { error }; + } + console.log("Password reset email sent"); + return { error: null }; + } catch (error) { + console.error("Password reset error:", error); + return { error }; + } + } + async signOut() { + try { + console.log("Attempting sign out"); + if (this.currentSession) { + await this.endSession(this.currentSession.session_id); + } + const { error } = await this.supabase.auth.signOut(); + if (error) { + console.error("Sign out error:", error.message); + return { error }; + } + this.currentSession = null; + console.log("Sign out successful"); + return { error: null }; + } catch (error) { + console.error("Sign out error:", error); + return { error }; + } + } + // Session Management + async getCurrentUser() { + const { + data: { user } + } = await this.supabase.auth.getUser(); + return user; + } + async getSession() { + const { + data: { session } + } = await this.supabase.auth.getSession(); + return session; + } + async isAuthenticated() { + const user = await this.getCurrentUser(); + return user !== null; + } + normalizeOAuthCallbackPayload(authData) { + const out = {}; + if (!authData || typeof authData !== "object") { + return out; + } + if (typeof authData.code === "string" && authData.code) { + out.code = authData.code; + } + if (authData.access_token && authData.refresh_token) { + out.access_token = authData.access_token; + out.refresh_token = authData.refresh_token; + return out; + } + const tryParseHash = (raw) => { + const h2 = raw.replace(/^#/, ""); + const params = new URLSearchParams(h2); + const at = params.get("access_token"); + const rt = params.get("refresh_token"); + if (at && rt) { + out.access_token = at; + out.refresh_token = rt; + return true; + } + return false; + }; + const urlLike = typeof authData.redirect_url === "string" ? authData.redirect_url : typeof authData.redirectUrl === "string" ? authData.redirectUrl : typeof authData.url === "string" ? authData.url : typeof authData.callback_url === "string" ? authData.callback_url : null; + if (urlLike?.includes("#")) { + const frag = urlLike.split("#")[1]; + if (frag) { + tryParseHash(frag); + } + } + if (!out.access_token && typeof authData.fragment === "string" && authData.fragment) { + tryParseHash(authData.fragment); + } + if (authData.access_token) { + out.access_token = authData.access_token; + } + if (authData.refresh_token) { + out.refresh_token = authData.refresh_token; + } + return out; + } + /** + * Handle OAuth callback data (similar to Electron's handleOAuthRedirectCallback) + * Processes auth data from manual input and exchanges it for a session + */ + async handleOAuthCallbackData(authData) { + const flowId = authData?.flow_id || authData?.flowId || "unknown"; + try { + console.log(`[Oasis OAuth][${flowId}] Handling callback data:`, authData); + const normalized = this.normalizeOAuthCallbackPayload(authData); + if (!normalized.code && !(normalized.access_token && normalized.refresh_token)) { + const safeKeys = Object.keys(authData || {}).filter( + (k3) => !/^(access_token|refresh_token|provider_token)$/i.test(k3) + ); + console.warn( + `[Oasis OAuth][${flowId}] Incomplete handoff (no code or tokens). Keys: ${safeKeys.join(", ")}` + ); + this.clearActiveOAuthLaunch(flowId); + return { + success: false, + error: "Complete sign-in in the browser window that opened, then return here." + }; + } + if (normalized.code) { + console.log( + `[Oasis OAuth][${flowId}] Exchanging auth code for session...` + ); + const { data, error } = await this.supabase.auth.exchangeCodeForSession( + normalized.code + ); + if (error) { + console.error( + `[Oasis OAuth][${flowId}] Failed to exchange code for session:`, + error.message + ); + this.clearActiveOAuthLaunch(flowId); + return { success: false, error: error.message }; + } else { + console.log( + `[Oasis OAuth][${flowId}] Exchanged code for session for user:`, + data.user?.id + ); + if (data.user) { + await this.rpcEnsureUserProfile(data.user); + const existingProfile = await this.getUserProfile(); + if (!existingProfile) { + await this.createUserProfile( + data.user, + data.user.user_metadata?.name + ); + console.log( + `[Oasis OAuth][${flowId}] Created user profile from OAuth callback` + ); + } + await this.updateLastLogin(data.user.id); + await this.createSession(data.user.id); + } + this.clearActiveOAuthLaunch(flowId); + return { success: true }; + } + } + if (normalized.access_token && normalized.refresh_token) { + console.log(`[Oasis OAuth][${flowId}] Setting session from tokens...`); + const { data, error } = await this.supabase.auth.setSession({ + access_token: normalized.access_token, + refresh_token: normalized.refresh_token + }); + if (error) { + console.error( + `[Oasis OAuth][${flowId}] Failed to set session from tokens:`, + error.message + ); + this.clearActiveOAuthLaunch(flowId); + return { success: false, error: error.message }; + } else { + console.log( + `[Oasis OAuth][${flowId}] Set session from tokens for user:`, + data.user?.id + ); + if (data.user) { + await this.rpcEnsureUserProfile(data.user); + const existingProfile = await this.getUserProfile(); + if (!existingProfile) { + await this.createUserProfile( + data.user, + data.user.user_metadata?.name + ); + console.log( + `[Oasis OAuth][${flowId}] Created user profile from tokens` + ); + } + await this.updateLastLogin(data.user.id); + await this.createSession(data.user.id); + } + this.clearActiveOAuthLaunch(flowId); + return { success: true }; + } + } + console.warn( + `[Oasis OAuth][${flowId}] No valid OAuth data after normalization` + ); + this.clearActiveOAuthLaunch(flowId); + return { + success: false, + error: "Complete sign-in in the browser window that opened, then return here." + }; + } catch (error) { + console.error( + `[Oasis OAuth][${flowId}] Error handling callback data:`, + error + ); + this.clearActiveOAuthLaunch(flowId); + return { + success: false, + error: error instanceof Error ? error.message : "Unknown error" + }; + } + } + // User Profile Management + async getUserProfile() { + try { + const user = await this.getCurrentUser(); + if (!user) return null; + const { data, error } = await this.supabase.from("users").select("*").eq("user_id", user.id).single(); + if (error) { + console.error("Error fetching user profile:", error.message); + return null; + } + return data; + } catch (error) { + console.error("Error fetching user profile:", error); + return null; + } + } + // Auth State Management + onAuthStateChange(callback) { + this.authStateCallbacks.push(callback); + } + async handleAuthStateChange(event, session) { + const user = session?.user || null; + const authState = { + user, + session, + isAuthenticated: user !== null + }; + this.authStateCallbacks.forEach((callback) => { + try { + callback(authState); + } catch (error) { + console.error("Error in auth state callback:", error); + } + }); + if (event === "SIGNED_IN" && user) { + await this.rpcEnsureUserProfile(user); + await this.trackSessionForUser(user.id); + } else if (event === "SIGNED_OUT" && this.currentSession) { + this.lastTrackedSessionUserId = null; + await this.endSession(this.currentSession.session_id); + this.currentSession = null; + } else if (event === "SIGNED_OUT") { + this.lastTrackedSessionUserId = null; + } + } + async rpcEnsureUserProfile(user) { + try { + const meta = user.user_metadata; + const fullName = typeof meta?.full_name === "string" ? meta.full_name : void 0; + const metaName = typeof meta?.name === "string" ? meta.name : void 0; + const { error } = await this.supabase.rpc("ensure_user_profile", { + p_email: user.email ?? "", + p_name: fullName ?? metaName ?? null + }); + if (error) { + console.warn("ensure_user_profile RPC:", error.message); + } + } catch (error) { + console.warn("ensure_user_profile RPC failed:", error); + } + } + // Database Operations + async createUserProfile(user, name) { + try { + const { error } = await this.supabase.from("users").insert({ + user_id: user.id, + email: user.email, + name: name || user.user_metadata?.name || user.email.split("@")[0], + password_hash: "", + // Supabase handles this + status: "active" + }); + if (error) { + console.error("Error creating user profile:", error.message); + } else { + console.log("User profile created successfully"); + } + } catch (error) { + console.error("Error creating user profile:", error); + } + } + async updateLastLogin(userId) { + try { + const { error } = await this.supabase.from("users").update({ last_login: (/* @__PURE__ */ new Date()).toISOString() }).eq("user_id", userId); + if (error) { + console.error("Error updating last login:", error.message); + } + } catch (error) { + console.error("Error updating last login:", error); + } + } + async trackSessionForUser(userId) { + if (this.currentSession?.user_id === userId && !this.currentSession?.ended_at) { + this.lastTrackedSessionUserId = userId; + return; + } + if (this.lastTrackedSessionUserId === userId) { + return; + } + if (this.sessionTrackInFlight?.userId === userId) { + await this.sessionTrackInFlight.promise; + return; + } + const pendingTrack = { + userId, + promise: Promise.resolve() + }; + pendingTrack.promise = this.createSession(userId).finally(() => { + if (this.sessionTrackInFlight === pendingTrack) { + this.sessionTrackInFlight = null; + } + }); + this.sessionTrackInFlight = pendingTrack; + await pendingTrack.promise; + this.lastTrackedSessionUserId = userId; + } + async createSession(userId) { + try { + const deviceInfo = { + platform: "browser", + version: ENV.APP_VERSION, + userAgent: window.navigator.userAgent + }; + const { data, error } = await this.supabase.from("sessions").insert({ + user_id: userId, + device_info: deviceInfo + }).select().single(); + if (error) { + if (error.message.includes("row-level security policy")) { + console.warn( + "Session tracking skipped due to RLS policy (non-critical):", + error.message + ); + } else { + console.error("Error creating session:", error.message); + } + } else if (data) { + this.currentSession = data; + console.log("Session created:", data.session_id); + } + } catch (error) { + console.error("Error creating session:", error); + } + } + async endSession(sessionId) { + try { + const { error } = await this.supabase.from("sessions").update({ ended_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("session_id", sessionId); + if (error) { + console.error("Error ending session:", error.message); + } else { + console.log("Session ended:", sessionId); + } + } catch (error) { + console.error("Error ending session:", error); + } + } + // Utility Methods + handleAuthError(error) { + if (error.message && (error.message.startsWith("GOOGLE_OAUTH_URL:") || error.message.startsWith("AZURE_OAUTH_URL:") || error.message.startsWith("APPLE_OAUTH_URL:"))) { + return error.message; + } + switch (error.message) { + case "Invalid login credentials": + return "Invalid email or password. Please try again."; + case "Email not confirmed": + return "Please check your email and click the confirmation link."; + case "User already registered": + return "An account with this email already exists."; + case "Password should be at least 6 characters": + return "Password must be at least 6 characters long."; + case "Unable to validate email address: invalid format": + return "Please enter a valid email address."; + case "OAuth provider not found": + return "Google sign-in is not configured. Please contact support."; + case "OAuth account not linked": + return "This Google account is not linked to an existing account."; + case "Google sign-in is blocked by browser security. Please use email/password authentication instead.": + return "Google sign-in is blocked by browser security. Please use email/password authentication instead."; + case "Popup blocked. Please allow popups for this site and try again.": + return "Popup blocked. Please allow popups for this site and try again."; + case "Google sign-in was cancelled or failed. Please try again.": + return "Google sign-in was cancelled or failed. Please try again."; + case "Google sign-in timed out. Please try again.": + return "Google sign-in timed out. Please try again."; + case "Failed to generate OAuth URL": + return "Failed to generate OAuth URL. Please try again."; + case "Failed to open OAuth URL. Please allow popups and try again.": + return "Failed to open OAuth URL. Please allow popups and try again."; + default: + return error.message || "An unexpected error occurred. Please try again."; + } + } + }; + var supabaseAuth = SupabaseAuth.getInstance(); + if (typeof window !== "undefined") { + window.supabaseAuth = supabaseAuth; + } + + // src/services/subscription.ts + var PLAN_LIMITS = { + free: 50, + basic: 1500, + // $20/mo + pro: 3e3 + // $40/mo + }; + var PLAN_DAILY_TOKEN_LIMITS = { + free: 1e5, + basic: 1e6, + pro: 2e6 + }; + var DEFAULT_LIMIT = 50; + var DEFAULT_DAILY_TOKEN_LIMIT = 1e5; + var COST_TEXT = 1; + var COST_VOICE = 10; + var logDebug2 = (message, ...meta) => { + assistantLogger.debug( + "subscription", + String(message ?? ""), + meta.length === 0 ? void 0 : meta.length === 1 ? meta[0] : meta + ); + }; + var logWarn2 = (message, ...meta) => { + assistantLogger.warn( + "subscription", + String(message ?? ""), + meta.length === 0 ? void 0 : meta.length === 1 ? meta[0] : meta + ); + }; + var logError2 = (message, ...meta) => { + assistantLogger.error( + "subscription", + String(message ?? ""), + meta.length === 0 ? void 0 : meta.length === 1 ? meta[0] : meta + ); + }; + var OPTIMISTIC_FEEDBACK_BONUS_KEY = "oasis.daily_training_bonus.verified."; + function utcCalendarDateString() { + const d3 = /* @__PURE__ */ new Date(); + d3.setUTCHours(0, 0, 0, 0); + return d3.toISOString().slice(0, 10); + } + function readOptimisticFeedbackBonusTokensToday() { + try { + const raw = sessionStorage.getItem( + OPTIMISTIC_FEEDBACK_BONUS_KEY + utcCalendarDateString() + ); + const n2 = parseInt(String(raw || "0"), 10); + return Number.isFinite(n2) && n2 >= 0 ? n2 : 0; + } catch { + return 0; + } + } + function writeOptimisticFeedbackBonusTokensToday(total) { + try { + sessionStorage.setItem( + OPTIMISTIC_FEEDBACK_BONUS_KEY + utcCalendarDateString(), + String(Math.max(0, Math.floor(total))) + ); + } catch { + } + } + var SubscriptionService = class _SubscriptionService { + static instance; + // Cache current plan details to avoid hitting DB on every keystroke + cachedLimit = null; + cachedUsage = 0; + lastFetchTime = 0; + CACHE_TTL = 60 * 1e3; + // 1 minute cache + cachedDailyLimit = null; + cachedDailyUsedFromApi = null; + cachedDailyRemainingFromApi = null; + cachedDailyTokensFromDb = 0; + cachedDailyTokensFromDbOk = false; + cachedDailyTokenLimitSupabase = null; + cachedFeedbackBonusTokensToday = 0; + constructor() { + } + static getInstance() { + if (!_SubscriptionService.instance) { + _SubscriptionService.instance = new _SubscriptionService(); + } + return _SubscriptionService.instance; + } + /** + * Call after a qualifying training save succeeds so the daily bar reflects bonus tokens + * even when `feedback_token_grants` is unavailable. Persists for the current UTC calendar day. + */ + appendOptimisticTrainingBonus(amount) { + if (!Number.isFinite(amount) || amount <= 0) { + return; + } + const add = Math.floor(amount); + const prevCached = this.cachedFeedbackBonusTokensToday; + writeOptimisticFeedbackBonusTokensToday( + readOptimisticFeedbackBonusTokensToday() + add + ); + const fromStorage = readOptimisticFeedbackBonusTokensToday(); + this.cachedFeedbackBonusTokensToday = Math.max( + prevCached + add, + fromStorage + ); + } + getUsageBarSnapshot() { + return this.getDailyTokenUsageForDisplay(); + } + updateFromQuota(quota) { + if (!quota) return; + if (quota.monthly_limit !== void 0) { + this.cachedLimit = quota.monthly_limit; + } + if (quota.monthly_used !== void 0) { + this.cachedUsage = quota.monthly_used; + } + if (quota.daily_limit !== void 0) { + this.cachedDailyLimit = quota.daily_limit; + } + if (quota.daily_used !== void 0) { + this.cachedDailyUsedFromApi = quota.daily_used; + } + if (quota.daily_remaining !== void 0) { + this.cachedDailyRemainingFromApi = quota.daily_remaining; + } + this.lastFetchTime = Date.now(); + logDebug2( + `updateFromQuota: monthly limit=${this.cachedLimit} used=${this.cachedUsage}; daily limit=${this.cachedDailyLimit} used=${this.cachedDailyUsedFromApi}` + ); + } + /** + * Apply `usage_stats` from Supabase Edge assist (post-`record_llm_usage`). + * Avoid calling `trackUsage` for the same request when this object is present. + */ + updateFromAssistUsageStats(stats) { + if (!stats || typeof stats !== "object") { + return; + } + const patch = {}; + if (typeof stats.total_tokens === "number" && Number.isFinite(stats.total_tokens)) { + patch.daily_used = stats.total_tokens; + } + if (typeof stats.limit === "number" && Number.isFinite(stats.limit)) { + patch.daily_limit = stats.limit; + } + if (typeof stats.remaining === "number" && Number.isFinite(stats.remaining)) { + patch.daily_remaining = stats.remaining; + } + if (Object.keys(patch).length > 0) { + this.updateFromQuota(patch); + } + } + getDailyTokenUsageForDisplay() { + const fromSupabaseLimit = this.cachedDailyTokenLimitSupabase !== null && this.cachedDailyTokenLimitSupabase > 0 ? this.cachedDailyTokenLimitSupabase : null; + const baseLimit = Math.max( + 1, + fromSupabaseLimit ?? DEFAULT_DAILY_TOKEN_LIMIT + ); + const bonusTokens = Math.max(0, this.cachedFeedbackBonusTokensToday); + const limit = baseLimit + bonusTokens; + const fromApi = this.cachedDailyUsedFromApi ?? 0; + const fromDb = this.cachedDailyTokensFromDb; + const used = Math.max( + 0, + this.cachedDailyTokensFromDbOk ? fromDb : Math.max(fromApi, fromDb) + ); + const remaining = Math.max(0, limit - used); + const percentOfBase = baseLimit > 0 ? Math.min(9999, Math.round(used / baseLimit * 1e3) / 10) : 0; + const percentUsed = limit > 0 ? Math.min(9999, Math.round(used / limit * 1e3) / 10) : 0; + const local = { + used, + limit, + baseLimit, + bonusTokens, + remaining, + percentUsed, + percentOfBase + }; + const qLimit = this.cachedDailyLimit; + const qUsed = this.cachedDailyUsedFromApi; + const qRem = this.cachedDailyRemainingFromApi; + if (qLimit != null && qLimit > 0 && qUsed != null && qRem != null && Number.isFinite(qUsed) && Number.isFinite(qRem) && Math.abs(qUsed + qRem - qLimit) <= 2 && qLimit >= local.limit) { + const qBonus = Math.max(0, qLimit - local.baseLimit); + const qPercentOfBase = local.baseLimit > 0 ? Math.min(9999, Math.round(qUsed / local.baseLimit * 1e3) / 10) : 0; + const qPercentUsed = qLimit > 0 ? Math.min(9999, Math.round(qUsed / qLimit * 1e3) / 10) : 0; + return { + used: qUsed, + limit: qLimit, + baseLimit: local.baseLimit, + bonusTokens: qBonus, + remaining: qRem, + percentUsed: qPercentUsed, + percentOfBase: qPercentOfBase + }; + } + return local; + } + async getUsageBarData() { + await this.forceRefresh(); + return this.getUsageBarSnapshot(); + } + /** + * Track usage for a command + * @param type 'text' or 'voice' + * @param model Optional model name for record keeping + */ + /** + * Log Gemini tokens for assist **routing** only (`usage_count` / monthly units stay 0). + * Final assistant turns still use `trackUsage` from the graph stream. + */ + recordAssistRoutingTokens(meta) { + void this.recordAssistRoutingTokensAsync(meta); + } + async recordAssistRoutingTokensAsync(meta) { + const user = await supabaseAuth.getCurrentUser(); + if (!user) { + logWarn2("recordAssistRoutingTokens: No user found."); + return; + } + const input = Number(meta.input_tokens ?? 0); + const output = Number(meta.output_tokens ?? 0); + if (!Number.isFinite(input) || !Number.isFinite(output) || input <= 0 && output <= 0) { + return; + } + const supabase = supabaseAuth.supabase; + const { error } = await supabase.from("llm_usage").insert({ + user_id: user.id, + tokens_used: 0, + usage_count: 0, + model_used: "assist-router", + success: true, + command_type: meta.command_type ?? null, + user_intent: meta.user_intent ?? null, + input_tokens: input, + output_tokens: output + }); + if (error) { + logError2("recordAssistRoutingTokens: DB insert failed", error); + } else { + logDebug2("recordAssistRoutingTokens: logged routing tokens", { + input, + output + }); + } + } + async trackUsage(type, model = "gemini-1.5-flash", meta) { + const user = await supabaseAuth.getCurrentUser(); + if (!user) { + logWarn2("trackUsage: No user found."); + return; + } + const units = type === "voice" ? COST_VOICE : COST_TEXT; + logDebug2( + `trackUsage: Tracking ${units} units for ${type} (User: ${user.id})` + ); + this.cachedUsage += units; + logDebug2(`trackUsage: cachedUsage is now ${this.cachedUsage}`); + localMemory.saveUsage(user.id, this.cachedUsage).catch((e2) => logError2("Failed to save local usage:", e2)); + const supabase = supabaseAuth.supabase; + supabase.from("llm_usage").insert({ + user_id: user.id, + tokens_used: units, + usage_count: units, + model_used: `${type}:${model}`, + success: true, + command_type: meta?.command_type ?? null, + user_intent: meta?.user_intent ?? null, + input_tokens: meta?.input_tokens ?? 0, + output_tokens: meta?.output_tokens ?? 0 + }).then(({ error }) => { + if (error) logError2("Failed to track usage (DB Insert):", error); + else logDebug2("trackUsage: DB insert successful"); + }); + } + /** + * Check if the user can proceed with a command + */ + async checkAvailability() { + const user = await supabaseAuth.getCurrentUser(); + if (!user) { + return { totalUnits: 0, limit: 0, remaining: 0, isLimitReached: true }; + } + if (this.lastFetchTime === 0 || Date.now() - this.lastFetchTime > this.CACHE_TTL) { + await this.refreshUsageData(user.id); + } + const limit = this.cachedLimit ?? DEFAULT_LIMIT; + const remaining = Math.max(0, limit - this.cachedUsage); + return { + totalUnits: this.cachedUsage, + limit, + remaining, + isLimitReached: this.cachedUsage >= limit + }; + } + getSubscriptionUrl() { + return "https://kahana.co/oasis-pricing"; + } + async forceRefresh() { + const user = await supabaseAuth.getCurrentUser(); + if (user) { + this.lastFetchTime = 0; + await this.refreshUsageData(user.id); + } + } + async refreshUsageData(userId) { + const supabase = supabaseAuth.supabase; + logDebug2("refreshUsageData: syncing usage..."); + let limit = DEFAULT_LIMIT; + const { data: planData, error: planError } = await supabase.from("user_plans").select( + ` + plan_id, + stripe_subscription_id, + is_active, + plans ( name, llm_call_limit ) + ` + ).eq("user_id", userId).eq("is_active", true).maybeSingle(); + logDebug2(`refreshUsageData: Primary query result:`, { + planData, + planError, + hasPlansJoin: planData && planData.plans ? true : false, + userId + }); + let planNameKey = "free"; + let planIdForDaily = null; + if (planData) { + if (planData.plan_id != null) { + planIdForDaily = String(planData.plan_id); + } + const joined = planData.plans; + if (joined && typeof joined.name === "string" && joined.name) { + planNameKey = joined.name.toLowerCase(); + } + } + if (planData && planData.plans) { + const dbLimit = planData.plans.llm_call_limit; + const planName = (planData.plans.name || "").toLowerCase(); + if (dbLimit) { + limit = dbLimit; + logDebug2(`refreshUsageData: Using plan limit from DB: ${limit}`); + } else if (PLAN_LIMITS[planName]) { + limit = PLAN_LIMITS[planName]; + logDebug2( + `refreshUsageData: Using plan limit from name mapping: ${limit}` + ); + } + } else if (planData && planData.is_active) { + const stripeSubId = planData.stripe_subscription_id; + const hasStripeSubscription = stripeSubId && typeof stripeSubId === "string" && stripeSubId.trim() !== ""; + logDebug2( + `refreshUsageData: Plans join failed but planData exists, checking stripe_subscription_id:`, + { + stripeSubId, + hasStripeSubscription, + is_active: planData.is_active + } + ); + if (hasStripeSubscription) { + limit = PLAN_LIMITS["basic"]; + planNameKey = "basic"; + logDebug2( + `refreshUsageData: Using Basic plan limit (1500) based on stripe_subscription_id from primary query: ${stripeSubId}` + ); + } else { + logWarn2( + "refreshUsageData: Plan data exists but no valid stripe_subscription_id, trying fallback query" + ); + } + } + if (limit === DEFAULT_LIMIT) { + logWarn2( + "refreshUsageData: Limit still at default, trying fallback query without join" + ); + const { data: fallbackData, error: fallbackError } = await supabase.from("user_plans").select("plan_id, stripe_subscription_id, is_active").eq("user_id", userId).eq("is_active", true).maybeSingle(); + logDebug2(`refreshUsageData: Fallback query result:`, { + fallbackData, + fallbackError, + userId + }); + if (fallbackError) { + logError2("refreshUsageData: Fallback query error:", fallbackError); + } + if (fallbackData && fallbackData.is_active) { + if (planIdForDaily === null && fallbackData.plan_id != null) { + planIdForDaily = String(fallbackData.plan_id); + } + const stripeSubId = fallbackData.stripe_subscription_id; + const hasStripeSubscription = stripeSubId && typeof stripeSubId === "string" && stripeSubId.trim() !== ""; + logDebug2(`refreshUsageData: Checking stripe_subscription_id:`, { + stripeSubId, + hasStripeSubscription, + type: typeof stripeSubId + }); + if (hasStripeSubscription) { + limit = PLAN_LIMITS["basic"]; + planNameKey = "basic"; + logDebug2( + `refreshUsageData: Using Basic plan limit (1500) based on stripe_subscription_id: ${stripeSubId}` + ); + } else { + logWarn2( + "refreshUsageData: Active plan found but no valid stripe_subscription_id, using free plan limit" + ); + } + } else { + logWarn2( + "refreshUsageData: No active plan found for user, using free plan limit", + { + fallbackData, + userId + } + ); + } + } + logDebug2(`refreshUsageData: Final limit set to: ${limit}`); + this.cachedLimit = limit; + let dbTotal = 0; + const startOfMonth = /* @__PURE__ */ new Date(); + startOfMonth.setDate(1); + startOfMonth.setHours(0, 0, 0, 0); + const { data: usageData, error: usageError } = await supabase.from("llm_usage").select("usage_count").eq("user_id", userId).gte("created_at", startOfMonth.toISOString()); + if (usageData) { + dbTotal = usageData.reduce( + (acc, row) => acc + (row.usage_count || 0), + 0 + ); + } + const localTotal = await localMemory.getUsage(userId); + if (!usageError && usageData) { + this.cachedUsage = dbTotal; + localMemory.saveUsage(userId, dbTotal).catch((e2) => logWarn2("refreshUsageData: sync local:", e2)); + } else { + if (usageError) { + logWarn2( + "refreshUsageData: DB fetch failed (RLS?), using local only.", + usageError.message + ); + } + this.cachedUsage = Math.max(dbTotal, localTotal); + } + logDebug2( + `refreshUsageData: DB=${dbTotal}, Local=${localTotal} -> Final=${this.cachedUsage}` + ); + let dailyTokLimit = null; + if (planIdForDaily) { + const { data: planRow, error: planRowErr } = await supabase.from("plans").select("daily_token_limit").eq("id", planIdForDaily).maybeSingle(); + if (!planRowErr && planRow && planRow.daily_token_limit != null) { + const n2 = Number(planRow.daily_token_limit); + if (Number.isFinite(n2) && n2 > 0) { + dailyTokLimit = n2; + } + } + } + this.cachedDailyTokenLimitSupabase = dailyTokLimit ?? PLAN_DAILY_TOKEN_LIMITS[planNameKey] ?? DEFAULT_DAILY_TOKEN_LIMIT; + const startOfUtcDay = /* @__PURE__ */ new Date(); + startOfUtcDay.setUTCHours(0, 0, 0, 0); + const utcGrantDate = startOfUtcDay.toISOString().slice(0, 10); + let grantSum = 0; + const { data: grantRows, error: grantErr } = await supabase.from("feedback_token_grants").select("tokens").eq("user_id", userId).eq("grant_date_utc", utcGrantDate); + if (!grantErr && grantRows) { + grantSum = grantRows.reduce( + (acc, row) => acc + (Number(row.tokens) || 0), + 0 + ); + } else if (grantErr) { + logDebug2( + "refreshUsageData: feedback_token_grants unavailable or error", + grantErr.message + ); + } + const optimistic = readOptimisticFeedbackBonusTokensToday(); + this.cachedFeedbackBonusTokensToday = Math.max( + grantSum, + optimistic, + this.cachedFeedbackBonusTokensToday + ); + this.cachedDailyTokensFromDbOk = false; + const { data: dayRows, error: dayErr } = await supabase.from("llm_usage").select("input_tokens, output_tokens").eq("user_id", userId).gte("created_at", startOfUtcDay.toISOString()); + if (!dayErr && dayRows) { + this.cachedDailyTokensFromDbOk = true; + this.cachedDailyTokensFromDb = dayRows.reduce( + (acc, row) => acc + (Number(row.input_tokens) || 0) + (Number(row.output_tokens) || 0), + 0 + ); + } else { + if (dayErr) { + logWarn2( + "refreshUsageData: daily token aggregate failed", + dayErr.message + ); + } + } + this.lastFetchTime = Date.now(); + } + }; + var subscriptionService = SubscriptionService.getInstance(); + + // src/services/historyCollector.ts + function getPlacesUtils() { + const topWin = window.top; + const Services = topWin?.Services || window.Services; + if (Services?.wm) { + const browserWin = Services.wm.getMostRecentWindow("navigator:browser"); + return browserWin?.PlacesUtils; + } + return topWin?.PlacesUtils; + } + var EXCLUDED_PREFIXES = [ + "about:", + "chrome://", + "moz-extension://", + "resource://", + "data:", + "blob:", + "javascript:", + "view-source:" + ]; + var SEARCH_ENGINE_PATTERNS = [ + /^https?:\/\/(www\.)?google\.\w+\/search\?/, + /^https?:\/\/(www\.)?bing\.com\/search\?/, + /^https?:\/\/(www\.)?duckduckgo\.com\/\?q=/, + /^https?:\/\/(www\.)?yahoo\.com\/search/, + /^https?:\/\/(www\.)?baidu\.com\/s\?/, + /^https?:\/\/(www\.)?search\.yahoo\.com\// + ]; + function isSearchEnginePage(url) { + return SEARCH_ENGINE_PATTERNS.some((pattern) => pattern.test(url)); + } + function isUserVisibleUrl(url) { + if (!url) return false; + if (EXCLUDED_PREFIXES.some((prefix) => url.startsWith(prefix))) return false; + if (isSearchEnginePage(url)) return false; + return true; + } + var SNIPPET_MAX_LENGTH = 500; + var SNIPPET_FETCH_TIMEOUT = 5e3; + async function fetchPageSnippet(url) { + try { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), SNIPPET_FETCH_TIMEOUT); + const response = await fetch(url, { + signal: controller.signal, + headers: { Accept: "text/html" } + }); + clearTimeout(timeout); + if (!response.ok) return ""; + const contentType = response.headers.get("content-type") || ""; + if (!contentType.includes("text/html") && !contentType.includes("text/plain")) { + return ""; + } + const html2 = await response.text(); + const textContent = html2.replace(/]*>[\s\S]*?<\/script>/gi, "").replace(/]*>[\s\S]*?<\/style>/gi, "").replace(/]*>[\s\S]*?<\/nav>/gi, "").replace(/]*>[\s\S]*?<\/header>/gi, "").replace(/]*>[\s\S]*?<\/footer>/gi, "").replace(/<[^>]+>/g, " ").replace(/&[a-zA-Z]+;/g, " ").replace(/\s+/g, " ").trim().substring(0, SNIPPET_MAX_LENGTH); + return textContent; + } catch { + return ""; + } + } + async function fetchRecentHistory(maxResults = 200, includeSnippets = false) { + const PlacesUtils = getPlacesUtils(); + if (!PlacesUtils) { + console.warn("[HistoryCollector] PlacesUtils not available"); + return []; + } + try { + console.time("[HistoryCollector] Fetch history"); + const options = PlacesUtils.history.getNewQueryOptions(); + options.sortingMode = options.SORT_BY_DATE_DESCENDING; + options.maxResults = maxResults * 2; + options.includeHidden = false; + const query = PlacesUtils.history.getNewQuery(); + const result = PlacesUtils.history.executeQuery(query, options); + const root = result.root; + root.containerOpen = true; + const entries2 = []; + const seenUrls = /* @__PURE__ */ new Set(); + for (let i2 = 0; i2 < root.childCount && entries2.length < maxResults; i2++) { + const node = root.getChild(i2); + const url = node.uri; + if (!isUserVisibleUrl(url)) continue; + if (seenUrls.has(url)) continue; + seenUrls.add(url); + entries2.push({ + title: node.title || url, + // fallback to URL if no title + url, + // Places stores time in microseconds; convert to ms + visitDate: Math.floor(node.time / 1e3), + snippet: "" + // populated below if includeSnippets=true + }); + } + root.containerOpen = false; + console.timeEnd("[HistoryCollector] Fetch history"); + console.log( + `[HistoryCollector] Fetched ${entries2.length} unique history entries` + ); + if (includeSnippets && entries2.length > 0) { + console.log( + `[HistoryCollector] Fetching snippets for ${entries2.length} entries...` + ); + console.time("[HistoryCollector] Fetch snippets"); + const BATCH_SIZE = 5; + for (let i2 = 0; i2 < entries2.length; i2 += BATCH_SIZE) { + const batch = entries2.slice(i2, i2 + BATCH_SIZE); + const snippets = await Promise.all( + batch.map((e2) => fetchPageSnippet(e2.url)) + ); + batch.forEach((entry, j3) => { + entry.snippet = snippets[j3]; + }); + } + const withSnippets = entries2.filter((e2) => e2.snippet.length > 0).length; + console.timeEnd("[HistoryCollector] Fetch snippets"); + console.log( + `[HistoryCollector] Got snippets for ${withSnippets}/${entries2.length} entries` + ); + } + return entries2; + } catch (e2) { + console.error("[HistoryCollector] Failed to fetch history:", e2); + return []; + } + } + + // src/services/embeddingService.ts + var VECTOR_DIMENSIONS = 384; + var EMBEDDING_WORKER_PAGE_URL = "chrome://browser/content/assistant/embedding-worker.html"; + var FRAME_SCRIPT_URL = "chrome://browser/content/assistant/embedding-frame-script.js"; + var EmbeddingService = class { + browser = null; + ready = false; + modelLoaded = false; + readyPromise = null; + pendingRequests = /* @__PURE__ */ new Map(); + requestCounter = 0; + async ensureBrowser() { + if (this.ready) return; + if (this.readyPromise) { + await this.readyPromise; + return; + } + this.readyPromise = new Promise((resolve, reject) => { + console.log("[EmbeddingService] Creating remote content browser..."); + try { + const Services = window.Services || window.top?.Services || globalThis.Services; + const browserWin = Services?.wm?.getMostRecentWindow("navigator:browser"); + if (!browserWin) { + reject(new Error("Could not find main browser window")); + return; + } + this.browser = browserWin.document.createXULElement("browser"); + this.browser.setAttribute("type", "content"); + this.browser.setAttribute("remote", "true"); + this.browser.setAttribute("src", EMBEDDING_WORKER_PAGE_URL); + this.browser.style.cssText = "display:none; width:0; height:0; position:fixed; visibility:hidden;"; + browserWin.document.documentElement.appendChild(this.browser); + console.log("[EmbeddingService] Browser element appended, waiting for init..."); + setTimeout(() => { + try { + if (!this.browser.messageManager) { + console.error("[EmbeddingService] messageManager not available after timeout"); + reject(new Error("messageManager not available")); + return; + } + console.log("[EmbeddingService] Loading frame script..."); + this.browser.messageManager.loadFrameScript(FRAME_SCRIPT_URL, false); + this.browser.messageManager.addMessageListener("EmbedWorkerReady", () => { + if (this.ready) return; + console.log("[EmbeddingService] \u2705 Worker ready in content process!"); + this.ready = true; + resolve(); + }); + this.browser.messageManager.addMessageListener("EmbedModelLoaded", () => { + console.log("[EmbeddingService] Model loaded in content process"); + this.modelLoaded = true; + }); + this.browser.messageManager.addMessageListener("EmbedResponse", (msg) => { + const { id, embedding, error } = msg.data; + const pending = this.pendingRequests.get(id); + if (pending) { + this.pendingRequests.delete(id); + if (error) { + pending.reject(new Error(error)); + } else { + pending.resolve(embedding); + } + } + }); + console.log("[EmbeddingService] Message listeners set up"); + } catch (err) { + console.error("[EmbeddingService] Setup failed:", err); + reject(err); + } + }, 1e3); + setTimeout(() => { + if (!this.ready) { + console.error("[EmbeddingService] Timeout: never received EmbedWorkerReady"); + reject(new Error("Embedding browser failed to initialize within 60s")); + } + }, 6e4); + } catch (err) { + console.error("[EmbeddingService] Failed to create browser:", err); + reject(err); + } + }); + await this.readyPromise; + } + async embed(text2) { + await this.ensureBrowser(); + const id = `embed-${++this.requestCounter}`; + return new Promise((resolve, reject) => { + this.pendingRequests.set(id, { resolve, reject }); + this.browser.messageManager.sendAsyncMessage("EmbedRequest", { id, text: text2 }); + const timeout = this.modelLoaded ? 3e4 : 12e4; + setTimeout(() => { + if (this.pendingRequests.has(id)) { + this.pendingRequests.delete(id); + reject(new Error(`Embedding timed out after ${timeout / 1e3}s`)); + } + }, timeout); + }); + } + async embedBatch(texts) { + const results = []; + for (const text2 of texts) { + results.push(await this.embed(text2)); + } + return results; + } + /** + * Start loading the model in the background. + * Does not block — just kicks off the download. + * If it fails, no harm done — ensureBrowser() will retry on first search. + */ + preload() { + if (this.ready || this.readyPromise) return; + console.log("[EmbeddingService] \u{1F680} Background pre-warming started..."); + this.ensureBrowser().catch((err) => { + console.warn("[EmbeddingService] Pre-warming failed (will retry on search):", err); + this.readyPromise = null; + }); + } + isLoaded() { + return this.modelLoaded; + } + }; + var embeddingService = new EmbeddingService(); + + // node_modules/@orama/orama/dist/browser/components/tokenizer/languages.js + var STEMMERS = { + arabic: "ar", + armenian: "am", + bulgarian: "bg", + czech: "cz", + danish: "dk", + dutch: "nl", + english: "en", + finnish: "fi", + french: "fr", + german: "de", + greek: "gr", + hungarian: "hu", + indian: "in", + indonesian: "id", + irish: "ie", + italian: "it", + lithuanian: "lt", + nepali: "np", + norwegian: "no", + portuguese: "pt", + romanian: "ro", + russian: "ru", + serbian: "rs", + slovenian: "ru", + spanish: "es", + swedish: "se", + tamil: "ta", + turkish: "tr", + ukrainian: "uk", + sanskrit: "sk" + }; + var SPLITTERS = { + dutch: /[^A-Za-zàèéìòóù0-9_'-]+/gim, + english: /[^A-Za-zàèéìòóù0-9_'-]+/gim, + french: /[^a-z0-9äâàéèëêïîöôùüûœç-]+/gim, + italian: /[^A-Za-zàèéìòóù0-9_'-]+/gim, + norwegian: /[^a-z0-9_æøåÆØÅäÄöÖüÜ]+/gim, + portuguese: /[^a-z0-9à-úÀ-Ú]/gim, + russian: /[^a-z0-9а-яА-ЯёЁ]+/gim, + spanish: /[^a-z0-9A-Zá-úÁ-ÚñÑüÜ]+/gim, + swedish: /[^a-z0-9_åÅäÄöÖüÜ-]+/gim, + german: /[^a-z0-9A-ZäöüÄÖÜß]+/gim, + finnish: /[^a-z0-9äöÄÖ]+/gim, + danish: /[^a-z0-9æøåÆØÅ]+/gim, + hungarian: /[^a-z0-9áéíóöőúüűÁÉÍÓÖŐÚÜŰ]+/gim, + romanian: /[^a-z0-9ăâîșțĂÂÎȘȚ]+/gim, + serbian: /[^a-z0-9čćžšđČĆŽŠĐ]+/gim, + turkish: /[^a-z0-9çÇğĞıİöÖşŞüÜ]+/gim, + lithuanian: /[^a-z0-9ąčęėįšųūžĄČĘĖĮŠŲŪŽ]+/gim, + arabic: /[^a-z0-9أ-ي]+/gim, + nepali: /[^a-z0-9अ-ह]+/gim, + irish: /[^a-z0-9áéíóúÁÉÍÓÚ]+/gim, + indian: /[^a-z0-9अ-ह]+/gim, + armenian: /[^a-z0-9ա-ֆ]+/gim, + greek: /[^a-z0-9α-ωά-ώ]+/gim, + indonesian: /[^a-z0-9]+/gim, + ukrainian: /[^a-z0-9а-яА-ЯіїєІЇЄ]+/gim, + slovenian: /[^a-z0-9螚ȎŠ]+/gim, + bulgarian: /[^a-z0-9а-яА-Я]+/gim, + tamil: /[^a-z0-9அ-ஹ]+/gim, + sanskrit: /[^a-z0-9A-Zāīūṛḷṃṁḥśṣṭḍṇṅñḻḹṝ]+/gim, + czech: /[^A-Z0-9a-zěščřžýáíéúůóťďĚŠČŘŽÝÁÍÉÓÚŮŤĎ-]+/gim + }; + var SUPPORTED_LANGUAGES = Object.keys(STEMMERS); + function getLocale(language) { + return language !== void 0 && SUPPORTED_LANGUAGES.includes(language) ? STEMMERS[language] : void 0; + } + + // node_modules/@orama/orama/dist/browser/utils.js + var baseId = Date.now().toString().slice(5); + var lastId = 0; + var nano = BigInt(1e3); + var milli = BigInt(1e6); + var second = BigInt(1e9); + var MAX_ARGUMENT_FOR_STACK = 65535; + function safeArrayPush(arr2, newArr) { + if (newArr.length < MAX_ARGUMENT_FOR_STACK) { + Array.prototype.push.apply(arr2, newArr); + } else { + const newArrLength = newArr.length; + for (let i2 = 0; i2 < newArrLength; i2 += MAX_ARGUMENT_FOR_STACK) { + Array.prototype.push.apply(arr2, newArr.slice(i2, i2 + MAX_ARGUMENT_FOR_STACK)); + } + } + } + function sprintf(template, ...args) { + return template.replace(/%(?:(?\d+)\$)?(?-?\d*\.?\d*)(?[dfs])/g, function(...replaceArgs) { + const groups = replaceArgs[replaceArgs.length - 1]; + const { width: rawWidth, type, position } = groups; + const replacement = position ? args[Number.parseInt(position) - 1] : args.shift(); + const width = rawWidth === "" ? 0 : Number.parseInt(rawWidth); + switch (type) { + case "d": + return replacement.toString().padStart(width, "0"); + case "f": { + let value = replacement; + const [padding, precision] = rawWidth.split(".").map((w3) => Number.parseFloat(w3)); + if (typeof precision === "number" && precision >= 0) { + value = value.toFixed(precision); + } + return typeof padding === "number" && padding >= 0 ? value.toString().padStart(width, "0") : value.toString(); + } + case "s": + return width < 0 ? replacement.toString().padEnd(-width, " ") : replacement.toString().padStart(width, " "); + default: + return replacement; + } + }); + } + function isInsideWebWorker() { + return typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope; + } + function isInsideNode() { + return typeof process !== "undefined" && process.release && process.release.name === "node"; + } + function getNanosecondTimeViaPerformance() { + return BigInt(Math.floor(performance.now() * 1e6)); + } + function formatNanoseconds(value) { + if (typeof value === "number") { + value = BigInt(value); + } + if (value < nano) { + return `${value}ns`; + } else if (value < milli) { + return `${value / nano}\u03BCs`; + } else if (value < second) { + return `${value / milli}ms`; + } + return `${value / second}s`; + } + function getNanosecondsTime() { + if (isInsideWebWorker()) { + return getNanosecondTimeViaPerformance(); + } + if (isInsideNode()) { + return process.hrtime.bigint(); + } + if (typeof process !== "undefined" && typeof process?.hrtime?.bigint === "function") { + return process.hrtime.bigint(); + } + if (typeof performance !== "undefined") { + return getNanosecondTimeViaPerformance(); + } + return BigInt(0); + } + function uniqueId() { + return `${baseId}-${lastId++}`; + } + function getOwnProperty2(object, property) { + if (Object.hasOwn === void 0) { + return Object.prototype.hasOwnProperty.call(object, property) ? object[property] : void 0; + } + return Object.hasOwn(object, property) ? object[property] : void 0; + } + function sortTokenScorePredicate(a2, b3) { + if (b3[1] === a2[1]) { + return a2[0] - b3[0]; + } + return b3[1] - a2[1]; + } + function intersect(arrays) { + if (arrays.length === 0) { + return []; + } else if (arrays.length === 1) { + return arrays[0]; + } + for (let i2 = 1; i2 < arrays.length; i2++) { + if (arrays[i2].length < arrays[0].length) { + const tmp = arrays[0]; + arrays[0] = arrays[i2]; + arrays[i2] = tmp; + } + } + const set2 = /* @__PURE__ */ new Map(); + for (const elem of arrays[0]) { + set2.set(elem, 1); + } + for (let i2 = 1; i2 < arrays.length; i2++) { + let found = 0; + for (const elem of arrays[i2]) { + const count3 = set2.get(elem); + if (count3 === i2) { + set2.set(elem, count3 + 1); + found++; + } + } + if (found === 0) + return []; + } + return arrays[0].filter((e2) => { + const count3 = set2.get(e2); + if (count3 !== void 0) + set2.set(e2, 0); + return count3 === arrays.length; + }); + } + function getDocumentProperties(doc, paths) { + const properties = {}; + const pathsLength = paths.length; + for (let i2 = 0; i2 < pathsLength; i2++) { + const path = paths[i2]; + const pathTokens = path.split("."); + let current = doc; + const pathTokensLength = pathTokens.length; + for (let j3 = 0; j3 < pathTokensLength; j3++) { + current = current[pathTokens[j3]]; + if (typeof current === "object") { + if (current !== null && "lat" in current && "lon" in current && typeof current.lat === "number" && typeof current.lon === "number") { + current = properties[path] = current; + break; + } else if (!Array.isArray(current) && current !== null && j3 === pathTokensLength - 1) { + current = void 0; + break; + } + } else if ((current === null || typeof current !== "object") && j3 < pathTokensLength - 1) { + current = void 0; + break; + } + } + if (typeof current !== "undefined") { + properties[path] = current; + } + } + return properties; + } + function getNested(obj, path) { + const props = getDocumentProperties(obj, [path]); + return props[path]; + } + var mapDistanceToMeters = { + cm: 0.01, + m: 1, + km: 1e3, + ft: 0.3048, + yd: 0.9144, + mi: 1609.344 + }; + function convertDistanceToMeters(distance, unit) { + const ratio = mapDistanceToMeters[unit]; + if (ratio === void 0) { + throw new Error(createError("INVALID_DISTANCE_SUFFIX", distance).message); + } + return distance * ratio; + } + function removeVectorsFromHits(searchResult, vectorProperties) { + searchResult.hits = searchResult.hits.map((result) => ({ + ...result, + document: { + ...result.document, + // Remove embeddings from the result + ...vectorProperties.reduce((acc, prop) => { + const path = prop.split("."); + const lastKey = path.pop(); + let obj = acc; + for (const key of path) { + obj[key] = obj[key] ?? {}; + obj = obj[key]; + } + obj[lastKey] = null; + return acc; + }, result.document) + } + })); + } + function isAsyncFunction(func) { + if (Array.isArray(func)) { + return func.some((item) => isAsyncFunction(item)); + } + return func?.constructor?.name === "AsyncFunction"; + } + var withIntersection = "intersection" in /* @__PURE__ */ new Set(); + function setIntersection(...sets) { + if (sets.length === 0) { + return /* @__PURE__ */ new Set(); + } + if (sets.length === 1) { + return sets[0]; + } + if (sets.length === 2) { + const set1 = sets[0]; + const set2 = sets[1]; + if (withIntersection) { + return set1.intersection(set2); + } + const result = /* @__PURE__ */ new Set(); + const base2 = set1.size < set2.size ? set1 : set2; + const other = base2 === set1 ? set2 : set1; + for (const value of base2) { + if (other.has(value)) { + result.add(value); + } + } + return result; + } + const min = { + index: 0, + size: sets[0].size + }; + for (let i2 = 1; i2 < sets.length; i2++) { + if (sets[i2].size < min.size) { + min.index = i2; + min.size = sets[i2].size; + } + } + if (withIntersection) { + let base2 = sets[min.index]; + for (let i2 = 0; i2 < sets.length; i2++) { + if (i2 === min.index) { + continue; + } + base2 = base2.intersection(sets[i2]); + } + return base2; + } + const base = sets[min.index]; + for (let i2 = 0; i2 < sets.length; i2++) { + if (i2 === min.index) { + continue; + } + const other = sets[i2]; + for (const value of base) { + if (!other.has(value)) { + base.delete(value); + } + } + } + return base; + } + var withUnion = "union" in /* @__PURE__ */ new Set(); + function setUnion(set1, set2) { + if (withUnion) { + if (set1) { + return set1.union(set2); + } + return set2; + } + if (!set1) { + return new Set(set2); + } + return /* @__PURE__ */ new Set([...set1, ...set2]); + } + function setDifference(set1, set2) { + const result = /* @__PURE__ */ new Set(); + for (const value of set1) { + if (!set2.has(value)) { + result.add(value); + } + } + return result; + } + + // node_modules/@orama/orama/dist/browser/errors.js + var allLanguages = SUPPORTED_LANGUAGES.join("\n - "); + var errors = { + NO_LANGUAGE_WITH_CUSTOM_TOKENIZER: "Do not pass the language option to create when using a custom tokenizer.", + LANGUAGE_NOT_SUPPORTED: `Language "%s" is not supported. +Supported languages are: + - ${allLanguages}`, + INVALID_STEMMER_FUNCTION_TYPE: `config.stemmer property must be a function.`, + MISSING_STEMMER: `As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.orama.com/docs/orama-js/text-analysis/stemming for more information.`, + CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY: "Custom stop words array must only contain strings.", + UNSUPPORTED_COMPONENT: `Unsupported component "%s".`, + COMPONENT_MUST_BE_FUNCTION: `The component "%s" must be a function.`, + COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS: `The component "%s" must be a function or an array of functions.`, + INVALID_SCHEMA_TYPE: `Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.`, + DOCUMENT_ID_MUST_BE_STRING: `Document id must be of type "string". Got "%s" instead.`, + DOCUMENT_ALREADY_EXISTS: `A document with id "%s" already exists.`, + DOCUMENT_DOES_NOT_EXIST: `A document with id "%s" does not exists.`, + MISSING_DOCUMENT_PROPERTY: `Missing searchable property "%s".`, + INVALID_DOCUMENT_PROPERTY: `Invalid document property "%s": expected "%s", got "%s"`, + UNKNOWN_INDEX: `Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s`, + INVALID_BOOST_VALUE: `Boost value must be a number greater than, or less than 0.`, + INVALID_FILTER_OPERATION: `You can only use one operation per filter, you requested %d.`, + SCHEMA_VALIDATION_FAILURE: `Cannot insert document due schema validation failure on "%s" property.`, + INVALID_SORT_SCHEMA_TYPE: `Unsupported sort schema type "%s" at "%s". Expected "string" or "number".`, + CANNOT_SORT_BY_ARRAY: `Cannot configure sort for "%s" because it is an array (%s).`, + UNABLE_TO_SORT_ON_UNKNOWN_FIELD: `Unable to sort on unknown field "%s". Allowed fields: %s`, + SORT_DISABLED: `Sort is disabled. Please read the documentation at https://docs.orama.com/docs/orama-js for more information.`, + UNKNOWN_GROUP_BY_PROPERTY: `Unknown groupBy property "%s".`, + INVALID_GROUP_BY_PROPERTY: `Invalid groupBy property "%s". Allowed types: "%s", but given "%s".`, + UNKNOWN_FILTER_PROPERTY: `Unknown filter property "%s".`, + UNKNOWN_VECTOR_PROPERTY: `Unknown vector property "%s". Make sure the property exists in the schema and is configured as a vector.`, + INVALID_VECTOR_SIZE: `Vector size must be a number greater than 0. Got "%s" instead.`, + INVALID_VECTOR_VALUE: `Vector value must be a number greater than 0. Got "%s" instead.`, + INVALID_INPUT_VECTOR: `Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead. +Input vectors must be of the size declared in the schema, as calculating similarity between vectors of different sizes can lead to unexpected results.`, + WRONG_SEARCH_PROPERTY_TYPE: `Property "%s" is not searchable. Only "string" properties are searchable.`, + FACET_NOT_SUPPORTED: `Facet doens't support the type "%s".`, + INVALID_DISTANCE_SUFFIX: `Invalid distance suffix "%s". Valid suffixes are: cm, m, km, mi, yd, ft.`, + INVALID_SEARCH_MODE: `Invalid search mode "%s". Valid modes are: "fulltext", "vector", "hybrid".`, + MISSING_VECTOR_AND_SECURE_PROXY: `No vector was provided and no secure proxy was configured. Please provide a vector or configure an Orama Secure Proxy to perform hybrid search.`, + MISSING_TERM: `"term" is a required parameter when performing hybrid search. Please provide a search term.`, + INVALID_VECTOR_INPUT: `Invalid "vector" property. Expected an object with "value" and "property" properties, but got "%s" instead.`, + PLUGIN_CRASHED: `A plugin crashed during initialization. Please check the error message for more information:`, + PLUGIN_SECURE_PROXY_NOT_FOUND: `Could not find '@orama/secure-proxy-plugin' installed in your Orama instance. +Please install it before proceeding with creating an answer session. +Read more at https://docs.orama.com/docs/orama-js/plugins/plugin-secure-proxy#plugin-secure-proxy +`, + PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL: `Could not find a chat model defined in the secure proxy plugin configuration. +Please provide a chat model before proceeding with creating an answer session. +Read more at https://docs.orama.com/docs/orama-js/plugins/plugin-secure-proxy#plugin-secure-proxy +`, + ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT: `The last message in the session is not an assistant message. Cannot regenerate non-assistant messages.`, + PLUGIN_COMPONENT_CONFLICT: `The component "%s" is already defined. The plugin "%s" is trying to redefine it.` + }; + function createError(code, ...args) { + const error = new Error(sprintf(errors[code] ?? `Unsupported Orama Error code: ${code}`, ...args)); + error.code = code; + if ("captureStackTrace" in Error.prototype) { + Error.captureStackTrace(error); + } + return error; + } + + // node_modules/@orama/orama/dist/browser/components/defaults.js + function formatElapsedTime(n2) { + return { + raw: Number(n2), + formatted: formatNanoseconds(n2) + }; + } + function getDocumentIndexId(doc) { + if (doc.id) { + if (typeof doc.id !== "string") { + throw createError("DOCUMENT_ID_MUST_BE_STRING", typeof doc.id); + } + return doc.id; + } + return uniqueId(); + } + function validateSchema(doc, schema4) { + for (const [prop, type] of Object.entries(schema4)) { + const value = doc[prop]; + if (typeof value === "undefined") { + continue; + } + if (type === "geopoint" && typeof value === "object" && typeof value.lon === "number" && typeof value.lat === "number") { + continue; + } + if (type === "enum" && (typeof value === "string" || typeof value === "number")) { + continue; + } + if (type === "enum[]" && Array.isArray(value)) { + const valueLength = value.length; + for (let i2 = 0; i2 < valueLength; i2++) { + if (typeof value[i2] !== "string" && typeof value[i2] !== "number") { + return prop + "." + i2; + } + } + continue; + } + if (isVectorType(type)) { + const vectorSize = getVectorSize(type); + if (!Array.isArray(value) || value.length !== vectorSize) { + throw createError("INVALID_INPUT_VECTOR", prop, vectorSize, value.length); + } + continue; + } + if (isArrayType(type)) { + if (!Array.isArray(value)) { + return prop; + } + const expectedType = getInnerType(type); + const valueLength = value.length; + for (let i2 = 0; i2 < valueLength; i2++) { + if (typeof value[i2] !== expectedType) { + return prop + "." + i2; + } + } + continue; + } + if (typeof type === "object") { + if (!value || typeof value !== "object") { + return prop; + } + const subProp = validateSchema(value, type); + if (subProp) { + return prop + "." + subProp; + } + continue; + } + if (typeof value !== type) { + return prop; + } + } + return void 0; + } + var IS_ARRAY_TYPE = { + string: false, + number: false, + boolean: false, + enum: false, + geopoint: false, + "string[]": true, + "number[]": true, + "boolean[]": true, + "enum[]": true + }; + var INNER_TYPE = { + "string[]": "string", + "number[]": "number", + "boolean[]": "boolean", + "enum[]": "enum" + }; + function isGeoPointType(type) { + return type === "geopoint"; + } + function isVectorType(type) { + return typeof type === "string" && /^vector\[\d+\]$/.test(type); + } + function isArrayType(type) { + return typeof type === "string" && IS_ARRAY_TYPE[type]; + } + function getInnerType(type) { + return INNER_TYPE[type]; + } + function getVectorSize(type) { + const size = Number(type.slice(7, -1)); + switch (true) { + case isNaN(size): + throw createError("INVALID_VECTOR_VALUE", type); + case size <= 0: + throw createError("INVALID_VECTOR_SIZE", type); + default: + return size; + } + } + + // node_modules/@orama/orama/dist/browser/components/internal-document-id-store.js + function createInternalDocumentIDStore() { + return { + idToInternalId: /* @__PURE__ */ new Map(), + internalIdToId: [], + save, + load + }; + } + function save(store2) { + return { + internalIdToId: store2.internalIdToId + }; + } + function load(orama, raw) { + const { internalIdToId } = raw; + orama.internalDocumentIDStore.idToInternalId.clear(); + orama.internalDocumentIDStore.internalIdToId = []; + const internalIdToIdLength = internalIdToId.length; + for (let i2 = 0; i2 < internalIdToIdLength; i2++) { + const internalIdItem = internalIdToId[i2]; + orama.internalDocumentIDStore.idToInternalId.set(internalIdItem, i2 + 1); + orama.internalDocumentIDStore.internalIdToId.push(internalIdItem); + } + } + function getInternalDocumentId(store2, id) { + if (typeof id === "string") { + const internalId = store2.idToInternalId.get(id); + if (internalId) { + return internalId; + } + const currentId = store2.idToInternalId.size + 1; + store2.idToInternalId.set(id, currentId); + store2.internalIdToId.push(id); + return currentId; + } + if (id > store2.internalIdToId.length) { + return getInternalDocumentId(store2, id.toString()); + } + return id; + } + function getDocumentIdFromInternalId(store2, internalId) { + if (store2.internalIdToId.length < internalId) { + throw new Error(`Invalid internalId ${internalId}`); + } + return store2.internalIdToId[internalId - 1]; + } + + // node_modules/@orama/orama/dist/browser/components/documents-store.js + function create2(_2, sharedInternalDocumentStore) { + return { + sharedInternalDocumentStore, + docs: {}, + count: 0 + }; + } + function get(store2, id) { + const internalId = getInternalDocumentId(store2.sharedInternalDocumentStore, id); + return store2.docs[internalId]; + } + function getMultiple(store2, ids) { + const idsLength = ids.length; + const found = Array.from({ length: idsLength }); + for (let i2 = 0; i2 < idsLength; i2++) { + const internalId = getInternalDocumentId(store2.sharedInternalDocumentStore, ids[i2]); + found[i2] = store2.docs[internalId]; + } + return found; + } + function getAll(store2) { + return store2.docs; + } + function store(store2, id, internalId, doc) { + if (typeof store2.docs[internalId] !== "undefined") { + return false; + } + store2.docs[internalId] = doc; + store2.count++; + return true; + } + function remove2(store2, id) { + const internalId = getInternalDocumentId(store2.sharedInternalDocumentStore, id); + if (typeof store2.docs[internalId] === "undefined") { + return false; + } + delete store2.docs[internalId]; + store2.count--; + return true; + } + function count(store2) { + return store2.count; + } + function load2(sharedInternalDocumentStore, raw) { + const rawDocument = raw; + return { + docs: rawDocument.docs, + count: rawDocument.count, + sharedInternalDocumentStore + }; + } + function save2(store2) { + return { + docs: store2.docs, + count: store2.count + }; + } + function createDocumentsStore() { + return { + create: create2, + get, + getMultiple, + getAll, + store, + remove: remove2, + count, + load: load2, + save: save2 + }; + } + + // node_modules/@orama/orama/dist/browser/components/plugins.js + var AVAILABLE_PLUGIN_HOOKS = [ + "beforeInsert", + "afterInsert", + "beforeRemove", + "afterRemove", + "beforeUpdate", + "afterUpdate", + "beforeUpsert", + "afterUpsert", + "beforeSearch", + "afterSearch", + "beforeInsertMultiple", + "afterInsertMultiple", + "beforeRemoveMultiple", + "afterRemoveMultiple", + "beforeUpdateMultiple", + "afterUpdateMultiple", + "beforeUpsertMultiple", + "afterUpsertMultiple", + "beforeLoad", + "afterLoad", + "afterCreate" + ]; + function getAllPluginsByHook(orama, hook) { + const pluginsToRun = []; + const pluginsLength = orama.plugins?.length; + if (!pluginsLength) { + return pluginsToRun; + } + for (let i2 = 0; i2 < pluginsLength; i2++) { + try { + const plugin = orama.plugins[i2]; + if (typeof plugin[hook] === "function") { + pluginsToRun.push(plugin[hook]); + } + } catch (error) { + console.error("Caught error in getAllPluginsByHook:", error); + throw createError("PLUGIN_CRASHED"); + } + } + return pluginsToRun; + } + + // node_modules/@orama/orama/dist/browser/components/hooks.js + var OBJECT_COMPONENTS = ["tokenizer", "index", "documentsStore", "sorter", "pinning"]; + var FUNCTION_COMPONENTS = [ + "validateSchema", + "getDocumentIndexId", + "getDocumentProperties", + "formatElapsedTime" + ]; + function runSingleHook(hooks, orama, id, doc) { + const needAsync = hooks.some(isAsyncFunction); + if (needAsync) { + return (async () => { + for (const hook of hooks) { + await hook(orama, id, doc); + } + })(); + } else { + for (const hook of hooks) { + hook(orama, id, doc); + } + } + } + function runAfterSearch(hooks, db, params, language, results) { + const needAsync = hooks.some(isAsyncFunction); + if (needAsync) { + return (async () => { + for (const hook of hooks) { + await hook(db, params, language, results); + } + })(); + } else { + for (const hook of hooks) { + hook(db, params, language, results); + } + } + } + function runBeforeSearch(hooks, db, params, language) { + const needAsync = hooks.some(isAsyncFunction); + if (needAsync) { + return (async () => { + for (const hook of hooks) { + await hook(db, params, language); + } + })(); + } else { + for (const hook of hooks) { + hook(db, params, language); + } + } + } + function runAfterCreate(hooks, db) { + const needAsync = hooks.some(isAsyncFunction); + if (needAsync) { + return (async () => { + for (const hook of hooks) { + await hook(db); + } + })(); + } else { + for (const hook of hooks) { + hook(db); + } + } + } + + // node_modules/@orama/orama/dist/browser/trees/avl.js + var AVLNode = class _AVLNode { + k; + v; + l = null; + r = null; + h = 1; + constructor(key, value) { + this.k = key; + this.v = new Set(value); + } + updateHeight() { + this.h = Math.max(_AVLNode.getHeight(this.l), _AVLNode.getHeight(this.r)) + 1; + } + static getHeight(node) { + return node ? node.h : 0; + } + getBalanceFactor() { + return _AVLNode.getHeight(this.l) - _AVLNode.getHeight(this.r); + } + rotateLeft() { + const newRoot = this.r; + this.r = newRoot.l; + newRoot.l = this; + this.updateHeight(); + newRoot.updateHeight(); + return newRoot; + } + rotateRight() { + const newRoot = this.l; + this.l = newRoot.r; + newRoot.r = this; + this.updateHeight(); + newRoot.updateHeight(); + return newRoot; + } + toJSON() { + return { + k: this.k, + v: Array.from(this.v), + l: this.l ? this.l.toJSON() : null, + r: this.r ? this.r.toJSON() : null, + h: this.h + }; + } + static fromJSON(json) { + const node = new _AVLNode(json.k, json.v); + node.l = json.l ? _AVLNode.fromJSON(json.l) : null; + node.r = json.r ? _AVLNode.fromJSON(json.r) : null; + node.h = json.h; + return node; + } + }; + var AVLTree = class _AVLTree { + root = null; + insertCount = 0; + constructor(key, value) { + if (key !== void 0 && value !== void 0) { + this.root = new AVLNode(key, value); + } + } + insert(key, value, rebalanceThreshold = 1e3) { + this.root = this.insertNode(this.root, key, value, rebalanceThreshold); + } + insertMultiple(key, value, rebalanceThreshold = 1e3) { + for (const v6 of value) { + this.insert(key, v6, rebalanceThreshold); + } + } + // Rebalance the tree if the insert count reaches the threshold. + // This will improve insertion performance since we won't be rebalancing the tree on every insert. + // When inserting docs using `insertMultiple`, the threshold will be set to the number of docs being inserted. + // We can force rebalancing the tree by setting the threshold to 1 (default). + rebalance() { + if (this.root) { + this.root = this.rebalanceNode(this.root); + } + } + toJSON() { + return { + root: this.root ? this.root.toJSON() : null, + insertCount: this.insertCount + }; + } + static fromJSON(json) { + const tree = new _AVLTree(); + tree.root = json.root ? AVLNode.fromJSON(json.root) : null; + tree.insertCount = json.insertCount || 0; + return tree; + } + insertNode(node, key, value, rebalanceThreshold) { + if (node === null) { + return new AVLNode(key, [value]); + } + const path = []; + let current = node; + let parent = null; + while (current !== null) { + path.push({ parent, node: current }); + if (key < current.k) { + if (current.l === null) { + current.l = new AVLNode(key, [value]); + path.push({ parent: current, node: current.l }); + break; + } else { + parent = current; + current = current.l; + } + } else if (key > current.k) { + if (current.r === null) { + current.r = new AVLNode(key, [value]); + path.push({ parent: current, node: current.r }); + break; + } else { + parent = current; + current = current.r; + } + } else { + current.v.add(value); + return node; + } + } + let needRebalance = false; + if (this.insertCount++ % rebalanceThreshold === 0) { + needRebalance = true; + } + for (let i2 = path.length - 1; i2 >= 0; i2--) { + const { parent: parent2, node: currentNode } = path[i2]; + currentNode.updateHeight(); + if (needRebalance) { + const rebalancedNode = this.rebalanceNode(currentNode); + if (parent2) { + if (parent2.l === currentNode) { + parent2.l = rebalancedNode; + } else if (parent2.r === currentNode) { + parent2.r = rebalancedNode; + } + } else { + node = rebalancedNode; + } + } + } + return node; + } + rebalanceNode(node) { + const balanceFactor = node.getBalanceFactor(); + if (balanceFactor > 1) { + if (node.l && node.l.getBalanceFactor() >= 0) { + return node.rotateRight(); + } else if (node.l) { + node.l = node.l.rotateLeft(); + return node.rotateRight(); + } + } + if (balanceFactor < -1) { + if (node.r && node.r.getBalanceFactor() <= 0) { + return node.rotateLeft(); + } else if (node.r) { + node.r = node.r.rotateRight(); + return node.rotateLeft(); + } + } + return node; + } + find(key) { + const node = this.findNodeByKey(key); + return node ? node.v : null; + } + contains(key) { + return this.find(key) !== null; + } + getSize() { + let count3 = 0; + const stack = []; + let current = this.root; + while (current || stack.length > 0) { + while (current) { + stack.push(current); + current = current.l; + } + current = stack.pop(); + count3++; + current = current.r; + } + return count3; + } + isBalanced() { + if (!this.root) + return true; + const stack = [this.root]; + while (stack.length > 0) { + const node = stack.pop(); + const balanceFactor = node.getBalanceFactor(); + if (Math.abs(balanceFactor) > 1) { + return false; + } + if (node.l) + stack.push(node.l); + if (node.r) + stack.push(node.r); + } + return true; + } + remove(key) { + this.root = this.removeNode(this.root, key); + } + removeDocument(key, id) { + const node = this.findNodeByKey(key); + if (!node) { + return; + } + if (node.v.size === 1) { + this.root = this.removeNode(this.root, key); + } else { + node.v = new Set([...node.v.values()].filter((v6) => v6 !== id)); + } + } + findNodeByKey(key) { + let node = this.root; + while (node) { + if (key < node.k) { + node = node.l; + } else if (key > node.k) { + node = node.r; + } else { + return node; + } + } + return null; + } + removeNode(node, key) { + if (node === null) + return null; + const path = []; + let current = node; + while (current !== null && current.k !== key) { + path.push(current); + if (key < current.k) { + current = current.l; + } else { + current = current.r; + } + } + if (current === null) { + return node; + } + if (current.l === null || current.r === null) { + const child = current.l ? current.l : current.r; + if (path.length === 0) { + node = child; + } else { + const parent = path[path.length - 1]; + if (parent.l === current) { + parent.l = child; + } else { + parent.r = child; + } + } + } else { + let successorParent = current; + let successor = current.r; + while (successor.l !== null) { + successorParent = successor; + successor = successor.l; + } + current.k = successor.k; + current.v = successor.v; + if (successorParent.l === successor) { + successorParent.l = successor.r; + } else { + successorParent.r = successor.r; + } + current = successorParent; + } + path.push(current); + for (let i2 = path.length - 1; i2 >= 0; i2--) { + const currentNode = path[i2]; + currentNode.updateHeight(); + const rebalancedNode = this.rebalanceNode(currentNode); + if (i2 > 0) { + const parent = path[i2 - 1]; + if (parent.l === currentNode) { + parent.l = rebalancedNode; + } else if (parent.r === currentNode) { + parent.r = rebalancedNode; + } + } else { + node = rebalancedNode; + } + } + return node; + } + rangeSearch(min, max) { + const result = /* @__PURE__ */ new Set(); + const stack = []; + let current = this.root; + while (current || stack.length > 0) { + while (current) { + stack.push(current); + current = current.l; + } + current = stack.pop(); + if (current.k >= min && current.k <= max) { + for (const value of current.v) { + result.add(value); + } + } + if (current.k > max) { + break; + } + current = current.r; + } + return result; + } + greaterThan(key, inclusive = false) { + const result = /* @__PURE__ */ new Set(); + const stack = []; + let current = this.root; + while (current || stack.length > 0) { + while (current) { + stack.push(current); + current = current.r; + } + current = stack.pop(); + if (inclusive && current.k >= key || !inclusive && current.k > key) { + for (const value of current.v) { + result.add(value); + } + } else if (current.k <= key) { + break; + } + current = current.l; + } + return result; + } + lessThan(key, inclusive = false) { + const result = /* @__PURE__ */ new Set(); + const stack = []; + let current = this.root; + while (current || stack.length > 0) { + while (current) { + stack.push(current); + current = current.l; + } + current = stack.pop(); + if (inclusive && current.k <= key || !inclusive && current.k < key) { + for (const value of current.v) { + result.add(value); + } + } else if (current.k > key) { + break; + } + current = current.r; + } + return result; + } + }; + + // node_modules/@orama/orama/dist/browser/trees/flat.js + var FlatTree = class _FlatTree { + numberToDocumentId; + constructor() { + this.numberToDocumentId = /* @__PURE__ */ new Map(); + } + insert(key, value) { + if (this.numberToDocumentId.has(key)) { + this.numberToDocumentId.get(key).add(value); + } else { + this.numberToDocumentId.set(key, /* @__PURE__ */ new Set([value])); + } + } + find(key) { + const idSet = this.numberToDocumentId.get(key); + return idSet ? Array.from(idSet) : null; + } + remove(key) { + this.numberToDocumentId.delete(key); + } + removeDocument(id, key) { + const idSet = this.numberToDocumentId.get(key); + if (idSet) { + idSet.delete(id); + if (idSet.size === 0) { + this.numberToDocumentId.delete(key); + } + } + } + contains(key) { + return this.numberToDocumentId.has(key); + } + getSize() { + let size = 0; + for (const idSet of this.numberToDocumentId.values()) { + size += idSet.size; + } + return size; + } + filter(operation) { + const operationKeys = Object.keys(operation); + if (operationKeys.length !== 1) { + throw new Error("Invalid operation"); + } + const operationType = operationKeys[0]; + switch (operationType) { + case "eq": { + const value = operation[operationType]; + const idSet = this.numberToDocumentId.get(value); + return idSet ? Array.from(idSet) : []; + } + case "in": { + const values = operation[operationType]; + const resultSet = /* @__PURE__ */ new Set(); + for (const value of values) { + const idSet = this.numberToDocumentId.get(value); + if (idSet) { + for (const id of idSet) { + resultSet.add(id); + } + } + } + return Array.from(resultSet); + } + case "nin": { + const excludeValues = new Set(operation[operationType]); + const resultSet = /* @__PURE__ */ new Set(); + for (const [key, idSet] of this.numberToDocumentId.entries()) { + if (!excludeValues.has(key)) { + for (const id of idSet) { + resultSet.add(id); + } + } + } + return Array.from(resultSet); + } + default: + throw new Error("Invalid operation"); + } + } + filterArr(operation) { + const operationKeys = Object.keys(operation); + if (operationKeys.length !== 1) { + throw new Error("Invalid operation"); + } + const operationType = operationKeys[0]; + switch (operationType) { + case "containsAll": { + const values = operation[operationType]; + const idSets = values.map((value) => this.numberToDocumentId.get(value) ?? /* @__PURE__ */ new Set()); + if (idSets.length === 0) + return []; + const intersection = idSets.reduce((prev, curr) => { + return new Set([...prev].filter((id) => curr.has(id))); + }); + return Array.from(intersection); + } + case "containsAny": { + const values = operation[operationType]; + const idSets = values.map((value) => this.numberToDocumentId.get(value) ?? /* @__PURE__ */ new Set()); + if (idSets.length === 0) + return []; + const union = idSets.reduce((prev, curr) => { + return /* @__PURE__ */ new Set([...prev, ...curr]); + }); + return Array.from(union); + } + default: + throw new Error("Invalid operation"); + } + } + static fromJSON(json) { + if (!json.numberToDocumentId) { + throw new Error("Invalid Flat Tree JSON"); + } + const tree = new _FlatTree(); + for (const [key, ids] of json.numberToDocumentId) { + tree.numberToDocumentId.set(key, new Set(ids)); + } + return tree; + } + toJSON() { + return { + numberToDocumentId: Array.from(this.numberToDocumentId.entries()).map(([key, idSet]) => [key, Array.from(idSet)]) + }; + } + }; + + // node_modules/@orama/orama/dist/browser/components/levenshtein.js + function _boundedLevenshtein(term, word, tolerance) { + if (tolerance < 0) + return -1; + if (term === word) + return 0; + const m3 = term.length; + const n2 = word.length; + if (m3 === 0) + return n2 <= tolerance ? n2 : -1; + if (n2 === 0) + return m3 <= tolerance ? m3 : -1; + const diff = Math.abs(m3 - n2); + if (term.startsWith(word)) { + return diff <= tolerance ? diff : -1; + } + if (word.startsWith(term)) { + return 0; + } + if (diff > tolerance) + return -1; + const matrix = []; + for (let i2 = 0; i2 <= m3; i2++) { + matrix[i2] = [i2]; + for (let j3 = 1; j3 <= n2; j3++) { + matrix[i2][j3] = i2 === 0 ? j3 : 0; + } + } + for (let i2 = 1; i2 <= m3; i2++) { + let rowMin = Infinity; + for (let j3 = 1; j3 <= n2; j3++) { + if (term[i2 - 1] === word[j3 - 1]) { + matrix[i2][j3] = matrix[i2 - 1][j3 - 1]; + } else { + matrix[i2][j3] = Math.min( + matrix[i2 - 1][j3] + 1, + // deletion + matrix[i2][j3 - 1] + 1, + // insertion + matrix[i2 - 1][j3 - 1] + 1 + // substitution + ); + } + rowMin = Math.min(rowMin, matrix[i2][j3]); + } + if (rowMin > tolerance) { + return -1; + } + } + return matrix[m3][n2] <= tolerance ? matrix[m3][n2] : -1; + } + function syncBoundedLevenshtein(term, w3, tolerance) { + const distance = _boundedLevenshtein(term, w3, tolerance); + return { + distance, + isBounded: distance >= 0 + }; + } + + // node_modules/@orama/orama/dist/browser/trees/radix.js + var RadixNode = class _RadixNode { + // Node key + k; + // Node subword + s; + // Node children + c = /* @__PURE__ */ new Map(); + // Node documents + d = /* @__PURE__ */ new Set(); + // Node end + e; + // Node word + w = ""; + constructor(key, subWord, end) { + this.k = key; + this.s = subWord; + this.e = end; + } + updateParent(parent) { + this.w = parent.w + this.s; + } + addDocument(docID) { + this.d.add(docID); + } + removeDocument(docID) { + return this.d.delete(docID); + } + findAllWords(output, term, exact, tolerance) { + const stack = [this]; + while (stack.length > 0) { + const node = stack.pop(); + if (node.e) { + const { w: w3, d: docIDs } = node; + if (exact && w3 !== term) { + continue; + } + if (getOwnProperty2(output, w3) !== null) { + if (tolerance) { + const difference = Math.abs(term.length - w3.length); + if (difference <= tolerance && syncBoundedLevenshtein(term, w3, tolerance).isBounded) { + output[w3] = []; + } else { + continue; + } + } else { + output[w3] = []; + } + } + if (getOwnProperty2(output, w3) != null && docIDs.size > 0) { + const docs = output[w3]; + for (const docID of docIDs) { + if (!docs.includes(docID)) { + docs.push(docID); + } + } + } + } + if (node.c.size > 0) { + stack.push(...node.c.values()); + } + } + return output; + } + insert(word, docId) { + let node = this; + let i2 = 0; + const wordLength = word.length; + while (i2 < wordLength) { + const currentCharacter = word[i2]; + const childNode = node.c.get(currentCharacter); + if (childNode) { + const edgeLabel = childNode.s; + const edgeLabelLength = edgeLabel.length; + let j3 = 0; + while (j3 < edgeLabelLength && i2 + j3 < wordLength && edgeLabel[j3] === word[i2 + j3]) { + j3++; + } + if (j3 === edgeLabelLength) { + node = childNode; + i2 += j3; + if (i2 === wordLength) { + if (!childNode.e) { + childNode.e = true; + } + childNode.addDocument(docId); + return; + } + continue; + } + const commonPrefix = edgeLabel.slice(0, j3); + const newEdgeLabel = edgeLabel.slice(j3); + const newWordLabel = word.slice(i2 + j3); + const inbetweenNode = new _RadixNode(commonPrefix[0], commonPrefix, false); + node.c.set(commonPrefix[0], inbetweenNode); + inbetweenNode.updateParent(node); + childNode.s = newEdgeLabel; + childNode.k = newEdgeLabel[0]; + inbetweenNode.c.set(newEdgeLabel[0], childNode); + childNode.updateParent(inbetweenNode); + if (newWordLabel) { + const newNode = new _RadixNode(newWordLabel[0], newWordLabel, true); + newNode.addDocument(docId); + inbetweenNode.c.set(newWordLabel[0], newNode); + newNode.updateParent(inbetweenNode); + } else { + inbetweenNode.e = true; + inbetweenNode.addDocument(docId); + } + return; + } else { + const newNode = new _RadixNode(currentCharacter, word.slice(i2), true); + newNode.addDocument(docId); + node.c.set(currentCharacter, newNode); + newNode.updateParent(node); + return; + } + } + if (!node.e) { + node.e = true; + } + node.addDocument(docId); + } + _findLevenshtein(term, index2, tolerance, originalTolerance, output) { + const stack = [{ node: this, index: index2, tolerance }]; + while (stack.length > 0) { + const { node, index: index3, tolerance: tolerance2 } = stack.pop(); + if (node.w.startsWith(term)) { + node.findAllWords(output, term, false, 0); + continue; + } + if (tolerance2 < 0) { + continue; + } + if (node.e) { + const { w: w3, d: docIDs } = node; + if (w3) { + if (syncBoundedLevenshtein(term, w3, originalTolerance).isBounded) { + output[w3] = []; + } + if (getOwnProperty2(output, w3) !== void 0 && docIDs.size > 0) { + const docs = new Set(output[w3]); + for (const docID of docIDs) { + docs.add(docID); + } + output[w3] = Array.from(docs); + } + } + } + if (index3 >= term.length) { + continue; + } + const currentChar = term[index3]; + if (node.c.has(currentChar)) { + const childNode = node.c.get(currentChar); + stack.push({ node: childNode, index: index3 + 1, tolerance: tolerance2 }); + } + stack.push({ node, index: index3 + 1, tolerance: tolerance2 - 1 }); + for (const [character, childNode] of node.c) { + stack.push({ node: childNode, index: index3, tolerance: tolerance2 - 1 }); + if (character !== currentChar) { + stack.push({ node: childNode, index: index3 + 1, tolerance: tolerance2 - 1 }); + } + } + } + } + find(params) { + const { term, exact, tolerance } = params; + if (tolerance && !exact) { + const output = {}; + this._findLevenshtein(term, 0, tolerance, tolerance, output); + return output; + } else { + let node = this; + let i2 = 0; + const termLength = term.length; + while (i2 < termLength) { + const character = term[i2]; + const childNode = node.c.get(character); + if (childNode) { + const edgeLabel = childNode.s; + const edgeLabelLength = edgeLabel.length; + let j3 = 0; + while (j3 < edgeLabelLength && i2 + j3 < termLength && edgeLabel[j3] === term[i2 + j3]) { + j3++; + } + if (j3 === edgeLabelLength) { + node = childNode; + i2 += j3; + } else if (i2 + j3 === termLength) { + if (j3 === termLength - i2) { + if (exact) { + return {}; + } else { + const output2 = {}; + childNode.findAllWords(output2, term, exact, tolerance); + return output2; + } + } else { + return {}; + } + } else { + return {}; + } + } else { + return {}; + } + } + const output = {}; + node.findAllWords(output, term, exact, tolerance); + return output; + } + } + contains(term) { + let node = this; + let i2 = 0; + const termLength = term.length; + while (i2 < termLength) { + const character = term[i2]; + const childNode = node.c.get(character); + if (childNode) { + const edgeLabel = childNode.s; + const edgeLabelLength = edgeLabel.length; + let j3 = 0; + while (j3 < edgeLabelLength && i2 + j3 < termLength && edgeLabel[j3] === term[i2 + j3]) { + j3++; + } + if (j3 < edgeLabelLength) { + return false; + } + i2 += edgeLabelLength; + node = childNode; + } else { + return false; + } + } + return true; + } + removeWord(term) { + if (!term) { + return false; + } + let node = this; + const termLength = term.length; + const stack = []; + for (let i2 = 0; i2 < termLength; i2++) { + const character = term[i2]; + if (node.c.has(character)) { + const childNode = node.c.get(character); + stack.push({ parent: node, character }); + i2 += childNode.s.length - 1; + node = childNode; + } else { + return false; + } + } + node.d.clear(); + node.e = false; + while (stack.length > 0 && node.c.size === 0 && !node.e && node.d.size === 0) { + const { parent, character } = stack.pop(); + parent.c.delete(character); + node = parent; + } + return true; + } + removeDocumentByWord(term, docID, exact = true) { + if (!term) { + return true; + } + let node = this; + const termLength = term.length; + for (let i2 = 0; i2 < termLength; i2++) { + const character = term[i2]; + if (node.c.has(character)) { + const childNode = node.c.get(character); + i2 += childNode.s.length - 1; + node = childNode; + if (exact && node.w !== term) { + } else { + node.removeDocument(docID); + } + } else { + return false; + } + } + return true; + } + static getCommonPrefix(a2, b3) { + const len = Math.min(a2.length, b3.length); + let i2 = 0; + while (i2 < len && a2.charCodeAt(i2) === b3.charCodeAt(i2)) { + i2++; + } + return a2.slice(0, i2); + } + toJSON() { + return { + w: this.w, + s: this.s, + e: this.e, + k: this.k, + d: Array.from(this.d), + c: Array.from(this.c?.entries())?.map(([key, node]) => [key, node.toJSON()]) + }; + } + static fromJSON(json) { + const node = new _RadixNode(json.k, json.s, json.e); + node.w = json.w; + node.d = new Set(json.d); + node.c = new Map(json?.c?.map(([key, nodeJson]) => [key, _RadixNode.fromJSON(nodeJson)]) || []); + return node; + } + }; + var RadixTree = class _RadixTree extends RadixNode { + constructor() { + super("", "", false); + } + static fromJSON(json) { + const tree = new _RadixTree(); + tree.w = json.w; + tree.s = json.s; + tree.e = json.e; + tree.k = json.k; + tree.d = new Set(json.d); + tree.c = new Map(json?.c?.map(([key, nodeJson]) => [key, RadixNode.fromJSON(nodeJson)]) || []); + return tree; + } + toJSON() { + return super.toJSON(); + } + }; + + // node_modules/@orama/orama/dist/browser/trees/bkd.js + var K2 = 2; + var EARTH_RADIUS = 6371e3; + var BKDNode = class _BKDNode { + point; + docIDs; + left; + right; + parent; + constructor(point, docIDs) { + this.point = point; + this.docIDs = new Set(docIDs); + this.left = null; + this.right = null; + this.parent = null; + } + toJSON() { + return { + point: this.point, + docIDs: Array.from(this.docIDs), + left: this.left ? this.left.toJSON() : null, + right: this.right ? this.right.toJSON() : null + }; + } + static fromJSON(json, parent = null) { + const node = new _BKDNode(json.point, json.docIDs); + node.parent = parent; + if (json.left) { + node.left = _BKDNode.fromJSON(json.left, node); + } + if (json.right) { + node.right = _BKDNode.fromJSON(json.right, node); + } + return node; + } + }; + var BKDTree = class _BKDTree { + root; + nodeMap; + constructor() { + this.root = null; + this.nodeMap = /* @__PURE__ */ new Map(); + } + getPointKey(point) { + return `${point.lon},${point.lat}`; + } + insert(point, docIDs) { + const pointKey = this.getPointKey(point); + const existingNode = this.nodeMap.get(pointKey); + if (existingNode) { + docIDs.forEach((id) => existingNode.docIDs.add(id)); + return; + } + const newNode = new BKDNode(point, docIDs); + this.nodeMap.set(pointKey, newNode); + if (this.root == null) { + this.root = newNode; + return; + } + let node = this.root; + let depth = 0; + while (true) { + const axis = depth % K2; + if (axis === 0) { + if (point.lon < node.point.lon) { + if (node.left == null) { + node.left = newNode; + newNode.parent = node; + return; + } + node = node.left; + } else { + if (node.right == null) { + node.right = newNode; + newNode.parent = node; + return; + } + node = node.right; + } + } else { + if (point.lat < node.point.lat) { + if (node.left == null) { + node.left = newNode; + newNode.parent = node; + return; + } + node = node.left; + } else { + if (node.right == null) { + node.right = newNode; + newNode.parent = node; + return; + } + node = node.right; + } + } + depth++; + } + } + contains(point) { + const pointKey = this.getPointKey(point); + return this.nodeMap.has(pointKey); + } + getDocIDsByCoordinates(point) { + const pointKey = this.getPointKey(point); + const node = this.nodeMap.get(pointKey); + if (node) { + return Array.from(node.docIDs); + } + return null; + } + removeDocByID(point, docID) { + const pointKey = this.getPointKey(point); + const node = this.nodeMap.get(pointKey); + if (node) { + node.docIDs.delete(docID); + if (node.docIDs.size === 0) { + this.nodeMap.delete(pointKey); + this.deleteNode(node); + } + } + } + deleteNode(node) { + const parent = node.parent; + const child = node.left ? node.left : node.right; + if (child) { + child.parent = parent; + } + if (parent) { + if (parent.left === node) { + parent.left = child; + } else if (parent.right === node) { + parent.right = child; + } + } else { + this.root = child; + if (this.root) { + this.root.parent = null; + } + } + } + searchByRadius(center, radius, inclusive = true, sort = "asc", highPrecision = false) { + const distanceFn = highPrecision ? _BKDTree.vincentyDistance : _BKDTree.haversineDistance; + const stack = [{ node: this.root, depth: 0 }]; + const result = []; + while (stack.length > 0) { + const { node, depth } = stack.pop(); + if (node == null) + continue; + const dist = distanceFn(center, node.point); + if (inclusive ? dist <= radius : dist > radius) { + result.push({ point: node.point, docIDs: Array.from(node.docIDs) }); + } + if (node.left != null) { + stack.push({ node: node.left, depth: depth + 1 }); + } + if (node.right != null) { + stack.push({ node: node.right, depth: depth + 1 }); + } + } + if (sort) { + result.sort((a2, b3) => { + const distA = distanceFn(center, a2.point); + const distB = distanceFn(center, b3.point); + return sort.toLowerCase() === "asc" ? distA - distB : distB - distA; + }); + } + return result; + } + searchByPolygon(polygon, inclusive = true, sort = null, highPrecision = false) { + const stack = [{ node: this.root, depth: 0 }]; + const result = []; + while (stack.length > 0) { + const { node, depth } = stack.pop(); + if (node == null) + continue; + if (node.left != null) { + stack.push({ node: node.left, depth: depth + 1 }); + } + if (node.right != null) { + stack.push({ node: node.right, depth: depth + 1 }); + } + const isInsidePolygon = _BKDTree.isPointInPolygon(polygon, node.point); + if (isInsidePolygon && inclusive || !isInsidePolygon && !inclusive) { + result.push({ point: node.point, docIDs: Array.from(node.docIDs) }); + } + } + const centroid = _BKDTree.calculatePolygonCentroid(polygon); + if (sort) { + const distanceFn = highPrecision ? _BKDTree.vincentyDistance : _BKDTree.haversineDistance; + result.sort((a2, b3) => { + const distA = distanceFn(centroid, a2.point); + const distB = distanceFn(centroid, b3.point); + return sort.toLowerCase() === "asc" ? distA - distB : distB - distA; + }); + } + return result; + } + toJSON() { + return { + root: this.root ? this.root.toJSON() : null + }; + } + static fromJSON(json) { + const tree = new _BKDTree(); + if (json.root) { + tree.root = BKDNode.fromJSON(json.root); + tree.buildNodeMap(tree.root); + } + return tree; + } + buildNodeMap(node) { + if (node == null) + return; + const pointKey = this.getPointKey(node.point); + this.nodeMap.set(pointKey, node); + if (node.left) { + this.buildNodeMap(node.left); + } + if (node.right) { + this.buildNodeMap(node.right); + } + } + static calculatePolygonCentroid(polygon) { + let totalArea = 0; + let centroidX = 0; + let centroidY = 0; + const polygonLength = polygon.length; + for (let i2 = 0, j3 = polygonLength - 1; i2 < polygonLength; j3 = i2++) { + const xi = polygon[i2].lon; + const yi = polygon[i2].lat; + const xj = polygon[j3].lon; + const yj = polygon[j3].lat; + const areaSegment = xi * yj - xj * yi; + totalArea += areaSegment; + centroidX += (xi + xj) * areaSegment; + centroidY += (yi + yj) * areaSegment; + } + totalArea /= 2; + const centroidCoordinate = 6 * totalArea; + centroidX /= centroidCoordinate; + centroidY /= centroidCoordinate; + return { lon: centroidX, lat: centroidY }; + } + static isPointInPolygon(polygon, point) { + let isInside = false; + const x3 = point.lon; + const y3 = point.lat; + const polygonLength = polygon.length; + for (let i2 = 0, j3 = polygonLength - 1; i2 < polygonLength; j3 = i2++) { + const xi = polygon[i2].lon; + const yi = polygon[i2].lat; + const xj = polygon[j3].lon; + const yj = polygon[j3].lat; + const intersect2 = yi > y3 !== yj > y3 && x3 < (xj - xi) * (y3 - yi) / (yj - yi) + xi; + if (intersect2) + isInside = !isInside; + } + return isInside; + } + static haversineDistance(coord1, coord2) { + const P2 = Math.PI / 180; + const lat1 = coord1.lat * P2; + const lat2 = coord2.lat * P2; + const deltaLat = (coord2.lat - coord1.lat) * P2; + const deltaLon = (coord2.lon - coord1.lon) * P2; + const a2 = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) + Math.cos(lat1) * Math.cos(lat2) * Math.sin(deltaLon / 2) * Math.sin(deltaLon / 2); + const c3 = 2 * Math.atan2(Math.sqrt(a2), Math.sqrt(1 - a2)); + return EARTH_RADIUS * c3; + } + static vincentyDistance(coord1, coord2) { + const a2 = 6378137; + const f3 = 1 / 298.257223563; + const b3 = (1 - f3) * a2; + const P2 = Math.PI / 180; + const lat1 = coord1.lat * P2; + const lat2 = coord2.lat * P2; + const deltaLon = (coord2.lon - coord1.lon) * P2; + const U1 = Math.atan((1 - f3) * Math.tan(lat1)); + const U2 = Math.atan((1 - f3) * Math.tan(lat2)); + const sinU1 = Math.sin(U1); + const cosU1 = Math.cos(U1); + const sinU2 = Math.sin(U2); + const cosU2 = Math.cos(U2); + let lambda = deltaLon; + let prevLambda; + let iterationLimit = 1e3; + let sinSigma; + let cosSigma; + let sigma; + let sinAlpha; + let cos2Alpha; + let cos2SigmaM; + do { + const sinLambda = Math.sin(lambda); + const cosLambda = Math.cos(lambda); + sinSigma = Math.sqrt(cosU2 * sinLambda * (cosU2 * sinLambda) + (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda) * (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda)); + if (sinSigma === 0) + return 0; + cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda; + sigma = Math.atan2(sinSigma, cosSigma); + sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma; + cos2Alpha = 1 - sinAlpha * sinAlpha; + cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cos2Alpha; + if (isNaN(cos2SigmaM)) + cos2SigmaM = 0; + const C3 = f3 / 16 * cos2Alpha * (4 + f3 * (4 - 3 * cos2Alpha)); + prevLambda = lambda; + lambda = deltaLon + (1 - C3) * f3 * sinAlpha * (sigma + C3 * sinSigma * (cos2SigmaM + C3 * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM))); + } while (Math.abs(lambda - prevLambda) > 1e-12 && --iterationLimit > 0); + if (iterationLimit === 0) { + return NaN; + } + const uSquared = cos2Alpha * (a2 * a2 - b3 * b3) / (b3 * b3); + const A = 1 + uSquared / 16384 * (4096 + uSquared * (-768 + uSquared * (320 - 175 * uSquared))); + const B2 = uSquared / 1024 * (256 + uSquared * (-128 + uSquared * (74 - 47 * uSquared))); + const deltaSigma = B2 * sinSigma * (cos2SigmaM + B2 / 4 * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) - B2 / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM * cos2SigmaM))); + const s2 = b3 * A * (sigma - deltaSigma); + return s2; + } + }; + + // node_modules/@orama/orama/dist/browser/trees/bool.js + var BoolNode = class _BoolNode { + true; + false; + constructor() { + this.true = /* @__PURE__ */ new Set(); + this.false = /* @__PURE__ */ new Set(); + } + insert(value, bool) { + if (bool) { + this.true.add(value); + } else { + this.false.add(value); + } + } + delete(value, bool) { + if (bool) { + this.true.delete(value); + } else { + this.false.delete(value); + } + } + getSize() { + return this.true.size + this.false.size; + } + toJSON() { + return { + true: Array.from(this.true), + false: Array.from(this.false) + }; + } + static fromJSON(json) { + const node = new _BoolNode(); + node.true = new Set(json.true); + node.false = new Set(json.false); + return node; + } + }; + + // node_modules/@orama/orama/dist/browser/components/algorithms.js + function BM25(tf, matchingCount, docsCount, fieldLength, averageFieldLength, { k: k3, b: b3, d: d3 }) { + const idf = Math.log(1 + (docsCount - matchingCount + 0.5) / (matchingCount + 0.5)); + return idf * (d3 + tf * (k3 + 1)) / (tf + k3 * (1 - b3 + b3 * fieldLength / averageFieldLength)); + } + + // node_modules/@orama/orama/dist/browser/trees/vector.js + var DEFAULT_SIMILARITY = 0.8; + var VectorIndex = class _VectorIndex { + size; + vectors = /* @__PURE__ */ new Map(); + constructor(size) { + this.size = size; + } + add(internalDocumentId, value) { + if (!(value instanceof Float32Array)) { + value = new Float32Array(value); + } + const magnitude = getMagnitude(value, this.size); + this.vectors.set(internalDocumentId, [magnitude, value]); + } + remove(internalDocumentId) { + this.vectors.delete(internalDocumentId); + } + find(vector, similarity, whereFiltersIDs) { + if (!(vector instanceof Float32Array)) { + vector = new Float32Array(vector); + } + const results = findSimilarVectors(vector, whereFiltersIDs, this.vectors, this.size, similarity); + return results; + } + toJSON() { + const vectors = []; + for (const [id, [magnitude, vector]] of this.vectors) { + vectors.push([id, [magnitude, Array.from(vector)]]); + } + return { + size: this.size, + vectors + }; + } + static fromJSON(json) { + const raw = json; + const index2 = new _VectorIndex(raw.size); + for (const [id, [magnitude, vector]] of raw.vectors) { + index2.vectors.set(id, [magnitude, new Float32Array(vector)]); + } + return index2; + } + }; + function getMagnitude(vector, vectorLength) { + let magnitude = 0; + for (let i2 = 0; i2 < vectorLength; i2++) { + magnitude += vector[i2] * vector[i2]; + } + return Math.sqrt(magnitude); + } + function findSimilarVectors(targetVector, keys, vectors, length, threshold) { + const targetMagnitude = getMagnitude(targetVector, length); + const similarVectors = []; + const base = keys ? keys : vectors.keys(); + for (const vectorId of base) { + const entry = vectors.get(vectorId); + if (!entry) { + continue; + } + const magnitude = entry[0]; + const vector = entry[1]; + let dotProduct = 0; + for (let i2 = 0; i2 < length; i2++) { + dotProduct += targetVector[i2] * vector[i2]; + } + const similarity = dotProduct / (targetMagnitude * magnitude); + if (similarity >= threshold) { + similarVectors.push([vectorId, similarity]); + } + } + return similarVectors; + } + + // node_modules/@orama/orama/dist/browser/components/index.js + function insertDocumentScoreParameters(index2, prop, id, tokens, docsCount) { + const internalId = getInternalDocumentId(index2.sharedInternalDocumentStore, id); + index2.avgFieldLength[prop] = ((index2.avgFieldLength[prop] ?? 0) * (docsCount - 1) + tokens.length) / docsCount; + index2.fieldLengths[prop][internalId] = tokens.length; + index2.frequencies[prop][internalId] = {}; + } + function insertTokenScoreParameters(index2, prop, id, tokens, token) { + let tokenFrequency = 0; + for (const t2 of tokens) { + if (t2 === token) { + tokenFrequency++; + } + } + const internalId = getInternalDocumentId(index2.sharedInternalDocumentStore, id); + const tf = tokenFrequency / tokens.length; + index2.frequencies[prop][internalId][token] = tf; + if (!(token in index2.tokenOccurrences[prop])) { + index2.tokenOccurrences[prop][token] = 0; + } + index2.tokenOccurrences[prop][token] = (index2.tokenOccurrences[prop][token] ?? 0) + 1; + } + function removeDocumentScoreParameters(index2, prop, id, docsCount) { + const internalId = getInternalDocumentId(index2.sharedInternalDocumentStore, id); + if (docsCount > 1) { + index2.avgFieldLength[prop] = (index2.avgFieldLength[prop] * docsCount - index2.fieldLengths[prop][internalId]) / (docsCount - 1); + } else { + index2.avgFieldLength[prop] = void 0; + } + index2.fieldLengths[prop][internalId] = void 0; + index2.frequencies[prop][internalId] = void 0; + } + function removeTokenScoreParameters(index2, prop, token) { + index2.tokenOccurrences[prop][token]--; + } + function create3(orama, sharedInternalDocumentStore, schema4, index2, prefix = "") { + if (!index2) { + index2 = { + sharedInternalDocumentStore, + indexes: {}, + vectorIndexes: {}, + searchableProperties: [], + searchablePropertiesWithTypes: {}, + frequencies: {}, + tokenOccurrences: {}, + avgFieldLength: {}, + fieldLengths: {} + }; + } + for (const [prop, type] of Object.entries(schema4)) { + const path = `${prefix}${prefix ? "." : ""}${prop}`; + if (typeof type === "object" && !Array.isArray(type)) { + create3(orama, sharedInternalDocumentStore, type, index2, path); + continue; + } + if (isVectorType(type)) { + index2.searchableProperties.push(path); + index2.searchablePropertiesWithTypes[path] = type; + index2.vectorIndexes[path] = { + type: "Vector", + node: new VectorIndex(getVectorSize(type)), + isArray: false + }; + } else { + const isArray = /\[/.test(type); + switch (type) { + case "boolean": + case "boolean[]": + index2.indexes[path] = { type: "Bool", node: new BoolNode(), isArray }; + break; + case "number": + case "number[]": + index2.indexes[path] = { type: "AVL", node: new AVLTree(0, []), isArray }; + break; + case "string": + case "string[]": + index2.indexes[path] = { type: "Radix", node: new RadixTree(), isArray }; + index2.avgFieldLength[path] = 0; + index2.frequencies[path] = {}; + index2.tokenOccurrences[path] = {}; + index2.fieldLengths[path] = {}; + break; + case "enum": + case "enum[]": + index2.indexes[path] = { type: "Flat", node: new FlatTree(), isArray }; + break; + case "geopoint": + index2.indexes[path] = { type: "BKD", node: new BKDTree(), isArray }; + break; + default: + throw createError("INVALID_SCHEMA_TYPE", Array.isArray(type) ? "array" : type, path); + } + index2.searchableProperties.push(path); + index2.searchablePropertiesWithTypes[path] = type; + } + } + return index2; + } + function insertScalarBuilder(implementation, index2, prop, internalId, language, tokenizer, docsCount, options) { + return (value) => { + const { type, node } = index2.indexes[prop]; + switch (type) { + case "Bool": { + node[value ? "true" : "false"].add(internalId); + break; + } + case "AVL": { + const avlRebalanceThreshold = options?.avlRebalanceThreshold ?? 1; + node.insert(value, internalId, avlRebalanceThreshold); + break; + } + case "Radix": { + const tokens = tokenizer.tokenize(value, language, prop, false); + implementation.insertDocumentScoreParameters(index2, prop, internalId, tokens, docsCount); + for (const token of tokens) { + implementation.insertTokenScoreParameters(index2, prop, internalId, tokens, token); + node.insert(token, internalId); + } + break; + } + case "Flat": { + node.insert(value, internalId); + break; + } + case "BKD": { + node.insert(value, [internalId]); + break; + } + } + }; + } + function insert(implementation, index2, prop, id, internalId, value, schemaType, language, tokenizer, docsCount, options) { + if (isVectorType(schemaType)) { + return insertVector(index2, prop, value, id, internalId); + } + const insertScalar = insertScalarBuilder(implementation, index2, prop, internalId, language, tokenizer, docsCount, options); + if (!isArrayType(schemaType)) { + return insertScalar(value); + } + const elements = value; + const elementsLength = elements.length; + for (let i2 = 0; i2 < elementsLength; i2++) { + insertScalar(elements[i2]); + } + } + function insertVector(index2, prop, value, id, internalDocumentId) { + index2.vectorIndexes[prop].node.add(internalDocumentId, value); + } + function removeScalar(implementation, index2, prop, id, internalId, value, schemaType, language, tokenizer, docsCount) { + if (isVectorType(schemaType)) { + index2.vectorIndexes[prop].node.remove(internalId); + return true; + } + const { type, node } = index2.indexes[prop]; + switch (type) { + case "AVL": { + node.removeDocument(value, internalId); + return true; + } + case "Bool": { + node[value ? "true" : "false"].delete(internalId); + return true; + } + case "Radix": { + const tokens = tokenizer.tokenize(value, language, prop); + implementation.removeDocumentScoreParameters(index2, prop, id, docsCount); + for (const token of tokens) { + implementation.removeTokenScoreParameters(index2, prop, token); + node.removeDocumentByWord(token, internalId); + } + return true; + } + case "Flat": { + node.removeDocument(internalId, value); + return true; + } + case "BKD": { + node.removeDocByID(value, internalId); + return false; + } + } + } + function remove3(implementation, index2, prop, id, internalId, value, schemaType, language, tokenizer, docsCount) { + if (!isArrayType(schemaType)) { + return removeScalar(implementation, index2, prop, id, internalId, value, schemaType, language, tokenizer, docsCount); + } + const innerSchemaType = getInnerType(schemaType); + const elements = value; + const elementsLength = elements.length; + for (let i2 = 0; i2 < elementsLength; i2++) { + removeScalar(implementation, index2, prop, id, internalId, elements[i2], innerSchemaType, language, tokenizer, docsCount); + } + return true; + } + function calculateResultScores(index2, prop, term, ids, docsCount, bm25Relevance, resultsMap, boostPerProperty, whereFiltersIDs, keywordMatchesMap) { + const documentIDs = Array.from(ids); + const avgFieldLength = index2.avgFieldLength[prop]; + const fieldLengths = index2.fieldLengths[prop]; + const oramaOccurrences = index2.tokenOccurrences[prop]; + const oramaFrequencies = index2.frequencies[prop]; + const termOccurrences = typeof oramaOccurrences[term] === "number" ? oramaOccurrences[term] ?? 0 : 0; + const documentIDsLength = documentIDs.length; + for (let k3 = 0; k3 < documentIDsLength; k3++) { + const internalId = documentIDs[k3]; + if (whereFiltersIDs && !whereFiltersIDs.has(internalId)) { + continue; + } + if (!keywordMatchesMap.has(internalId)) { + keywordMatchesMap.set(internalId, /* @__PURE__ */ new Map()); + } + const propertyMatches = keywordMatchesMap.get(internalId); + propertyMatches.set(prop, (propertyMatches.get(prop) || 0) + 1); + const tf = oramaFrequencies?.[internalId]?.[term] ?? 0; + const bm25 = BM25(tf, termOccurrences, docsCount, fieldLengths[internalId], avgFieldLength, bm25Relevance); + if (resultsMap.has(internalId)) { + resultsMap.set(internalId, resultsMap.get(internalId) + bm25 * boostPerProperty); + } else { + resultsMap.set(internalId, bm25 * boostPerProperty); + } + } + } + function search(index2, term, tokenizer, language, propertiesToSearch, exact, tolerance, boost, relevance, docsCount, whereFiltersIDs, threshold = 0) { + const tokens = tokenizer.tokenize(term, language); + const keywordsCount = tokens.length || 1; + const keywordMatchesMap = /* @__PURE__ */ new Map(); + const tokenFoundMap = /* @__PURE__ */ new Map(); + const resultsMap = /* @__PURE__ */ new Map(); + for (const prop of propertiesToSearch) { + if (!(prop in index2.indexes)) { + continue; + } + const tree = index2.indexes[prop]; + const { type } = tree; + if (type !== "Radix") { + throw createError("WRONG_SEARCH_PROPERTY_TYPE", prop); + } + const boostPerProperty = boost[prop] ?? 1; + if (boostPerProperty <= 0) { + throw createError("INVALID_BOOST_VALUE", boostPerProperty); + } + if (tokens.length === 0 && !term) { + tokens.push(""); + } + const tokenLength = tokens.length; + for (let i2 = 0; i2 < tokenLength; i2++) { + const token = tokens[i2]; + const searchResult = tree.node.find({ term: token, exact, tolerance }); + const termsFound = Object.keys(searchResult); + if (termsFound.length > 0) { + tokenFoundMap.set(token, true); + } + const termsFoundLength = termsFound.length; + for (let j3 = 0; j3 < termsFoundLength; j3++) { + const word = termsFound[j3]; + const ids = searchResult[word]; + calculateResultScores(index2, prop, word, ids, docsCount, relevance, resultsMap, boostPerProperty, whereFiltersIDs, keywordMatchesMap); + } + } + } + const results = Array.from(resultsMap.entries()).map(([id, score]) => [id, score]).sort((a2, b3) => b3[1] - a2[1]); + if (results.length === 0) { + return []; + } + if (threshold === 1) { + return results; + } + if (threshold === 0) { + if (keywordsCount === 1) { + return results; + } + for (const token of tokens) { + if (!tokenFoundMap.get(token)) { + return []; + } + } + const fullMatches2 = results.filter(([id]) => { + const propertyMatches = keywordMatchesMap.get(id); + if (!propertyMatches) + return false; + return Array.from(propertyMatches.values()).some((matches) => matches === keywordsCount); + }); + return fullMatches2; + } + const fullMatches = results.filter(([id]) => { + const propertyMatches = keywordMatchesMap.get(id); + if (!propertyMatches) + return false; + return Array.from(propertyMatches.values()).some((matches) => matches === keywordsCount); + }); + if (fullMatches.length > 0) { + const remainingResults = results.filter(([id]) => !fullMatches.some(([fid]) => fid === id)); + const additionalResults = Math.ceil(remainingResults.length * threshold); + return [...fullMatches, ...remainingResults.slice(0, additionalResults)]; + } + return results; + } + function searchByWhereClause(index2, tokenizer, filters, language) { + if ("and" in filters && filters.and && Array.isArray(filters.and)) { + const andFilters = filters.and; + if (andFilters.length === 0) { + return /* @__PURE__ */ new Set(); + } + const results = andFilters.map((filter) => searchByWhereClause(index2, tokenizer, filter, language)); + return setIntersection(...results); + } + if ("or" in filters && filters.or && Array.isArray(filters.or)) { + const orFilters = filters.or; + if (orFilters.length === 0) { + return /* @__PURE__ */ new Set(); + } + const results = orFilters.map((filter) => searchByWhereClause(index2, tokenizer, filter, language)); + return results.reduce((acc, set2) => setUnion(acc, set2), /* @__PURE__ */ new Set()); + } + if ("not" in filters && filters.not) { + const notFilter = filters.not; + const allDocs = /* @__PURE__ */ new Set(); + const docsStore = index2.sharedInternalDocumentStore; + for (let i2 = 1; i2 <= docsStore.internalIdToId.length; i2++) { + allDocs.add(i2); + } + const notResult = searchByWhereClause(index2, tokenizer, notFilter, language); + return setDifference(allDocs, notResult); + } + const filterKeys = Object.keys(filters); + const filtersMap = filterKeys.reduce((acc, key) => ({ + [key]: /* @__PURE__ */ new Set(), + ...acc + }), {}); + for (const param of filterKeys) { + const operation = filters[param]; + if (typeof index2.indexes[param] === "undefined") { + throw createError("UNKNOWN_FILTER_PROPERTY", param); + } + const { node, type, isArray } = index2.indexes[param]; + if (type === "Bool") { + const idx = node; + const filteredIDs = operation ? idx.true : idx.false; + filtersMap[param] = setUnion(filtersMap[param], filteredIDs); + continue; + } + if (type === "BKD") { + let reqOperation; + if ("radius" in operation) { + reqOperation = "radius"; + } else if ("polygon" in operation) { + reqOperation = "polygon"; + } else { + throw new Error(`Invalid operation ${operation}`); + } + if (reqOperation === "radius") { + const { value, coordinates, unit = "m", inside = true, highPrecision = false } = operation[reqOperation]; + const distanceInMeters = convertDistanceToMeters(value, unit); + const ids = node.searchByRadius(coordinates, distanceInMeters, inside, void 0, highPrecision); + filtersMap[param] = addGeoResult(filtersMap[param], ids); + } else { + const { coordinates, inside = true, highPrecision = false } = operation[reqOperation]; + const ids = node.searchByPolygon(coordinates, inside, void 0, highPrecision); + filtersMap[param] = addGeoResult(filtersMap[param], ids); + } + continue; + } + if (type === "Radix" && (typeof operation === "string" || Array.isArray(operation))) { + for (const raw of [operation].flat()) { + const term = tokenizer.tokenize(raw, language, param); + for (const t2 of term) { + const filteredIDsResults = node.find({ term: t2, exact: true }); + filtersMap[param] = addFindResult(filtersMap[param], filteredIDsResults); + } + } + continue; + } + const operationKeys = Object.keys(operation); + if (operationKeys.length > 1) { + throw createError("INVALID_FILTER_OPERATION", operationKeys.length); + } + if (type === "Flat") { + const results = new Set(isArray ? node.filterArr(operation) : node.filter(operation)); + filtersMap[param] = setUnion(filtersMap[param], results); + continue; + } + if (type === "AVL") { + const operationOpt = operationKeys[0]; + const operationValue = operation[operationOpt]; + let filteredIDs; + switch (operationOpt) { + case "gt": { + filteredIDs = node.greaterThan(operationValue, false); + break; + } + case "gte": { + filteredIDs = node.greaterThan(operationValue, true); + break; + } + case "lt": { + filteredIDs = node.lessThan(operationValue, false); + break; + } + case "lte": { + filteredIDs = node.lessThan(operationValue, true); + break; + } + case "eq": { + const ret = node.find(operationValue); + filteredIDs = ret ?? /* @__PURE__ */ new Set(); + break; + } + case "between": { + const [min, max] = operationValue; + filteredIDs = node.rangeSearch(min, max); + break; + } + default: + throw createError("INVALID_FILTER_OPERATION", operationOpt); + } + filtersMap[param] = setUnion(filtersMap[param], filteredIDs); + } + } + return setIntersection(...Object.values(filtersMap)); + } + function getSearchableProperties(index2) { + return index2.searchableProperties; + } + function getSearchablePropertiesWithTypes(index2) { + return index2.searchablePropertiesWithTypes; + } + function load3(sharedInternalDocumentStore, raw) { + const { indexes: rawIndexes, vectorIndexes: rawVectorIndexes, searchableProperties, searchablePropertiesWithTypes, frequencies, tokenOccurrences, avgFieldLength, fieldLengths } = raw; + const indexes = {}; + const vectorIndexes = {}; + for (const prop of Object.keys(rawIndexes)) { + const { node, type, isArray } = rawIndexes[prop]; + switch (type) { + case "Radix": + indexes[prop] = { + type: "Radix", + node: RadixTree.fromJSON(node), + isArray + }; + break; + case "Flat": + indexes[prop] = { + type: "Flat", + node: FlatTree.fromJSON(node), + isArray + }; + break; + case "AVL": + indexes[prop] = { + type: "AVL", + node: AVLTree.fromJSON(node), + isArray + }; + break; + case "BKD": + indexes[prop] = { + type: "BKD", + node: BKDTree.fromJSON(node), + isArray + }; + break; + case "Bool": + indexes[prop] = { + type: "Bool", + node: BoolNode.fromJSON(node), + isArray + }; + break; + default: + indexes[prop] = rawIndexes[prop]; + } + } + for (const idx of Object.keys(rawVectorIndexes)) { + vectorIndexes[idx] = { + type: "Vector", + isArray: false, + node: VectorIndex.fromJSON(rawVectorIndexes[idx]) + }; + } + return { + sharedInternalDocumentStore, + indexes, + vectorIndexes, + searchableProperties, + searchablePropertiesWithTypes, + frequencies, + tokenOccurrences, + avgFieldLength, + fieldLengths + }; + } + function save3(index2) { + const { indexes, vectorIndexes, searchableProperties, searchablePropertiesWithTypes, frequencies, tokenOccurrences, avgFieldLength, fieldLengths } = index2; + const dumpVectorIndexes = {}; + for (const idx of Object.keys(vectorIndexes)) { + dumpVectorIndexes[idx] = vectorIndexes[idx].node.toJSON(); + } + const savedIndexes = {}; + for (const name of Object.keys(indexes)) { + const { type, node, isArray } = indexes[name]; + if (type === "Flat" || type === "Radix" || type === "AVL" || type === "BKD" || type === "Bool") { + savedIndexes[name] = { + type, + node: node.toJSON(), + isArray + }; + } else { + savedIndexes[name] = indexes[name]; + savedIndexes[name].node = savedIndexes[name].node.toJSON(); + } + } + return { + indexes: savedIndexes, + vectorIndexes: dumpVectorIndexes, + searchableProperties, + searchablePropertiesWithTypes, + frequencies, + tokenOccurrences, + avgFieldLength, + fieldLengths + }; + } + function createIndex() { + return { + create: create3, + insert, + remove: remove3, + insertDocumentScoreParameters, + insertTokenScoreParameters, + removeDocumentScoreParameters, + removeTokenScoreParameters, + calculateResultScores, + search, + searchByWhereClause, + getSearchableProperties, + getSearchablePropertiesWithTypes, + load: load3, + save: save3 + }; + } + function addGeoResult(set2, ids) { + if (!set2) { + set2 = /* @__PURE__ */ new Set(); + } + const idsLength = ids.length; + for (let i2 = 0; i2 < idsLength; i2++) { + const entry = ids[i2].docIDs; + const idsLength2 = entry.length; + for (let j3 = 0; j3 < idsLength2; j3++) { + set2.add(entry[j3]); + } + } + return set2; + } + function createGeoTokenScores(ids, centerPoint, highPrecision = false) { + const distanceFn = highPrecision ? BKDTree.vincentyDistance : BKDTree.haversineDistance; + const results = []; + const distances = []; + for (const { point } of ids) { + distances.push(distanceFn(centerPoint, point)); + } + const maxDistance = Math.max(...distances); + let index2 = 0; + for (const { docIDs } of ids) { + const distance = distances[index2]; + const score = maxDistance - distance + 1; + for (const docID of docIDs) { + results.push([docID, score]); + } + index2++; + } + results.sort((a2, b3) => b3[1] - a2[1]); + return results; + } + function isGeosearchOnlyQuery(filters, index2) { + const filterKeys = Object.keys(filters); + if (filterKeys.length !== 1) { + return { isGeoOnly: false }; + } + const param = filterKeys[0]; + const operation = filters[param]; + if (typeof index2.indexes[param] === "undefined") { + return { isGeoOnly: false }; + } + const { type } = index2.indexes[param]; + if (type === "BKD" && operation && ("radius" in operation || "polygon" in operation)) { + return { isGeoOnly: true, geoProperty: param, geoOperation: operation }; + } + return { isGeoOnly: false }; + } + function searchByGeoWhereClause(index2, filters) { + const indexTyped = index2; + const geoInfo = isGeosearchOnlyQuery(filters, indexTyped); + if (!geoInfo.isGeoOnly || !geoInfo.geoProperty || !geoInfo.geoOperation) { + return null; + } + const { node } = indexTyped.indexes[geoInfo.geoProperty]; + const operation = geoInfo.geoOperation; + const bkdNode = node; + let results; + if ("radius" in operation) { + const { value, coordinates, unit = "m", inside = true, highPrecision = false } = operation.radius; + const centerPoint = coordinates; + const distanceInMeters = convertDistanceToMeters(value, unit); + results = bkdNode.searchByRadius(centerPoint, distanceInMeters, inside, "asc", highPrecision); + return createGeoTokenScores(results, centerPoint, highPrecision); + } else if ("polygon" in operation) { + const { coordinates, inside = true, highPrecision = false } = operation.polygon; + results = bkdNode.searchByPolygon(coordinates, inside, "asc", highPrecision); + const centroid = BKDTree.calculatePolygonCentroid(coordinates); + return createGeoTokenScores(results, centroid, highPrecision); + } + return null; + } + function addFindResult(set2, filteredIDsResults) { + if (!set2) { + set2 = /* @__PURE__ */ new Set(); + } + const keys = Object.keys(filteredIDsResults); + const keysLength = keys.length; + for (let i2 = 0; i2 < keysLength; i2++) { + const ids = filteredIDsResults[keys[i2]]; + const idsLength = ids.length; + for (let j3 = 0; j3 < idsLength; j3++) { + set2.add(ids[j3]); + } + } + return set2; + } + + // node_modules/@orama/orama/dist/browser/components/sorter.js + function innerCreate(orama, sharedInternalDocumentStore, schema4, sortableDeniedProperties, prefix) { + const sorter = { + language: orama.tokenizer.language, + sharedInternalDocumentStore, + enabled: true, + isSorted: true, + sortableProperties: [], + sortablePropertiesWithTypes: {}, + sorts: {} + }; + for (const [prop, type] of Object.entries(schema4)) { + const path = `${prefix}${prefix ? "." : ""}${prop}`; + if (sortableDeniedProperties.includes(path)) { + continue; + } + if (typeof type === "object" && !Array.isArray(type)) { + const ret = innerCreate(orama, sharedInternalDocumentStore, type, sortableDeniedProperties, path); + safeArrayPush(sorter.sortableProperties, ret.sortableProperties); + sorter.sorts = { + ...sorter.sorts, + ...ret.sorts + }; + sorter.sortablePropertiesWithTypes = { + ...sorter.sortablePropertiesWithTypes, + ...ret.sortablePropertiesWithTypes + }; + continue; + } + if (!isVectorType(type)) { + switch (type) { + case "boolean": + case "number": + case "string": + sorter.sortableProperties.push(path); + sorter.sortablePropertiesWithTypes[path] = type; + sorter.sorts[path] = { + docs: /* @__PURE__ */ new Map(), + orderedDocsToRemove: /* @__PURE__ */ new Map(), + orderedDocs: [], + type + }; + break; + case "geopoint": + case "enum": + continue; + case "enum[]": + case "boolean[]": + case "number[]": + case "string[]": + continue; + default: + throw createError("INVALID_SORT_SCHEMA_TYPE", Array.isArray(type) ? "array" : type, path); + } + } + } + return sorter; + } + function create4(orama, sharedInternalDocumentStore, schema4, config) { + const isSortEnabled = config?.enabled !== false; + if (!isSortEnabled) { + return { + disabled: true + }; + } + return innerCreate(orama, sharedInternalDocumentStore, schema4, (config || {}).unsortableProperties || [], ""); + } + function insert2(sorter, prop, id, value) { + if (!sorter.enabled) { + return; + } + sorter.isSorted = false; + const internalId = getInternalDocumentId(sorter.sharedInternalDocumentStore, id); + const s2 = sorter.sorts[prop]; + if (s2.orderedDocsToRemove.has(internalId)) { + ensureOrderedDocsAreDeletedByProperty(sorter, prop); + } + s2.docs.set(internalId, s2.orderedDocs.length); + s2.orderedDocs.push([internalId, value]); + } + function ensureIsSorted(sorter) { + if (sorter.isSorted || !sorter.enabled) { + return; + } + const properties = Object.keys(sorter.sorts); + for (const prop of properties) { + ensurePropertyIsSorted(sorter, prop); + } + sorter.isSorted = true; + } + function stringSort(language, value, d3) { + return value[1].localeCompare(d3[1], getLocale(language)); + } + function numberSort(value, d3) { + return value[1] - d3[1]; + } + function booleanSort(value, d3) { + return d3[1] ? -1 : 1; + } + function ensurePropertyIsSorted(sorter, prop) { + const s2 = sorter.sorts[prop]; + let predicate; + switch (s2.type) { + case "string": + predicate = stringSort.bind(null, sorter.language); + break; + case "number": + predicate = numberSort.bind(null); + break; + case "boolean": + predicate = booleanSort.bind(null); + break; + } + s2.orderedDocs.sort(predicate); + const orderedDocsLength = s2.orderedDocs.length; + for (let i2 = 0; i2 < orderedDocsLength; i2++) { + const docId = s2.orderedDocs[i2][0]; + s2.docs.set(docId, i2); + } + } + function ensureOrderedDocsAreDeleted(sorter) { + const properties = Object.keys(sorter.sorts); + for (const prop of properties) { + ensureOrderedDocsAreDeletedByProperty(sorter, prop); + } + } + function ensureOrderedDocsAreDeletedByProperty(sorter, prop) { + const s2 = sorter.sorts[prop]; + if (!s2.orderedDocsToRemove.size) + return; + s2.orderedDocs = s2.orderedDocs.filter((doc) => !s2.orderedDocsToRemove.has(doc[0])); + s2.orderedDocsToRemove.clear(); + } + function remove4(sorter, prop, id) { + if (!sorter.enabled) { + return; + } + const s2 = sorter.sorts[prop]; + const internalId = getInternalDocumentId(sorter.sharedInternalDocumentStore, id); + const index2 = s2.docs.get(internalId); + if (!index2) + return; + s2.docs.delete(internalId); + s2.orderedDocsToRemove.set(internalId, true); + } + function sortBy(sorter, docIds, by) { + if (!sorter.enabled) { + throw createError("SORT_DISABLED"); + } + const property = by.property; + const isDesc = by.order === "DESC"; + const s2 = sorter.sorts[property]; + if (!s2) { + throw createError("UNABLE_TO_SORT_ON_UNKNOWN_FIELD", property, sorter.sortableProperties.join(", ")); + } + ensureOrderedDocsAreDeletedByProperty(sorter, property); + ensureIsSorted(sorter); + docIds.sort((a2, b3) => { + const indexOfA = s2.docs.get(getInternalDocumentId(sorter.sharedInternalDocumentStore, a2[0])); + const indexOfB = s2.docs.get(getInternalDocumentId(sorter.sharedInternalDocumentStore, b3[0])); + const isAIndexed = typeof indexOfA !== "undefined"; + const isBIndexed = typeof indexOfB !== "undefined"; + if (!isAIndexed && !isBIndexed) { + return 0; + } + if (!isAIndexed) { + return 1; + } + if (!isBIndexed) { + return -1; + } + return isDesc ? indexOfB - indexOfA : indexOfA - indexOfB; + }); + return docIds; + } + function getSortableProperties(sorter) { + if (!sorter.enabled) { + return []; + } + return sorter.sortableProperties; + } + function getSortablePropertiesWithTypes(sorter) { + if (!sorter.enabled) { + return {}; + } + return sorter.sortablePropertiesWithTypes; + } + function load4(sharedInternalDocumentStore, raw) { + const rawDocument = raw; + if (!rawDocument.enabled) { + return { + enabled: false + }; + } + const sorts = Object.keys(rawDocument.sorts).reduce((acc, prop) => { + const { docs, orderedDocs, type } = rawDocument.sorts[prop]; + acc[prop] = { + docs: new Map(Object.entries(docs).map(([k3, v6]) => [+k3, v6])), + orderedDocsToRemove: /* @__PURE__ */ new Map(), + orderedDocs, + type + }; + return acc; + }, {}); + return { + sharedInternalDocumentStore, + language: rawDocument.language, + sortableProperties: rawDocument.sortableProperties, + sortablePropertiesWithTypes: rawDocument.sortablePropertiesWithTypes, + sorts, + enabled: true, + isSorted: rawDocument.isSorted + }; + } + function save4(sorter) { + if (!sorter.enabled) { + return { + enabled: false + }; + } + ensureOrderedDocsAreDeleted(sorter); + ensureIsSorted(sorter); + const sorts = Object.keys(sorter.sorts).reduce((acc, prop) => { + const { docs, orderedDocs, type } = sorter.sorts[prop]; + acc[prop] = { + docs: Object.fromEntries(docs.entries()), + orderedDocs, + type + }; + return acc; + }, {}); + return { + language: sorter.language, + sortableProperties: sorter.sortableProperties, + sortablePropertiesWithTypes: sorter.sortablePropertiesWithTypes, + sorts, + enabled: sorter.enabled, + isSorted: sorter.isSorted + }; + } + function createSorter() { + return { + create: create4, + insert: insert2, + remove: remove4, + save: save4, + load: load4, + sortBy, + getSortableProperties, + getSortablePropertiesWithTypes + }; + } + + // node_modules/@orama/orama/dist/browser/components/tokenizer/diacritics.js + var DIACRITICS_CHARCODE_START = 192; + var DIACRITICS_CHARCODE_END = 383; + var CHARCODE_REPLACE_MAPPING = [ + 65, + 65, + 65, + 65, + 65, + 65, + 65, + 67, + 69, + 69, + 69, + 69, + 73, + 73, + 73, + 73, + 69, + 78, + 79, + 79, + 79, + 79, + 79, + null, + 79, + 85, + 85, + 85, + 85, + 89, + 80, + 115, + 97, + 97, + 97, + 97, + 97, + 97, + 97, + 99, + 101, + 101, + 101, + 101, + 105, + 105, + 105, + 105, + 101, + 110, + 111, + 111, + 111, + 111, + 111, + null, + 111, + 117, + 117, + 117, + 117, + 121, + 112, + 121, + 65, + 97, + 65, + 97, + 65, + 97, + 67, + 99, + 67, + 99, + 67, + 99, + 67, + 99, + 68, + 100, + 68, + 100, + 69, + 101, + 69, + 101, + 69, + 101, + 69, + 101, + 69, + 101, + 71, + 103, + 71, + 103, + 71, + 103, + 71, + 103, + 72, + 104, + 72, + 104, + 73, + 105, + 73, + 105, + 73, + 105, + 73, + 105, + 73, + 105, + 73, + 105, + 74, + 106, + 75, + 107, + 107, + 76, + 108, + 76, + 108, + 76, + 108, + 76, + 108, + 76, + 108, + 78, + 110, + 78, + 110, + 78, + 110, + 110, + 78, + 110, + 79, + 111, + 79, + 111, + 79, + 111, + 79, + 111, + 82, + 114, + 82, + 114, + 82, + 114, + 83, + 115, + 83, + 115, + 83, + 115, + 83, + 115, + 84, + 116, + 84, + 116, + 84, + 116, + 85, + 117, + 85, + 117, + 85, + 117, + 85, + 117, + 85, + 117, + 85, + 117, + 87, + 119, + 89, + 121, + 89, + 90, + 122, + 90, + 122, + 90, + 122, + 115 + ]; + function replaceChar(charCode) { + if (charCode < DIACRITICS_CHARCODE_START || charCode > DIACRITICS_CHARCODE_END) + return charCode; + return CHARCODE_REPLACE_MAPPING[charCode - DIACRITICS_CHARCODE_START] || charCode; + } + function replaceDiacritics(str) { + const stringCharCode = []; + for (let idx = 0; idx < str.length; idx++) { + stringCharCode[idx] = replaceChar(str.charCodeAt(idx)); + } + return String.fromCharCode(...stringCharCode); + } + + // node_modules/@orama/orama/dist/browser/components/tokenizer/english-stemmer.js + var step2List = { + ational: "ate", + tional: "tion", + enci: "ence", + anci: "ance", + izer: "ize", + bli: "ble", + alli: "al", + entli: "ent", + eli: "e", + ousli: "ous", + ization: "ize", + ation: "ate", + ator: "ate", + alism: "al", + iveness: "ive", + fulness: "ful", + ousness: "ous", + aliti: "al", + iviti: "ive", + biliti: "ble", + logi: "log" + }; + var step3List = { + icate: "ic", + ative: "", + alize: "al", + iciti: "ic", + ical: "ic", + ful: "", + ness: "" + }; + var c = "[^aeiou]"; + var v2 = "[aeiouy]"; + var C2 = c + "[^aeiouy]*"; + var V = v2 + "[aeiou]*"; + var mgr0 = "^(" + C2 + ")?" + V + C2; + var meq1 = "^(" + C2 + ")?" + V + C2 + "(" + V + ")?$"; + var mgr1 = "^(" + C2 + ")?" + V + C2 + V + C2; + var s_v = "^(" + C2 + ")?" + v2; + function stemmer(w3) { + let stem; + let suffix; + let re2; + let re22; + let re3; + let re4; + if (w3.length < 3) { + return w3; + } + const firstch = w3.substring(0, 1); + if (firstch == "y") { + w3 = firstch.toUpperCase() + w3.substring(1); + } + re2 = /^(.+?)(ss|i)es$/; + re22 = /^(.+?)([^s])s$/; + if (re2.test(w3)) { + w3 = w3.replace(re2, "$1$2"); + } else if (re22.test(w3)) { + w3 = w3.replace(re22, "$1$2"); + } + re2 = /^(.+?)eed$/; + re22 = /^(.+?)(ed|ing)$/; + if (re2.test(w3)) { + const fp = re2.exec(w3); + re2 = new RegExp(mgr0); + if (re2.test(fp[1])) { + re2 = /.$/; + w3 = w3.replace(re2, ""); + } + } else if (re22.test(w3)) { + const fp = re22.exec(w3); + stem = fp[1]; + re22 = new RegExp(s_v); + if (re22.test(stem)) { + w3 = stem; + re22 = /(at|bl|iz)$/; + re3 = new RegExp("([^aeiouylsz])\\1$"); + re4 = new RegExp("^" + C2 + v2 + "[^aeiouwxy]$"); + if (re22.test(w3)) { + w3 = w3 + "e"; + } else if (re3.test(w3)) { + re2 = /.$/; + w3 = w3.replace(re2, ""); + } else if (re4.test(w3)) { + w3 = w3 + "e"; + } + } + } + re2 = /^(.+?)y$/; + if (re2.test(w3)) { + const fp = re2.exec(w3); + stem = fp?.[1]; + re2 = new RegExp(s_v); + if (stem && re2.test(stem)) { + w3 = stem + "i"; + } + } + re2 = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/; + if (re2.test(w3)) { + const fp = re2.exec(w3); + stem = fp?.[1]; + suffix = fp?.[2]; + re2 = new RegExp(mgr0); + if (stem && re2.test(stem)) { + w3 = stem + step2List[suffix]; + } + } + re2 = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/; + if (re2.test(w3)) { + const fp = re2.exec(w3); + stem = fp?.[1]; + suffix = fp?.[2]; + re2 = new RegExp(mgr0); + if (stem && re2.test(stem)) { + w3 = stem + step3List[suffix]; + } + } + re2 = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/; + re22 = /^(.+?)(s|t)(ion)$/; + if (re2.test(w3)) { + const fp = re2.exec(w3); + stem = fp?.[1]; + re2 = new RegExp(mgr1); + if (stem && re2.test(stem)) { + w3 = stem; + } + } else if (re22.test(w3)) { + const fp = re22.exec(w3); + stem = fp?.[1] ?? "" + fp?.[2] ?? ""; + re22 = new RegExp(mgr1); + if (re22.test(stem)) { + w3 = stem; + } + } + re2 = /^(.+?)e$/; + if (re2.test(w3)) { + const fp = re2.exec(w3); + stem = fp?.[1]; + re2 = new RegExp(mgr1); + re22 = new RegExp(meq1); + re3 = new RegExp("^" + C2 + v2 + "[^aeiouwxy]$"); + if (stem && (re2.test(stem) || re22.test(stem) && !re3.test(stem))) { + w3 = stem; + } + } + re2 = /ll$/; + re22 = new RegExp(mgr1); + if (re2.test(w3) && re22.test(w3)) { + re2 = /.$/; + w3 = w3.replace(re2, ""); + } + if (firstch == "y") { + w3 = firstch.toLowerCase() + w3.substring(1); + } + return w3; + } + + // node_modules/@orama/orama/dist/browser/components/tokenizer/index.js + function normalizeToken(prop, token, withCache = true) { + const key = `${this.language}:${prop}:${token}`; + if (withCache && this.normalizationCache.has(key)) { + return this.normalizationCache.get(key); + } + if (this.stopWords?.includes(token)) { + if (withCache) { + this.normalizationCache.set(key, ""); + } + return ""; + } + if (this.stemmer && !this.stemmerSkipProperties.has(prop)) { + token = this.stemmer(token); + } + token = replaceDiacritics(token); + if (withCache) { + this.normalizationCache.set(key, token); + } + return token; + } + function trim(text2) { + while (text2[text2.length - 1] === "") { + text2.pop(); + } + while (text2[0] === "") { + text2.shift(); + } + return text2; + } + function tokenize(input, language, prop, withCache = true) { + if (language && language !== this.language) { + throw createError("LANGUAGE_NOT_SUPPORTED", language); + } + if (typeof input !== "string") { + return [input]; + } + const normalizeToken2 = this.normalizeToken.bind(this, prop ?? ""); + let tokens; + if (prop && this.tokenizeSkipProperties.has(prop)) { + tokens = [normalizeToken2(input, withCache)]; + } else { + const splitRule = SPLITTERS[this.language]; + tokens = input.toLowerCase().split(splitRule).map((t2) => normalizeToken2(t2, withCache)).filter(Boolean); + } + const trimTokens = trim(tokens); + if (!this.allowDuplicates) { + return Array.from(new Set(trimTokens)); + } + return trimTokens; + } + function createTokenizer(config = {}) { + if (!config.language) { + config.language = "english"; + } else if (!SUPPORTED_LANGUAGES.includes(config.language)) { + throw createError("LANGUAGE_NOT_SUPPORTED", config.language); + } + let stemmer2; + if (config.stemming || config.stemmer && !("stemming" in config)) { + if (config.stemmer) { + if (typeof config.stemmer !== "function") { + throw createError("INVALID_STEMMER_FUNCTION_TYPE"); + } + stemmer2 = config.stemmer; + } else { + if (config.language === "english") { + stemmer2 = stemmer; + } else { + throw createError("MISSING_STEMMER", config.language); + } + } + } + let stopWords; + if (config.stopWords !== false) { + stopWords = []; + if (Array.isArray(config.stopWords)) { + stopWords = config.stopWords; + } else if (typeof config.stopWords === "function") { + stopWords = config.stopWords(stopWords); + } else if (config.stopWords) { + throw createError("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY"); + } + if (!Array.isArray(stopWords)) { + throw createError("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY"); + } + for (const s2 of stopWords) { + if (typeof s2 !== "string") { + throw createError("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY"); + } + } + } + const tokenizer = { + tokenize, + language: config.language, + stemmer: stemmer2, + stemmerSkipProperties: new Set(config.stemmerSkipProperties ? [config.stemmerSkipProperties].flat() : []), + tokenizeSkipProperties: new Set(config.tokenizeSkipProperties ? [config.tokenizeSkipProperties].flat() : []), + stopWords, + allowDuplicates: Boolean(config.allowDuplicates), + normalizeToken, + normalizationCache: /* @__PURE__ */ new Map() + }; + tokenizer.tokenize = tokenize.bind(tokenizer); + tokenizer.normalizeToken = normalizeToken; + return tokenizer; + } + + // node_modules/@orama/orama/dist/browser/components/pinning.js + function create5(sharedInternalDocumentStore) { + return { + sharedInternalDocumentStore, + rules: /* @__PURE__ */ new Map() + }; + } + function addRule(store2, rule) { + if (store2.rules.has(rule.id)) { + throw new Error(`PINNING_RULE_ALREADY_EXISTS: A pinning rule with id "${rule.id}" already exists. Use updateRule to modify it.`); + } + store2.rules.set(rule.id, rule); + } + function updateRule(store2, rule) { + if (!store2.rules.has(rule.id)) { + throw new Error(`PINNING_RULE_NOT_FOUND: Cannot update pinning rule with id "${rule.id}" because it does not exist. Use addRule to create it.`); + } + store2.rules.set(rule.id, rule); + } + function removeRule(store2, ruleId) { + return store2.rules.delete(ruleId); + } + function getRule(store2, ruleId) { + return store2.rules.get(ruleId); + } + function getAllRules(store2) { + return Array.from(store2.rules.values()); + } + function matchesCondition(term, condition) { + const normalizedTerm = term.toLowerCase().trim(); + const normalizedPattern = condition.pattern.toLowerCase().trim(); + switch (condition.anchoring) { + case "is": + return normalizedTerm === normalizedPattern; + case "starts_with": + return normalizedTerm.startsWith(normalizedPattern); + case "contains": + return normalizedTerm.includes(normalizedPattern); + default: + return false; + } + } + function matchesRule(term, rule) { + if (!term) { + return false; + } + return rule.conditions.every((condition) => matchesCondition(term, condition)); + } + function getMatchingRules(store2, term) { + if (!term) { + return []; + } + const matchingRules = []; + for (const rule of store2.rules.values()) { + if (matchesRule(term, rule)) { + matchingRules.push(rule); + } + } + return matchingRules; + } + function load5(sharedInternalDocumentStore, raw) { + const rawStore = raw; + return { + sharedInternalDocumentStore, + rules: new Map(rawStore?.rules ?? []) + }; + } + function save5(store2) { + return { + rules: Array.from(store2.rules.entries()) + }; + } + function createPinning() { + return { + create: create5, + addRule, + updateRule, + removeRule, + getRule, + getAllRules, + getMatchingRules, + load: load5, + save: save5 + }; + } + + // node_modules/@orama/orama/dist/browser/methods/create.js + function validateComponents(components) { + const defaultComponents = { + formatElapsedTime, + getDocumentIndexId, + getDocumentProperties, + validateSchema + }; + for (const rawKey of FUNCTION_COMPONENTS) { + const key = rawKey; + if (components[key]) { + if (typeof components[key] !== "function") { + throw createError("COMPONENT_MUST_BE_FUNCTION", key); + } + } else { + components[key] = defaultComponents[key]; + } + } + for (const rawKey of Object.keys(components)) { + if (!OBJECT_COMPONENTS.includes(rawKey) && !FUNCTION_COMPONENTS.includes(rawKey)) { + throw createError("UNSUPPORTED_COMPONENT", rawKey); + } + } + } + function create6({ schema: schema4, sort, language, components, id, plugins }) { + if (!components) { + components = {}; + } + for (const plugin of plugins ?? []) { + if (!("getComponents" in plugin)) { + continue; + } + if (typeof plugin.getComponents !== "function") { + continue; + } + const pluginComponents = plugin.getComponents(schema4); + const keys = Object.keys(pluginComponents); + for (const key of keys) { + if (components[key]) { + throw createError("PLUGIN_COMPONENT_CONFLICT", key, plugin.name); + } + } + components = { + ...components, + ...pluginComponents + }; + } + if (!id) { + id = uniqueId(); + } + let tokenizer = components.tokenizer; + let index2 = components.index; + let documentsStore = components.documentsStore; + let sorter = components.sorter; + let pinning = components.pinning; + if (!tokenizer) { + tokenizer = createTokenizer({ language: language ?? "english" }); + } else if (!tokenizer.tokenize) { + tokenizer = createTokenizer(tokenizer); + } else { + const customTokenizer = tokenizer; + tokenizer = customTokenizer; + } + if (components.tokenizer && language) { + throw createError("NO_LANGUAGE_WITH_CUSTOM_TOKENIZER"); + } + const internalDocumentStore = createInternalDocumentIDStore(); + index2 ||= createIndex(); + sorter ||= createSorter(); + documentsStore ||= createDocumentsStore(); + pinning ||= createPinning(); + validateComponents(components); + const { getDocumentProperties: getDocumentProperties2, getDocumentIndexId: getDocumentIndexId2, validateSchema: validateSchema2, formatElapsedTime: formatElapsedTime2 } = components; + const orama = { + data: {}, + caches: {}, + schema: schema4, + tokenizer, + index: index2, + sorter, + documentsStore, + pinning, + internalDocumentIDStore: internalDocumentStore, + getDocumentProperties: getDocumentProperties2, + getDocumentIndexId: getDocumentIndexId2, + validateSchema: validateSchema2, + beforeInsert: [], + afterInsert: [], + beforeRemove: [], + afterRemove: [], + beforeUpdate: [], + afterUpdate: [], + beforeUpsert: [], + afterUpsert: [], + beforeSearch: [], + afterSearch: [], + beforeInsertMultiple: [], + afterInsertMultiple: [], + beforeRemoveMultiple: [], + afterRemoveMultiple: [], + beforeUpdateMultiple: [], + afterUpdateMultiple: [], + beforeUpsertMultiple: [], + afterUpsertMultiple: [], + afterCreate: [], + formatElapsedTime: formatElapsedTime2, + id, + plugins, + version: getVersion() + }; + orama.data = { + index: orama.index.create(orama, internalDocumentStore, schema4), + docs: orama.documentsStore.create(orama, internalDocumentStore), + sorting: orama.sorter.create(orama, internalDocumentStore, schema4, sort), + pinning: orama.pinning.create(internalDocumentStore) + }; + for (const hook of AVAILABLE_PLUGIN_HOOKS) { + orama[hook] = (orama[hook] ?? []).concat(getAllPluginsByHook(orama, hook)); + } + const afterCreate = orama["afterCreate"]; + if (afterCreate) { + runAfterCreate(afterCreate, orama); + } + return orama; + } + function getVersion() { + return "{{VERSION}}"; + } + + // node_modules/@orama/orama/dist/browser/methods/docs.js + function count2(db) { + return db.documentsStore.count(db.data.docs); + } + + // node_modules/@orama/orama/dist/browser/methods/insert.js + function insert3(orama, doc, language, skipHooks, options) { + const errorProperty = orama.validateSchema(doc, orama.schema); + if (errorProperty) { + throw createError("SCHEMA_VALIDATION_FAILURE", errorProperty); + } + const asyncNeeded = isAsyncFunction(orama.beforeInsert) || isAsyncFunction(orama.afterInsert) || isAsyncFunction(orama.index.beforeInsert) || isAsyncFunction(orama.index.insert) || isAsyncFunction(orama.index.afterInsert); + if (asyncNeeded) { + return innerInsertAsync(orama, doc, language, skipHooks, options); + } + return innerInsertSync(orama, doc, language, skipHooks, options); + } + var ENUM_TYPE = /* @__PURE__ */ new Set(["enum", "enum[]"]); + var STRING_NUMBER_TYPE = /* @__PURE__ */ new Set(["string", "number"]); + async function innerInsertAsync(orama, doc, language, skipHooks, options) { + const { index: index2, docs } = orama.data; + const id = orama.getDocumentIndexId(doc); + if (typeof id !== "string") { + throw createError("DOCUMENT_ID_MUST_BE_STRING", typeof id); + } + const internalId = getInternalDocumentId(orama.internalDocumentIDStore, id); + if (!skipHooks) { + await runSingleHook(orama.beforeInsert, orama, id, doc); + } + if (!orama.documentsStore.store(docs, id, internalId, doc)) { + throw createError("DOCUMENT_ALREADY_EXISTS", id); + } + const docsCount = orama.documentsStore.count(docs); + const indexableProperties = orama.index.getSearchableProperties(index2); + const indexablePropertiesWithTypes = orama.index.getSearchablePropertiesWithTypes(index2); + const indexableValues = orama.getDocumentProperties(doc, indexableProperties); + for (const [key, value] of Object.entries(indexableValues)) { + if (typeof value === "undefined") + continue; + const actualType = typeof value; + const expectedType = indexablePropertiesWithTypes[key]; + validateDocumentProperty(actualType, expectedType, key, value); + } + await indexAndSortDocument(orama, id, indexableProperties, indexableValues, docsCount, language, doc, options); + if (!skipHooks) { + await runSingleHook(orama.afterInsert, orama, id, doc); + } + return id; + } + function innerInsertSync(orama, doc, language, skipHooks, options) { + const { index: index2, docs } = orama.data; + const id = orama.getDocumentIndexId(doc); + if (typeof id !== "string") { + throw createError("DOCUMENT_ID_MUST_BE_STRING", typeof id); + } + const internalId = getInternalDocumentId(orama.internalDocumentIDStore, id); + if (!skipHooks) { + runSingleHook(orama.beforeInsert, orama, id, doc); + } + if (!orama.documentsStore.store(docs, id, internalId, doc)) { + throw createError("DOCUMENT_ALREADY_EXISTS", id); + } + const docsCount = orama.documentsStore.count(docs); + const indexableProperties = orama.index.getSearchableProperties(index2); + const indexablePropertiesWithTypes = orama.index.getSearchablePropertiesWithTypes(index2); + const indexableValues = orama.getDocumentProperties(doc, indexableProperties); + for (const [key, value] of Object.entries(indexableValues)) { + if (typeof value === "undefined") + continue; + const actualType = typeof value; + const expectedType = indexablePropertiesWithTypes[key]; + validateDocumentProperty(actualType, expectedType, key, value); + } + indexAndSortDocumentSync(orama, id, indexableProperties, indexableValues, docsCount, language, doc, options); + if (!skipHooks) { + runSingleHook(orama.afterInsert, orama, id, doc); + } + return id; + } + function validateDocumentProperty(actualType, expectedType, key, value) { + if (isGeoPointType(expectedType) && typeof value === "object" && typeof value.lon === "number" && typeof value.lat === "number") { + return; + } + if (isVectorType(expectedType) && Array.isArray(value)) + return; + if (isArrayType(expectedType) && Array.isArray(value)) + return; + if (ENUM_TYPE.has(expectedType) && STRING_NUMBER_TYPE.has(actualType)) + return; + if (actualType !== expectedType) { + throw createError("INVALID_DOCUMENT_PROPERTY", key, expectedType, actualType); + } + } + async function indexAndSortDocument(orama, id, indexableProperties, indexableValues, docsCount, language, doc, options) { + for (const prop of indexableProperties) { + const value = indexableValues[prop]; + if (typeof value === "undefined") + continue; + const expectedType = orama.index.getSearchablePropertiesWithTypes(orama.data.index)[prop]; + await orama.index.beforeInsert?.(orama.data.index, prop, id, value, expectedType, language, orama.tokenizer, docsCount); + const internalId = orama.internalDocumentIDStore.idToInternalId.get(id); + await orama.index.insert(orama.index, orama.data.index, prop, id, internalId, value, expectedType, language, orama.tokenizer, docsCount, options); + await orama.index.afterInsert?.(orama.data.index, prop, id, value, expectedType, language, orama.tokenizer, docsCount); + } + const sortableProperties = orama.sorter.getSortableProperties(orama.data.sorting); + const sortableValues = orama.getDocumentProperties(doc, sortableProperties); + for (const prop of sortableProperties) { + const value = sortableValues[prop]; + if (typeof value === "undefined") + continue; + const expectedType = orama.sorter.getSortablePropertiesWithTypes(orama.data.sorting)[prop]; + orama.sorter.insert(orama.data.sorting, prop, id, value, expectedType, language); + } + } + function indexAndSortDocumentSync(orama, id, indexableProperties, indexableValues, docsCount, language, doc, options) { + for (const prop of indexableProperties) { + const value = indexableValues[prop]; + if (typeof value === "undefined") + continue; + const expectedType = orama.index.getSearchablePropertiesWithTypes(orama.data.index)[prop]; + const internalDocumentId = getInternalDocumentId(orama.internalDocumentIDStore, id); + orama.index.beforeInsert?.(orama.data.index, prop, id, value, expectedType, language, orama.tokenizer, docsCount); + orama.index.insert(orama.index, orama.data.index, prop, id, internalDocumentId, value, expectedType, language, orama.tokenizer, docsCount, options); + orama.index.afterInsert?.(orama.data.index, prop, id, value, expectedType, language, orama.tokenizer, docsCount); + } + const sortableProperties = orama.sorter.getSortableProperties(orama.data.sorting); + const sortableValues = orama.getDocumentProperties(doc, sortableProperties); + for (const prop of sortableProperties) { + const value = sortableValues[prop]; + if (typeof value === "undefined") + continue; + const expectedType = orama.sorter.getSortablePropertiesWithTypes(orama.data.sorting)[prop]; + orama.sorter.insert(orama.data.sorting, prop, id, value, expectedType, language); + } + } + + // node_modules/@orama/orama/dist/browser/constants.js + var MODE_FULLTEXT_SEARCH = "fulltext"; + var MODE_HYBRID_SEARCH = "hybrid"; + var MODE_VECTOR_SEARCH = "vector"; + + // node_modules/@orama/orama/dist/browser/components/facets.js + function sortAsc(a2, b3) { + return a2[1] - b3[1]; + } + function sortDesc(a2, b3) { + return b3[1] - a2[1]; + } + function sortingPredicateBuilder(order = "desc") { + return order.toLowerCase() === "asc" ? sortAsc : sortDesc; + } + function getFacets(orama, results, facetsConfig) { + const facets = {}; + const allIDs = results.map(([id]) => id); + const allDocs = orama.documentsStore.getMultiple(orama.data.docs, allIDs); + const facetKeys = Object.keys(facetsConfig); + const properties = orama.index.getSearchablePropertiesWithTypes(orama.data.index); + for (const facet of facetKeys) { + let values; + if (properties[facet] === "number") { + const { ranges } = facetsConfig[facet]; + const rangesLength = ranges.length; + const tmp = Array.from({ length: rangesLength }); + for (let i2 = 0; i2 < rangesLength; i2++) { + const range = ranges[i2]; + tmp[i2] = [`${range.from}-${range.to}`, 0]; + } + values = Object.fromEntries(tmp); + } + facets[facet] = { + count: 0, + values: values ?? {} + }; + } + const allDocsLength = allDocs.length; + for (let i2 = 0; i2 < allDocsLength; i2++) { + const doc = allDocs[i2]; + for (const facet of facetKeys) { + const facetValue = facet.includes(".") ? getNested(doc, facet) : doc[facet]; + const propertyType = properties[facet]; + const facetValues = facets[facet].values; + switch (propertyType) { + case "number": { + const ranges = facetsConfig[facet].ranges; + calculateNumberFacetBuilder(ranges, facetValues)(facetValue); + break; + } + case "number[]": { + const alreadyInsertedValues = /* @__PURE__ */ new Set(); + const ranges = facetsConfig[facet].ranges; + const calculateNumberFacet = calculateNumberFacetBuilder(ranges, facetValues, alreadyInsertedValues); + for (const v6 of facetValue) { + calculateNumberFacet(v6); + } + break; + } + case "boolean": + case "enum": + case "string": { + calculateBooleanStringOrEnumFacetBuilder(facetValues, propertyType)(facetValue); + break; + } + case "boolean[]": + case "enum[]": + case "string[]": { + const alreadyInsertedValues = /* @__PURE__ */ new Set(); + const innerType = propertyType === "boolean[]" ? "boolean" : "string"; + const calculateBooleanStringOrEnumFacet = calculateBooleanStringOrEnumFacetBuilder(facetValues, innerType, alreadyInsertedValues); + for (const v6 of facetValue) { + calculateBooleanStringOrEnumFacet(v6); + } + break; + } + default: + throw createError("FACET_NOT_SUPPORTED", propertyType); + } + } + } + for (const facet of facetKeys) { + const currentFacet = facets[facet]; + currentFacet.count = Object.keys(currentFacet.values).length; + if (properties[facet] === "string") { + const stringFacetDefinition = facetsConfig[facet]; + const sortingPredicate = sortingPredicateBuilder(stringFacetDefinition.sort); + currentFacet.values = Object.fromEntries(Object.entries(currentFacet.values).sort(sortingPredicate).slice(stringFacetDefinition.offset ?? 0, stringFacetDefinition.limit ?? 10)); + } + } + return facets; + } + function calculateNumberFacetBuilder(ranges, values, alreadyInsertedValues) { + return (facetValue) => { + for (const range of ranges) { + const value = `${range.from}-${range.to}`; + if (alreadyInsertedValues?.has(value)) { + continue; + } + if (facetValue >= range.from && facetValue <= range.to) { + if (values[value] === void 0) { + values[value] = 1; + } else { + values[value]++; + alreadyInsertedValues?.add(value); + } + } + } + }; + } + function calculateBooleanStringOrEnumFacetBuilder(values, propertyType, alreadyInsertedValues) { + const defaultValue = propertyType === "boolean" ? "false" : ""; + return (facetValue) => { + const value = facetValue?.toString() ?? defaultValue; + if (alreadyInsertedValues?.has(value)) { + return; + } + values[value] = (values[value] ?? 0) + 1; + alreadyInsertedValues?.add(value); + }; + } + + // node_modules/@orama/orama/dist/browser/components/groups.js + var DEFAULT_REDUCE = { + reducer: (_2, acc, res, index2) => { + acc[index2] = res; + return acc; + }, + getInitialValue: (length) => Array.from({ length }) + }; + var ALLOWED_TYPES = ["string", "number", "boolean"]; + function getGroups(orama, results, groupBy) { + const properties = groupBy.properties; + const propertiesLength = properties.length; + const schemaProperties = orama.index.getSearchablePropertiesWithTypes(orama.data.index); + for (let i2 = 0; i2 < propertiesLength; i2++) { + const property = properties[i2]; + if (typeof schemaProperties[property] === "undefined") { + throw createError("UNKNOWN_GROUP_BY_PROPERTY", property); + } + if (!ALLOWED_TYPES.includes(schemaProperties[property])) { + throw createError("INVALID_GROUP_BY_PROPERTY", property, ALLOWED_TYPES.join(", "), schemaProperties[property]); + } + } + const allIDs = results.map(([id]) => getDocumentIdFromInternalId(orama.internalDocumentIDStore, id)); + const allDocs = orama.documentsStore.getMultiple(orama.data.docs, allIDs); + const allDocsLength = allDocs.length; + const returnedCount = groupBy.maxResult || Number.MAX_SAFE_INTEGER; + const listOfValues = []; + const g2 = {}; + for (let i2 = 0; i2 < propertiesLength; i2++) { + const groupByKey = properties[i2]; + const group = { + property: groupByKey, + perValue: {} + }; + const values = /* @__PURE__ */ new Set(); + for (let j3 = 0; j3 < allDocsLength; j3++) { + const doc = allDocs[j3]; + const value = getNested(doc, groupByKey); + if (typeof value === "undefined") { + continue; + } + const keyValue = typeof value !== "boolean" ? value : "" + value; + const perValue = group.perValue[keyValue] ?? { + indexes: [], + count: 0 + }; + if (perValue.count >= returnedCount) { + continue; + } + perValue.indexes.push(j3); + perValue.count++; + group.perValue[keyValue] = perValue; + values.add(value); + } + listOfValues.push(Array.from(values)); + g2[groupByKey] = group; + } + const combinations = calculateCombination(listOfValues); + const combinationsLength = combinations.length; + const groups = []; + for (let i2 = 0; i2 < combinationsLength; i2++) { + const combination = combinations[i2]; + const combinationLength = combination.length; + const group = { + values: [], + indexes: [] + }; + const indexes = []; + for (let j3 = 0; j3 < combinationLength; j3++) { + const value = combination[j3]; + const property = properties[j3]; + indexes.push(g2[property].perValue[typeof value !== "boolean" ? value : "" + value].indexes); + group.values.push(value); + } + group.indexes = intersect(indexes).sort((a2, b3) => a2 - b3); + if (group.indexes.length === 0) { + continue; + } + groups.push(group); + } + const groupsLength = groups.length; + const res = Array.from({ length: groupsLength }); + for (let i2 = 0; i2 < groupsLength; i2++) { + const group = groups[i2]; + const reduce = groupBy.reduce || DEFAULT_REDUCE; + const docs = group.indexes.map((index2) => { + return { + id: allIDs[index2], + score: results[index2][1], + document: allDocs[index2] + }; + }); + const func = reduce.reducer.bind(null, group.values); + const initialValue = reduce.getInitialValue(group.indexes.length); + const aggregationValue = docs.reduce(func, initialValue); + res[i2] = { + values: group.values, + result: aggregationValue + }; + } + return res; + } + function calculateCombination(arrs, index2 = 0) { + if (index2 + 1 === arrs.length) + return arrs[index2].map((item) => [item]); + const head = arrs[index2]; + const c3 = calculateCombination(arrs, index2 + 1); + const combinations = []; + for (const value of head) { + for (const combination of c3) { + const result = [value]; + safeArrayPush(result, combination); + combinations.push(result); + } + } + return combinations; + } + + // node_modules/@orama/orama/dist/browser/components/pinning-manager.js + function applyPinningRules(orama, pinningStore, uniqueDocsArray, searchTerm) { + const matchingRules = getMatchingRules(pinningStore, searchTerm); + if (matchingRules.length === 0) { + return uniqueDocsArray; + } + const allPromotions = matchingRules.flatMap((rule) => rule.consequence.promote); + allPromotions.sort((a2, b3) => a2.position - b3.position); + const pinnedInternalIds = /* @__PURE__ */ new Set(); + const promotionsMap = /* @__PURE__ */ new Map(); + const positionsTaken = /* @__PURE__ */ new Set(); + for (const promotion of allPromotions) { + const internalId = getInternalDocumentId(orama.internalDocumentIDStore, promotion.doc_id); + if (internalId === void 0) { + continue; + } + if (promotionsMap.has(internalId)) { + const existingPosition = promotionsMap.get(internalId); + if (promotion.position < existingPosition) { + promotionsMap.set(internalId, promotion.position); + } + continue; + } + if (positionsTaken.has(promotion.position)) { + continue; + } + pinnedInternalIds.add(internalId); + promotionsMap.set(internalId, promotion.position); + positionsTaken.add(promotion.position); + } + if (promotionsMap.size === 0) { + return uniqueDocsArray; + } + const unpinnedResults = uniqueDocsArray.filter(([id]) => !pinnedInternalIds.has(id)); + const BASE_PIN_SCORE = 1e6; + const pinnedResults = []; + for (const [internalId, position] of promotionsMap.entries()) { + const existingResult = uniqueDocsArray.find(([id]) => id === internalId); + if (existingResult) { + pinnedResults.push([internalId, BASE_PIN_SCORE - position]); + } else { + const doc = orama.documentsStore.get(orama.data.docs, internalId); + if (doc) { + pinnedResults.push([internalId, 0]); + } + } + } + pinnedResults.sort((a2, b3) => { + const posA = promotionsMap.get(a2[0]) ?? Infinity; + const posB = promotionsMap.get(b3[0]) ?? Infinity; + return posA - posB; + }); + const finalResults = []; + const pinnedByPosition = /* @__PURE__ */ new Map(); + for (const pinnedResult of pinnedResults) { + const position = promotionsMap.get(pinnedResult[0]); + pinnedByPosition.set(position, pinnedResult); + } + let unpinnedIndex = 0; + let currentPosition = 0; + while (currentPosition < unpinnedResults.length + pinnedResults.length) { + if (pinnedByPosition.has(currentPosition)) { + finalResults.push(pinnedByPosition.get(currentPosition)); + currentPosition++; + } else if (unpinnedIndex < unpinnedResults.length) { + finalResults.push(unpinnedResults[unpinnedIndex]); + unpinnedIndex++; + currentPosition++; + } else { + break; + } + } + for (const [position, pinnedResult] of pinnedByPosition.entries()) { + if (position >= finalResults.length) { + finalResults.push(pinnedResult); + } + } + return finalResults; + } + + // node_modules/@orama/orama/dist/browser/methods/search-fulltext.js + function innerFullTextSearch(orama, params, language) { + const { term, properties } = params; + const index2 = orama.data.index; + let propertiesToSearch = orama.caches["propertiesToSearch"]; + if (!propertiesToSearch) { + const propertiesToSearchWithTypes = orama.index.getSearchablePropertiesWithTypes(index2); + propertiesToSearch = orama.index.getSearchableProperties(index2); + propertiesToSearch = propertiesToSearch.filter((prop) => propertiesToSearchWithTypes[prop].startsWith("string")); + orama.caches["propertiesToSearch"] = propertiesToSearch; + } + if (properties && properties !== "*") { + for (const prop of properties) { + if (!propertiesToSearch.includes(prop)) { + throw createError("UNKNOWN_INDEX", prop, propertiesToSearch.join(", ")); + } + } + propertiesToSearch = propertiesToSearch.filter((prop) => properties.includes(prop)); + } + const hasFilters = Object.keys(params.where ?? {}).length > 0; + let whereFiltersIDs; + if (hasFilters) { + whereFiltersIDs = orama.index.searchByWhereClause(index2, orama.tokenizer, params.where, language); + } + let uniqueDocsIDs; + const threshold = params.threshold !== void 0 && params.threshold !== null ? params.threshold : 1; + if (term || properties) { + const docsCount = count2(orama); + uniqueDocsIDs = orama.index.search(index2, term || "", orama.tokenizer, language, propertiesToSearch, params.exact || false, params.tolerance || 0, params.boost || {}, applyDefault(params.relevance), docsCount, whereFiltersIDs, threshold); + if (params.exact && term) { + const searchTerms = term.trim().split(/\s+/); + uniqueDocsIDs = uniqueDocsIDs.filter(([docId]) => { + const doc = orama.documentsStore.get(orama.data.docs, docId); + if (!doc) + return false; + for (const prop of propertiesToSearch) { + const propValue = getPropValue(doc, prop); + if (typeof propValue === "string") { + const hasAllTerms = searchTerms.every((searchTerm) => { + const regex2 = new RegExp(`\\b${escapeRegex(searchTerm)}\\b`); + return regex2.test(propValue); + }); + if (hasAllTerms) { + return true; + } + } + } + return false; + }); + } + } else { + if (hasFilters) { + const geoResults = searchByGeoWhereClause(index2, params.where); + if (geoResults) { + uniqueDocsIDs = geoResults; + } else { + const docIds = whereFiltersIDs ? Array.from(whereFiltersIDs) : []; + uniqueDocsIDs = docIds.map((k3) => [+k3, 0]); + } + } else { + const docIds = Object.keys(orama.documentsStore.getAll(orama.data.docs)); + uniqueDocsIDs = docIds.map((k3) => [+k3, 0]); + } + } + return uniqueDocsIDs; + } + function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + } + function getPropValue(obj, path) { + const keys = path.split("."); + let value = obj; + for (const key of keys) { + if (value && typeof value === "object" && key in value) { + value = value[key]; + } else { + return void 0; + } + } + return value; + } + function fullTextSearch(orama, params, language) { + const timeStart = getNanosecondsTime(); + function performSearchLogic() { + const vectorProperties = Object.keys(orama.data.index.vectorIndexes); + const shouldCalculateFacets = params.facets && Object.keys(params.facets).length > 0; + const { limit = 10, offset = 0, distinctOn, includeVectors = false } = params; + const isPreflight = params.preflight === true; + let uniqueDocsArray = innerFullTextSearch(orama, params, language); + if (params.sortBy) { + if (typeof params.sortBy === "function") { + const ids = uniqueDocsArray.map(([id]) => id); + const docs = orama.documentsStore.getMultiple(orama.data.docs, ids); + const docsWithIdAndScore = docs.map((d3, i2) => [ + uniqueDocsArray[i2][0], + uniqueDocsArray[i2][1], + d3 + ]); + docsWithIdAndScore.sort(params.sortBy); + uniqueDocsArray = docsWithIdAndScore.map(([id, score]) => [id, score]); + } else { + uniqueDocsArray = orama.sorter.sortBy(orama.data.sorting, uniqueDocsArray, params.sortBy).map(([id, score]) => [getInternalDocumentId(orama.internalDocumentIDStore, id), score]); + } + } else { + uniqueDocsArray = uniqueDocsArray.sort(sortTokenScorePredicate); + } + uniqueDocsArray = applyPinningRules(orama, orama.data.pinning, uniqueDocsArray, params.term); + let results; + if (!isPreflight) { + results = distinctOn ? fetchDocumentsWithDistinct(orama, uniqueDocsArray, offset, limit, distinctOn) : fetchDocuments(orama, uniqueDocsArray, offset, limit); + } + const searchResult = { + elapsed: { + formatted: "", + raw: 0 + }, + hits: [], + count: uniqueDocsArray.length + }; + if (typeof results !== "undefined") { + searchResult.hits = results.filter(Boolean); + if (!includeVectors) { + removeVectorsFromHits(searchResult, vectorProperties); + } + } + if (shouldCalculateFacets) { + const facets = getFacets(orama, uniqueDocsArray, params.facets); + searchResult.facets = facets; + } + if (params.groupBy) { + searchResult.groups = getGroups(orama, uniqueDocsArray, params.groupBy); + } + searchResult.elapsed = orama.formatElapsedTime(getNanosecondsTime() - timeStart); + return searchResult; + } + async function executeSearchAsync() { + if (orama.beforeSearch) { + await runBeforeSearch(orama.beforeSearch, orama, params, language); + } + const searchResult = performSearchLogic(); + if (orama.afterSearch) { + await runAfterSearch(orama.afterSearch, orama, params, language, searchResult); + } + return searchResult; + } + const asyncNeeded = orama.beforeSearch?.length || orama.afterSearch?.length; + if (asyncNeeded) { + return executeSearchAsync(); + } + return performSearchLogic(); + } + var defaultBM25Params = { + k: 1.2, + b: 0.75, + d: 0.5 + }; + function applyDefault(bm25Relevance) { + const r2 = bm25Relevance ?? {}; + r2.k = r2.k ?? defaultBM25Params.k; + r2.b = r2.b ?? defaultBM25Params.b; + r2.d = r2.d ?? defaultBM25Params.d; + return r2; + } + + // node_modules/@orama/orama/dist/browser/methods/search-vector.js + function innerVectorSearch(orama, params, language) { + const vector = params.vector; + if (vector && (!("value" in vector) || !("property" in vector))) { + throw createError("INVALID_VECTOR_INPUT", Object.keys(vector).join(", ")); + } + const vectorIndex = orama.data.index.vectorIndexes[vector.property]; + if (!vectorIndex) { + throw createError("UNKNOWN_VECTOR_PROPERTY", vector.property); + } + const vectorSize = vectorIndex.node.size; + if (vector?.value.length !== vectorSize) { + if (vector?.property === void 0 || vector?.value.length === void 0) { + throw createError("INVALID_INPUT_VECTOR", "undefined", vectorSize, "undefined"); + } + throw createError("INVALID_INPUT_VECTOR", vector.property, vectorSize, vector.value.length); + } + const index2 = orama.data.index; + let whereFiltersIDs; + const hasFilters = Object.keys(params.where ?? {}).length > 0; + if (hasFilters) { + whereFiltersIDs = orama.index.searchByWhereClause(index2, orama.tokenizer, params.where, language); + } + return vectorIndex.node.find(vector.value, params.similarity ?? DEFAULT_SIMILARITY, whereFiltersIDs); + } + function searchVector(orama, params, language = "english") { + const timeStart = getNanosecondsTime(); + function performSearchLogic() { + let results = innerVectorSearch(orama, params, language).sort(sortTokenScorePredicate); + results = applyPinningRules(orama, orama.data.pinning, results, void 0); + let facetsResults = []; + const shouldCalculateFacets = params.facets && Object.keys(params.facets).length > 0; + if (shouldCalculateFacets) { + const facets = getFacets(orama, results, params.facets); + facetsResults = facets; + } + const vectorProperty = params.vector.property; + const includeVectors = params.includeVectors ?? false; + const limit = params.limit ?? 10; + const offset = params.offset ?? 0; + const docs = Array.from({ length: limit }); + for (let i2 = 0; i2 < limit; i2++) { + const result = results[i2 + offset]; + if (!result) { + break; + } + const doc = orama.data.docs.docs[result[0]]; + if (doc) { + if (!includeVectors) { + doc[vectorProperty] = null; + } + const newDoc = { + id: getDocumentIdFromInternalId(orama.internalDocumentIDStore, result[0]), + score: result[1], + document: doc + }; + docs[i2] = newDoc; + } + } + let groups = []; + if (params.groupBy) { + groups = getGroups(orama, results, params.groupBy); + } + const timeEnd = getNanosecondsTime(); + const elapsedTime = timeEnd - timeStart; + return { + count: results.length, + hits: docs.filter(Boolean), + elapsed: { + raw: Number(elapsedTime), + formatted: formatNanoseconds(elapsedTime) + }, + ...facetsResults ? { facets: facetsResults } : {}, + ...groups ? { groups } : {} + }; + } + async function executeSearchAsync() { + if (orama.beforeSearch) { + await runBeforeSearch(orama.beforeSearch, orama, params, language); + } + const results = performSearchLogic(); + if (orama.afterSearch) { + await runAfterSearch(orama.afterSearch, orama, params, language, results); + } + return results; + } + const asyncNeeded = orama.beforeSearch?.length || orama.afterSearch?.length; + if (asyncNeeded) { + return executeSearchAsync(); + } + return performSearchLogic(); + } + + // node_modules/@orama/orama/dist/browser/methods/search-hybrid.js + function innerHybridSearch(orama, params, language) { + const fullTextIDs = minMaxScoreNormalization(innerFullTextSearch(orama, params, language)); + const vectorIDs = innerVectorSearch(orama, params, language); + const hybridWeights = params.hybridWeights; + return mergeAndRankResults(fullTextIDs, vectorIDs, params.term ?? "", hybridWeights); + } + function hybridSearch(orama, params, language) { + const timeStart = getNanosecondsTime(); + function performSearchLogic() { + let uniqueTokenScores = innerHybridSearch(orama, params, language); + uniqueTokenScores = applyPinningRules(orama, orama.data.pinning, uniqueTokenScores, params.term); + let facetsResults; + const shouldCalculateFacets = params.facets && Object.keys(params.facets).length > 0; + if (shouldCalculateFacets) { + facetsResults = getFacets(orama, uniqueTokenScores, params.facets); + } + let groups; + if (params.groupBy) { + groups = getGroups(orama, uniqueTokenScores, params.groupBy); + } + const offset = params.offset ?? 0; + const limit = params.limit ?? 10; + const results = fetchDocuments(orama, uniqueTokenScores, offset, limit).filter(Boolean); + const timeEnd = getNanosecondsTime(); + const returningResults = { + count: uniqueTokenScores.length, + elapsed: { + raw: Number(timeEnd - timeStart), + formatted: formatNanoseconds(timeEnd - timeStart) + }, + hits: results, + ...facetsResults ? { facets: facetsResults } : {}, + ...groups ? { groups } : {} + }; + const includeVectors = params.includeVectors ?? false; + if (!includeVectors) { + const vectorProperties = Object.keys(orama.data.index.vectorIndexes); + removeVectorsFromHits(returningResults, vectorProperties); + } + return returningResults; + } + async function executeSearchAsync() { + if (orama.beforeSearch) { + await runBeforeSearch(orama.beforeSearch, orama, params, language); + } + const results = performSearchLogic(); + if (orama.afterSearch) { + await runAfterSearch(orama.afterSearch, orama, params, language, results); + } + return results; + } + const asyncNeeded = orama.beforeSearch?.length || orama.afterSearch?.length; + if (asyncNeeded) { + return executeSearchAsync(); + } + return performSearchLogic(); + } + function extractScore(token) { + return token[1]; + } + function minMaxScoreNormalization(results) { + const maxScore = Math.max.apply(Math, results.map(extractScore)); + return results.map(([id, score]) => [id, score / maxScore]); + } + function normalizeScore(score, maxScore) { + return score / maxScore; + } + function hybridScoreBuilder(textWeight, vectorWeight) { + return (textScore, vectorScore) => textScore * textWeight + vectorScore * vectorWeight; + } + function mergeAndRankResults(textResults, vectorResults, query, hybridWeights) { + const maxTextScore = Math.max.apply(Math, textResults.map(extractScore)); + const maxVectorScore = Math.max.apply(Math, vectorResults.map(extractScore)); + const hasHybridWeights = hybridWeights && hybridWeights.text && hybridWeights.vector; + const { text: textWeight, vector: vectorWeight } = hasHybridWeights ? hybridWeights : getQueryWeights(query); + const mergedResults = /* @__PURE__ */ new Map(); + const textResultsLength = textResults.length; + const hybridScore = hybridScoreBuilder(textWeight, vectorWeight); + for (let i2 = 0; i2 < textResultsLength; i2++) { + const [id, score] = textResults[i2]; + const normalizedScore = normalizeScore(score, maxTextScore); + const hybridScoreValue = hybridScore(normalizedScore, 0); + mergedResults.set(id, hybridScoreValue); + } + const vectorResultsLength = vectorResults.length; + for (let i2 = 0; i2 < vectorResultsLength; i2++) { + const [resultId, score] = vectorResults[i2]; + const normalizedScore = normalizeScore(score, maxVectorScore); + const existingRes = mergedResults.get(resultId) ?? 0; + mergedResults.set(resultId, existingRes + hybridScore(0, normalizedScore)); + } + return [...mergedResults].sort((a2, b3) => b3[1] - a2[1]); + } + function getQueryWeights(query) { + return { + text: 0.5, + vector: 0.5 + }; + } + + // node_modules/@orama/orama/dist/browser/methods/search.js + function search2(orama, params, language) { + const mode = params.mode ?? MODE_FULLTEXT_SEARCH; + if (mode === MODE_FULLTEXT_SEARCH) { + return fullTextSearch(orama, params, language); + } + if (mode === MODE_VECTOR_SEARCH) { + return searchVector(orama, params); + } + if (mode === MODE_HYBRID_SEARCH) { + return hybridSearch(orama, params); + } + throw createError("INVALID_SEARCH_MODE", mode); + } + function fetchDocumentsWithDistinct(orama, uniqueDocsArray, offset, limit, distinctOn) { + const docs = orama.data.docs; + const values = /* @__PURE__ */ new Map(); + const results = []; + const resultIDs = /* @__PURE__ */ new Set(); + const uniqueDocsArrayLength = uniqueDocsArray.length; + let count3 = 0; + for (let i2 = 0; i2 < uniqueDocsArrayLength; i2++) { + const idAndScore = uniqueDocsArray[i2]; + if (typeof idAndScore === "undefined") { + continue; + } + const [id, score] = idAndScore; + if (resultIDs.has(id)) { + continue; + } + const doc = orama.documentsStore.get(docs, id); + const value = getNested(doc, distinctOn); + if (typeof value === "undefined" || values.has(value)) { + continue; + } + values.set(value, true); + count3++; + if (count3 <= offset) { + continue; + } + results.push({ id: getDocumentIdFromInternalId(orama.internalDocumentIDStore, id), score, document: doc }); + resultIDs.add(id); + if (count3 >= offset + limit) { + break; + } + } + return results; + } + function fetchDocuments(orama, uniqueDocsArray, offset, limit) { + const docs = orama.data.docs; + const results = Array.from({ + length: limit + }); + const resultIDs = /* @__PURE__ */ new Set(); + for (let i2 = offset; i2 < limit + offset; i2++) { + const idAndScore = uniqueDocsArray[i2]; + if (typeof idAndScore === "undefined") { + break; + } + const [id, score] = idAndScore; + if (!resultIDs.has(id)) { + const fullDoc = orama.documentsStore.get(docs, id); + results[i2] = { id: getDocumentIdFromInternalId(orama.internalDocumentIDStore, id), score, document: fullDoc }; + resultIDs.add(id); + } + } + return results; + } + + // node_modules/@orama/orama/dist/browser/methods/serialization.js + function load6(orama, raw) { + orama.internalDocumentIDStore.load(orama, raw.internalDocumentIDStore); + orama.data.index = orama.index.load(orama.internalDocumentIDStore, raw.index); + orama.data.docs = orama.documentsStore.load(orama.internalDocumentIDStore, raw.docs); + orama.data.sorting = orama.sorter.load(orama.internalDocumentIDStore, raw.sorting); + orama.data.pinning = orama.pinning.load(orama.internalDocumentIDStore, raw.pinning); + orama.tokenizer.language = raw.language; + } + function save6(orama) { + return { + internalDocumentIDStore: orama.internalDocumentIDStore.save(orama.internalDocumentIDStore), + index: orama.index.save(orama.data.index), + docs: orama.documentsStore.save(orama.data.docs), + sorting: orama.sorter.save(orama.data.sorting), + pinning: orama.pinning.save(orama.data.pinning), + language: orama.tokenizer.language + }; + } + + // node_modules/@orama/orama/dist/browser/types.js + var kInsertions = Symbol("orama.insertions"); + var kRemovals = Symbol("orama.removals"); + + // src/services/historyVectorStore.ts + var IDB_NAME = "oasis-semantic-search"; + var IDB_STORE = "vector-index"; + var IDB_KEY_SNAPSHOT = "orama-snapshot"; + var IDB_KEY_URLS = "indexed-urls"; + var HistoryVectorStore = class { + db = null; + async init() { + if (this.db) return; + this.db = create6({ + schema: { + title: "string", + url: "string", + snippet: "string", + visitDate: "number", + embedding: `vector[${VECTOR_DIMENSIONS}]` + } + }); + console.log("[HistoryVectorStore] Orama DB created"); + } + async addItem(item) { + await this.init(); + await insert3(this.db, { + title: item.title, + url: item.url, + snippet: item.snippet, + visitDate: item.visitDate, + embedding: item.embedding + }); + } + async search(queryEmbedding, limit = 10, minSimilarity = 0.15) { + await this.init(); + const results = await search2(this.db, { + mode: "vector", + vector: { + value: queryEmbedding, + property: "embedding" + }, + similarity: minSimilarity, + limit, + includeVectors: false + }); + return results.hits.map((hit) => ({ + title: hit.document.title, + url: hit.document.url, + snippet: hit.document.snippet, + visitDate: hit.document.visitDate, + score: hit.score + })); + } + async hybridSearch(queryText, queryEmbedding, limit = 10) { + await this.init(); + try { + const results = await search2(this.db, { + mode: "hybrid", + term: queryText, + vector: { + value: queryEmbedding, + property: "embedding" + }, + similarity: 0.1, + limit, + includeVectors: false, + hybridWeights: { + text: 0.4, + vector: 0.6 + } + }); + return results.hits.map((hit) => ({ + title: hit.document.title, + url: hit.document.url, + snippet: hit.document.snippet, + visitDate: hit.document.visitDate, + score: hit.score + })); + } catch (err) { + console.warn("[HistoryVectorStore] Hybrid search failed, falling back to vector:", err); + return this.search(queryEmbedding, limit, 0.1); + } + } + async keywordSearch(queryText, limit = 10) { + await this.init(); + try { + const results = await search2(this.db, { + mode: "fulltext", + term: queryText, + limit, + includeVectors: false + }); + return results.hits.map((hit) => ({ + title: hit.document.title, + url: hit.document.url, + snippet: hit.document.snippet, + visitDate: hit.document.visitDate, + score: hit.score + })); + } catch (err) { + console.warn("[HistoryVectorStore] Keyword search failed:", err); + return []; + } + } + async getCount() { + await this.init(); + return count2(this.db); + } + async clear() { + this.db = null; + await this.init(); + } + // ─── IndexedDB Persistence ───────────────────────────────── + /** + * Save the current Orama DB state + indexed URLs to IndexedDB. + */ + async saveToStorage(indexedUrls) { + if (!this.db) return; + try { + const snapshot = save6(this.db); + const snapshotJson = JSON.stringify(snapshot); + const urlsJson = JSON.stringify([...indexedUrls]); + await this.idbPut(IDB_KEY_SNAPSHOT, snapshotJson); + await this.idbPut(IDB_KEY_URLS, urlsJson); + console.log( + `[HistoryVectorStore] Saved to IndexedDB (${(snapshotJson.length / 1024).toFixed(1)} KB snapshot, ${indexedUrls.size} URLs)` + ); + } catch (err) { + console.warn("[HistoryVectorStore] Failed to save to IndexedDB:", err); + } + } + /** + * Restore the Orama DB + indexed URLs from IndexedDB. + * Returns the set of indexed URLs if restore was successful, null if not. + */ + async restoreFromStorage() { + try { + const snapshotJson = await this.idbGet(IDB_KEY_SNAPSHOT); + const urlsJson = await this.idbGet(IDB_KEY_URLS); + if (!snapshotJson) { + console.log("[HistoryVectorStore] No saved data in IndexedDB"); + return null; + } + await this.init(); + const snapshot = JSON.parse(snapshotJson); + load6(this.db, snapshot); + const itemCount = await count2(this.db); + console.log( + `[HistoryVectorStore] Restored ${itemCount} entries from IndexedDB` + ); + const urls = urlsJson ? new Set(JSON.parse(urlsJson)) : /* @__PURE__ */ new Set(); + return urls; + } catch (err) { + console.warn("[HistoryVectorStore] Failed to restore from IndexedDB:", err); + this.db = null; + return null; + } + } + /** + * Clear the persisted data from IndexedDB. + */ + async clearStorage() { + try { + await this.idbDelete(IDB_KEY_SNAPSHOT); + await this.idbDelete(IDB_KEY_URLS); + console.log("[HistoryVectorStore] Cleared IndexedDB storage"); + } catch (err) { + console.warn("[HistoryVectorStore] Failed to clear IndexedDB:", err); + } + } + // ─── IndexedDB Helpers ───────────────────────────────────── + openIDB() { + return new Promise((resolve, reject) => { + if (typeof indexedDB === "undefined" || !indexedDB) { + reject(new Error("IndexedDB not available")); + return; + } + const request = indexedDB.open(IDB_NAME, 1); + request.onupgradeneeded = () => { + if (!request.result.objectStoreNames.contains(IDB_STORE)) { + request.result.createObjectStore(IDB_STORE); + } + }; + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); + } + async idbPut(key, value) { + const db = await this.openIDB(); + return new Promise((resolve, reject) => { + const tx = db.transaction(IDB_STORE, "readwrite"); + tx.objectStore(IDB_STORE).put(value, key); + tx.oncomplete = () => { + db.close(); + resolve(); + }; + tx.onerror = () => { + db.close(); + reject(tx.error); + }; + }); + } + async idbGet(key) { + const db = await this.openIDB(); + return new Promise((resolve, reject) => { + const tx = db.transaction(IDB_STORE, "readonly"); + const getReq = tx.objectStore(IDB_STORE).get(key); + getReq.onsuccess = () => { + db.close(); + resolve(getReq.result || null); + }; + getReq.onerror = () => { + db.close(); + reject(getReq.error); + }; + }); + } + async idbDelete(key) { + const db = await this.openIDB(); + return new Promise((resolve, reject) => { + const tx = db.transaction(IDB_STORE, "readwrite"); + tx.objectStore(IDB_STORE).delete(key); + tx.oncomplete = () => { + db.close(); + resolve(); + }; + tx.onerror = () => { + db.close(); + reject(tx.error); + }; + }); + } + }; + var historyVectorStore = new HistoryVectorStore(); + + // src/services/semanticHistorySearch.ts + var MAX_HISTORY_ENTRIES = 500; + function buildEmbeddingText(title, url, snippet) { + if (snippet) { + return `${title} ${snippet}`; + } + try { + const parsed = new URL(url); + const domain = parsed.hostname.replace(/^www\./, ""); + const pathWords = parsed.pathname.split(/[\/\-_.]/).filter((w3) => w3.length > 2 && !/^[0-9a-f]{8,}$/i.test(w3)).join(" "); + const searchParams = parsed.searchParams.get("q") || parsed.searchParams.get("query") || ""; + return `${title} ${domain} ${pathWords} ${searchParams}`.replace(/\s+/g, " ").trim(); + } catch { + return `${title} ${url}`; + } + } + function mergeSearchResults(primary, secondary, limit) { + const seen = new Set(primary.map((r2) => r2.url)); + const merged = [...primary]; + for (const result of secondary) { + if (!seen.has(result.url)) { + merged.push(result); + seen.add(result.url); + } + } + return merged.slice(0, limit); + } + var SemanticHistorySearch = class { + indexed = false; + indexingPromise = null; + indexedUrls = /* @__PURE__ */ new Set(); + // Track what's already indexed + lastIndexTime = 0; + // Timestamp of last indexing + /** + * Ensure history is indexed. On first call, tries to restore from + * IndexedDB. If no saved data, does a full index. On subsequent + * calls, incrementally indexes only NEW entries. + */ + async ensureIndexed() { + if (this.indexingPromise) { + await this.indexingPromise; + return; + } + if (!this.indexed) { + this.indexingPromise = this.tryRestoreOrFullIndex(); + try { + await this.indexingPromise; + } finally { + this.indexingPromise = null; + } + return; + } + this.indexingPromise = this.doIncrementalIndex(); + try { + await this.indexingPromise; + } finally { + this.indexingPromise = null; + } + } + /** + * Try to restore from IndexedDB first. If no saved data, do full index. + * After indexing, save to IndexedDB for next session. + */ + async tryRestoreOrFullIndex() { + console.log("[SemanticSearch] Checking IndexedDB for saved index..."); + console.time("[SemanticSearch] Restore from IndexedDB"); + const restoredUrls = await historyVectorStore.restoreFromStorage(); + if (restoredUrls && restoredUrls.size > 0) { + console.timeEnd("[SemanticSearch] Restore from IndexedDB"); + this.indexedUrls = restoredUrls; + this.indexed = true; + console.log(`[SemanticSearch] \u2705 Restored ${restoredUrls.size} entries from IndexedDB \u2014 skipping full index`); + await this.doIncrementalIndex(); + return; + } + console.timeEnd("[SemanticSearch] Restore from IndexedDB"); + console.log("[SemanticSearch] No saved index found \u2014 starting full index"); + await this.doFullIndex(); + await this.persistToStorage(); + } + /** + * Full index — happens on first search when no saved data exists. + */ + async doFullIndex() { + console.log("[SemanticSearch] Starting full history indexing..."); + console.time("[SemanticSearch] Total indexing time"); + try { + const entries2 = await fetchRecentHistory(MAX_HISTORY_ENTRIES, true); + if (entries2.length === 0) { + console.warn("[SemanticSearch] No history entries found to index"); + this.indexed = true; + return; + } + console.log( + `[SemanticSearch] Generating embeddings for ${entries2.length} entries...` + ); + let successCount = 0; + for (let i2 = 0; i2 < entries2.length; i2++) { + const entry = entries2[i2]; + try { + const textToEmbed = buildEmbeddingText(entry.title, entry.url, entry.snippet); + const embedding = await embeddingService.embed(textToEmbed); + await historyVectorStore.addItem({ + title: entry.title, + url: entry.url, + snippet: entry.snippet || entry.title, + visitDate: entry.visitDate, + embedding + }); + this.indexedUrls.add(entry.url); + successCount++; + if ((i2 + 1) % 50 === 0) { + console.log( + `[SemanticSearch] Indexed ${i2 + 1}/${entries2.length} entries...` + ); + } + } catch (err) { + console.warn( + `[SemanticSearch] Failed to embed entry "${entry.title}":`, + err + ); + } + } + const dbCount = await historyVectorStore.getCount(); + console.timeEnd("[SemanticSearch] Total indexing time"); + console.log( + `[SemanticSearch] Indexing complete. ${successCount}/${entries2.length} entries indexed (${dbCount} in DB)` + ); + this.indexed = true; + this.lastIndexTime = Date.now(); + } catch (err) { + console.error("[SemanticSearch] Indexing failed:", err); + throw err; + } + } + /** + * Incremental index — only embed entries not already in the index. + * Runs quickly since it only processes new pages visited since last index. + * Saves to IndexedDB if new entries were added. + */ + async doIncrementalIndex() { + try { + const entries2 = await fetchRecentHistory(MAX_HISTORY_ENTRIES, false); + const newUrls = entries2.filter((e2) => !this.indexedUrls.has(e2.url)); + if (newUrls.length === 0) { + return; + } + const newEntries = await Promise.all( + newUrls.map(async (entry) => { + try { + const response = await fetch(entry.url, { + signal: AbortSignal.timeout(5e3), + headers: { "Accept": "text/html" } + }); + if (!response.ok) return entry; + const ct = response.headers.get("content-type") || ""; + if (!ct.includes("text/html")) return entry; + const html2 = await response.text(); + entry.snippet = html2.replace(/]*>[\s\S]*?<\/script>/gi, "").replace(/]*>[\s\S]*?<\/style>/gi, "").replace(/]*>[\s\S]*?<\/nav>/gi, "").replace(/]*>[\s\S]*?<\/header>/gi, "").replace(/]*>[\s\S]*?<\/footer>/gi, "").replace(/<[^>]+>/g, " ").replace(/&[a-zA-Z]+;/g, " ").replace(/\s+/g, " ").trim().substring(0, 1e3); + } catch { + } + return entry; + }) + ); + console.log( + `[SemanticSearch] Incremental update: ${newEntries.length} new entries to index` + ); + let successCount = 0; + for (const entry of newEntries) { + try { + const textToEmbed = buildEmbeddingText(entry.title, entry.url, entry.snippet); + const embedding = await embeddingService.embed(textToEmbed); + await historyVectorStore.addItem({ + title: entry.title, + url: entry.url, + snippet: entry.snippet || entry.title, + visitDate: entry.visitDate, + embedding + }); + this.indexedUrls.add(entry.url); + successCount++; + } catch (err) { + console.warn( + `[SemanticSearch] Failed to embed entry "${entry.title}":`, + err + ); + } + } + const dbCount = await historyVectorStore.getCount(); + console.log( + `[SemanticSearch] Incremental update done. ${successCount} new entries added (${dbCount} total in DB)` + ); + this.lastIndexTime = Date.now(); + if (successCount > 0) { + await this.persistToStorage(); + } + } catch (err) { + console.error("[SemanticSearch] Incremental indexing failed:", err); + } + } + /** + * Save current state to IndexedDB for persistence across restarts. + */ + async persistToStorage() { + try { + await historyVectorStore.saveToStorage(this.indexedUrls); + } catch (err) { + console.warn("[SemanticSearch] Failed to persist to storage:", err); + } + } + async search(query, limit = 10) { + await this.ensureIndexed(); + console.time("[SemanticSearch] Search"); + const queryEmbedding = await embeddingService.embed(query); + let results = await historyVectorStore.hybridSearch(query, queryEmbedding, limit); + if (results.length === 0) { + console.log("[SemanticSearch] Hybrid returned 0 \u2014 trying keyword fallback"); + const keywordResults = await historyVectorStore.keywordSearch(query, limit); + results = mergeSearchResults(results, keywordResults, limit); + } + if (results.length === 0) { + console.log("[SemanticSearch] Still 0 \u2014 trying pure vector with low threshold"); + const vectorResults = await historyVectorStore.search(queryEmbedding, limit, 0.05); + results = mergeSearchResults(results, vectorResults, limit); + } + console.timeEnd("[SemanticSearch] Search"); + console.log( + `[SemanticSearch] Found ${results.length} results for "${query}"` + ); + return results; + } + async reindex() { + this.indexed = false; + this.indexedUrls.clear(); + await historyVectorStore.clear(); + await historyVectorStore.clearStorage(); + await this.ensureIndexed(); + } + isReady() { + return this.indexed; + } + }; + var semanticHistorySearch = new SemanticHistorySearch(); + window.semanticHistorySearch = semanticHistorySearch; + + // src/utils/searchMemoryUtils.ts + function hasBookmarkFolderCandidates(results) { + return results.some((r2) => { + const rawType = String(r2.metadata?.type || "").toLowerCase(); + return isBookmarkFolderType(rawType); + }); + } + function buildFolderUrlMap(folders) { + const folderToUrls = /* @__PURE__ */ new Map(); + for (const folder of folders) { + const name = normalizeMemoryName(folder?.name || ""); + if (!name) continue; + const urls = /* @__PURE__ */ new Set(); + for (const item of folder.items || []) { + const url = String(item?.url || "").trim(); + if (url) urls.add(url); + } + folderToUrls.set(name, urls); + } + return folderToUrls; + } + function filterStaleBookmarkFolderResults(results, folderToUrls) { + let dropped = 0; + const filtered = results.filter((result) => { + if (getMemoryDocSource(result) !== "bookmark-folder") { + return true; + } + const folderName = getMemoryDocFolderName(result); + const folderUrls = folderToUrls.get(folderName); + if (!folderUrls) { + dropped++; + return false; + } + const url = getMemoryDocUrl(result); + if (!url) { + return true; + } + if (!folderUrls.has(url)) { + dropped++; + return false; + } + return true; + }); + return { results: filtered, dropped }; + } + + // src/utils/intentParser.ts + var ACTION_WORD_RE = /\b(?:open|close|delete|remove|create|make|new|add|save|move|put|rename|list|show|search|find|summarize|split|organize|copy)\b/i; + var ACTION_OBJECT_RE = /\b(?:tab|tabs|group|folder|bookmark|window|history|memory|page|url|result|split)\b/i; + var LIST_VERB_RE = /^list\b/i; + var SHOW_VERB_RE = /^show\b/i; + var LIST_OBJECT_RE = /\b(?:tabs?|tab\s*groups?|groups?|bookmark\s*folders?|folders?|hubs?)\b/i; + var SEARCH_FAMILY_RE = /^(?:search|find|look\s*up)\b|^have\s+i\s+(?:visited|been\s+to|seen|saved|bookmarked|read|looked\s+at)\b|^do\s+i\s+have\b|^what(?:'s|\s+is|\s+did\s+i\s+(?:save|read|visit|look\s+at|browse))\s+/i; + var HISTORY_FAMILY_RE = /\b(?:visited|browsed|looked\s+at|read|viewed)\b.*\b(?:page|pages|site|sites|article|articles|earlier|before|recently|yesterday|last\s+week|previously)\b|\b(?:page|pages|site|sites|article|articles)\s+(?:i|i've|i\s+have)\s+(?:visited|read|seen|looked\s+at|browsed|viewed)\b|\b(?:pull|get|find|show)\s+that\s+(?:page|article|site)\b|\bwhat\s+(?:was|were|is)\s+that\s+.{2,}\s+(?:i\s+was|i've\s+been)\s+(?:reading|looking\s+at|browsing|viewing)\b|\b(?:my|the)\s+(?:browsing\s+)?history\b|\bpages\s+(?:i(?:'ve)?\s+)?visited\b|\bwhat\s+(?:did\s+i|have\s+i)\s+(?:visit|read|browse|look\s+at|view)\b/i; + var MUTATION_FAMILY_RE = /^(?:add|save|move|put|close|delete|remove|rename|create|make|split|unsplit|ungroup)\b/i; + var GROUP_LABEL_RE = /\btab\s*group\b|\bgroup\b/i; + var FOLDER_LABEL_RE = /\bbookmark\s*folder\b|\bfolder\b|\bhub\b|\bbookmarks?\b/i; + var GENERIC_FOLDER_NAME_RE = /^(?:bookmark(?:\s+folders?)?|folders?|hubs?)$/i; + function cleanCaptured(text2) { + return String(text2 || "").replace(/["']/g, "").replace(/^\s*(?:my|the)\s+/i, "").trim(); + } + function extractContainerType(text2) { + const hasGroup = GROUP_LABEL_RE.test(text2); + const hasFolder = FOLDER_LABEL_RE.test(text2); + if (hasGroup && hasFolder) { + return null; + } + if (hasGroup) { + return "tab-group"; + } + if (hasFolder) { + return "bookmark-folder"; + } + return null; + } + function extractTargetName(raw) { + let name = cleanCaptured(raw); + name = name.replace(/^bookmark\s+folder\s+/i, ""); + name = name.replace(/^bookmarks?\s+/i, ""); + name = name.replace(/^tab\s*group\s+/i, ""); + name = name.replace(/^folder\s+/i, ""); + name = name.replace(/^hub\s+/i, ""); + name = name.replace(/^group\s+/i, ""); + name = name.replace(/\s+bookmarks?\s*$/i, ""); + name = name.replace(/\s+bookmark\s+folder\s*$/i, ""); + name = name.replace(/\s+tab\s*group\s*$/i, ""); + name = name.replace(/\s+folder\s*$/i, ""); + name = name.replace(/\s+hub\s*$/i, ""); + name = name.replace(/\s+group\s*$/i, ""); + return name.trim(); + } + function isNonContainerTarget(rawTarget) { + return /\bnew\s+window\b|\bwindow\b|\bsplit\s*view\b/i.test(rawTarget); + } + function looksActionableText(text2) { + const input = String(text2 || ""); + return ACTION_WORD_RE.test(input) && ACTION_OBJECT_RE.test(input); + } + var LIST_OPEN_TABS_QUESTION_RE = /^(?:what|which)\s+tabs\b|\btabs\s+do\s+i\s+have\s+open\b|\btabs\s+are\s+open\b/i; + function classifyCommandFamily(commandText) { + const input = String(commandText || "").trim(); + if (!input) { + return "other"; + } + if (LIST_OPEN_TABS_QUESTION_RE.test(input)) { + return "list"; + } + if (LIST_VERB_RE.test(input)) { + return "list"; + } + if (SHOW_VERB_RE.test(input) && LIST_OBJECT_RE.test(input)) { + return "list"; + } + if (SEARCH_FAMILY_RE.test(input) || HISTORY_FAMILY_RE.test(input)) { + return "search"; + } + if (MUTATION_FAMILY_RE.test(input)) { + return "mutation"; + } + return "other"; + } + function normalizeRouteName(value) { + return String(value || "").trim().toLowerCase(); + } + function parseContainerAddIntent(commandText) { + const input = String(commandText || "").trim(); + if (!input) return null; + const allMatch = input.match( + /^(?add|save|move|put)\s+all\s+(?:tabs?|existing\s+tabs?)\s+to\s+(?.+)$/i + ); + if (allMatch?.groups) { + if (isNonContainerTarget(allMatch.groups.target)) { + return null; + } + const explicitContainer = extractContainerType(allMatch.groups.target); + const targetName = extractTargetName(allMatch.groups.target); + if (!targetName) return null; + return { + rawText: input, + normalizedText: input.toLowerCase(), + verb: allMatch.groups.verb.toLowerCase(), + isActionLike: true, + explicitContainer, + targetName, + all: true, + kind: "container_add" + }; + } + const currentMatch = input.match( + /^(?add|save|move|put)\s+(?:this|current|active)\s+tab\s+to\s+(?.+)$/i + ); + if (currentMatch?.groups) { + if (isNonContainerTarget(currentMatch.groups.target)) { + return null; + } + const explicitContainer = extractContainerType(currentMatch.groups.target); + const targetName = extractTargetName(currentMatch.groups.target); + if (!targetName) return null; + return { + rawText: input, + normalizedText: input.toLowerCase(), + verb: currentMatch.groups.verb.toLowerCase(), + isActionLike: true, + explicitContainer, + targetName, + current: true, + kind: "container_add" + }; + } + const queryMatch = input.match( + /^(?add|save|move|put)\s+(?.+?)\s+to\s+(?.+)$/i + ); + if (queryMatch?.groups) { + if (isNonContainerTarget(queryMatch.groups.target)) { + return null; + } + const explicitContainer = extractContainerType(queryMatch.groups.target); + const targetName = extractTargetName(queryMatch.groups.target); + const query = cleanCaptured(queryMatch.groups.query); + if (!targetName || !query) return null; + return { + rawText: input, + normalizedText: input.toLowerCase(), + verb: queryMatch.groups.verb.toLowerCase(), + isActionLike: true, + explicitContainer, + targetName, + all: /^(?:all\s+tabs?|all\s+existing\s+tabs?)$/i.test(query), + current: /^(?:this|current|active)\s+tab$/i.test(query), + query, + kind: "container_add" + }; + } + return null; + } + function parseCloseDeleteTargetIntent(commandText) { + const input = String(commandText || "").trim(); + if (!input) return null; + const match = input.match(/^(?close|delete|remove)\s+(?.+)$/i); + if (!match?.groups) return null; + const verb = match.groups.verb.toLowerCase(); + const target = cleanCaptured(match.groups.target); + if (!target) return null; + return { + rawText: input, + normalizedText: input.toLowerCase(), + verb, + isActionLike: true, + explicitContainer: extractContainerType(target), + targetName: extractTargetName(target), + kind: "close_delete_target" + }; + } + function parseSearchFolderSlots(commandText) { + const input = String(commandText || "").trim(); + if (!input) return null; + const quotedQueryFirst = input.match( + /^(?:search|find|look\s*up)\s+(?:for\s+)?(?.+?)\s+(?:in|inside|within|from)\s+(?:my\s+)?(?:the\s+)?["'](?[^"']+?)["']\s*(?:bookmark\s+folder|folder|hub|bookmarks?)?\s*$/i + ); + if (quotedQueryFirst?.groups) { + const folder = cleanCaptured(quotedQueryFirst.groups.folder); + if (!folder || GENERIC_FOLDER_NAME_RE.test(folder)) { + return null; + } + return { + query: cleanCaptured(quotedQueryFirst.groups.query), + folder + }; + } + const quotedFolderFirst = input.match( + /^(?:search|find|look\s*up)\s+(?:(?:in|inside|within|from)\s+)?(?:my\s+)?(?:the\s+)?["'](?[^"']+?)["']\s*(?:bookmark\s+folder|folder|hub|bookmarks?)?\s+(?:for\s+)?(?.+?)\s*$/i + ); + if (quotedFolderFirst?.groups) { + const folder = cleanCaptured(quotedFolderFirst.groups.folder); + if (!folder || GENERIC_FOLDER_NAME_RE.test(folder)) { + return null; + } + return { + query: cleanCaptured(quotedFolderFirst.groups.query), + folder + }; + } + const queryFirst = input.match( + /^(?:search|find|look\s*up)\s+(?:for\s+)?(?.+?)\s+(?:in|inside|within|from)\s+(?:my\s+)?(?:the\s+)?(?[\w\s-]+?)\s+(?:bookmark\s+folder|folder|hub|bookmarks?)\s*$/i + ); + if (queryFirst?.groups) { + const folder = cleanCaptured(queryFirst.groups.folder); + if (!folder || GENERIC_FOLDER_NAME_RE.test(folder)) { + return null; + } + return { + query: cleanCaptured(queryFirst.groups.query), + folder + }; + } + const folderFirst = input.match( + /^(?:search|find|look\s*up)\s+(?:(?:in|inside|within|from)\s+)?(?:my\s+)?(?:the\s+)?(?[\w\s-]+?)\s+(?:bookmark\s+folder|folder|hub|bookmarks?)\s+(?:for\s+)?(?.+?)\s*$/i + ); + if (folderFirst?.groups) { + const folder = cleanCaptured(folderFirst.groups.folder); + if (!folder || GENERIC_FOLDER_NAME_RE.test(folder)) { + return null; + } + return { + query: cleanCaptured(folderFirst.groups.query), + folder + }; + } + return null; + } + function parseSearchMemoryIntent(commandText) { + const input = String(commandText || "").trim(); + if (!input) { + return null; + } + const folderSourceScope = input.match( + /^(?:search|find|look\s*up)\s+(?:(?:in|inside|within|from)\s+)?(?:my\s+)?(?:the\s+)?(?:bookmark\s+folders?|folders?|hubs?|bookmarks?)\s+(?:for\s+)?(?.+?)\s*$/i + ); + if (folderSourceScope?.groups?.query) { + const scopedQuery = cleanCaptured(folderSourceScope.groups.query); + if (scopedQuery) { + return { query: scopedQuery, source: "bookmark-folder" }; + } + } + const folderSlots = parseSearchFolderSlots(input); + if (folderSlots) { + return folderSlots; + } + const wildcard = input.match( + /what(?:'s|\s+is|\s+did\s+i\s+save)\s+in\s+(?:my\s+)?(?:the\s+)?(?[\w\s-]+?)\s+(?:bookmark\s+folder|folder|hub|bookmarks?)\b/i + ); + const wildcardFolder = wildcard?.groups?.folder; + if (wildcardFolder) { + return { query: "*", folder: cleanCaptured(wildcardFolder) }; + } + const queryMatch = input.match( + /(?:search|find|look\s*up)\s+(?:for\s+)?(?:(?:in|inside|within|from)\s+(?:my\s+)?(?:history|bookmarks?|memory|tabs?)\s+)?"?(?.+?)"?\s*$/i + ) || input.match( + /have\s+i\s+(?:visited|been\s+to|seen|saved|bookmarked)\s+(?:any\s+)?"?(?.+?)"?\s*$/i + ) || input.match( + /(?:do\s+i\s+have)\s+(?:any(?:thing)?\s+(?:about|on|related\s+to)\s+)?"?(?.+?)"?\s*(?:saved|bookmarked|in\s+my)/i + ); + const query = cleanCaptured(queryMatch?.groups?.query || ""); + if (!query) { + return null; + } + return { query }; + } + + // src/utils/knownSites.ts + var SITE_NAMES = [ + "youtube", + "google", + "gmail", + "github", + "twitter", + "instagram", + "facebook", + "reddit", + "netflix", + "spotify", + "amazon", + "wikipedia", + "slack", + "notion", + "linear", + "figma", + "jira", + "vercel", + "supabase", + "openai", + "anthropic", + "claude", + "chatgpt", + "linkedin", + "whatsapp", + "discord", + "twitch", + "tiktok", + "pinterest", + "dropbox", + "zoom", + "meet", + "calendar", + "drive", + "docs", + "sheets", + "maps" + ]; + var KNOWN_SITE_NAMES_PATTERN = SITE_NAMES.join("|"); + var KNOWN_SITES_HINT_RE = new RegExp( + `\\b(?:${KNOWN_SITE_NAMES_PATTERN})\\b`, + "i" + ); + var DEFAULT_URLS = { + youtube: "https://www.youtube.com", + google: "https://www.google.com", + gmail: "https://mail.google.com", + github: "https://github.com", + twitter: "https://twitter.com", + instagram: "https://www.instagram.com", + facebook: "https://www.facebook.com", + reddit: "https://www.reddit.com", + netflix: "https://www.netflix.com", + spotify: "https://open.spotify.com", + amazon: "https://www.amazon.com", + wikipedia: "https://www.wikipedia.org", + slack: "https://slack.com", + notion: "https://www.notion.so", + linear: "https://linear.app", + figma: "https://www.figma.com", + jira: "https://www.atlassian.com/software/jira", + vercel: "https://vercel.com", + supabase: "https://supabase.com", + openai: "https://chat.openai.com", + anthropic: "https://www.anthropic.com", + claude: "https://claude.ai", + chatgpt: "https://chatgpt.com", + linkedin: "https://www.linkedin.com", + whatsapp: "https://web.whatsapp.com", + discord: "https://discord.com", + twitch: "https://www.twitch.tv", + tiktok: "https://www.tiktok.com", + pinterest: "https://www.pinterest.com", + dropbox: "https://www.dropbox.com", + zoom: "https://zoom.us", + meet: "https://meet.google.com", + calendar: "https://calendar.google.com", + drive: "https://drive.google.com", + docs: "https://docs.google.com", + sheets: "https://sheets.google.com", + maps: "https://maps.google.com" + }; + var TYPO_ALIASES = { + youtub: "youtube" + }; + var LOOKUP = new Map([ + ...Object.entries(DEFAULT_URLS), + ...Object.entries(TYPO_ALIASES).map( + ([typo, canon]) => [ + typo, + DEFAULT_URLS[canon] ?? `https://www.${canon}.com` + ] + ) + ]); + function resolveKnownSiteToUrl(raw) { + const key = String(raw || "").trim().toLowerCase().replace(/^["']|["']$/g, ""); + if (!key) { + return null; + } + return LOOKUP.get(key) ?? null; + } + + // src/utils/explicitRouteRules.ts + function toolDecision(next, reason, args) { + return { type: "tool", next, args, reason }; + } + function firstUrlLike(input) { + const urlMatch = input.match(/\b(https?:\/\/[^\s]+)\b/i); + if (urlMatch?.[1]) { + return urlMatch[1].trim(); + } + const domainMatch = input.match(/\b([a-z0-9.-]+\.[a-z]{2,}(?:\/[^\s]*)?)\b/i); + if (domainMatch?.[1]) { + return domainMatch[1].trim(); + } + return null; + } + function firstMatch(input, patterns) { + for (const pattern of patterns) { + const match = input.match(pattern); + if (match) { + return match; + } + } + return null; + } + function trimOpenTarget(raw) { + return String(raw || "").trim().replace(/^["']|["']$/g, "").replace(/[.!?]+$/g, "").trim(); + } + function resolveTargetForNewTab(targetRaw) { + const target = trimOpenTarget(targetRaw); + if (!target) { + return null; + } + const urlHit = firstUrlLike(target); + if (urlHit) { + return { url: urlHit }; + } + const siteUrl = resolveKnownSiteToUrl(target); + if (siteUrl) { + return { url: siteUrl }; + } + return { query: target }; + } + var OPEN_TARGET_IN_NEW_TAB_RE = /^(?:open|visit|go\s+to|launch)\s+(?.+?)\s+in\s+(?:a\s+)?new\s+tab\b/i; + var EXPLICIT_ROUTE_RULES = [ + { + next: "copy_tab_urls", + reason: "explicit-copy-tab-urls", + resolve: (input) => /\bcopy\s+(?:all\s+)?tab\s+urls?\b/i.test(input) ? {} : null + }, + { + next: "new_window", + reason: "explicit-new-window", + resolve: (input) => /^\s*(?:new\s+window|open\s+(?:a\s+)?new\s+window|create\s+(?:a\s+)?new\s+window|make\s+(?:a\s+)?new\s+window)\b/i.test( + input + ) ? {} : null + }, + { + next: "new_tab_to_right", + reason: "explicit-blank-new-tab", + resolve: (input) => { + const s2 = input.trim().replace(/[.!?]+$/g, "").trim(); + if (/^\s*new\s+tab(?:\s+please)?\s*$/i.test(s2) || /^\s*(?:open\s+(?:up\s+)?(?:a\s+)?new\s+tab|(?:create|add)\s+(?:a\s+)?new\s+tab)(?:\s+please)?\s*$/i.test( + s2 + )) { + return {}; + } + return null; + } + }, + { + next: "organize_windows", + reason: "explicit-organize-windows", + resolve: (input) => /\borganize\s+windows?\b/i.test(input) ? {} : null + }, + { + next: "show_subscription", + reason: "explicit-show-subscription", + resolve: (input) => /\b(?:show|check|view)\s+(?:my\s+)?subscription\b/i.test(input) ? {} : null + }, + { + next: "show_url", + reason: "explicit-show-url", + resolve: (input) => { + const match = input.match( + /(?:show|open)\s+url\s+(?https?:\/\/[^\s]+|[a-z0-9.-]+\.[a-z]{2,}(?:\/[^\s]*)?)/i + ); + const url = match?.groups?.url?.trim(); + return url ? { url } : null; + } + }, + { + next: "open_bookmark_folder", + reason: "explicit-open-folder-tabgroup", + resolve: (input) => { + const match = firstMatch(input, [ + /open\s+(?:the\s+)?(?:my\s+)?(?:bookmark\s+)?folder\s+"?(?[\w\s]+?)"?\s+(?:(?:as|in)\s+(?:a\s+)?(?:new\s+)?tab\s*group)/i, + /open\s+(?:my\s+)?"?(?[\w\s]+?)"?\s+(?:bookmark\s+)?folder\s+(?:(?:as|in)\s+(?:a\s+)?(?:new\s+)?tab\s*group)/i + ]); + const name = match?.groups?.name?.trim(); + return name ? { name, where: "tabgroup" } : null; + } + }, + { + next: "open_bookmark_folder", + reason: "explicit-open-folder-window", + resolve: (input) => { + const match = firstMatch(input, [ + /open\s+(?:the\s+)?(?:my\s+)?(?:bookmark\s+)?folder\s+"?(?[\w\s]+?)"?\s+(?:in\s+(?:a\s+)?(?:new\s+)?window)/i, + /open\s+(?:my\s+)?"?(?[\w\s]+?)"?\s+(?:bookmark\s+)?folder\s+(?:in\s+(?:a\s+)?(?:new\s+)?window)/i + ]); + const name = match?.groups?.name?.trim(); + return name ? { name, where: "window" } : null; + } + }, + { + next: "open_bookmark_folder", + reason: "explicit-open-folder", + resolve: (input) => { + const match = firstMatch(input, [ + /open\s+(?:the\s+)?(?:my\s+)?(?:bookmark\s+)?folder\s+"?(?[\w\s]+?)"?\s*$/i, + /open\s+(?:my\s+)?"?(?[\w\s]+?)"?\s+(?:bookmark\s+)?folder\s*$/i + ]); + const name = match?.groups?.name?.trim(); + return name ? { name } : null; + } + }, + { + next: "open_url", + reason: "explicit-open-target-in-new-tab-url", + resolve: (input) => { + const match = input.match(OPEN_TARGET_IN_NEW_TAB_RE); + const targetRaw = match?.groups?.target?.trim(); + if (!targetRaw) { + return null; + } + const args = resolveTargetForNewTab(targetRaw); + return args && "url" in args && args.url ? { url: args.url } : null; + } + }, + { + next: "web_search", + reason: "explicit-open-target-in-new-tab-search", + resolve: (input) => { + const match = input.match(OPEN_TARGET_IN_NEW_TAB_RE); + const targetRaw = match?.groups?.target?.trim(); + if (!targetRaw) { + return null; + } + const args = resolveTargetForNewTab(targetRaw); + return args && "query" in args && args.query ? { query: args.query } : null; + } + }, + { + next: "open_url", + reason: "explicit-open-url", + resolve: (input) => { + const match = input.match( + /open\s+(?:a\s+)?(?:new\s+)?tab\s+(?:to\s+|with\s+)?"?(?[^\s"']+)"?/i + ); + const url = match?.groups?.url?.trim(); + return url ? { url } : null; + } + }, + { + next: "open_url", + reason: "open-url-like", + resolve: (input, lower) => { + if (!/^open\s+/i.test(lower)) { + return null; + } + const url = firstUrlLike(input); + return url ? { url } : null; + } + }, + { + next: "web_search", + reason: "open-query-as-search", + resolve: (input) => { + const match = input.match( + /^open\s+(?:a\s+)?(?:new\s+)?tab\s+(?:for\s+|with\s+)?(?.+)$/i + ); + const query = match?.groups?.query?.trim(); + if (!query) { + return null; + } + if (firstUrlLike(query)) { + return null; + } + return { query }; + } + }, + // ───────────────────────────────────────────────────────────────────────── + // BROWSING HISTORY SEARCH (search_history) + // Matches queries about pages the user VISITED (not bookmarked) + // Examples: "what did I read about X", "find that article I visited" + // ───────────────────────────────────────────────────────────────────────── + { + next: "search_history", + reason: "explicit-history-search", + resolve: (input) => { + const patterns = [ + { re: /(?:what|which)\s+(?:was|were|is)\s+that\s+(?.+?)\s+(?:i\s+was|i've\s+been|i\s+have\s+been)\s+(?:reading|looking\s+at|browsing|viewing)/i }, + { re: /(?:pull|get|find|show)\s+(?:up\s+)?(?:me\s+)?(?:that\s+)?(?:page|article|site)\s+(?:about|on|regarding)\s+(?.+?)(?:\s+(?:from|in)\s+(?:my\s+)?history)?$/i }, + { re: /(?:pull|get|find|show|look)\s+(?:up\s+)?(?:for\s+)?(?:me\s+)?(?.+?)\s+(?:from|in)\s+(?:my\s+)?(?:browsing\s+)?history/i }, + { re: /(?:can\s+you\s+)?(?:pull|get|find|show|look)\s+(?:up\s+)?(?:for\s+)?(?:me\s+)?(?.+?)\s+(?:from|in)\s+(?:my\s+)?(?:browsing\s+)?history/i }, + { re: /(?:search|find|look\s*up)\s+(?:my\s+)?(?:browsing\s+)?history\s+(?:for|about)\s+(?.+)/i }, + { re: /(?:i\s+was\s+(?:reading|looking\s+at|browsing|viewing))\s+(?:something|a\s+page|an?\s+article|a\s+site)\s+(?:about|on|regarding)\s+(?.+)/i }, + { re: /what\s+(?:pages?|sites?|articles?)\s+(?:have\s+i|did\s+i|i)\s+(?:visited?|read|browsed?|looked?\s+at|viewed?|seen)\s+(?:about|on|regarding)\s+(?.+?)(?:\s+(?:recently|earlier|before|previously|yesterday))?$/i }, + { re: /what\s+(?:did\s+i|have\s+i)\s+(?:visit|read|browse|look\s+at|view)\s+(?:about\s+)?(?.+?)(?:\s+(?:recently|earlier|before|previously|yesterday))?$/i }, + { re: /what\s+(?:pages?|sites?|articles?)\s+(?:have\s+i|did\s+i)\s+(?:visited?|read|browsed?|viewed?|seen)(?:\s+(?:recently|earlier|before|previously|yesterday))?$/i, queryGroup: "recent browsing history" } + ]; + for (const { re: re2, queryGroup } of patterns) { + const match = input.match(re2); + if (match) { + const query = match.groups?.query?.trim() || queryGroup || ""; + if (query) return { query }; + } + } + if (/\b(?:my|the)\s+(?:browsing\s+)?history\b/i.test(input)) { + const cleaned = input.replace(/^(?:can\s+you\s+)?(?:search|find|look\s*(?:up|for)?|show|pull\s*up?|get)\s+/i, "").replace(/\s+(?:from|in)\s+(?:my\s+)?(?:browsing\s+)?history\b.*/i, "").replace(/\s*(?:my|the)\s+(?:browsing\s+)?history\s*/i, "").replace(/^(?:for|about|on|regarding)\s+/i, "").trim(); + return { query: cleaned || "recent browsing history" }; + } + return null; + } + } + ]; + function resolveExplicitRoute(input) { + const lower = input.toLowerCase(); + for (const rule of EXPLICIT_ROUTE_RULES) { + const args = rule.resolve(input, lower); + if (args) { + return toolDecision(rule.next, rule.reason, args); + } + } + return null; + } + + // src/utils/commandManifest.ts + var COMMAND_MANIFEST = [ + { + id: "list.bookmark.folders", + family: "list", + commandName: "list_bookmark_folders", + phrases: [ + "list bookmark folders", + "list my bookmark folders", + "list my bookmarks", + "list bookmarks", + "show bookmark folders", + "show my bookmark folders", + "show bookmarks", + "show my bookmarks", + "list folders", + "show folders", + "list hubs", + "show hubs" + ] + }, + { + id: "list.tab.groups", + family: "list", + commandName: "list_tab_groups", + phrases: [ + "list tab groups", + "show tab groups", + "list groups", + "show groups", + "list my tab groups", + "show my tab groups" + ] + }, + { + id: "list.window.tabs", + family: "list", + commandName: "list_tabs", + phrases: [ + "list tabs", + "show tabs", + "list my tabs", + "list my open tabs", + "what tabs do i have open", + "which tabs are open", + "what tabs are open", + "tabs do i have open" + ], + condition: (context) => context.hasOpenTabs + }, + { + id: "list.container.tabs", + family: "list", + commandName: "list_tabs", + phrases: ["list tabs in", "show tabs in", "list my", "show my", "list the", "show the"], + slots: [ + { name: "name", type: "target_name", source: "rest", optional: true }, + { name: "scope", type: "scope", source: "rest", optional: true } + ] + }, + { + id: "search.history", + family: "search", + commandName: "search_history", + priority: 2, + phrases: [ + "list my recent browsing history", + "list my browsing history", + "show my browsing history", + "show my recent browsing history", + "list recent browsing history", + "what is in my browsing history", + "whats in my browsing history", + "what pages did i visit", + "what did i read", + "what did i browse", + "find that article", + "find that page", + "find that site", + "what sites did i visit", + "pages i visited", + "articles i read", + "browsing history", + "search history", + "search my history", + "search my browser history", + "search my browsing history", + "find in my history", + "what was that page", + "what was that site", + "what was that article", + "did i visit", + "did i look at", + "did i read", + "did i browse" + ], + slots: [ + { + name: "query", + type: "string", + source: "quoted_or_rest", + optional: true + } + ] + }, + { + id: "search.memory", + family: "search", + commandName: "search_memory", + phrases: [ + "search", + "find", + "look up", + "have i visited", + "have i", + "what is in", + "do i have" + ], + slots: [ + { name: "query", type: "string", source: "quoted_or_rest" }, + { name: "folder", type: "target_name", source: "rest", optional: true } + ] + }, + { + id: "mutation.container.add", + family: "mutation", + commandName: "add_tab_to_bookmark_folder", + phrases: ["add", "save", "move", "put"], + slots: [ + { name: "name", type: "target_name", source: "rest", optional: true }, + { name: "query", type: "string", source: "quoted_or_rest", optional: true } + ] + }, + { + id: "mutation.target.delete", + family: "mutation", + commandName: "resolve_ambiguity", + phrases: ["close", "delete", "remove"], + slots: [{ name: "target", type: "target_name", source: "rest", optional: true }] + } + ]; + + // src/utils/manifestResolver.ts + function phraseMatchScore(input, phrase) { + const source = normalizeRouteName(input); + const target = normalizeRouteName(phrase); + if (!source || !target) { + return 0; + } + if (source === target) { + return 1; + } + if (source.startsWith(target)) { + return 0.9; + } + if (source.includes(target)) { + return 0.75; + } + return 0; + } + function checkCondition(definition, context) { + if (!definition.condition) { + return true; + } + return definition.condition(context); + } + function resolveManifestCandidates(input, context, manifest = COMMAND_MANIFEST) { + const normalizedInput = normalizeRouteName(input); + if (!normalizedInput) { + return []; + } + const candidates = []; + for (const definition of manifest) { + if (!checkCondition(definition, context)) { + continue; + } + let bestScore = 0; + for (const phrase of definition.phrases) { + const score = phraseMatchScore(normalizedInput, phrase); + if (score > bestScore) { + bestScore = score; + } + } + if (bestScore <= 0) { + continue; + } + candidates.push({ + definition, + args: {}, + score: bestScore + (definition.priority || 0) * 0.01 + }); + } + return candidates.sort((a2, b3) => b3.score - a2.score); + } + function resolveManifestCommand(input, context, manifest = COMMAND_MANIFEST) { + const candidates = resolveManifestCandidates(input, context, manifest); + return candidates[0] || null; + } + + // src/utils/manifestListResolver.ts + var WINDOW_SCOPE_ALIASES = /* @__PURE__ */ new Set([ + "window", + "current window", + "this window", + "open tabs", + "all open tabs", + "tabs", + "all tabs", + "my tabs", + "current tabs", + "active tabs" + ]); + function cleanTargetName(value) { + return String(value || "").replace(/["']/g, "").replace(/^\s*(?:my|the)\s+/i, "").replace(/\s+(?:please|now)\s*$/i, "").trim(); + } + function isListBookmarkFoldersCommand(input) { + return /^(?:list|show)\s+(?:all\s+)?(?:my\s+)?(?:bookmark\s+)?(?:bookmarks?|folders?|hubs?)\s*$/i.test( + String(input || "").trim() + ); + } + function isListTabGroupsCommand(input) { + return /^(?:list|show)\s+(?:all\s+)?(?:my\s+)?(?:tab\s+)?groups?\s*$/i.test( + String(input || "").trim() + ); + } + function parseListTabsTarget(input) { + const command = String(input || "").trim(); + if (!/^(?:list|show)\b/i.test(command)) { + return null; + } + if (/\btab\s*groups?\b/i.test(command) && !/\btabs?\s+(?:in|from)\b/i.test(command)) { + return null; + } + const tabsWithTarget = command.match(/\btabs?\s+(?:in|from)\s+(?.+)$/i); + if (tabsWithTarget?.groups?.target) { + const rawTarget = cleanTargetName(tabsWithTarget.groups.target); + if (!rawTarget) { + return {}; + } + const hasGroup = /\btab\s*group\b|\bgroup\b/i.test(rawTarget); + const hasFolder = /\bbookmark\s*folder\b|\bfolder\b|\bhub\b|\bbookmarks?\b/i.test( + rawTarget + ); + const explicitContainer = hasGroup && !hasFolder ? "tab-group" : hasFolder && !hasGroup ? "bookmark-folder" : void 0; + const targetName2 = cleanTargetName( + rawTarget.replace( + /\b(?:tab\s*group|bookmark\s*folder|group|folder|hub|bookmarks?)\b/gi, + " " + ) + ); + if (!targetName2) { + return explicitContainer ? { explicitContainer } : {}; + } + return { targetName: targetName2, explicitContainer }; + } + if (/^(?:list|show)\s+(?:all\s+)?(?:my\s+)?tabs?\b/i.test(command)) { + return {}; + } + const containerNameMatch = command.match( + /^(?:list|show)\s+(?:tabs?\s+(?:in|from)\s+)?(?:my\s+|the\s+)?(?.+?)\s+(?tab\s*group|group|bookmark\s*folder|folder|hub|bookmarks?)(?:\s+tabs?)?\s*$/i + ); + if (containerNameMatch?.groups?.container) { + const targetName2 = cleanTargetName(containerNameMatch.groups.name || ""); + const container = normalizeRouteName(containerNameMatch.groups.container); + const explicitContainer = container.includes("group") ? "tab-group" : "bookmark-folder"; + if (!targetName2) { + return { explicitContainer }; + } + return { targetName: targetName2, explicitContainer }; + } + const namedListMatch = command.match( + /^(?:list|show)\s+(?:my\s+|the\s+)?(?[\w\s-]+)\s*$/i + ); + if (!namedListMatch?.groups?.name) { + return null; + } + const targetName = cleanTargetName(namedListMatch.groups.name); + if (!targetName) { + return null; + } + if (/^(?:tabs?|tab\s*groups?|groups?|bookmark\s*folders?|folders?|hubs?|bookmarks?)$/i.test( + targetName + )) { + return null; + } + return { targetName }; + } + function isBrowsingHistoryListIntent(raw) { + return /\b(?:list|show)\s+(?:my\s+|the\s+)?(?:recent\s+)?browsing\s+history\b/i.test( + String(raw || "").trim() + ); + } + function resolveManifestListRoute(input, snapshot) { + if (isBrowsingHistoryListIntent(input)) { + return { + type: "tool", + next: "search_history", + args: { query: "" }, + reason: "list-phrasing-for-browsing-history" + }; + } + const topWin = getBrowserWindow(); + const tabCount = topWin?.gBrowser?.tabs ? Array.from(topWin.gBrowser.tabs).length : 0; + const candidate = resolveManifestCommand(input, { + snapshot, + hasOpenTabs: tabCount > 0, + hasPendingConfirmation: false + }); + if (!candidate || candidate.definition.family !== "list") { + return null; + } + if (candidate.definition.id === "list.bookmark.folders" || isListBookmarkFoldersCommand(input)) { + return { + type: "tool", + next: "list_bookmark_folders", + args: {}, + reason: "list-manifest-bookmark-folders" + }; + } + if (candidate.definition.id === "list.tab.groups" || isListTabGroupsCommand(input)) { + return { + type: "tool", + next: "list_tab_groups", + args: {}, + reason: "list-manifest-tab-groups" + }; + } + const parsed = parseListTabsTarget(input); + if (!parsed) { + if (candidate.definition.id === "list.window.tabs") { + return { + type: "tool", + next: "list_tabs", + args: {}, + reason: "list-manifest-open-window" + }; + } + return null; + } + const targetName = parsed.targetName; + const explicitContainer = parsed.explicitContainer; + if (explicitContainer === "tab-group") { + if (!targetName) { + return { + type: "chat", + actionable: true, + reason: "list-manifest-missing-group-name", + message: "Which tab group should I list tabs from?" + }; + } + return { + type: "tool", + next: "list_tabs", + args: { scope: "tab-group", name: targetName }, + reason: "list-manifest-explicit-group" + }; + } + if (explicitContainer === "bookmark-folder") { + if (!targetName) { + return { + type: "chat", + actionable: true, + reason: "list-manifest-missing-folder-name", + message: "Which bookmark folder should I list tabs from?" + }; + } + return { + type: "tool", + next: "list_tabs", + args: { scope: "bookmark-folder", name: targetName }, + reason: "list-manifest-explicit-folder" + }; + } + if (!targetName) { + return { + type: "tool", + next: "list_tabs", + args: {}, + reason: "list-manifest-open-window" + }; + } + const normalizedTarget = normalizeRouteName(targetName); + if (WINDOW_SCOPE_ALIASES.has(normalizedTarget)) { + return { + type: "tool", + next: "list_tabs", + args: {}, + reason: "list-manifest-window-alias" + }; + } + const targetInGroups = snapshot.groupNames.has(normalizedTarget); + const targetInFolders = snapshot.folderNames.has(normalizedTarget); + if (targetInGroups && !targetInFolders) { + return { + type: "tool", + next: "list_tabs", + args: { scope: "tab-group", name: targetName }, + reason: "list-manifest-resolved-group" + }; + } + if (targetInFolders && !targetInGroups) { + return { + type: "tool", + next: "list_tabs", + args: { scope: "bookmark-folder", name: targetName }, + reason: "list-manifest-resolved-folder" + }; + } + if (targetInFolders && targetInGroups) { + return { + type: "chat", + actionable: true, + reason: "list-manifest-ambiguous-target", + message: `I found both a tab group and a bookmark folder named "${targetName}". Say "list tabs in tab group ${targetName}" or "list tabs in bookmark folder ${targetName}".` + }; + } + return { + type: "tool", + next: "list_tabs", + args: { name: targetName }, + reason: "list-manifest-runtime-resolve-target" + }; + } + + // src/utils/manifestSearchResolver.ts + function cleanSearchTarget(value) { + const cleaned = String(value || "").replace(/["']/g, "").replace(/^\s*(?:my|the)\s+/i, "").trim(); + return cleaned.replace(/\s+(?:bookmark\s+folder|folder|hub|bookmarks?)\s*$/i, "").trim(); + } + function cleanSearchQuery(value) { + return String(value || "").replace(/["']/g, "").trim(); + } + function escapeRegExp(value) { + return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + } + function parseFolderSearchMissingQuery(input, snapshot) { + const match = String(input || "").trim().match( + /^(?:search|find|look\s*up)\s+(?:(?:in|inside|within|from)\s+)?(?:my\s+|the\s+)?(?.+?)\s+(?:bookmark\s+folder|folder|hub|bookmarks?)\s*$/i + ); + if (!match?.groups?.target) { + return null; + } + const targetName = cleanSearchTarget(match.groups.target); + if (!targetName) { + return null; + } + const targetNorm = normalizeRouteName(targetName); + if (!targetNorm || !snapshot.folderNames.has(targetNorm)) { + return null; + } + return targetName; + } + function parseImplicitFolderPrefixSearch(input, snapshot) { + const body = String(input || "").trim().replace(/^(?:search|find|look\s*up)\s+/i, "").replace(/^\s*(?:my|the)\s+/i, "").trim(); + if (!body) { + return null; + } + if (/\bfor\b/i.test(body) || /\b(?:in|inside|within|from)\b/i.test(body)) { + return null; + } + const folderNames = Array.from(snapshot.folderNames).sort( + (a2, b3) => b3.length - a2.length + ); + for (const folderNorm of folderNames) { + const pattern = new RegExp( + `^(?${escapeRegExp( + folderNorm + )})(?:\\s+(?:bookmark\\s+folder|folder|hub|bookmarks?))?\\s+(?.+)$`, + "i" + ); + const match = body.match(pattern); + if (!match?.groups) { + continue; + } + const folder = cleanSearchTarget(match.groups.folder); + const query = cleanSearchQuery(match.groups.query); + if (!folder || !query) { + continue; + } + return { query, folder }; + } + return null; + } + function parseImplicitFolderSearch(input, snapshot) { + const command = String(input || "").trim(); + const queryInTarget = command.match( + /^(?:search|find|look\s*up)\s+(?:for\s+)?(?.+?)\s+(?:in|inside|within|from)\s+(?:my\s+|the\s+)?(?.+?)\s*$/i + ); + if (queryInTarget?.groups) { + const targetName2 = cleanSearchTarget(queryInTarget.groups.target); + const query2 = cleanSearchQuery(queryInTarget.groups.query); + if (targetName2 && query2) { + const targetNorm2 = normalizeRouteName(targetName2); + if (targetNorm2 && snapshot.folderNames.has(targetNorm2)) { + return { query: query2, folder: targetName2 }; + } + } + } + const queryWithTrailingFolder = command.match( + /^(?:search|find|look\s*up)\s+(?:my\s+|the\s+)?(?[\w\s-]+?)\s+for\s+(?.+?)\s+(?:bookmark\s+folder|folder|hub|bookmarks?)\s*$/i + ); + if (queryWithTrailingFolder?.groups) { + const targetName2 = cleanSearchTarget(queryWithTrailingFolder.groups.target); + const query2 = cleanSearchQuery(queryWithTrailingFolder.groups.query); + if (targetName2 && query2) { + const targetNorm2 = normalizeRouteName(targetName2); + if (targetNorm2 && snapshot.folderNames.has(targetNorm2)) { + return { query: query2, folder: targetName2 }; + } + } + } + const match = command.match( + /^(?:search|find|look\s*up)\s+(?:my\s+|the\s+)?(?[\w\s-]+?)\s+for\s+(?.+?)\s*$/i + ); + if (!match?.groups) { + return null; + } + const targetName = cleanSearchTarget(match.groups.target); + const query = cleanSearchQuery(match.groups.query); + if (!targetName || !query) { + return null; + } + const targetNorm = normalizeRouteName(targetName); + if (!targetNorm) { + return null; + } + if (!snapshot.folderNames.has(targetNorm)) { + return null; + } + return { query, folder: targetName }; + } + function resolveManifestSearchRoute(input, snapshot) { + const topWin = getBrowserWindow(); + const tabCount = topWin?.gBrowser?.tabs ? Array.from(topWin.gBrowser.tabs).length : 0; + const candidate = resolveManifestCommand(input, { + snapshot, + hasOpenTabs: tabCount > 0, + hasPendingConfirmation: false + }); + if (!candidate || candidate.definition.family !== "search") { + return null; + } + if (candidate.definition.commandName === "search_history") { + const parsed2 = parseSearchMemoryIntent(input); + const query = parsed2?.query || input.replace(/^(?:find|search|what|did\s+i)\s+/i, "").trim(); + return { + type: "tool", + next: "search_history", + args: { query }, + reason: "search-manifest-history" + }; + } + const missingFolderQuery = parseFolderSearchMissingQuery(input, snapshot); + if (missingFolderQuery) { + return { + type: "chat", + reason: "search-manifest-folder-missing-query", + actionable: true, + message: `What should I search for in bookmark folder "${missingFolderQuery}"?` + }; + } + const parsed = parseSearchMemoryIntent(input); + const implicitFolder = parseImplicitFolderSearch(input, snapshot) || parseImplicitFolderPrefixSearch(input, snapshot); + const resolved = implicitFolder || parsed; + if (!resolved) { + return null; + } + const args = { query: resolved.query }; + if (resolved.folder) { + args.folder = resolved.folder; + } + if ("source" in resolved && resolved.source) { + args.source = resolved.source; + } + const reason = implicitFolder ? "search-manifest-implicit-folder" : resolved.folder ? "search-manifest-folder" : "source" in resolved && resolved.source === "bookmark-folder" ? "search-manifest-bookmark-folder-scope" : "search-manifest-memory"; + return { + type: "tool", + next: "search_memory", + args, + reason + }; + } + + // src/utils/entityResolver.ts + function resolveTargetName(targetName, snapshot) { + const normalizedTarget = normalizeRouteName(targetName); + const topWin = getBrowserWindow(); + const gBrowser = topWin?.gBrowser; + const tabMatches = []; + if (gBrowser?.tabs && normalizedTarget) { + const tabs = Array.from(gBrowser.tabs || []); + for (let i2 = 0; i2 < tabs.length; i2++) { + const tab = tabs[i2]; + const title = normalizeRouteName(tab?.label || ""); + const url = normalizeRouteName(tab?.linkedBrowser?.currentURI?.spec || ""); + if (title === normalizedTarget || url === normalizedTarget || normalizedTarget.length > 2 && (title.includes(normalizedTarget) || url.includes(normalizedTarget))) { + tabMatches.push(i2 + 1); + } + } + } + return { + targetInFolders: snapshot.folderNames.has(normalizedTarget), + targetInGroups: snapshot.groupNames.has(normalizedTarget), + tabMatches + }; + } + + // src/utils/mutationExplicitResolver.ts + function toolDecision2(next, reason, args) { + return { type: "tool", next, args, reason }; + } + function firstMatch2(input, patterns) { + for (const pattern of patterns) { + const match = input.match(pattern); + if (match) { + return match; + } + } + return null; + } + function numberArg(value) { + if (!value) { + return void 0; + } + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : void 0; + } + function extractIndices(input) { + return (input.match(/\d+/g) || []).map((value) => Number(value)).filter((value) => Number.isFinite(value) && value > 0); + } + var MUTATION_EXPLICIT_ROUTES = [ + { + next: "split_tabs", + reason: "mutation-explicit-split-tabs", + resolve: (input) => { + const match = input.match(/split\s+tabs?\s+(?[\d,\sand]+)/i); + const indicesRaw = match?.groups?.indices; + if (!indicesRaw) { + return null; + } + const indices = extractIndices(indicesRaw); + return indices.length >= 2 ? { indices } : null; + } + }, + { + next: "add_split_view", + reason: "mutation-explicit-add-split-view-two-tabs", + resolve: (input) => { + const match = input.match( + /(?:split|splitview|add)\s+(?:tabs?\s+)?(?
    \d+)\s+(?:and|,|with)\s+(?:tab\s+)?(?\d+)/i + ) || input.match( + /(?:add\s+)?tabs?\s+(?\d+)\s+(?:and|,|with)\s+(?:tab\s+)?(?\d+)\s+(?:to\s+)?(?:split\s*view|splitview)/i + ); + const a2 = numberArg(match?.groups?.a); + const b3 = numberArg(match?.groups?.b); + return a2 != null && b3 != null ? { indices: [a2, b3] } : null; + } + }, + { + next: "remove_split_view", + reason: "mutation-explicit-remove-split-view", + resolve: (input) => /(?:remove|disable|close)\s+split\s*view|unsplit\s+(?:tabs?|view)?/i.test( + input + ) ? {} : null + }, + { + next: "add_split_view", + reason: "mutation-explicit-add-split-view-colloquial", + resolve: (input) => { + const lower = input.toLowerCase(); + if (/\b(remove|disable|close|unsplit|don't|do not)\b/.test(lower)) { + return null; + } + if (/\b(?:two|2)\s+tabs?\s+(?:side\s*by\s*side|at\s+once)\b/i.test(input) || /\bshow\s+(?:two|2)\s+tabs?\s+(?:side\s*by\s*side|at\s+once)\b/i.test( + input + ) || /\bopen\s+.{0,40}\bsplit\s*view\b/i.test(input) || /\bsplitview\b/i.test(input)) { + return {}; + } + return null; + } + }, + { + next: "add_split_view", + reason: "mutation-explicit-add-split-view", + resolve: (input) => { + if (!/(?:add|create|enable)\s+split\s*view|split\s+(?:this\s+)?(?:tab|view)/i.test( + input + )) { + return null; + } + const withTabMatch = input.match( + /(?:with|and)\s+(?:tab\s+)?(?\d+)/i + ); + const withIndex = numberArg(withTabMatch?.groups?.index); + if (withIndex != null) { + return { withIndex }; + } + const withQueryMatch = input.match( + /(?:with|and)\s+(?:the\s+)?"?(?[^"\d][^"]+?)"?\s*(?:tab)?$/i + ); + const withQuery = withQueryMatch?.groups?.query?.trim(); + return withQuery ? { withQuery } : {}; + } + }, + { + next: "move_tab_to_new_window", + reason: "mutation-explicit-move-tab-new-window", + resolve: (input) => { + const match = input.match( + /(?:move)\s+(?:the\s+)?(?:current\s+)?tab(?:\s+(?\d+))?\s+to\s+(?:a\s+)?new\s+window/i + ); + if (!match) { + return null; + } + const index2 = numberArg(match.groups?.index); + return index2 != null ? { index: index2 } : {}; + } + }, + { + next: "close_tab", + reason: "mutation-explicit-close-tab", + resolve: (input) => { + const match = input.match( + /close\s+(?:the\s+)?(?:current\s+)?tab(?:\s+(?\d+))?/i + ); + if (!match) { + return null; + } + const index2 = numberArg(match.groups?.index); + return index2 != null ? { index: index2 } : {}; + } + }, + { + next: "remove_tab_from_group", + reason: "mutation-explicit-remove-tab-from-group", + resolve: (input) => { + const match = input.match( + /(?:remove|ungroup)\s+(?:the\s+)?(?:this\s+|current\s+|active\s+)?tab(?:\s+(?\d+))?\s+from\s+(?:its\s+)?(?:tab\s+)?group/i + ); + if (!match) { + return null; + } + const index2 = numberArg(match.groups?.index); + return index2 != null ? { index: index2 } : {}; + } + }, + { + next: "remove_tab_from_bookmark_folder", + reason: "mutation-explicit-remove-tab-from-folder", + resolve: (input) => { + const match = input.match( + /(?:remove|delete)\s+(?:this\s+)?(?:tab\s+)?from\s+(?:my\s+)?(?:the\s+)?(?:bookmark\s+)?folder\s+"?(?[\w\s]+?)"?\s*$/i + ); + const name = match?.groups?.name?.trim(); + return name ? { name } : null; + } + }, + { + next: "create_bookmark_folder", + reason: "mutation-explicit-create-folder-with-current", + resolve: (input) => { + const match = input.match( + /(?:create|make|new)\s+(?:a\s+)?(?:new\s+)?(?:bookmark\s+)?folder\s+(?:called\s+|named\s+)?"?(?[\w\s]+?)"?\s+and\s+(?:add|save|include|put)\s+(?:the\s+)?(?:current|this|active)\s+tab/i + ); + const name = match?.groups?.name?.trim(); + return name ? { name, include: "current" } : null; + } + }, + { + next: "create_bookmark_folder", + reason: "mutation-explicit-create-folder-with-all", + resolve: (input) => { + const match = input.match( + /(?:create|make|new)\s+(?:a\s+)?(?:new\s+)?(?:bookmark\s+)?folder\s+(?:called\s+|named\s+)?"?(?[\w\s]+?)"?\s+and\s+(?:add|save|include|put)\s+(?:all)\s+tabs/i + ); + const name = match?.groups?.name?.trim(); + return name ? { name, include: "all" } : null; + } + }, + { + next: "create_bookmark_folder", + reason: "mutation-explicit-create-folder", + resolve: (input) => { + const match = input.match( + /(?:create|make|new)\s+(?:a\s+)?(?:new\s+)?(?:bookmark\s+)?folder\s+(?:called\s+|named\s+)?"?(?[\w\s]+?)"?\s*$/i + ); + const name = match?.groups?.name?.trim(); + return name ? { name } : null; + } + }, + { + next: "delete_bookmark_folder", + reason: "mutation-explicit-delete-folder", + resolve: (input) => { + const match = firstMatch2(input, [ + /(?:delete|remove)\s+(?:the\s+)?(?:bookmark\s+)?folder\s+"?(?[\w\s]+?)"?\s*$/i, + /(?:delete|remove)\s+(?:the\s+)?"?(?[\w\s]+?)"?\s+(?:bookmark\s+)?folder/i + ]); + const name = match?.groups?.name?.trim(); + return name ? { name } : null; + } + }, + { + next: "rename_bookmark_folder", + reason: "mutation-explicit-rename-folder", + resolve: (input) => { + const match = input.match( + /rename\s+(?:the\s+)?(?:bookmark\s+)?folder\s+"?(?[\w\s]+?)"?\s+(?:to|as)\s+"?(?[\w\s]+?)"?\s*$/i + ); + const from = match?.groups?.from?.trim(); + const to = match?.groups?.to?.trim(); + return from && to ? { from, to } : null; + } + }, + { + next: "delete_tab_group", + reason: "mutation-explicit-delete-group", + resolve: (input) => { + const match = firstMatch2(input, [ + /(?:delete|remove)\s+(?:tab\s+)?group\s+"?(?[^"\n]+?)"?\s*$/i, + /(?:delete|remove)\s+(?:the\s+)?"?(?[^"\n]+?)"?\s+(?:tab\s+)?group/i + ]); + const name = match?.groups?.name?.trim(); + return name ? { name } : null; + } + }, + { + next: "create_tab_group", + reason: "mutation-explicit-create-group", + resolve: (input) => { + const match = input.match( + /(?:create|make|new)\s+(?:a\s+)?(?:new\s+)?(?:tab\s+)?(?:group|gorup)\s+(?:called\s+|named\s+)?"?(?.+)$/i + ); + if (!match?.groups?.name) { + return null; + } + let name = match.groups.name.trim(); + let openUrl; + const openInIt = name.match( + /\s+and\s+(?:open|go\s+to)\s+(.+?)\s+(?:in\s+it|in\s+the\s+group|in\s+that\s+group|there)$/i + ); + if (openInIt?.[1]) { + openUrl = openInIt[1].trim(); + name = name.replace(/\s+and\s+(?:open|go\s+to)\s+.+$/i, "").trim(); + } + name = name.replace(/\s+and\s+(?:add|open|put)\s+.+$/i, "").trim(); + name = name.replace(/\s+(?:with|using|from|for)\s+.*$/i, "").replace(/["']/g, "").trim(); + if (!name) { + return null; + } + const args = { name }; + if (openUrl) { + args.openUrl = openUrl; + } + const indicesMatch = input.match( + /(?:with\s+)?tabs?\s+([\d,\s]+(?:and\s+\d+)?)/i + ); + if (indicesMatch?.[1]) { + const indices = extractIndices(indicesMatch[1]); + if (indices.length > 0) { + args.indices = indices; + } + } + return args; + } + }, + { + next: "rename_tab_group", + reason: "mutation-explicit-rename-group", + resolve: (input) => { + const match = input.match( + /rename\s+(?:tab\s+)?group\s+"?(?[\w\s]+?)"?\s+(?:to|as)\s+"?(?[\w\s]+?)"?\s*$/i + ); + const from = match?.groups?.from?.trim(); + const to = match?.groups?.to?.trim(); + return from && to ? { from, to } : null; + } + } + ]; + function resolveExplicitMutationRoute(input) { + for (const rule of MUTATION_EXPLICIT_ROUTES) { + const args = rule.resolve(input); + if (args) { + return toolDecision2(rule.next, rule.reason, args); + } + } + return null; + } + + // src/utils/manifestMutationResolver.ts + function buildAmbiguityPayload(name, opts) { + return { + kind: opts.kind || "container_target", + name, + query: opts.query, + all: opts.all, + choices: opts.choices, + tabIndex: opts.tabIndex, + verb: opts.verb, + originalText: opts.originalText + }; + } + function resolveContainerAddRoute(input, snapshot) { + const parsed = parseContainerAddIntent(input); + if (!parsed || !parsed.targetName) { + return null; + } + const targetName = parsed.targetName; + const targetNorm = normalizeRouteName(targetName); + const targetInFolders = snapshot.folderNames.has(targetNorm); + const targetInGroups = snapshot.groupNames.has(targetNorm); + const addArgs = { name: targetName }; + if (parsed.all) { + addArgs.all = true; + } else if (parsed.query && !parsed.current) { + addArgs.query = parsed.query; + } + if (parsed.explicitContainer === "tab-group") { + return { + type: "tool", + next: "add_tab_to_group", + args: addArgs, + reason: "container-add-explicit-group" + }; + } + if (parsed.explicitContainer === "bookmark-folder") { + return { + type: "tool", + next: "add_tab_to_bookmark_folder", + args: addArgs, + reason: "container-add-explicit-folder" + }; + } + if (targetInFolders && targetInGroups) { + return { + type: "tool", + next: "resolve_ambiguity", + args: {}, + reason: "container-add-name-collision", + pendingAmbiguity: buildAmbiguityPayload(targetName, { + query: parsed.query, + all: parsed.all, + originalText: parsed.rawText + }) + }; + } + if (!targetInFolders && targetInGroups) { + return { + type: "tool", + next: "resolve_ambiguity", + args: {}, + reason: "container-add-only-group-exists", + pendingAmbiguity: buildAmbiguityPayload(targetName, { + query: parsed.query, + all: parsed.all, + originalText: parsed.rawText + }) + }; + } + return { + type: "tool", + next: "add_tab_to_bookmark_folder", + args: addArgs, + reason: targetInFolders ? "container-add-folder-exists" : "container-add-default-folder" + }; + } + function resolveCloseDeleteRoute(input, snapshot) { + const parsed = parseCloseDeleteTargetIntent(input); + if (!parsed?.targetName || !parsed.verb) { + return null; + } + const normalized = parsed.normalizedText; + if (/\b(?:tab\s+group|bookmark\s+folder|split\s*view|from\s+(?:my\s+)?(?:the\s+)?(?:bookmark\s+)?folder|from\s+(?:its\s+)?(?:tab\s+)?group|current\s+tab|tab\s+\d+)\b/i.test( + normalized + )) { + return null; + } + const resolution = resolveTargetName(parsed.targetName, snapshot); + const hasTab = resolution.tabMatches.length > 0; + const hasGroup = resolution.targetInGroups; + const hasFolder = resolution.targetInFolders; + const matches = [hasTab, hasGroup, hasFolder].filter(Boolean).length; + if (matches === 0) { + return null; + } + if (matches > 1) { + const choices = []; + if (hasTab) { + choices.push("tab"); + } + if (hasGroup) { + choices.push("tab-group"); + } + if (hasFolder) { + choices.push("bookmark-folder"); + } + return { + type: "tool", + next: "resolve_ambiguity", + args: {}, + reason: "close-delete-ambiguous-target", + pendingAmbiguity: buildAmbiguityPayload(parsed.targetName, { + kind: "close_delete_target", + choices, + tabIndex: resolution.tabMatches[0], + verb: parsed.verb, + originalText: parsed.rawText + }) + }; + } + if (hasGroup) { + return { + type: "tool", + next: "delete_tab_group", + args: { name: parsed.targetName }, + reason: "close-delete-resolved-group" + }; + } + if (hasFolder) { + return { + type: "tool", + next: "delete_bookmark_folder", + args: { name: parsed.targetName }, + reason: "close-delete-resolved-folder" + }; + } + return { + type: "tool", + next: "close_tab", + args: { index: resolution.tabMatches[0] }, + reason: "close-delete-resolved-tab" + }; + } + function resolveManifestMutationRoute(input, snapshot) { + return resolveExplicitMutationRoute(input) || resolveContainerAddRoute(input, snapshot) || resolveCloseDeleteRoute(input, snapshot); + } + + // src/utils/searchResultExplicitResolver.ts + function toolDecision3(next, reason, args) { + return { type: "tool", next, args, reason }; + } + function parseSearchResultIndex(input) { + const lower = String(input || "").toLowerCase(); + if (/\b(?:first|1st)\b/.test(lower)) return 1; + if (/\b(?:second|2nd)\b/.test(lower)) return 2; + if (/\b(?:third|3rd)\b/.test(lower)) return 3; + if (/\b(?:fourth|4th)\b/.test(lower)) return 4; + if (/\b(?:fifth|5th)\b/.test(lower)) return 5; + const numbered = lower.match(/(?:result\s*|number\s*|#)(\d+)/i); + if (!numbered?.[1]) { + return void 0; + } + const parsed = Number(numbered[1]); + return Number.isFinite(parsed) && parsed > 0 ? parsed : void 0; + } + var SEARCH_RESULT_ROUTES = [ + { + reason: "search-result-explicit-url", + resolve: (input) => { + const match = input.match( + /(?:open|go\s+to)\s+(?:the\s+)?(?:search\s+)?result(?:\s+url)?\s+(?https?:\/\/[^\s]+|[a-z0-9.-]+\.[a-z]{2,}(?:\/[^\s]*)?)/i + ); + const url = match?.groups?.url?.trim(); + return url ? { url } : null; + } + }, + { + reason: "search-result-followup", + resolve: (input) => { + if (!/^(?:open|go\s+to)\b/i.test(input)) { + return null; + } + const index2 = parseSearchResultIndex(input); + if (index2 != null) { + return { index: index2 }; + } + if (!/\b(?:it|that|this|one|result|last)\b/i.test(input)) { + return null; + } + return {}; + } + } + ]; + function resolveExplicitSearchResultRoute(input) { + for (const route of SEARCH_RESULT_ROUTES) { + const args = route.resolve(input); + if (args) { + return toolDecision3("open_search_result", route.reason, args); + } + } + return null; + } + + // src/utils/summarizeExplicitResolver.ts + function toolDecision4(next, reason, args) { + return { type: "tool", next, args, reason }; + } + function numberArg2(value) { + if (!value) { + return void 0; + } + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : void 0; + } + var SUMMARIZE_ROUTES = [ + { + reason: "summarize-current-tab", + resolve: (input) => /summarize\s+(?:the\s+)?(?:current|this|active)\s+tab/i.test(input) ? {} : null + }, + { + reason: "summarize-tab-index", + resolve: (input) => { + const match = input.match(/summarize\s+(?:the\s+)?tab\s+(?\d+)/i) || input.match(/summarize\s+(?:the\s+)?(?:first|1st)\s+tab/i); + if (!match) { + return null; + } + const index2 = numberArg2(match.groups?.index) ?? 1; + return { index: index2 }; + } + }, + { + reason: "summarize-tab-query", + resolve: (input) => { + const match = input.match( + /summarize\s+(?:the\s+)?"?(?[^"\d][^"]+?)"?\s*tab/i + ); + const query = match?.groups?.query?.trim(); + if (!query || /^(?:current|this|active)$/i.test(query)) { + return null; + } + return { query }; + } + }, + { + reason: "summarize-page", + resolve: (input) => /summarize\s+(?:this\s+)?(?:page|article|website|site)?|(?:what\s+is|tell\s+me\s+about)\s+this\s+(?:page|article|website|site)|give\s+(?:me\s+)?(?:a\s+)?summary/i.test( + input + ) ? {} : null + } + ]; + function resolveExplicitSummarizeRoute(input) { + for (const route of SUMMARIZE_ROUTES) { + const args = route.resolve(input); + if (args) { + return toolDecision4("summarize_page", route.reason, args); + } + } + return null; + } + + // src/utils/decisionEngine.ts + var FAMILY_HANDLERS = { + list: resolveManifestListRoute, + search: resolveManifestSearchRoute, + mutation: resolveManifestMutationRoute, + other: null + }; + function decideDeterministicRoute(commandText, snapshot) { + const input = String(commandText || "").trim(); + if (!input) { + return { type: "no_match", actionable: false, reason: "empty-input" }; + } + const family = classifyCommandFamily(input); + const familyHandler = FAMILY_HANDLERS[family]; + if (familyHandler) { + const familyDecision = familyHandler(input, snapshot); + if (familyDecision) { + return familyDecision; + } + } + const searchResultExplicit = resolveExplicitSearchResultRoute(input); + if (searchResultExplicit) { + return searchResultExplicit; + } + const summarizeExplicit = resolveExplicitSummarizeRoute(input); + if (summarizeExplicit) { + return summarizeExplicit; + } + const explicit = resolveExplicitRoute(input); + if (explicit) { + return explicit; + } + if (family === "list" || family === "search" || family === "mutation") { + return { + type: "chat", + actionable: true, + reason: `${family}-family-unresolved`, + message: family === "list" ? "I am not sure what you want listed. Say whether you mean open tabs, a tab group, or a bookmarks folder. [Help](https://kahana.co/docs)" : family === "search" ? "I am not sure what to search for. Include what to find and, if it helps, where (for example a folder or source). [Help](https://kahana.co/docs)" : "I am not sure which page or control you want to change. Say in plain language what should happen and where (for example which tab, site, or button). [Kahana documentation](https://kahana.co/docs)" + }; + } + const actionable = looksActionableText(input); + if (actionable) { + return { + type: "chat", + actionable: true, + reason: "actionable-but-unsupported", + message: "I could not match that to one clear, safe step in the browser. Describe what to change and where in more detail. [Help](https://kahana.co/docs)" + }; + } + return { type: "no_match", actionable: false, reason: "non-actionable" }; + } + + // src/utils/routingStateCache.ts + var RoutingStateCache = class { + folderNames = /* @__PURE__ */ new Set(); + groupNames = /* @__PURE__ */ new Set(); + dirty = true; + refreshing = false; + initialized = false; + lastRefresh = 0; + refreshTimer = null; + refreshTtlMs = 15e3; + normalizeEntityName(value) { + const normalized = normalizeRouteName(value || ""); + return normalized || null; + } + markFresh() { + this.dirty = false; + this.lastRefresh = Date.now(); + } + refreshGroupsFromBrowser(reason) { + const nextGroups = /* @__PURE__ */ new Set(); + const topWin = getBrowserWindow(); + const gBrowser = topWin?.gBrowser; + const groups = gBrowser?.getAllTabGroups ? gBrowser.getAllTabGroups() : gBrowser?.tabGroups || []; + for (const group of Array.from(groups || [])) { + const normalized = normalizeRouteName(group?.label || ""); + if (normalized) { + nextGroups.add(normalized); + } + } + this.groupNames = nextGroups; + this.markFresh(); + assistantLogger.debug("routing-state", "Groups refreshed", { + reason, + groups: nextGroups.size + }); + } + replaceFolderNames(names, reason) { + const nextFolders = /* @__PURE__ */ new Set(); + for (const name of names) { + const normalized = this.normalizeEntityName(name); + if (normalized) { + nextFolders.add(normalized); + } + } + this.folderNames = nextFolders; + this.markFresh(); + assistantLogger.debug("routing-state", "Folders replaced", { + reason, + folders: nextFolders.size + }); + } + ensureInitialized() { + if (this.initialized) { + return; + } + this.initialized = true; + const win = globalThis.window; + if (win?.addEventListener) { + win.addEventListener( + "TabGroupCreate", + () => { + try { + this.refreshGroupsFromBrowser("tab-group-create-event"); + } catch (error) { + assistantLogger.warn( + "routing-state", + "TabGroupCreate fast refresh failed", + error + ); + this.markDirty("tab-group-create"); + } + }, + true + ); + win.addEventListener( + "TabGroupRemoved", + () => { + try { + this.refreshGroupsFromBrowser("tab-group-removed-event"); + } catch (error) { + assistantLogger.warn( + "routing-state", + "TabGroupRemoved fast refresh failed", + error + ); + this.markDirty("tab-group-removed"); + } + }, + true + ); + win.addEventListener( + OASIS_EVENT_BOOKMARK_FOLDERS_CHANGED, + (event) => { + const detail = event.detail; + if (Array.isArray(detail?.folderNames)) { + this.replaceFolderNames(detail.folderNames, "bookmark-folders-event"); + return; + } + this.markDirty("bookmark-folders-event"); + } + ); + } + this.scheduleRefresh("init"); + } + markDirty(reason) { + this.dirty = true; + this.scheduleRefresh(reason); + } + applyMutation(mutation) { + this.ensureInitialized(); + if (mutation.kind === "dirty") { + this.markDirty(mutation.reason); + return; + } + const setRef = mutation.entity === "folder" ? this.folderNames : this.groupNames; + if (mutation.kind === "upsert") { + const normalized = this.normalizeEntityName(mutation.name); + if (normalized) { + setRef.add(normalized); + } + } else if (mutation.kind === "delete") { + const normalized = this.normalizeEntityName(mutation.name); + if (normalized) { + setRef.delete(normalized); + } + } else if (mutation.kind === "rename") { + const from = this.normalizeEntityName(mutation.from); + const to = this.normalizeEntityName(mutation.to); + if (from) { + setRef.delete(from); + } + if (to) { + setRef.add(to); + } + } + this.markFresh(); + this.scheduleRefresh(`mutation-${mutation.kind}`); + assistantLogger.debug("routing-state", "Mutation applied", { + kind: mutation.kind, + entity: mutation.entity + }); + } + getSnapshotSync() { + this.ensureInitialized(); + const now2 = Date.now(); + const stale = this.dirty || now2 - this.lastRefresh > this.refreshTtlMs || this.lastRefresh === 0; + if (stale) { + this.scheduleRefresh("snapshot-stale"); + } + return { + folderNames: new Set(this.folderNames), + groupNames: new Set(this.groupNames), + stale + }; + } + scheduleRefresh(reason) { + if (this.refreshTimer != null) { + return; + } + const timerHost = globalThis.window; + if (!timerHost?.setTimeout) { + return; + } + this.refreshTimer = timerHost.setTimeout(() => { + this.refreshTimer = null; + void this.refreshNow(reason); + }, 120); + } + async refreshNow(reason) { + if (this.refreshing) { + this.dirty = true; + return; + } + this.refreshing = true; + try { + const nextFolders = /* @__PURE__ */ new Set(); + const folderSnapshot = await bookmarkFolders.getAllReadOnly(); + if (folderSnapshot.ok) { + for (const folder of folderSnapshot.folders) { + const normalized = normalizeRouteName(folder.name); + if (normalized) { + nextFolders.add(normalized); + } + } + } + const nextGroups = /* @__PURE__ */ new Set(); + this.refreshGroupsFromBrowser("full-refresh"); + for (const groupName of this.groupNames) { + nextGroups.add(groupName); + } + this.folderNames = nextFolders; + this.groupNames = nextGroups; + this.markFresh(); + assistantLogger.debug("routing-state", "State refreshed", { + reason, + folders: nextFolders.size, + groups: nextGroups.size + }); + } catch (e2) { + assistantLogger.warn("routing-state", "Refresh failed", e2); + this.dirty = true; + } finally { + this.refreshing = false; + } + } + }; + var routingStateCache = new RoutingStateCache(); + + // src/utils/deterministicRouter.ts + function routeDeterministically(commandText) { + routingStateCache.ensureInitialized(); + const snapshot = routingStateCache.getSnapshotSync(); + return decideDeterministicRoute(commandText, snapshot); + } + function markRoutingStateDirty(reason) { + routingStateCache.applyMutation({ kind: "dirty", reason }); + } + function applyRoutingStateMutation(mutation) { + routingStateCache.applyMutation(mutation); + } + + // src/services/interactionState.ts + var InteractionStateStore = class { + pendingConfirmation = null; + pendingAmbiguity = null; + continuationQueue = []; + recentSearchResults = []; + assistantWindow; + constructor(assistantWindow2 = window) { + this.assistantWindow = assistantWindow2; + this.assistantWindow.oasisGetPendingConfirmation = () => this.getPendingConfirmation(); + this.assistantWindow.oasisClearPendingConfirmation = () => this.clearPendingConfirmation(); + this.assistantWindow.oasisGetPendingAmbiguity = () => this.getPendingAmbiguity(); + } + getPendingConfirmation() { + return this.pendingConfirmation; + } + setPendingConfirmation(pending) { + this.pendingConfirmation = pending; + if (pending) { + this.clearPendingAmbiguity(); + } + this.emitConfirmationUpdate(pending); + } + clearPendingConfirmation() { + this.pendingConfirmation = null; + this.emitConfirmationUpdate(null); + } + getPendingAmbiguity() { + return this.pendingAmbiguity; + } + setPendingAmbiguity(pending) { + this.pendingAmbiguity = pending; + if (pending) { + assistantLogger.debug("interaction", "Pending ambiguity set", { + kind: pending.kind, + name: pending.name, + query: pending.query || "", + all: !!pending.all + }); + return; + } + assistantLogger.debug("interaction", "Pending ambiguity cleared"); + } + clearPendingAmbiguity() { + this.pendingAmbiguity = null; + } + getContinuationQueue() { + return [...this.continuationQueue]; + } + setContinuationQueue(queue2) { + this.continuationQueue = queue2.map((item) => String(item || "").trim()).filter(Boolean); + assistantLogger.debug("interaction", "Continuation queue updated", { + length: this.continuationQueue.length + }); + } + takeContinuationQueue() { + const next = [...this.continuationQueue]; + this.continuationQueue = []; + if (next.length > 0) { + assistantLogger.debug("interaction", "Continuation queue consumed", { + length: next.length + }); + } + return next; + } + clearContinuationQueue() { + if (this.continuationQueue.length > 0) { + assistantLogger.debug("interaction", "Continuation queue cleared", { + length: this.continuationQueue.length + }); + } + this.continuationQueue = []; + } + getRecentSearchResults() { + return this.recentSearchResults.map((result) => ({ ...result })); + } + setRecentSearchResults(results) { + this.recentSearchResults = results.filter((result) => !!result.url).slice(0, 25).map((result) => ({ ...result })); + assistantLogger.debug("interaction", "Recent search results updated", { + count: this.recentSearchResults.length + }); + } + clearRecentSearchResults() { + if (this.recentSearchResults.length > 0) { + assistantLogger.debug("interaction", "Recent search results cleared"); + } + this.recentSearchResults = []; + } + emitConfirmationUpdate(pending) { + try { + const relay = this.assistantWindow.oasisSetPendingConfirmationRelay; + if (typeof relay === "function") { + relay(pending); + } + window.dispatchEvent( + new CustomEvent(OASIS_EVENT_CONFIRMATION_UPDATE, { detail: pending }) + ); + } catch (error) { + assistantLogger.error( + "interaction", + "Failed to update pending confirmation state", + error + ); + } + } + }; + var interactionState = new InteractionStateStore(); + function getPendingConfirmation() { + return interactionState.getPendingConfirmation(); + } + function setPendingConfirmation(pending) { + interactionState.setPendingConfirmation(pending); + } + function clearPendingConfirmation() { + interactionState.clearPendingConfirmation(); + } + function getPendingAmbiguity() { + return interactionState.getPendingAmbiguity(); + } + function setPendingAmbiguity(pending) { + interactionState.setPendingAmbiguity(pending); + } + function clearPendingAmbiguity() { + interactionState.clearPendingAmbiguity(); + } + function getContinuationQueue() { + return interactionState.getContinuationQueue(); + } + function setContinuationQueue(queue2) { + interactionState.setContinuationQueue(queue2); + } + function takeContinuationQueue() { + return interactionState.takeContinuationQueue(); + } + function clearContinuationQueue() { + interactionState.clearContinuationQueue(); + } + function getRecentSearchResults() { + return interactionState.getRecentSearchResults(); + } + function setRecentSearchResults(results) { + interactionState.setRecentSearchResults(results); + } + function clearRecentSearchResults() { + interactionState.clearRecentSearchResults(); + } + + // src/services/commandExecutionRegistry.ts + var commandExecutors = /* @__PURE__ */ new Map(); + function registerCommandExecutors(commands2) { + commandExecutors.clear(); + for (const command of commands2) { + commandExecutors.set(command.commandName, command); + } + } + function getCommandExecutor(commandName) { + const key = String(commandName || "").trim(); + if (!key) { + return null; + } + return commandExecutors.get(key) || null; + } + function listRegisteredCommandNames() { + return Array.from(commandExecutors.keys()); + } + + // src/commands.ts + function getChrome2() { + const { topWin, gBrowser, Services, PlacesUtils } = getChromeContext(); + return { topWin, gBrowser, Services, PlacesUtils }; + } + function stringArg(args, key) { + const value = args[key]; + return typeof value === "string" ? value : void 0; + } + function numberArg3(args, key) { + const value = args[key]; + return typeof value === "number" && Number.isFinite(value) ? value : void 0; + } + function booleanArg(args, key) { + const value = args[key]; + return typeof value === "boolean" ? value : void 0; + } + function numberArrayArg(args, key) { + const value = args[key]; + if (!Array.isArray(value)) return []; + return value.map( + (item) => typeof item === "number" && Number.isFinite(item) ? item : null + ).filter((item) => item != null); + } + function ambiguityTargetArg(args) { + const value = stringArg(args, "target"); + if (!value) { + return void 0; + } + const normalized = value.trim().toLowerCase(); + if (normalized === "bookmark-folder" || normalized === "tab-group" || normalized === "tab" || normalized === "cancel") { + return normalized; + } + return void 0; + } + function tabByIndexOrCurrent(gBrowser, index2) { + if (index2 == null) return gBrowser?.selectedTab || null; + return findTabByIndex(gBrowser, index2); + } + function tabByIndex(gBrowser, index2) { + const i2 = Math.max(1, Math.floor(index2)); + const tabs = Array.from(gBrowser.tabs); + if (i2 > tabs.length) return null; + return tabs[i2 - 1] || null; + } + function asTabOps(gBrowser) { + return gBrowser; + } + function normalizeQuery(value) { + return (value || "").trim().toLowerCase(); + } + function toWebSearchUrl(query) { + return `https://www.google.com/search?q=${encodeURIComponent(query)}`; + } + function analyzeGroupMoveImpact(tabsToMove) { + const affectedGroups = /* @__PURE__ */ new Set(); + const emptiedGroups = /* @__PURE__ */ new Set(); + for (const tab of tabsToMove) { + const group = tab.group; + if (!group) continue; + const groupName = group.label || "(unnamed)"; + affectedGroups.add(groupName); + const groupTabs = group.tabs || []; + const movingTabs = groupTabs.filter( + (groupTab) => tabsToMove.includes(groupTab) + ); + if (groupTabs.length > 0 && movingTabs.length === groupTabs.length) { + emptiedGroups.add(groupName); + } + } + return { + affectedGroups: Array.from(affectedGroups), + emptiedGroups: Array.from(emptiedGroups) + }; + } + var LIST_WINDOW_SCOPE_ALIASES = /* @__PURE__ */ new Set([ + "window", + "current window", + "this window", + "open tabs", + "all open tabs", + "tabs", + "all tabs", + "my tabs", + "current tabs", + "active tabs" + ]); + function normalizeListTargetName(value) { + let next = String(value || "").replace(/["']/g, " ").trim(); + next = next.replace(/^\s*(?:my|the)\s+/i, ""); + next = next.replace( + /\s+(?:tab\s*group|bookmark\s*folder|folder|group|hub)\s*$/i, + "" + ); + return next.trim(); + } + var ListTabsCommand = class { + commandName = "list_tabs"; + description = "List tabs. Accepts optional arguments: { scope?: 'window'|'tab-group'|'bookmark-folder', name?: string }. If name is provided without scope, resolves tab-group vs bookmark-folder by runtime state."; + async execute(args) { + const { gBrowser } = getChrome2(); + if (!gBrowser) return { message: "Browser UI (gBrowser) not available." }; + const scope = normalizeName(stringArg(args, "scope") || ""); + const name = normalizeListTargetName(stringArg(args, "name") || ""); + const listWindowTabs = () => { + const titles = getTabs(gBrowser).map((tab) => tabTitle(tab)); + return { message: JSON.stringify(titles.slice(0, 50)) }; + }; + const listGroupTabs = (groupName) => { + if (!groupName) { + return { message: "Which tab group should I list tabs from?" }; + } + const group = findGroupByName(gBrowser, groupName); + if (!group) { + return { message: `No tab group named "${groupName}".` }; + } + const tabs = (group.tabs || []).slice(0, 50).map((tab) => ({ + title: tabTitle(tab), + url: tabUrl(tab) + })); + if (tabs.length === 0) { + return { message: `Tab group "${groupName}" has no tabs.` }; + } + return { + message: `Tabs in tab group "${group.label || groupName}": ${JSON.stringify(tabs)}` + }; + }; + const listFolderTabs = async (folderName) => { + if (!folderName) { + return { message: "Which bookmark folder should I list tabs from?" }; + } + const foldersReadOnly = await bookmarkFolders.getAllReadOnly(); + if (!foldersReadOnly.ok) { + return { message: "Failed to read bookmark folders right now." }; + } + const target = normalizeName(folderName); + const folder = foldersReadOnly.folders.find( + (item) => normalizeName(item.name) === target + ); + if (!folder) { + return { message: `No bookmark folder named "${folderName}".` }; + } + const items = folder.items.slice(0, 50).map((item) => ({ + title: item.title || item.url, + url: item.url + })); + if (items.length === 0) { + return { message: `Bookmark folder "${folder.name}" is empty.` }; + } + return { + message: `Tabs in bookmark folder "${folder.name}": ${JSON.stringify(items)}` + }; + }; + if (scope === "window" || scope === "current-window" || scope === "this-window") { + return listWindowTabs(); + } + if (scope === "tab-group" || scope === "tab_group" || scope === "group") { + return listGroupTabs(name); + } + if (scope === "bookmark-folder" || scope === "bookmark_folder" || scope === "folder" || scope === "hub") { + return await listFolderTabs(name); + } + if (name) { + if (LIST_WINDOW_SCOPE_ALIASES.has(normalizeName(name))) { + return listWindowTabs(); + } + const group = findGroupByName(gBrowser, name); + const foldersReadOnly = await bookmarkFolders.getAllReadOnly(); + if (!foldersReadOnly.ok) { + if (group) { + return listGroupTabs(name); + } + return { + message: `I could not find a tab group named "${name}", and bookmark folders are temporarily unavailable. Try "list tabs", "list tabs in tab group ${name}", or retry in a moment.` + }; + } + const folder = foldersReadOnly.folders.find( + (item) => normalizeName(item.name) === normalizeName(name) + ); + if (group && folder) { + return { + message: `I found both a tab group and a bookmark folder named "${name}". Say "list tabs in tab group ${name}" or "list tabs in bookmark folder ${name}".` + }; + } + if (group) { + return listGroupTabs(name); + } + if (folder) { + return await listFolderTabs(name); + } + return { + message: `I could not find a tab group or bookmark folder named "${name}". Try "list tabs" for open tabs, or "list tabs in tab group ${name}" / "list tabs in bookmark folder ${name}".` + }; + } + return listWindowTabs(); + } + }; + var NewWindowCommand = class { + commandName = "new_window"; + description = "Open a new browser window."; + async execute(_args) { + const { topWin } = getChrome2(); + if (!topWin?.OpenBrowserWindow) + return { message: "Browser UI not available." }; + topWin.OpenBrowserWindow(); + return { message: "Successfully opened a new window." }; + } + }; + var OrganizeWindowsCommand = class { + commandName = "organize_windows"; + description = "Arrange two or more windows side-by-side."; + async execute(_args) { + const { Services } = getChrome2(); + const windowManager = Services?.wm; + const windows = windowManager?.getEnumerator?.("navigator:browser"); + if (!windows) return { message: "Services module not available." }; + const browserWindows = []; + while (windows.hasMoreElements()) { + const win = windows.getNext(); + const docEl = win.document?.documentElement; + if (!win.closed && docEl?.getAttribute("windowtype") === "navigator:browser") { + browserWindows.push(win); + } + } + if (browserWindows.length < 2) { + return { message: "You need at least two windows to organize." }; + } + const screen = browserWindows[0].screen; + const availWidth = screen.availWidth; + const availHeight = screen.availHeight; + const availLeft = screen.availLeft || 0; + const availTop = screen.availTop || 0; + const numWindows = browserWindows.length; + const windowWidth = Math.floor(availWidth / numWindows); + for (let i2 = 0; i2 < numWindows; i2++) { + const win = browserWindows[i2]; + if (win.windowState !== 1) { + win.restore(); + } + const xPos = availLeft + windowWidth * i2; + win.resizeTo(windowWidth, availHeight); + win.moveTo(xPos, availTop); + } + return { message: `Organized ${numWindows} windows side-by-side.` }; + } + }; + var ShowURLCommand = class { + commandName = "show_url"; + description = "Open a URL in a new tab."; + async execute(args) { + const { topWin } = getChrome2(); + if (!topWin?.openTrustedLinkIn) + return { message: "Browser UI not available." }; + const url = stringArg(args, "url"); + if (!url) return { message: "Missing 'url' argument." }; + topWin.openTrustedLinkIn(url, "tab"); + return { message: `Successfully opened URL: ${url}` }; + } + }; + var OpenUrlCommand = class { + commandName = "open_url"; + description = "Open a URL in a new browser tab. Arguments: { url: string }."; + async execute(args) { + const { topWin, Services } = getChrome2(); + const rawUrl = stringArg(args, "url"); + if (!rawUrl) { + return { message: "Missing 'url' argument." }; + } + if (!topWin?.openTrustedLinkIn) { + return { message: "Cannot open URL (openTrustedLinkIn not found)." }; + } + const normalizedInput = rawUrl.trim(); + if (!normalizedInput) { + return { message: "Missing 'url' argument." }; + } + let url = normalizedInput; + try { + url = withUriFixup(normalizedInput, Services); + } catch (error) { + assistantLogger.warn("commands", "Failed to fixup URI", error); + } + topWin.openTrustedLinkIn(url, "tab"); + return { message: `Opened URL in a new tab: ${url}` }; + } + }; + var WebSearchCommand = class { + commandName = "web_search"; + description = "Search the web in a new tab. Arguments: { query: string }."; + async execute(args) { + const { topWin } = getChrome2(); + const query = stringArg(args, "query"); + if (!query) { + return { message: "Missing 'query' argument." }; + } + if (!topWin?.openTrustedLinkIn) { + return { message: "Cannot open web search (openTrustedLinkIn not found)." }; + } + const searchUrl = toWebSearchUrl(query); + topWin.openTrustedLinkIn(searchUrl, "tab"); + return { message: `Opened web search for "${query}" in a new tab.` }; + } + }; + var OpenTabCommand = class { + commandName = "open_tab"; + description = "Legacy alias that opens a URL or web query in a new tab. Prefer open_url({url}) or web_search({query})."; + async execute(args) { + const url = stringArg(args, "url"); + const query = stringArg(args, "query"); + if (query?.trim()) { + return await new WebSearchCommand().execute({ query }); + } + if (!url) { + return { message: "Missing 'url' argument." }; + } + if (url.includes(" ")) { + return await new WebSearchCommand().execute({ query: url }); + } + return await new OpenUrlCommand().execute({ url }); + } + }; + var CloseTabCommand = class { + commandName = "close_tab"; + description = "Close the active tab (or a tab by index). Accepts arguments: { index?: number, confirmed?: boolean } (1-based)."; + async execute(args) { + const { gBrowser } = getChrome2(); + if (!gBrowser) return { message: "Browser UI (gBrowser) not available." }; + const idx = numberArg3(args, "index"); + const tab = tabByIndexOrCurrent(gBrowser, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + const title = tabTitle(tab); + if (booleanArg(args, "confirmed") !== true) { + setPendingConfirmation({ + command: "close_tab", + args: { ...args, confirmed: true }, + description: `Close tab "${title}"?` + }); + return { + message: `Requesting confirmation to close tab "${title}"...`, + requiresConfirmation: true, + confirmationData: { title } + }; + } + clearPendingConfirmation(); + gBrowser.removeTab?.(tab); + return { message: `Closed tab: ${title}` }; + } + }; + var ReloadTabCommand = class { + commandName = "reload_tab"; + description = "Reload the current tab or a tab by index. Accepts arguments: { index?: number } (1-based)."; + async execute(args) { + const gb = asTabOps(getChrome2().gBrowser); + if (!gb?.reloadTab) + return { message: "Browser UI (gBrowser.reloadTab) not available." }; + const idx = numberArg3(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + gb.reloadTab(tab); + return { message: `Reloaded tab: ${tabTitle(tab)}` }; + } + }; + var ToggleMuteTabCommand = class { + commandName = "toggle_mute_tab"; + description = "Toggle mute for the current tab or a tab by index. Accepts arguments: { index?: number } (1-based)."; + async execute(args) { + const { gBrowser } = getChrome2(); + if (!gBrowser) return { message: "Browser UI (gBrowser) not available." }; + const idx = numberArg3(args, "index"); + const tab = tabByIndexOrCurrent(gBrowser, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + const toggle = tab.toggleMuteAudio; + if (typeof toggle !== "function") + return { message: "Mute is not available for this tab." }; + toggle.call(tab); + return { message: `Toggled mute for: ${tabTitle(tab)}` }; + } + }; + var PinTabCommand = class { + commandName = "pin_tab"; + description = "Pin the current tab or a tab by index. Accepts arguments: { index?: number } (1-based)."; + async execute(args) { + const gb = asTabOps(getChrome2().gBrowser); + if (!gb?.pinTab) + return { message: "Browser UI (gBrowser.pinTab) not available." }; + const idx = numberArg3(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + if (tab.pinned) + return { message: `Tab is already pinned: ${tabTitle(tab)}` }; + gb.pinTab(tab, {}); + return { message: `Pinned tab: ${tabTitle(tab)}` }; + } + }; + var UnpinTabCommand = class { + commandName = "unpin_tab"; + description = "Unpin the current tab or a tab by index. Accepts arguments: { index?: number } (1-based)."; + async execute(args) { + const gb = asTabOps(getChrome2().gBrowser); + if (!gb?.unpinTab) + return { message: "Browser UI (gBrowser.unpinTab) not available." }; + const idx = numberArg3(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + if (!tab.pinned) return { message: `Tab is not pinned: ${tabTitle(tab)}` }; + gb.unpinTab(tab); + return { message: `Unpinned tab: ${tabTitle(tab)}` }; + } + }; + var UnloadTabCommand = class { + commandName = "unload_tab"; + description = "Unload (discard) the current tab or a tab by index to free memory. Accepts arguments: { index?: number } (1-based)."; + async execute(args) { + const gb = asTabOps(getChrome2().gBrowser); + if (!gb?.explicitUnloadTabs) { + return { message: "Tab unload is not available in this build." }; + } + const idx = numberArg3(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + await gb.explicitUnloadTabs([tab]); + return { message: `Unloaded tab: ${tabTitle(tab)}` }; + } + }; + var NewTabToRightCommand = class { + commandName = "new_tab_to_right"; + description = "Open a new tab immediately to the right of the current tab or a tab by index. Accepts arguments: { index?: number } (1-based)."; + async execute(args) { + const gb = asTabOps(getChrome2().gBrowser); + if (!gb?.addAdjacentNewTab) { + return { + message: "Browser UI (gBrowser.addAdjacentNewTab) not available." + }; + } + const idx = numberArg3(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + gb.addAdjacentNewTab(tab); + return { message: `Opened a new tab to the right of: ${tabTitle(tab)}` }; + } + }; + var DuplicateTabCommand = class { + commandName = "duplicate_tab"; + description = "Duplicate the current tab or a tab by index. Accepts arguments: { index?: number } (1-based)."; + async execute(args) { + const gb = asTabOps(getChrome2().gBrowser); + if (!gb?.duplicateTab) { + return { message: "Browser UI (gBrowser.duplicateTab) not available." }; + } + const idx = numberArg3(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + gb.duplicateTab(tab); + return { message: `Duplicated tab: ${tabTitle(tab)}` }; + } + }; + var BookmarkTabCommand = class { + commandName = "bookmark_tab"; + description = "Bookmark the current tab or a tab by index (default bookmarks location). Accepts arguments: { index?: number } (1-based)."; + async execute(args) { + const { topWin, gBrowser } = getChrome2(); + const hook = topWin?.PlacesCommandHook?.bookmarkTabs; + if (!hook || !gBrowser) return { message: "Bookmarking is not available." }; + const idx = numberArg3(args, "index"); + const tab = tabByIndexOrCurrent(gBrowser, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + hook([tab]); + return { message: `Bookmarked tab: ${tabTitle(tab)}` }; + } + }; + var MoveTabToStartCommand = class { + commandName = "move_tab_to_start"; + description = "Move the current tab or a tab by index to the start of the tab strip. Accepts arguments: { index?: number } (1-based)."; + async execute(args) { + const gb = asTabOps(getChrome2().gBrowser); + if (!gb?.moveTabToStart) + return { message: "Browser UI (gBrowser.moveTabToStart) not available." }; + const idx = numberArg3(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + gb.moveTabToStart(tab); + return { message: `Moved tab to start: ${tabTitle(tab)}` }; + } + }; + var MoveTabToEndCommand = class { + commandName = "move_tab_to_end"; + description = "Move the current tab or a tab by index to the end of the tab strip. Accepts arguments: { index?: number } (1-based)."; + async execute(args) { + const gb = asTabOps(getChrome2().gBrowser); + if (!gb?.moveTabToEnd) + return { message: "Browser UI (gBrowser.moveTabToEnd) not available." }; + const idx = numberArg3(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + gb.moveTabToEnd(tab); + return { message: `Moved tab to end: ${tabTitle(tab)}` }; + } + }; + var SelectAllTabsCommand = class { + commandName = "select_all_tabs"; + description = "Select all tabs in the current window for multi-tab actions. Accepts no arguments."; + async execute(_args) { + const gb = asTabOps(getChrome2().gBrowser); + if (!gb?.selectAllTabs) + return { message: "Browser UI (gBrowser.selectAllTabs) not available." }; + gb.selectAllTabs(); + return { message: "Selected all tabs in this window." }; + } + }; + var CloseDuplicateTabsCommand = class { + commandName = "close_duplicate_tabs"; + description = "Close duplicate tabs (same URL) relative to the current tab or a tab by index. Accepts arguments: { index?: number, confirmed?: boolean } (1-based)."; + async execute(args) { + const gb = asTabOps(getChrome2().gBrowser); + if (!gb?.getDuplicateTabsToClose || !gb.removeTabs) { + return { message: "Closing duplicate tabs is not available." }; + } + const idx = numberArg3(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + const dupes = gb.getDuplicateTabsToClose(tab); + if (!dupes.length) { + return { message: "No duplicate tabs to close for this tab." }; + } + if (booleanArg(args, "confirmed") !== true) { + setPendingConfirmation({ + command: "close_duplicate_tabs", + args: { ...args, confirmed: true }, + description: `Close ${dupes.length} duplicate tab(s)?` + }); + return { + message: `Requesting confirmation to close ${dupes.length} duplicate tab(s)...`, + requiresConfirmation: true, + confirmationData: { count: dupes.length } + }; + } + clearPendingConfirmation(); + gb.removeTabs(dupes, { isUserTriggered: true }); + return { message: `Closed ${dupes.length} duplicate tab(s).` }; + } + }; + var CloseTabsToRightCommand = class { + commandName = "close_tabs_to_right"; + description = "Close all tabs to the right of the current tab or a tab by index. Accepts arguments: { index?: number, confirmed?: boolean } (1-based)."; + async execute(args) { + const gb = asTabOps(getChrome2().gBrowser); + if (!gb?._getTabsToTheEndFrom || !gb.removeTabs) { + return { message: "Closing tabs to the right is not available." }; + } + const idx = numberArg3(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + const toClose = gb._getTabsToTheEndFrom(tab); + if (!toClose.length) { + return { message: "No tabs to the right to close." }; + } + if (booleanArg(args, "confirmed") !== true) { + setPendingConfirmation({ + command: "close_tabs_to_right", + args: { ...args, confirmed: true }, + description: `Close ${toClose.length} tab(s) to the right?` + }); + return { + message: `Requesting confirmation to close ${toClose.length} tab(s) to the right...`, + requiresConfirmation: true, + confirmationData: { count: toClose.length } + }; + } + clearPendingConfirmation(); + gb.removeTabs(toClose, { isUserTriggered: true }); + return { message: `Closed ${toClose.length} tab(s) to the right.` }; + } + }; + var CloseTabsToLeftCommand = class { + commandName = "close_tabs_to_left"; + description = "Close all tabs to the left of the current tab or a tab by index. Accepts arguments: { index?: number, confirmed?: boolean } (1-based)."; + async execute(args) { + const gb = asTabOps(getChrome2().gBrowser); + if (!gb?._getTabsToTheStartFrom || !gb.removeTabs) { + return { message: "Closing tabs to the left is not available." }; + } + const idx = numberArg3(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + const toClose = gb._getTabsToTheStartFrom(tab); + if (!toClose.length) { + return { message: "No tabs to the left to close." }; + } + if (booleanArg(args, "confirmed") !== true) { + setPendingConfirmation({ + command: "close_tabs_to_left", + args: { ...args, confirmed: true }, + description: `Close ${toClose.length} tab(s) to the left?` + }); + return { + message: `Requesting confirmation to close ${toClose.length} tab(s) to the left...`, + requiresConfirmation: true, + confirmationData: { count: toClose.length } + }; + } + clearPendingConfirmation(); + gb.removeTabs(toClose, { isUserTriggered: true }); + return { message: `Closed ${toClose.length} tab(s) to the left.` }; + } + }; + var CloseOtherTabsCommand = class { + commandName = "close_other_tabs"; + description = "Close all tabs except the current tab or a tab by index. Accepts arguments: { index?: number, confirmed?: boolean } (1-based)."; + async execute(args) { + const gb = asTabOps(getChrome2().gBrowser); + if (!gb?.removeAllTabsBut) + return { message: "Closing other tabs is not available." }; + const idx = numberArg3(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + const others = getTabs(gb).filter((t2) => t2 !== tab && !t2.pinned); + if (!others.length) { + return { message: "No other unpinned tabs to close." }; + } + if (booleanArg(args, "confirmed") !== true) { + setPendingConfirmation({ + command: "close_other_tabs", + args: { ...args, confirmed: true }, + description: `Close ${others.length} other tab(s) (keeping "${tabTitle(tab)}")?` + }); + return { + message: `Requesting confirmation to close ${others.length} other tab(s)...`, + requiresConfirmation: true, + confirmationData: { count: others.length } + }; + } + clearPendingConfirmation(); + gb.removeAllTabsBut(tab, { skipWarnAboutClosingTabs: true }); + return { message: `Closed other tabs (kept: ${tabTitle(tab)}).` }; + } + }; + var ReopenClosedTabCommand = class { + commandName = "reopen_closed_tab"; + description = "Reopen the most recently closed tab from this window's closed-tab list. Accepts arguments: { index?: number } (0 = most recent)."; + async execute(args) { + const { topWin } = getChrome2(); + const ss = topWin?.SessionStore; + if (!ss?.undoCloseTab) + return { + message: "Session restore (reopen closed tab) is not available." + }; + const index2 = numberArg3(args, "index"); + const reopened = ss.undoCloseTab(topWin, index2 ?? 0); + if (!reopened) return { message: "No closed tab to reopen." }; + return { message: "Reopened the last closed tab." }; + } + }; + var OpenSendTabToDeviceCommand = class { + commandName = "open_send_tab_to_device"; + description = 'Open Firefox Sync "Send Tab to Device" so the user can pick a synced device. Accepts no arguments.'; + async execute(_args) { + const { topWin } = getChrome2(); + const sync = topWin?.gSync; + const anchor = topWin?.document?.getElementById?.( + "fxa-toolbar-menu-button" + ); + if (!sync?.showSendToDeviceViewFromFxaMenu || !anchor) { + return { + message: "Could not open Send Tab to Device. Sign in to Sync and ensure the account toolbar button is visible." + }; + } + sync.showSendToDeviceViewFromFxaMenu(anchor); + return { message: "Opened Send Tab to Device." }; + } + }; + var OpenTabNoteCommand = class { + commandName = "open_tab_note"; + description = "Open the tab note editor for the current tab or a tab by index. Accepts arguments: { index?: number } (1-based)."; + async execute(args) { + const gb = asTabOps(getChrome2().gBrowser); + const menu = gb?.tabNoteMenu; + if (!menu?.openPanel) + return { message: "Tab notes are not available in this build." }; + const idx = numberArg3(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + menu.openPanel(tab, {}); + return { message: `Opened tab note for: ${tabTitle(tab)}` }; + } + }; + var MoveTabToNewWindowCommand = class { + commandName = "move_tab_to_new_window"; + description = "Move the active tab (or a tab by index) to a new window. Accepts arguments: { index?: number } (1-based)."; + async execute(args) { + const { topWin, gBrowser } = getChrome2(); + if (!gBrowser || !topWin?.OpenBrowserWindow) { + return { message: "Browser UI not available." }; + } + const idx = numberArg3(args, "index"); + const tab = tabByIndexOrCurrent(gBrowser, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + const title = tabTitle(tab); + const newWin = topWin.OpenBrowserWindow(); + await new Promise((r2) => setTimeout(r2, 250)); + newWin.gBrowser?.adoptTab?.(tab, 0); + return { message: `Moved tab to new window: ${title}` }; + } + }; + var CopyTabUrlsCommand = class { + commandName = "copy_tab_urls"; + description = "Copy all tab URLs in the current window to the clipboard (one per line). Accepts no arguments."; + async execute(_args) { + const { gBrowser } = getChrome2(); + if (!gBrowser) return { message: "Browser UI (gBrowser) not available." }; + const urls = getTabs(gBrowser).map((tab) => tabUrl(tab)).filter(Boolean); + const text2 = urls.join("\n"); + try { + await navigator.clipboard.writeText(text2); + return { message: `Copied ${urls.length} URLs to clipboard.` }; + } catch { + return { message: `Copied fallback. URLs: +${text2}` }; + } + } + }; + var CreateBookmarkFolderCommand = class { + commandName = "create_bookmark_folder"; + description = "Create a managed bookmark folder. Accepts arguments: { name: string, include?: 'none'|'current'|'all' }."; + async execute(args) { + const name = stringArg(args, "name") || ""; + const includeRaw = stringArg(args, "include"); + const include = includeRaw === "current" || includeRaw === "all" || includeRaw === "none" ? includeRaw : "none"; + const res = await bookmarkFolders.create(name, { include }); + applyRoutingStateMutation({ + kind: "upsert", + entity: "folder", + name: res.name + }); + return { + message: `Created bookmark folder "${res.name}" with ${res.count} items.` + }; + } + }; + var DeleteBookmarkFolderCommand = class { + commandName = "delete_bookmark_folder"; + description = "Delete a managed bookmark folder by name. Accepts arguments: { name: string, closeTabs?: boolean, confirmed?: boolean }."; + async execute(args) { + const name = stringArg(args, "name"); + if (!name) return { message: "Which folder should I delete?" }; + if (booleanArg(args, "confirmed") !== true) { + const closeTabs2 = booleanArg(args, "closeTabs") === true; + const closeMsg = closeTabs2 ? " and close all associated tabs" : ""; + setPendingConfirmation({ + command: "delete_bookmark_folder", + args: { ...args, confirmed: true }, + description: `Delete bookmark folder "${name}"${closeMsg}?` + }); + return { + message: `Requesting confirmation to delete bookmark folder "${name}"${closeMsg}...`, + requiresConfirmation: true, + confirmationData: { name, closeTabs: closeTabs2 } + }; + } + clearPendingConfirmation(); + const closeTabs = booleanArg(args, "closeTabs") === true; + const res = await bookmarkFolders.delete(name, { closeTabs }); + if (res.removed === 0) return { message: `No folder named "${name}".` }; + applyRoutingStateMutation({ + kind: "delete", + entity: "folder", + name: res.name + }); + return { + message: `Deleted bookmark folder "${res.name}" (${res.removed} items removed).` + }; + } + }; + var ListBookmarkFoldersCommand = class { + commandName = "list_bookmark_folders"; + description = "List all managed bookmark folders. Accepts no arguments."; + async execute(_args) { + const items = await bookmarkFolders.list(); + if (!items.length) return { message: "No bookmark folders yet." }; + return { + message: JSON.stringify(items.map((h2) => `${h2.name} (${h2.count})`)) + }; + } + }; + var RenameBookmarkFolderCommand = class { + commandName = "rename_bookmark_folder"; + description = "Rename a managed bookmark folder. Accepts arguments: { from: string, to: string }."; + async execute(args) { + const from = stringArg(args, "from"); + const to = stringArg(args, "to"); + if (!from || !to) + return { message: "Please provide old and new folder names." }; + const r2 = await bookmarkFolders.rename(from, to); + if (r2.ok) { + applyRoutingStateMutation({ + kind: "rename", + entity: "folder", + from, + to + }); + } + return { + message: r2.ok ? `Renamed "${from}" to "${to}".` : `Rename failed: ${r2.msg || "unknown error"}` + }; + } + }; + var AddTabToBookmarkFolderCommand = class { + commandName = "add_tab_to_bookmark_folder"; + description = "Add tabs to a managed bookmark folder. Accepts arguments: { name: string, query?: string, all?: boolean } (query matches title/URL). all=true adds all tabs. If no query/all, adds current tab."; + async execute(args) { + const name = stringArg(args, "name"); + if (!name) return { message: "Which folder should I add tabs to?" }; + const { gBrowser } = getChrome2(); + if (!gBrowser) return { message: "Browser UI not available." }; + const query = normalizeQuery(stringArg(args, "query")); + const all = booleanArg(args, "all") === true; + let tabsToAdd = []; + if (all) { + tabsToAdd = getTabs(gBrowser); + } else if (query) { + tabsToAdd = findTabsByQuery(gBrowser, query); + if (tabsToAdd.length === 0) { + return { + message: `No tabs found matching "${stringArg(args, "query") || ""}".` + }; + } + } else { + const current = gBrowser.selectedTab; + if (current) { + tabsToAdd = [current]; + } + } + if (tabsToAdd.length === 0) return { message: "No tabs available to add." }; + const r2 = await bookmarkFolders.addTabs(name, tabsToAdd); + if (!r2.ok) return { message: `Failed to add tabs to "${name}".` }; + applyRoutingStateMutation({ + kind: "upsert", + entity: "folder", + name + }); + const count3 = tabsToAdd.length; + return { message: `Added ${count3} tab(s) to bookmark folder "${name}".` }; + } + }; + var RemoveTabFromBookmarkFolderCommand = class { + commandName = "remove_tab_from_bookmark_folder"; + description = "Remove a tab from a managed bookmark folder. Accepts arguments: { name: string, url?: string } (defaults to current tab URL)."; + async execute(args) { + const name = stringArg(args, "name"); + if (!name) return { message: "Which folder?" }; + let url = stringArg(args, "url"); + if (!url) { + const { gBrowser } = getChrome2(); + if (gBrowser) { + url = tabUrl(gBrowser.selectedTab || null); + } + } + if (!url) return { message: "Could not determine URL to remove." }; + const r2 = await bookmarkFolders.removeUrl(name, url); + return { + message: r2.ok ? `Removed URL from folder "${name}".` : `Failed to remove URL from folder "${name}" (maybe not found).` + }; + } + }; + var OpenBookmarkFolderCommand = class { + commandName = "open_bookmark_folder"; + description = "Open all bookmarks from a managed folder. Accepts arguments: { name: string, where?: 'tabs'|'window'|'tabgroup' }. 'tabgroup' creates a new visual group."; + async execute(args) { + const name = stringArg(args, "name"); + if (!name) return { message: "Which folder should I open?" }; + const whereRaw = stringArg(args, "where"); + const where = whereRaw === "window" || whereRaw === "tabgroup" ? whereRaw : "tabs"; + const r2 = await bookmarkFolders.openFolder(name, where); + return { + message: r2.ok ? `Opened folder "${name}" in ${where}.` : `Failed to open folder "${name}".` + }; + } + }; + var AddSplitViewCommand = class { + commandName = "add_split_view"; + description = "Add split view with tabs side-by-side. Accepts arguments: { indices?: [number, number], withIndex?: number, withQuery?: string }. Use 'indices' to specify two tabs by number. Use 'withIndex' or 'withQuery' to split current tab with another. If no arguments, opens split view with a new tab."; + async execute(args) { + const { topWin, gBrowser, Services } = getChrome2(); + if (!gBrowser || !topWin) return { message: "Browser UI not available." }; + const splitViewEnabled = Services?.prefs?.getBoolPref?.( + "browser.tabs.splitView.enabled", + false + ); + if (!splitViewEnabled) { + return { message: "Split view is not enabled in this browser." }; + } + let tab1 = null; + let tab2 = null; + const indices = numberArrayArg(args, "indices"); + if (indices.length >= 2) { + const i1 = Math.max(1, Math.floor(indices[0])); + const i2 = Math.max(1, Math.floor(indices[1])); + const first = tabByIndex(gBrowser, i1); + const second2 = tabByIndex(gBrowser, i2); + if (!first) return { message: `No tab ${i1}.` }; + if (!second2) return { message: `No tab ${i2}.` }; + if (i1 === i2) return { message: "Cannot split a tab with itself." }; + tab1 = first; + tab2 = second2; + } else { + tab1 = gBrowser.selectedTab || null; + const withIndex = numberArg3(args, "withIndex"); + const withQuery = normalizeQuery(stringArg(args, "withQuery")); + if (withIndex != null) { + const i2 = Math.max(1, Math.floor(withIndex)); + tab2 = tabByIndex(gBrowser, i2); + if (!tab2) return { message: `No tab ${i2}.` }; + } else if (withQuery) { + tab2 = findTabsByQuery(gBrowser, withQuery)[0] || null; + if (!tab2) { + return { + message: `No tab found matching "${stringArg(args, "withQuery") || ""}".` + }; + } + } else { + tab2 = gBrowser.addTrustedTab?.("about:newtab") || null; + } + } + if (!tab1 || !tab2) + return { message: "Unable to resolve tabs for split view." }; + if (tab1 === tab2) { + return { message: "Cannot split a tab with itself." }; + } + if (tab1.pinned || tab2.pinned) { + return { message: "Cannot add pinned tabs to split view." }; + } + if (tab1.splitview) { + return { message: `Tab "${tab1.label}" is already in a split view.` }; + } + if (tab2.splitview) { + return { message: `Tab "${tab2.label}" is already in a split view.` }; + } + try { + gBrowser.addTabSplitView?.([tab1, tab2], { + insertBefore: tab1 + }); + const title1 = tabTitle(tab1); + const title2 = tabTitle(tab2); + return { + message: `Added split view: "${title1}" and "${title2}".` + }; + } catch (e2) { + return { message: `Failed to create split view: ${e2}` }; + } + } + }; + var RemoveSplitViewCommand = class { + commandName = "remove_split_view"; + description = "Remove split view from the current tab (unsplit tabs)."; + async execute(_args) { + const { gBrowser } = getChrome2(); + if (!gBrowser) return { message: "Browser UI not available." }; + const currentTab = gBrowser.selectedTab; + if (!currentTab) return { message: "No active tab found." }; + const splitview = currentTab.splitview; + if (!splitview?.unsplitTabs) { + return { message: "This tab is not in a split view." }; + } + try { + splitview.unsplitTabs(); + return { message: "Split view removed. Tabs are now separate." }; + } catch (e2) { + return { message: `Failed to remove split view: ${e2}` }; + } + } + }; + var SplitTabsCommand = class { + commandName = "split_tabs"; + description = "Split specified tabs into side-by-side windows. Accepts arguments: { indices: number[] }."; + async execute(args) { + const { topWin, gBrowser } = getChrome2(); + if (!gBrowser || !topWin?.OpenBrowserWindow) + return { message: "Browser UI not available." }; + const indices = numberArrayArg(args, "indices"); + if (indices.length < 2) { + return { + message: "Please provide at least 2 tab indices to split (e.g., { indices: [1, 2] })." + }; + } + const tabs = []; + for (const idx of indices) { + const i2 = Math.max(1, Math.floor(idx)); + const tab = tabByIndex(gBrowser, i2); + if (!tab) return { message: `No tab ${i2}.` }; + tabs.push(tab); + } + const screen = topWin.screen; + const availWidth = screen.availWidth; + const availHeight = screen.availHeight; + const availLeft = screen.availLeft || 0; + const availTop = screen.availTop || 0; + const numTabs = tabs.length; + const windows = []; + for (let i2 = 0; i2 < numTabs; i2++) { + const tab = tabs[i2]; + const title = tabTitle(tab); + const newWin = topWin.OpenBrowserWindow(); + windows.push({ win: newWin, tab, title }); + await new Promise((r2) => setTimeout(r2, 100)); + } + await new Promise((r2) => setTimeout(r2, 300)); + for (let i2 = 0; i2 < numTabs; i2++) { + const { win, tab } = windows[i2]; + const windowWidth = Math.floor(availWidth / numTabs); + const windowHeight = availHeight; + const xPos = availLeft + windowWidth * i2; + const yPos = availTop; + win.resizeTo(windowWidth, windowHeight); + win.moveTo(xPos, yPos); + try { + const sidebar = win.document?.getElementById("sidebar-box"); + if (sidebar && !sidebar.hidden) { + win.SidebarController?.hide?.(); + } + } catch (e2) { + assistantLogger.warn("commands", "Failed to close sidebar", e2); + } + win.gBrowser?.adoptTab?.(tab, 0); + } + const tabTitles = windows.map((w3) => w3.title).join(", "); + return { message: `Split ${numTabs} tabs side-by-side: ${tabTitles}` }; + } + }; + var SummarizePageCommand = class { + commandName = "summarize_page"; + description = "Summarize the content of a webpage. Accepts arguments: { index?: number, query?: string }. Use 'index' for tab number (1-based), 'query' to find tab by title/URL. If no arguments, summarizes current tab."; + async execute(args) { + const { gBrowser } = getChrome2(); + if (!gBrowser) return { message: "Browser UI not available." }; + const idx = numberArg3(args, "index"); + let tab = tabByIndexOrCurrent(gBrowser, idx); + if (idx != null && !tab) return { message: `No tab ${idx}.` }; + const query = normalizeQuery(stringArg(args, "query")); + if (query && !idx) { + tab = findTabsByQuery(gBrowser, query)[0] || null; + if (!tab) { + return { + message: `No tab found matching "${stringArg(args, "query") || ""}".` + }; + } + } + const browser = tab?.linkedBrowser; + if (!browser) return { message: "No active tab found." }; + const url = browser.currentURI?.spec || ""; + const title = tabTitle(tab); + if (url.startsWith("about:") || url.startsWith("chrome://") || url.startsWith("moz-extension://")) { + return { message: "Cannot summarize browser internal pages." }; + } + try { + const currentWindowContext = browser.browsingContext?.currentWindowContext; + if (!currentWindowContext) { + return { + message: "Cannot access page content. The page may still be loading." + }; + } + const pageExtractor = currentWindowContext.getActor("PageExtractor"); + if (!pageExtractor) { + return { message: "Page content extractor not available." }; + } + let content = ""; + try { + content = await pageExtractor.getReaderModeContent?.() || ""; + } catch (e2) { + assistantLogger.warn( + "commands", + "Reader mode extraction failed, trying full text", + e2 + ); + } + if (!content || content.length < 50) { + try { + const result = await pageExtractor.getText?.(); + content = typeof result === "string" ? result : result?.text || ""; + } catch (e2) { + assistantLogger.warn("commands", "Full text extraction failed", e2); + } + } + content = content.replace(/\s+/g, " ").replace(/\n\s*\n/g, "\n").trim(); + if (!content || content.length < 50) { + return { + message: "Not enough content found on this page to summarize." + }; + } + const maxLength = 12e3; + if (content.length > maxLength) { + content = content.substring(0, maxLength) + "..."; + } + return { + message: `__SUMMARIZE_REQUEST__ +Title: ${title} +URL: ${url} + +Content: +${content}` + }; + } catch (e2) { + return { message: `Failed to extract page content: ${e2}` }; + } + } + }; + var SearchMemoryCommand = class { + commandName = "search_memory"; + description = `Search across multiple local sources: browsing history, bookmarks (including managed bookmark folders), open tabs, tab groups, and stored memory. Arguments: { query: string, folder?: string, source?: 'bookmark-folder' }. 'folder' filters to a specific managed bookmark folder; 'source' can scope to bookmark-folder results. Returns JSON with: { summary: string, resultsBySource: { [source]: [{ title, url, snippet }] }, results: [{ index, source, title, url, context, snippet }] }. Sources are: "history", "bookmark", "bookmark-folder", "tab", "tab-group", "memory".`; + async execute(args) { + const query = stringArg(args, "query"); + const folder = stringArg(args, "folder"); + const source = stringArg(args, "source"); + const sourceScope = source === "bookmark-folder" ? "bookmark-folder" : void 0; + if (!query) return { message: "Missing 'query' argument." }; + let results = await localMemory.search( + query, + 10, + folder ? { folder } : void 0 + ); + if (hasBookmarkFolderCandidates(results)) { + const snapshot = await bookmarkFolders.getAllReadOnly(); + if (snapshot.ok) { + const folderToUrls = buildFolderUrlMap(snapshot.folders); + const filtered = filterStaleBookmarkFolderResults( + results, + folderToUrls + ); + results = filtered.results; + if (filtered.dropped > 0) { + assistantLogger.debug( + "search-memory", + "Dropped stale bookmark-folder results", + { dropped: filtered.dropped } + ); + } + } else { + assistantLogger.warn( + "search-memory", + "Read-only folder snapshot failed; returning lexical results" + ); + } + } + const folderScoped = Boolean(folder); + const requiresBookmarkFolderOnly = folderScoped || sourceScope === "bookmark-folder"; + if (requiresBookmarkFolderOnly) { + const before = results.length; + results = results.filter( + (r2) => getMemoryDocSource(r2) === "bookmark-folder" + ); + if (before !== results.length) { + assistantLogger.debug( + "search-memory", + "Restricted results to bookmark-folder scope", + { + before, + after: results.length, + folderScoped, + sourceScope: sourceScope || "none" + } + ); + } + } + const scopeSuffix = folder ? ` in bookmark folder "${folder}"` : sourceScope === "bookmark-folder" ? " in bookmark folders" : ""; + if (results.length === 0) { + clearRecentSearchResults(); + if (!folderScoped && !sourceScope && query.trim() !== "*") { + setPendingConfirmation({ + command: "web_search", + args: { query }, + description: `No local matches found for "${query}". Search the web in a new tab?` + }); + return { + message: `No local matches found for "${query}". Would you like me to open a web search in a new tab?`, + requiresConfirmation: true, + confirmationData: { query, url: toWebSearchUrl(query) } + }; + } + const guidance = folder ? ` Try "list tabs in bookmark folder ${folder}" to inspect what is saved there.` : ""; + return { + message: `No matches found for "${query}"${scopeSuffix}.${guidance}` + }; + } + const sourceMap = { + history: "history", + bookmark: "bookmark", + tab: "tab", + "tab-group": "tab-group", + hub_item: "bookmark-folder", + bookmark_folder_item: "bookmark-folder", + memory: "memory" + }; + const structured = results.map((r2, i2) => { + const rawType = r2.metadata?.type || "memory"; + const source2 = sourceMap[rawType] || rawType; + const resolvedUrl = r2.url || r2.metadata?.url || r2.metadata?.hubName || ""; + return { + index: i2 + 1, + source: source2, + title: r2.metadata?.title || "(no title)", + url: resolvedUrl, + bookmarkGuid: r2.metadata?.bookmarkGuid || void 0, + context: r2.metadata?.context || (source2 === "history" ? "Browsing History" : source2 === "bookmark" ? "Bookmarks" : source2 === "bookmark-folder" ? `Bookmark Folder: ${r2.metadata?.hubName || "unknown"}` : source2 === "tab" ? "Open Tab" : source2 === "tab-group" ? "Tab Group" : "Memory"), + snippet: r2.text.length > 120 ? r2.text.substring(0, 120) + "..." : r2.text + }; + }); + setRecentSearchResults(structured); + const resultsBySource = {}; + for (const r2 of structured) { + const bucket = resultsBySource[r2.source] ??= []; + bucket.push({ + title: r2.title, + url: r2.url, + snippet: r2.snippet ?? "", + bookmarkGuid: r2.bookmarkGuid + }); + } + const sourceCounts = Object.entries(resultsBySource).map(([src, items]) => `${items.length} from ${src}`).join(", "); + const summary = `Found ${structured.length} result(s) for "${query}"${scopeSuffix}: ${sourceCounts}.`; + return { + message: JSON.stringify({ + summary, + resultsBySource, + results: structured + }) + }; + } + }; + var GetRecentSearchResultsCommand = class { + commandName = "get_recent_search_results"; + description = "Get cached results from the most recent search_memory command. Arguments: { limit?: number }."; + async execute(args) { + const limit = numberArg3(args, "limit"); + const cappedLimit = limit != null ? Math.max(1, Math.min(Math.floor(limit), 25)) : 5; + const recent = getRecentSearchResults(); + if (recent.length === 0) { + return { + message: JSON.stringify({ + summary: "No recent search results available.", + results: [] + }) + }; + } + const results = recent.slice(0, cappedLimit).map((result, idx) => ({ + index: idx + 1, + source: result.source, + title: result.title, + url: result.url, + bookmarkGuid: result.bookmarkGuid, + context: result.context, + snippet: result.snippet + })); + return { + message: JSON.stringify({ + summary: `Found ${results.length} cached recent search result(s).`, + results + }) + }; + } + }; + var OpenSearchResultCommand = class { + commandName = "open_search_result"; + description = "Open a search result. Accepts arguments: { url?: string, index?: number, type?: string, bookmarkGuid?: string }. If index is provided (or omitted), resolves from recent search results. If type is 'tab', switches to it if found."; + async execute(args) { + let url = stringArg(args, "url"); + const index2 = numberArg3(args, "index"); + let type = stringArg(args, "type"); + let bookmarkGuid = stringArg(args, "bookmarkGuid"); + if (!url) { + const recent = getRecentSearchResults(); + if (recent.length === 0) { + return { + message: "No recent search result is available to open. Run a search first or pass a URL." + }; + } + const targetIndex = index2 != null ? Math.max(1, Math.floor(index2)) : 1; + const selected = recent[targetIndex - 1]; + if (!selected?.url) { + return { + message: `Result index ${targetIndex} is out of range. I currently have ${recent.length} recent result(s).` + }; + } + url = selected.url; + bookmarkGuid = bookmarkGuid || selected.bookmarkGuid; + if (!type && selected.source === "tab") { + type = "tab"; + } + } + const { topWin, gBrowser, PlacesUtils } = getChrome2(); + if (!topWin?.openTrustedLinkIn || !gBrowser) + return { message: "Browser UI not available." }; + if (bookmarkGuid && PlacesUtils?.bookmarks?.fetch) { + try { + const fetched = await PlacesUtils.bookmarks.fetch(bookmarkGuid); + const bookmark = Array.isArray(fetched) ? fetched[0] : fetched; + const freshUrl = toUrlString2(bookmark?.url); + if (freshUrl) { + url = freshUrl; + } + } catch (e2) { + assistantLogger.warn( + "open-search-result", + `Failed bookmark GUID lookup guid=${bookmarkGuid}`, + e2 + ); + } + } + if (!url) return { message: "Missing 'url' argument." }; + if (type === "tab") { + const foundTab = getTabs(gBrowser).find((tab) => tabUrl(tab) === url); + if (foundTab) { + gBrowser.selectedTab = foundTab; + return { message: `Switched to tab: ${url}` }; + } + } + topWin.openTrustedLinkIn(url, "tab"); + return { message: `Opened in new tab: ${url}` }; + } + }; + var ShowSubscriptionCommand = class { + commandName = "show_subscription"; + description = "Show the current subscription plan and usage options."; + async execute(_args) { + const { topWin } = getChrome2(); + if (!topWin?.openTrustedLinkIn) + return { message: "Browser UI not available." }; + const stats = await subscriptionService.checkAvailability(); + const url = subscriptionService.getSubscriptionUrl(); + topWin.openTrustedLinkIn(url, "tab"); + return { + message: `Opened subscription page. +Usage this month: ${stats.totalUnits} units / ${stats.limit} limit.` + }; + } + }; + var ListTabGroupsCommand = class { + commandName = "list_tab_groups"; + description = "List all tab groups in the current window. Accepts no arguments."; + async execute(_args) { + const { gBrowser } = getChrome2(); + if (!gBrowser) return { message: "Browser UI (gBrowser) not available." }; + const groups = getTabGroups(gBrowser); + if (groups.length === 0) { + return { message: "No tab groups in this window." }; + } + const groupInfo = groups.map((group) => ({ + name: group.label || "(unnamed)", + tabCount: (group.tabs || []).length, + collapsed: group.collapsed || false + })); + return { message: JSON.stringify(groupInfo) }; + } + }; + var CreateTabGroupCommand = class { + commandName = "create_tab_group"; + description = "Create a new tab group from specified tabs. Accepts arguments: { name: string, indices?: number[], openUrl?: string, confirmed?: boolean }. Use 'openUrl' to open a URL in the new group. If no indices provided, creates with current tab (or new tab if current is already grouped)."; + async execute(args) { + const { gBrowser, Services } = getChrome2(); + if (!gBrowser) return { message: "Browser UI (gBrowser) not available." }; + const name = stringArg(args, "name") || "New Group"; + const indices = numberArrayArg(args, "indices"); + let tabsToGroup = []; + let createdNewTab = false; + const openUrl = stringArg(args, "openUrl"); + if (indices.length > 0) { + for (const idx of indices) { + const i2 = Math.max(1, Math.floor(idx)); + const tab = tabByIndex(gBrowser, i2); + if (!tab) return { message: `No tab ${i2}.` }; + tabsToGroup.push(tab); + } + } else if (openUrl) { + let url = openUrl; + if (!url.includes("://")) { + try { + url = withUriFixup(url, Services); + } catch (e2) { + if (!url.startsWith("http")) { + url = "https://" + url; + } + } + } + const newTab = gBrowser.addTrustedTab?.(url); + if (!newTab) + return { message: "Failed to open a tab for the new group." }; + tabsToGroup = [newTab]; + createdNewTab = true; + } else { + const currentTab = gBrowser.selectedTab || null; + if (currentTab?.group) { + const newTab = gBrowser.addTrustedTab?.("about:newtab"); + if (!newTab) + return { message: "Failed to create a tab for the new group." }; + tabsToGroup = [newTab]; + createdNewTab = true; + } else { + if (!currentTab) return { message: "No active tab available." }; + tabsToGroup = [currentTab]; + } + } + const groupableTabs = tabsToGroup.filter((tab) => !tab.pinned); + if (groupableTabs.length === 0) { + return { message: "No groupable tabs (pinned tabs cannot be grouped)." }; + } + const tabsInGroups = groupableTabs.filter((tab) => !!tab.group); + if (tabsInGroups.length > 0 && booleanArg(args, "confirmed") !== true) { + const impact = analyzeGroupMoveImpact(tabsInGroups); + const groupNames = impact.affectedGroups.join(", "); + let warningMsg = `${tabsInGroups.length} tab(s) will be moved from existing group(s): ${groupNames}.`; + if (impact.emptiedGroups.length > 0) { + warningMsg += ` This will delete the following empty group(s): ${impact.emptiedGroups.join(", ")}.`; + } + warningMsg += ` Create "${name}" anyway?`; + setPendingConfirmation({ + command: "create_tab_group", + args: { ...args, confirmed: true }, + description: warningMsg + }); + return { + message: warningMsg, + requiresConfirmation: true, + confirmationData: { + name, + affectedGroups: impact.affectedGroups, + willBeEmpty: impact.emptiedGroups + } + }; + } + clearPendingConfirmation(); + try { + gBrowser.addTabGroup?.(groupableTabs, { label: name }); + applyRoutingStateMutation({ + kind: "upsert", + entity: "group", + name + }); + let msg; + if (openUrl) { + msg = `Created tab group "${name}" and opened ${openUrl} in it.`; + } else if (createdNewTab) { + msg = `Created tab group "${name}" with a new tab.`; + } else { + msg = `Created tab group "${name}" with ${groupableTabs.length} tab(s).`; + } + return { message: msg }; + } catch (e2) { + return { message: `Failed to create tab group: ${e2}` }; + } + } + }; + var DeleteTabGroupCommand = class { + commandName = "delete_tab_group"; + description = "Delete a tab group by name. Accepts arguments: { name: string, closeTabs?: boolean, confirmed?: boolean }."; + async execute(args) { + const { gBrowser } = getChrome2(); + if (!gBrowser) return { message: "Browser UI (gBrowser) not available." }; + const name = stringArg(args, "name"); + if (!name) return { message: "Which tab group should I delete?" }; + const group = findGroupByName(gBrowser, name); + if (!group) { + return { message: `No tab group named "${name}".` }; + } + const tabCount = (group.tabs || []).length; + const closeTabs = booleanArg(args, "closeTabs") === true; + if (booleanArg(args, "confirmed") !== true) { + const closeMsg = closeTabs ? " and close all its tabs" : " (tabs will be ungrouped)"; + setPendingConfirmation({ + command: "delete_tab_group", + args: { ...args, confirmed: true }, + description: `Delete tab group "${name}"${closeMsg}?` + }); + return { + message: `Requesting confirmation to delete tab group "${name}" (${tabCount} tabs)${closeMsg}...`, + requiresConfirmation: true, + confirmationData: { name, tabCount, closeTabs } + }; + } + clearPendingConfirmation(); + try { + const tabs = group.tabs || []; + if (closeTabs) { + for (const tab of tabs) { + gBrowser.removeTab?.(tab); + } + } else { + for (const tab of tabs) { + gBrowser.ungroupTab?.(tab); + } + } + applyRoutingStateMutation({ + kind: "delete", + entity: "group", + name: group.label || name + }); + return { + message: `Deleted tab group "${name}"${closeTabs ? " and closed its tabs" : ""}.` + }; + } catch (e2) { + return { message: `Failed to delete tab group: ${e2}` }; + } + } + }; + var AddTabToGroupCommand = class { + commandName = "add_tab_to_group"; + description = "Add tab(s) to an existing tab group. Accepts arguments: { name: string, query?: string, index?: number, all?: boolean, confirmed?: boolean }. Use 'query' to find tab by title/URL. Use 'all: true' to add all ungrouped tabs. If no query/index/all, adds current tab."; + async execute(args) { + const { gBrowser } = getChrome2(); + if (!gBrowser) return { message: "Browser UI (gBrowser) not available." }; + const name = stringArg(args, "name"); + if (!name) return { message: "Which tab group should I add the tab to?" }; + const group = findGroupByName(gBrowser, name); + if (!group) { + return { + message: `No tab group named "${name}". Use create_tab_group to create one first.` + }; + } + let tabsToAdd = []; + const query = normalizeQuery(stringArg(args, "query")); + const idx = numberArg3(args, "index"); + const all = booleanArg(args, "all"); + if (all === true) { + tabsToAdd = getTabs(gBrowser).filter((tab) => !tab.group); + } else if (query) { + tabsToAdd = findTabsByQuery(gBrowser, query); + if (tabsToAdd.length === 0) { + return { + message: `No tabs found matching "${stringArg(args, "query") || ""}".` + }; + } + } else if (idx != null) { + const tab = tabByIndex(gBrowser, idx); + if (!tab) return { message: `No tab ${idx}.` }; + tabsToAdd = [tab]; + } else { + const selected = gBrowser.selectedTab; + if (selected) { + tabsToAdd = [selected]; + } + } + const groupableTabs = tabsToAdd.filter((tab) => !tab.pinned); + if (groupableTabs.length === 0) { + return { + message: "No groupable tabs found (pinned tabs cannot be grouped, or all tabs are already in groups)." + }; + } + const tabsInOtherGroups = groupableTabs.filter( + (tab) => tab.group && tab.group !== group + ); + if (tabsInOtherGroups.length > 0 && booleanArg(args, "confirmed") !== true) { + const impact = analyzeGroupMoveImpact(tabsInOtherGroups); + const groupNames = impact.affectedGroups.join(", "); + let warningMsg = `${tabsInOtherGroups.length} tab(s) will be moved from existing group(s): ${groupNames}.`; + if (impact.emptiedGroups.length > 0) { + warningMsg += ` This will delete the following empty group(s): ${impact.emptiedGroups.join(", ")}.`; + } + warningMsg += ` Add to "${name}" anyway?`; + setPendingConfirmation({ + command: "add_tab_to_group", + args: { ...args, confirmed: true }, + description: warningMsg + }); + return { + message: warningMsg, + requiresConfirmation: true, + confirmationData: { + name, + affectedGroups: impact.affectedGroups, + willBeEmpty: impact.emptiedGroups + } + }; + } + clearPendingConfirmation(); + try { + group.addTabs?.(groupableTabs); + applyRoutingStateMutation({ + kind: "upsert", + entity: "group", + name: group.label || name + }); + const titles = groupableTabs.map((tab) => tabTitle(tab)).join(", "); + return { + message: `Added ${groupableTabs.length} tab(s) to group "${name}": ${titles}` + }; + } catch (e2) { + return { message: `Failed to add tab to group: ${e2}` }; + } + } + }; + var RemoveTabFromGroupCommand = class { + commandName = "remove_tab_from_group"; + description = "Remove a tab from its tab group (ungroup it). Accepts arguments: { index?: number }. If no index, uses current tab."; + async execute(args) { + const { gBrowser } = getChrome2(); + if (!gBrowser) return { message: "Browser UI (gBrowser) not available." }; + const idx = numberArg3(args, "index"); + const tab = tabByIndexOrCurrent(gBrowser, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + const title = tabTitle(tab); + if (!tab.group) { + return { message: `Tab "${title}" is not in any group.` }; + } + try { + if (gBrowser.ungroupTab) { + gBrowser.ungroupTab(tab); + markRoutingStateDirty("remove-tab-from-group"); + return { message: `Removed tab "${title}" from its group.` }; + } else { + return { + message: "Tab ungrouping is not available in this Firefox version." + }; + } + } catch (e2) { + return { message: `Failed to remove tab from group: ${e2}` }; + } + } + }; + var RenameTabGroupCommand = class { + commandName = "rename_tab_group"; + description = "Rename a tab group. Accepts arguments: { from: string, to: string }."; + async execute(args) { + const { gBrowser } = getChrome2(); + if (!gBrowser) return { message: "Browser UI (gBrowser) not available." }; + const from = stringArg(args, "from"); + const to = stringArg(args, "to"); + if (!from || !to) + return { message: "Please provide old and new group names." }; + const groups = getTabGroups(gBrowser); + const group = findGroupByName(gBrowser, from); + if (!group) { + return { message: `No tab group named "${from}".` }; + } + const existingWithNewName = groups.find( + (existingGroup) => normalizeName(existingGroup.label || "") === normalizeName(to) + ); + if (existingWithNewName) { + return { message: `A tab group named "${to}" already exists.` }; + } + try { + group.label = to; + applyRoutingStateMutation({ + kind: "rename", + entity: "group", + from, + to + }); + return { message: `Renamed tab group "${from}" to "${to}".` }; + } catch (e2) { + return { message: `Failed to rename tab group: ${e2}` }; + } + } + }; + var ResolveAmbiguityCommand = class { + commandName = "resolve_ambiguity"; + description = "Resolve an ambiguous request. Accepts arguments: { target?: 'bookmark-folder'|'tab-group'|'tab'|'cancel' }."; + async execute(args) { + const pending = getPendingAmbiguity(); + if (!pending) { + return { message: "No pending ambiguous request to resolve." }; + } + const target = ambiguityTargetArg(args); + if (target === "cancel") { + clearPendingAmbiguity(); + return { message: "Okay, cancelled that request." }; + } + if (pending.kind === "close_delete_target") { + const allowed = new Set( + pending.choices || ["tab", "tab-group", "bookmark-folder"] + ); + if (!target || !allowed.has(target)) { + const optionLabels = Array.from(allowed).map((opt) => { + if (opt === "tab-group") return "tab group"; + if (opt === "bookmark-folder") return "bookmark folder"; + return "tab"; + }); + const choicesText = optionLabels.length > 1 ? `${optionLabels.slice(0, -1).join(", ")} or ${optionLabels[optionLabels.length - 1]}` : optionLabels[0] || "tab, tab group, or bookmark folder"; + return { + message: `I found multiple matches for "${pending.name}". Do you mean ${choicesText}?` + }; + } + clearPendingAmbiguity(); + assistantLogger.debug("ambiguity", "Resolved close/delete target", { + target, + name: pending.name + }); + if (target === "tab") { + const cmd3 = new CloseTabCommand(); + return await cmd3.execute( + pending.tabIndex ? { index: pending.tabIndex } : {} + ); + } + if (target === "tab-group") { + const cmd3 = new DeleteTabGroupCommand(); + return await cmd3.execute({ name: pending.name }); + } + const cmd2 = new DeleteBookmarkFolderCommand(); + return await cmd2.execute({ name: pending.name }); + } + if (target !== "bookmark-folder" && target !== "tab-group") { + return { + message: `Do you mean a bookmark folder or a tab group for "${pending.name}"? Reply with "bookmark folder" or "tab group".` + }; + } + clearPendingAmbiguity(); + assistantLogger.debug("ambiguity", "Resolved container target", { + target, + name: pending.name + }); + if (target === "tab-group") { + const cmd2 = new AddTabToGroupCommand(); + return await cmd2.execute({ + name: pending.name, + query: pending.query, + all: pending.all + }); + } + const cmd = new AddTabToBookmarkFolderCommand(); + return await cmd.execute({ + name: pending.name, + query: pending.query, + all: pending.all + }); + } + }; + var ConfirmActionCommand = class { + commandName = "confirm_action"; + description = "Confirm or cancel a pending action. Accepts arguments: { confirmed: boolean }."; + async execute(args) { + const pending = getPendingConfirmation(); + assistantLogger.debug("confirm-action", "Received confirmation input", { + hasPending: !!pending + }); + if (!pending) { + assistantLogger.debug("confirm-action", "No pending confirmation found"); + clearContinuationQueue(); + return { message: "No pending action to confirm." }; + } + const confirmed = args?.confirmed; + if (confirmed !== true && confirmed !== false) { + return { + message: `Pending action: ${pending.description}. Reply "yes" to confirm or "no" to cancel.` + }; + } + if (!confirmed) { + clearPendingConfirmation(); + clearContinuationQueue(); + return { message: "Action cancelled." }; + } + const cmd = getCommandExecutor(pending.command); + if (!cmd) { + clearPendingConfirmation(); + clearContinuationQueue(); + const known = listRegisteredCommandNames().sort(); + return { + message: `Unknown command: ${pending.command}. Known commands: ${known.join(", ")}` + }; + } + if (cmd.commandName === this.commandName) { + clearPendingConfirmation(); + clearContinuationQueue(); + return { message: "Cannot confirm confirm_action recursively." }; + } + return await cmd.execute(pending.args); + } + }; + function formatRelativeVisitTime(visitDate) { + const diff = Date.now() - visitDate; + const minutes = Math.floor(diff / 6e4); + if (minutes < 1) return "just now"; + if (minutes < 60) return `${minutes}m ago`; + const hours = Math.floor(minutes / 60); + if (hours < 24) return `${hours}h ago`; + const days = Math.floor(hours / 24); + if (days === 1) return "yesterday"; + if (days < 7) return `${days}d ago`; + if (days < 30) return `${Math.floor(days / 7)}w ago`; + return new Date(visitDate).toLocaleDateString(); + } + var SearchHistorySemanticCommand = class { + commandName = "search_history"; + description = `Search the user's recent browsing history (AI semantic search). Use for pages visited, articles read, topics in history. Arguments: { query: string }. If the user asks to list or show their history without a topic, pass query as "" to return recent visits.`; + async execute(args) { + const qVal = args?.query; + const query = typeof qVal === "string" ? qVal.trim() : ""; + if (!query) { + try { + const entries2 = await fetchRecentHistory(15, false); + if (entries2.length === 0) { + return { + message: "No browsing history found yet, or history could not be read. Open a few websites, then try again." + }; + } + const formatted = entries2.map((r2, i2) => ({ + index: i2 + 1, + title: r2.title, + url: r2.url, + visited: new Date(r2.visitDate).toLocaleDateString() + })); + return { message: JSON.stringify(formatted) }; + } catch (e2) { + console.error("[SearchHistorySemantic] Recent list failed:", e2); + return { + message: "Could not read browsing history. If this persists, check the Browser Console for [HistoryCollector] errors." + }; + } + } + try { + const results = await semanticHistorySearch.search(query, 10); + const MIN_RELEVANCE = 0.3; + const MAX_RESULTS = 5; + const filtered = results.filter((r2) => r2.score >= MIN_RELEVANCE).slice(0, MAX_RESULTS); + if (filtered.length === 0) { + let recent = []; + try { + recent = await fetchRecentHistory(50, false); + } catch { + recent = []; + } + if (recent.length === 0) { + return { + message: `No browsing history is available in this profile (0 visits from Places). That usually means Firefox's history database did not load \u2014 try ./mach run --temp-profile, or delete obj-*/tmp/profile-default and rebuild, then visit a few https sites and retry. Searched for: "${query}".` + }; + } + return { + message: `No history entries matched "${query}" among recent visits (Places has ${recent.length} recent URLs indexed for lookup). Try a shorter keyword (e.g. domain name), visit the page again, or check Library \u2192 History.` + }; + } + const formatted = filtered.map((r2, i2) => ({ + index: i2 + 1, + title: r2.title, + url: r2.url, + relevance: Math.round(r2.score * 100) + "%", + visited: formatRelativeVisitTime(r2.visitDate) + })); + return { message: JSON.stringify(formatted) }; + } catch (e2) { + console.error("[SearchHistorySemantic] Search failed:", e2); + return { + message: `History search failed: ${e2.message || "Unknown error"}. The embedding model may still be loading \u2014 please try again in a moment.` + }; + } + } + }; + + // src/assistant/commandsRegistry.ts + var COMMAND_ARG_SCHEMA = { + list_tabs: `{"scope?":"window|tab-group|bookmark-folder","name?":"string"}`, + open_url: `{"url":"string"}`, + web_search: `{"query":"string"}`, + open_tab: `{"url":"string"} (legacy alias; prefer open_url/web_search)`, + close_tab: `{"index?":"number","confirmed?":"boolean"}`, + move_tab_to_new_window: `{"index?":"number"}`, + copy_tab_urls: `{}`, + split_tabs: `{"indices":"number[]"}`, + add_split_view: `{"indices?":"number[]","withIndex?":"number","withQuery?":"string"}`, + remove_split_view: `{}`, + create_bookmark_folder: `{"name":"string","include?":"none|current|all"}`, + delete_bookmark_folder: `{"name":"string","confirmed?":"boolean"}`, + list_bookmark_folders: `{}`, + rename_bookmark_folder: `{"from":"string","to":"string"}`, + add_tab_to_bookmark_folder: `{"name":"string","query?":"string","all?":"boolean"}`, + remove_tab_from_bookmark_folder: `{"name":"string","query?":"string","all?":"boolean"}`, + open_bookmark_folder: `{"name":"string","where?":"tabgroup|window"}`, + list_tab_groups: `{}`, + create_tab_group: `{"name":"string","indices?":"number[]","openUrl?":"string","confirmed?":"boolean"}`, + delete_tab_group: `{"name":"string","confirmed?":"boolean"}`, + add_tab_to_group: `{"name":"string","query?":"string","all?":"boolean","confirmed?":"boolean"}`, + remove_tab_from_group: `{"index?":"number"}`, + rename_tab_group: `{"from":"string","to":"string"}`, + resolve_ambiguity: `{"target?":"bookmark-folder|tab-group|tab|cancel"}`, + confirm_action: `{"confirmed":"boolean"}`, + new_window: `{}`, + new_tab_to_right: `{"index?":"number"}`, + organize_windows: `{}`, + show_url: `{"url":"string"}`, + search_memory: `{"query":"string","folder?":"string","source?":"bookmark-folder"}`, + get_recent_search_results: `{"limit?":"number"}`, + open_search_result: `{"url?":"string","index?":"number","type?":"tab","bookmarkGuid?":"string"}`, + summarize_page: `{"index?":"number","query?":"string"}`, + show_subscription: `{}`, + search_history: `{"query":"string (optional; omit or "" for recent visits)"}` + }; + function toAssistToolDescription(command) { + const schema4 = COMMAND_ARG_SCHEMA[command.commandName]; + if (!schema4) { + return command.description; + } + return `${command.description} Args JSON: ${schema4}`; + } + function createAssistantCommandsRegistry() { + const commands2 = [ + new ListTabsCommand(), + new OpenUrlCommand(), + new WebSearchCommand(), + new OpenTabCommand(), + new CloseTabCommand(), + new ReloadTabCommand(), + new ToggleMuteTabCommand(), + new PinTabCommand(), + new UnpinTabCommand(), + new UnloadTabCommand(), + new NewTabToRightCommand(), + new DuplicateTabCommand(), + new BookmarkTabCommand(), + new MoveTabToStartCommand(), + new MoveTabToEndCommand(), + new SelectAllTabsCommand(), + new CloseDuplicateTabsCommand(), + new CloseTabsToRightCommand(), + new CloseTabsToLeftCommand(), + new CloseOtherTabsCommand(), + new ReopenClosedTabCommand(), + new OpenSendTabToDeviceCommand(), + new OpenTabNoteCommand(), + new MoveTabToNewWindowCommand(), + new CopyTabUrlsCommand(), + new SplitTabsCommand(), + new AddSplitViewCommand(), + new RemoveSplitViewCommand(), + new CreateBookmarkFolderCommand(), + new DeleteBookmarkFolderCommand(), + new ListBookmarkFoldersCommand(), + new RenameBookmarkFolderCommand(), + new AddTabToBookmarkFolderCommand(), + new RemoveTabFromBookmarkFolderCommand(), + new OpenBookmarkFolderCommand(), + new ListTabGroupsCommand(), + new CreateTabGroupCommand(), + new DeleteTabGroupCommand(), + new AddTabToGroupCommand(), + new RemoveTabFromGroupCommand(), + new RenameTabGroupCommand(), + new ResolveAmbiguityCommand(), + new ConfirmActionCommand(), + new NewWindowCommand(), + new OrganizeWindowsCommand(), + new ShowURLCommand(), + new SearchMemoryCommand(), + new GetRecentSearchResultsCommand(), + new OpenSearchResultCommand(), + new SummarizePageCommand(), + new ShowSubscriptionCommand(), + // Semantic history search (local embeddings + vector DB) + new SearchHistorySemanticCommand() + ]; + registerCommandExecutors(commands2); + return { + commands: commands2, + toolCommandNames: new Set(commands2.map((command) => command.commandName)), + assistTools: commands2.map((command) => ({ + name: command.commandName, + description: toAssistToolDescription(command) + })) + }; + } + + // src/assistant/constants.ts + var ASSISTANT_RECURSION_LIMIT = 24; + var MAX_NESTED_COMMANDS = 3; + var INTERNAL_CHAIN_NOTICE_ARG = "__oasisChainNotice"; + var STREAM_GUARD_MESSAGE = "I stopped this request to avoid a routing loop. Please rephrase and try again."; + + // src/assistant/agentLoopDriver.ts + var AGENT_END = "__end__"; + function mergeAgentState(prev, patch) { + return { + messages: patch.messages && patch.messages.length > 0 ? [...prev.messages, ...patch.messages] : prev.messages, + lastWorker: patch.lastWorker ?? prev.lastWorker, + next: patch.next !== void 0 && patch.next !== "" ? String(patch.next) : prev.next, + args: patch.args !== void 0 ? patch.args : prev.args, + commandQueue: patch.commandQueue !== void 0 ? patch.commandQueue : prev.commandQueue + }; + } + async function* streamAgentLoop(params) { + const { + initialMessages, + maxSteps, + supervisorNode, + chatNode, + toolAgents, + memberNames + } = params; + const memberSet = new Set(memberNames); + let state = { + messages: [...initialMessages], + lastWorker: "", + next: "", + args: {}, + commandQueue: [] + }; + let cursor = "supervisor"; + for (let i2 = 0; i2 < maxSteps; i2++) { + if (cursor === AGENT_END) { + yield { __end__: true }; + return; + } + if (cursor === "supervisor") { + const patch = await supervisorNode(state); + state = mergeAgentState(state, patch); + cursor = state.next && state.next !== "" ? state.next : AGENT_END; + continue; + } + if (cursor === "chat") { + const patch = await chatNode(state); + state = mergeAgentState(state, patch); + yield { chat: patch }; + yield { __end__: true }; + return; + } + const toolFn = toolAgents[cursor]; + if (toolFn && memberSet.has(cursor)) { + const patch = await toolFn(state); + state = mergeAgentState(state, patch); + yield { [cursor]: patch }; + const nextCursor = String(patch.next ?? "supervisor"); + if (nextCursor === AGENT_END) { + yield { __end__: true }; + return; + } + cursor = nextCursor; + continue; + } + assistantLogger.warn("agentLoop", "Unknown graph node; stopping.", { + cursor + }); + yield { __end__: true }; + return; + } + assistantLogger.warn("agentLoop", "Recursion limit reached; stopping.", { + maxSteps + }); + yield { __end__: true }; + } + + // src/voiceLambdaIamFetch.ts + init_module2(); + + // node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/fromCognitoIdentity.js + init_dist_es2(); + + // node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/resolveLogins.js + function resolveLogins(logins) { + return Promise.all(Object.keys(logins).reduce((arr2, name) => { + const tokenOrProvider = logins[name]; + if (typeof tokenOrProvider === "string") { + arr2.push([name, tokenOrProvider]); + } else { + arr2.push(tokenOrProvider().then((token) => [name, token])); + } + return arr2; + }, [])).then((resolvedPairs) => resolvedPairs.reduce((logins2, [key, value]) => { + logins2[key] = value; + return logins2; + }, {})); + } + + // node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/fromCognitoIdentity.js + function fromCognitoIdentity(parameters) { + return async (awsIdentityProperties) => { + parameters.logger?.debug("@aws-sdk/credential-provider-cognito-identity - fromCognitoIdentity"); + const { GetCredentialsForIdentityCommand: GetCredentialsForIdentityCommand2, CognitoIdentityClient: CognitoIdentityClient2 } = await Promise.resolve().then(() => (init_loadCognitoIdentity(), loadCognitoIdentity_exports)); + const fromConfigs = (property) => parameters.clientConfig?.[property] ?? parameters.parentClientConfig?.[property] ?? awsIdentityProperties?.callerClientConfig?.[property]; + const { Credentials: { AccessKeyId = throwOnMissingAccessKeyId(parameters.logger), Expiration, SecretKey = throwOnMissingSecretKey(parameters.logger), SessionToken } = throwOnMissingCredentials(parameters.logger) } = await (parameters.client ?? new CognitoIdentityClient2(Object.assign({}, parameters.clientConfig ?? {}, { + region: fromConfigs("region"), + profile: fromConfigs("profile") + }))).send(new GetCredentialsForIdentityCommand2({ + CustomRoleArn: parameters.customRoleArn, + IdentityId: parameters.identityId, + Logins: parameters.logins ? await resolveLogins(parameters.logins) : void 0 + })); + return { + identityId: parameters.identityId, + accessKeyId: AccessKeyId, + secretAccessKey: SecretKey, + sessionToken: SessionToken, + expiration: Expiration + }; + }; + } + function throwOnMissingAccessKeyId(logger2) { + throw new CredentialsProviderError("Response from Amazon Cognito contained no access key ID", { logger: logger2 }); + } + function throwOnMissingCredentials(logger2) { + throw new CredentialsProviderError("Response from Amazon Cognito contained no credentials", { logger: logger2 }); + } + function throwOnMissingSecretKey(logger2) { + throw new CredentialsProviderError("Response from Amazon Cognito contained no secret key", { logger: logger2 }); + } + + // node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/fromCognitoIdentityPool.js + init_dist_es2(); + + // node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/IndexedDbStorage.js + var STORE_NAME = "IdentityIds"; + var IndexedDbStorage = class { + dbName; + constructor(dbName = "aws:cognito-identity-ids") { + this.dbName = dbName; + } + getItem(key) { + return this.withObjectStore("readonly", (store2) => { + const req = store2.get(key); + return new Promise((resolve) => { + req.onerror = () => resolve(null); + req.onsuccess = () => resolve(req.result ? req.result.value : null); + }); + }).catch(() => null); + } + removeItem(key) { + return this.withObjectStore("readwrite", (store2) => { + const req = store2.delete(key); + return new Promise((resolve, reject) => { + req.onerror = () => reject(req.error); + req.onsuccess = () => resolve(); + }); + }); + } + setItem(id, value) { + return this.withObjectStore("readwrite", (store2) => { + const req = store2.put({ id, value }); + return new Promise((resolve, reject) => { + req.onerror = () => reject(req.error); + req.onsuccess = () => resolve(); + }); + }); + } + getDb() { + const openDbRequest = self.indexedDB.open(this.dbName, 1); + return new Promise((resolve, reject) => { + openDbRequest.onsuccess = () => { + resolve(openDbRequest.result); + }; + openDbRequest.onerror = () => { + reject(openDbRequest.error); + }; + openDbRequest.onblocked = () => { + reject(new Error("Unable to access DB")); + }; + openDbRequest.onupgradeneeded = () => { + const db = openDbRequest.result; + db.onerror = () => { + reject(new Error("Failed to create object store")); + }; + db.createObjectStore(STORE_NAME, { keyPath: "id" }); + }; + }); + } + withObjectStore(mode, action) { + return this.getDb().then((db) => { + const tx = db.transaction(STORE_NAME, mode); + tx.oncomplete = () => db.close(); + return new Promise((resolve, reject) => { + tx.onerror = () => reject(tx.error); + resolve(action(tx.objectStore(STORE_NAME))); + }).catch((err) => { + db.close(); + throw err; + }); + }); + } + }; + + // node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/InMemoryStorage.js + var InMemoryStorage = class { + store; + constructor(store2 = {}) { + this.store = store2; + } + getItem(key) { + if (key in this.store) { + return this.store[key]; + } + return null; + } + removeItem(key) { + delete this.store[key]; + } + setItem(key, value) { + this.store[key] = value; + } + }; + + // node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/localStorage.js + var inMemoryStorage = new InMemoryStorage(); + function localStorage2() { + if (typeof self === "object" && self.indexedDB) { + return new IndexedDbStorage(); + } + if (typeof window === "object" && window.localStorage) { + return window.localStorage; + } + return inMemoryStorage; + } + + // node_modules/@aws-sdk/credential-provider-cognito-identity/dist-es/fromCognitoIdentityPool.js + function fromCognitoIdentityPool({ accountId, cache: cache2 = localStorage2(), client: client2, clientConfig, customRoleArn, identityPoolId: identityPoolId2, logins, userIdentifier = !logins || Object.keys(logins).length === 0 ? "ANONYMOUS" : void 0, logger: logger2, parentClientConfig }) { + logger2?.debug("@aws-sdk/credential-provider-cognito-identity - fromCognitoIdentity"); + const cacheKey = userIdentifier ? `aws:cognito-identity-credentials:${identityPoolId2}:${userIdentifier}` : void 0; + let provider = async (awsIdentityProperties) => { + const { GetIdCommand: GetIdCommand2, CognitoIdentityClient: CognitoIdentityClient2 } = await Promise.resolve().then(() => (init_loadCognitoIdentity(), loadCognitoIdentity_exports)); + const fromConfigs = (property) => clientConfig?.[property] ?? parentClientConfig?.[property] ?? awsIdentityProperties?.callerClientConfig?.[property]; + const _client = client2 ?? new CognitoIdentityClient2(Object.assign({}, clientConfig ?? {}, { + region: fromConfigs("region"), + profile: fromConfigs("profile") + })); + let identityId = cacheKey && await cache2.getItem(cacheKey); + if (!identityId) { + const { IdentityId = throwOnMissingId(logger2) } = await _client.send(new GetIdCommand2({ + AccountId: accountId, + IdentityPoolId: identityPoolId2, + Logins: logins ? await resolveLogins(logins) : void 0 + })); + identityId = IdentityId; + if (cacheKey) { + Promise.resolve(cache2.setItem(cacheKey, identityId)).catch(() => { + }); + } + } + provider = fromCognitoIdentity({ + client: _client, + customRoleArn, + logins, + identityId + }); + return provider(awsIdentityProperties); + }; + return (awsIdentityProperties) => provider(awsIdentityProperties).catch(async (err) => { + if (cacheKey) { + Promise.resolve(cache2.removeItem(cacheKey)).catch(() => { + }); + } + throw err; + }); + } + function throwOnMissingId(logger2) { + throw new CredentialsProviderError("Response from Amazon Cognito contained no identity ID", { logger: logger2 }); + } + + // node_modules/@aws-sdk/protocol-http/dist-es/FieldPosition.js + var FieldPosition2; + (function(FieldPosition3) { + FieldPosition3[FieldPosition3["HEADER"] = 0] = "HEADER"; + FieldPosition3[FieldPosition3["TRAILER"] = 1] = "TRAILER"; + })(FieldPosition2 || (FieldPosition2 = {})); + + // node_modules/@aws-sdk/protocol-http/dist-es/httpRequest.js + var HttpRequest2 = class _HttpRequest { + constructor(options) { + this.method = options.method || "GET"; + this.hostname = options.hostname || "localhost"; + this.port = options.port; + this.query = options.query || {}; + this.headers = options.headers || {}; + this.body = options.body; + this.protocol = options.protocol ? options.protocol.slice(-1) !== ":" ? `${options.protocol}:` : options.protocol : "https:"; + this.path = options.path ? options.path.charAt(0) !== "/" ? `/${options.path}` : options.path : "/"; + this.username = options.username; + this.password = options.password; + this.fragment = options.fragment; + } + static isInstance(request) { + if (!request) + return false; + const req = request; + return "method" in req && "protocol" in req && "hostname" in req && "path" in req && typeof req["query"] === "object" && typeof req["headers"] === "object"; + } + clone() { + const cloned = new _HttpRequest({ + ...this, + headers: { ...this.headers } + }); + if (cloned.query) + cloned.query = cloneQuery2(cloned.query); + return cloned; + } + }; + function cloneQuery2(query) { + return Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param + }; + }, {}); + } + + // node_modules/@aws-sdk/eventstream-codec/dist-es/EventStreamCodec.js + var import_crc322 = __toESM(require_build2()); + + // node_modules/@aws-sdk/util-hex-encoding/dist-es/index.js + var SHORT_TO_HEX2 = {}; + var HEX_TO_SHORT2 = {}; + for (let i2 = 0; i2 < 256; i2++) { + let encodedByte = i2.toString(16).toLowerCase(); + if (encodedByte.length === 1) { + encodedByte = `0${encodedByte}`; + } + SHORT_TO_HEX2[i2] = encodedByte; + HEX_TO_SHORT2[encodedByte] = i2; + } + function fromHex2(encoded) { + if (encoded.length % 2 !== 0) { + throw new Error("Hex encoded strings must have an even number length"); + } + const out = new Uint8Array(encoded.length / 2); + for (let i2 = 0; i2 < encoded.length; i2 += 2) { + const encodedByte = encoded.slice(i2, i2 + 2).toLowerCase(); + if (encodedByte in HEX_TO_SHORT2) { + out[i2 / 2] = HEX_TO_SHORT2[encodedByte]; + } else { + throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); + } + } + return out; + } + function toHex2(bytes) { + let out = ""; + for (let i2 = 0; i2 < bytes.byteLength; i2++) { + out += SHORT_TO_HEX2[bytes[i2]]; + } + return out; + } + + // node_modules/@aws-sdk/eventstream-codec/dist-es/Int64.js + var Int642 = class _Int64 { + constructor(bytes) { + this.bytes = bytes; + if (bytes.byteLength !== 8) { + throw new Error("Int64 buffers must be exactly 8 bytes"); + } + } + static fromNumber(number) { + if (number > 9223372036854776e3 || number < -9223372036854776e3) { + throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); + } + const bytes = new Uint8Array(8); + for (let i2 = 7, remaining = Math.abs(Math.round(number)); i2 > -1 && remaining > 0; i2--, remaining /= 256) { + bytes[i2] = remaining; + } + if (number < 0) { + negate2(bytes); + } + return new _Int64(bytes); + } + valueOf() { + const bytes = this.bytes.slice(0); + const negative = bytes[0] & 128; + if (negative) { + negate2(bytes); + } + return parseInt(toHex2(bytes), 16) * (negative ? -1 : 1); + } + toString() { + return String(this.valueOf()); + } + }; + function negate2(bytes) { + for (let i2 = 0; i2 < 8; i2++) { + bytes[i2] ^= 255; + } + for (let i2 = 7; i2 > -1; i2--) { + bytes[i2]++; + if (bytes[i2] !== 0) + break; + } + } + + // node_modules/@aws-sdk/eventstream-codec/dist-es/HeaderMarshaller.js + var HeaderMarshaller = class { + constructor(toUtf83, fromUtf85) { + this.toUtf8 = toUtf83; + this.fromUtf8 = fromUtf85; + } + format(headers) { + const chunks = []; + for (const headerName of Object.keys(headers)) { + const bytes = this.fromUtf8(headerName); + chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); + } + const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); + let position = 0; + for (const chunk of chunks) { + out.set(chunk, position); + position += chunk.byteLength; + } + return out; + } + formatHeaderValue(header) { + switch (header.type) { + case "boolean": + return Uint8Array.from([header.value ? 0 : 1]); + case "byte": + return Uint8Array.from([2, header.value]); + case "short": + const shortView = new DataView(new ArrayBuffer(3)); + shortView.setUint8(0, 3); + shortView.setInt16(1, header.value, false); + return new Uint8Array(shortView.buffer); + case "integer": + const intView = new DataView(new ArrayBuffer(5)); + intView.setUint8(0, 4); + intView.setInt32(1, header.value, false); + return new Uint8Array(intView.buffer); + case "long": + const longBytes = new Uint8Array(9); + longBytes[0] = 5; + longBytes.set(header.value.bytes, 1); + return longBytes; + case "binary": + const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); + binView.setUint8(0, 6); + binView.setUint16(1, header.value.byteLength, false); + const binBytes = new Uint8Array(binView.buffer); + binBytes.set(header.value, 3); + return binBytes; + case "string": + const utf8Bytes = this.fromUtf8(header.value); + const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); + strView.setUint8(0, 7); + strView.setUint16(1, utf8Bytes.byteLength, false); + const strBytes = new Uint8Array(strView.buffer); + strBytes.set(utf8Bytes, 3); + return strBytes; + case "timestamp": + const tsBytes = new Uint8Array(9); + tsBytes[0] = 8; + tsBytes.set(Int642.fromNumber(header.value.valueOf()).bytes, 1); + return tsBytes; + case "uuid": + if (!UUID_PATTERN2.test(header.value)) { + throw new Error(`Invalid UUID received: ${header.value}`); + } + const uuidBytes = new Uint8Array(17); + uuidBytes[0] = 9; + uuidBytes.set(fromHex2(header.value.replace(/\-/g, "")), 1); + return uuidBytes; + } + } + parse(headers) { + const out = {}; + let position = 0; + while (position < headers.byteLength) { + const nameLength = headers.getUint8(position++); + const name = this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, nameLength)); + position += nameLength; + switch (headers.getUint8(position++)) { + case 0: + out[name] = { + type: BOOLEAN_TAG, + value: true + }; + break; + case 1: + out[name] = { + type: BOOLEAN_TAG, + value: false + }; + break; + case 2: + out[name] = { + type: BYTE_TAG, + value: headers.getInt8(position++) + }; + break; + case 3: + out[name] = { + type: SHORT_TAG, + value: headers.getInt16(position, false) + }; + position += 2; + break; + case 4: + out[name] = { + type: INT_TAG, + value: headers.getInt32(position, false) + }; + position += 4; + break; + case 5: + out[name] = { + type: LONG_TAG, + value: new Int642(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)) + }; + position += 8; + break; + case 6: + const binaryLength = headers.getUint16(position, false); + position += 2; + out[name] = { + type: BINARY_TAG, + value: new Uint8Array(headers.buffer, headers.byteOffset + position, binaryLength) + }; + position += binaryLength; + break; + case 7: + const stringLength = headers.getUint16(position, false); + position += 2; + out[name] = { + type: STRING_TAG, + value: this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, stringLength)) + }; + position += stringLength; + break; + case 8: + out[name] = { + type: TIMESTAMP_TAG, + value: new Date(new Int642(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)).valueOf()) + }; + position += 8; + break; + case 9: + const uuidBytes = new Uint8Array(headers.buffer, headers.byteOffset + position, 16); + position += 16; + out[name] = { + type: UUID_TAG, + value: `${toHex2(uuidBytes.subarray(0, 4))}-${toHex2(uuidBytes.subarray(4, 6))}-${toHex2(uuidBytes.subarray(6, 8))}-${toHex2(uuidBytes.subarray(8, 10))}-${toHex2(uuidBytes.subarray(10))}` + }; + break; + default: + throw new Error(`Unrecognized header type tag`); + } + } + return out; + } + }; + var HEADER_VALUE_TYPE2; + (function(HEADER_VALUE_TYPE3) { + HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["boolTrue"] = 0] = "boolTrue"; + HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["boolFalse"] = 1] = "boolFalse"; + HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["byte"] = 2] = "byte"; + HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["short"] = 3] = "short"; + HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["integer"] = 4] = "integer"; + HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["long"] = 5] = "long"; + HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["byteArray"] = 6] = "byteArray"; + HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["string"] = 7] = "string"; + HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["timestamp"] = 8] = "timestamp"; + HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3["uuid"] = 9] = "uuid"; + })(HEADER_VALUE_TYPE2 || (HEADER_VALUE_TYPE2 = {})); + var BOOLEAN_TAG = "boolean"; + var BYTE_TAG = "byte"; + var SHORT_TAG = "short"; + var INT_TAG = "integer"; + var LONG_TAG = "long"; + var BINARY_TAG = "binary"; + var STRING_TAG = "string"; + var TIMESTAMP_TAG = "timestamp"; + var UUID_TAG = "uuid"; + var UUID_PATTERN2 = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; + + // node_modules/@aws-sdk/eventstream-codec/dist-es/splitMessage.js + var import_crc32 = __toESM(require_build2()); + var PRELUDE_MEMBER_LENGTH = 4; + var PRELUDE_LENGTH = PRELUDE_MEMBER_LENGTH * 2; + var CHECKSUM_LENGTH = 4; + var MINIMUM_MESSAGE_LENGTH = PRELUDE_LENGTH + CHECKSUM_LENGTH * 2; + + // node_modules/@aws-sdk/util-middleware/dist-es/normalizeProvider.js + var normalizeProvider3 = (input) => { + if (typeof input === "function") + return input; + const promisified = Promise.resolve(input); + return () => promisified; + }; + + // node_modules/@aws-sdk/util-utf8/dist-es/fromUtf8.browser.js + var fromUtf84 = (input) => new TextEncoder().encode(input); + + // node_modules/@aws-sdk/util-utf8/dist-es/toUint8Array.js + var toUint8Array2 = (data) => { + if (typeof data === "string") { + return fromUtf84(data); + } + if (ArrayBuffer.isView(data)) { + return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); + } + return new Uint8Array(data); + }; + + // node_modules/@aws-sdk/util-utf8/dist-es/toUtf8.browser.js + var toUtf82 = (input) => new TextDecoder("utf-8").decode(input); + + // node_modules/@aws-sdk/signature-v4/dist-es/constants.js + var ALGORITHM_QUERY_PARAM2 = "X-Amz-Algorithm"; + var CREDENTIAL_QUERY_PARAM2 = "X-Amz-Credential"; + var AMZ_DATE_QUERY_PARAM2 = "X-Amz-Date"; + var SIGNED_HEADERS_QUERY_PARAM2 = "X-Amz-SignedHeaders"; + var EXPIRES_QUERY_PARAM2 = "X-Amz-Expires"; + var SIGNATURE_QUERY_PARAM2 = "X-Amz-Signature"; + var TOKEN_QUERY_PARAM2 = "X-Amz-Security-Token"; + var AUTH_HEADER2 = "authorization"; + var AMZ_DATE_HEADER2 = AMZ_DATE_QUERY_PARAM2.toLowerCase(); + var DATE_HEADER2 = "date"; + var GENERATED_HEADERS2 = [AUTH_HEADER2, AMZ_DATE_HEADER2, DATE_HEADER2]; + var SIGNATURE_HEADER2 = SIGNATURE_QUERY_PARAM2.toLowerCase(); + var SHA256_HEADER2 = "x-amz-content-sha256"; + var TOKEN_HEADER2 = TOKEN_QUERY_PARAM2.toLowerCase(); + var ALWAYS_UNSIGNABLE_HEADERS2 = { + authorization: true, + "cache-control": true, + connection: true, + expect: true, + from: true, + "keep-alive": true, + "max-forwards": true, + pragma: true, + referer: true, + te: true, + trailer: true, + "transfer-encoding": true, + upgrade: true, + "user-agent": true, + "x-amzn-trace-id": true + }; + var PROXY_HEADER_PATTERN2 = /^proxy-/; + var SEC_HEADER_PATTERN2 = /^sec-/; + var ALGORITHM_IDENTIFIER2 = "AWS4-HMAC-SHA256"; + var EVENT_ALGORITHM_IDENTIFIER2 = "AWS4-HMAC-SHA256-PAYLOAD"; + var UNSIGNED_PAYLOAD2 = "UNSIGNED-PAYLOAD"; + var MAX_CACHE_SIZE2 = 50; + var KEY_TYPE_IDENTIFIER2 = "aws4_request"; + var MAX_PRESIGNED_TTL2 = 60 * 60 * 24 * 7; + + // node_modules/@aws-sdk/signature-v4/dist-es/credentialDerivation.js + var signingKeyCache2 = {}; + var cacheQueue2 = []; + var createScope2 = (shortDate, region2, service) => `${shortDate}/${region2}/${service}/${KEY_TYPE_IDENTIFIER2}`; + var getSigningKey2 = async (sha256Constructor, credentials, shortDate, region2, service) => { + const credsHash = await hmac2(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId); + const cacheKey = `${shortDate}:${region2}:${service}:${toHex2(credsHash)}:${credentials.sessionToken}`; + if (cacheKey in signingKeyCache2) { + return signingKeyCache2[cacheKey]; + } + cacheQueue2.push(cacheKey); + while (cacheQueue2.length > MAX_CACHE_SIZE2) { + delete signingKeyCache2[cacheQueue2.shift()]; + } + let key = `AWS4${credentials.secretAccessKey}`; + for (const signable of [shortDate, region2, service, KEY_TYPE_IDENTIFIER2]) { + key = await hmac2(sha256Constructor, key, signable); + } + return signingKeyCache2[cacheKey] = key; + }; + var hmac2 = (ctor, secret, data) => { + const hash = new ctor(secret); + hash.update(toUint8Array2(data)); + return hash.digest(); + }; + + // node_modules/@aws-sdk/signature-v4/dist-es/getCanonicalHeaders.js + var getCanonicalHeaders2 = ({ headers }, unsignableHeaders, signableHeaders) => { + const canonical = {}; + for (const headerName of Object.keys(headers).sort()) { + if (headers[headerName] == void 0) { + continue; + } + const canonicalHeaderName = headerName.toLowerCase(); + if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS2 || unsignableHeaders?.has(canonicalHeaderName) || PROXY_HEADER_PATTERN2.test(canonicalHeaderName) || SEC_HEADER_PATTERN2.test(canonicalHeaderName)) { + if (!signableHeaders || signableHeaders && !signableHeaders.has(canonicalHeaderName)) { + continue; + } + } + canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " "); + } + return canonical; + }; + + // node_modules/@aws-sdk/util-uri-escape/dist-es/escape-uri.js + var escapeUri2 = (uri2) => encodeURIComponent(uri2).replace(/[!'()*]/g, hexEncode2); + var hexEncode2 = (c3) => `%${c3.charCodeAt(0).toString(16).toUpperCase()}`; + + // node_modules/@aws-sdk/signature-v4/dist-es/getCanonicalQuery.js + var getCanonicalQuery2 = ({ query = {} }) => { + const keys = []; + const serialized = {}; + for (const key of Object.keys(query).sort()) { + if (key.toLowerCase() === SIGNATURE_HEADER2) { + continue; + } + keys.push(key); + const value = query[key]; + if (typeof value === "string") { + serialized[key] = `${escapeUri2(key)}=${escapeUri2(value)}`; + } else if (Array.isArray(value)) { + serialized[key] = value.slice(0).sort().reduce((encoded, value2) => encoded.concat([`${escapeUri2(key)}=${escapeUri2(value2)}`]), []).join("&"); + } + } + return keys.map((key) => serialized[key]).filter((serialized2) => serialized2).join("&"); + }; + + // node_modules/@aws-sdk/is-array-buffer/dist-es/index.js + var isArrayBuffer2 = (arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; + + // node_modules/@aws-sdk/signature-v4/dist-es/getPayloadHash.js + var getPayloadHash2 = async ({ headers, body }, hashConstructor) => { + for (const headerName of Object.keys(headers)) { + if (headerName.toLowerCase() === SHA256_HEADER2) { + return headers[headerName]; + } + } + if (body == void 0) { + return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + } else if (typeof body === "string" || ArrayBuffer.isView(body) || isArrayBuffer2(body)) { + const hashCtor = new hashConstructor(); + hashCtor.update(toUint8Array2(body)); + return toHex2(await hashCtor.digest()); + } + return UNSIGNED_PAYLOAD2; + }; + + // node_modules/@aws-sdk/signature-v4/dist-es/headerUtil.js + var hasHeader2 = (soughtHeader, headers) => { + soughtHeader = soughtHeader.toLowerCase(); + for (const headerName of Object.keys(headers)) { + if (soughtHeader === headerName.toLowerCase()) { + return true; + } + } + return false; + }; + + // node_modules/@aws-sdk/signature-v4/dist-es/cloneRequest.js + var cloneRequest = ({ headers, query, ...rest }) => ({ + ...rest, + headers: { ...headers }, + query: query ? cloneQuery3(query) : void 0 + }); + var cloneQuery3 = (query) => Object.keys(query).reduce((carry, paramName) => { + const param = query[paramName]; + return { + ...carry, + [paramName]: Array.isArray(param) ? [...param] : param + }; + }, {}); + + // node_modules/@aws-sdk/signature-v4/dist-es/moveHeadersToQuery.js + var moveHeadersToQuery2 = (request, options = {}) => { + const { headers, query = {} } = typeof request.clone === "function" ? request.clone() : cloneRequest(request); + for (const name of Object.keys(headers)) { + const lname = name.toLowerCase(); + if (lname.slice(0, 6) === "x-amz-" && !options.unhoistableHeaders?.has(lname)) { + query[name] = headers[name]; + delete headers[name]; + } + } + return { + ...request, + headers, + query + }; + }; + + // node_modules/@aws-sdk/signature-v4/dist-es/prepareRequest.js + var prepareRequest2 = (request) => { + request = typeof request.clone === "function" ? request.clone() : cloneRequest(request); + for (const headerName of Object.keys(request.headers)) { + if (GENERATED_HEADERS2.indexOf(headerName.toLowerCase()) > -1) { + delete request.headers[headerName]; + } + } + return request; + }; + + // node_modules/@aws-sdk/signature-v4/dist-es/utilDate.js + var iso86012 = (time2) => toDate2(time2).toISOString().replace(/\.\d{3}Z$/, "Z"); + var toDate2 = (time2) => { + if (typeof time2 === "number") { + return new Date(time2 * 1e3); + } + if (typeof time2 === "string") { + if (Number(time2)) { + return new Date(Number(time2) * 1e3); + } + return new Date(time2); + } + return time2; + }; + + // node_modules/@aws-sdk/signature-v4/dist-es/SignatureV4.js + var SignatureV42 = class { + constructor({ applyChecksum, credentials, region: region2, service, sha256, uriEscapePath = true }) { + this.headerMarshaller = new HeaderMarshaller(toUtf82, fromUtf84); + this.service = service; + this.sha256 = sha256; + this.uriEscapePath = uriEscapePath; + this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true; + this.regionProvider = normalizeProvider3(region2); + this.credentialProvider = normalizeProvider3(credentials); + } + async presign(originalRequest, options = {}) { + const { signingDate = /* @__PURE__ */ new Date(), expiresIn = 3600, unsignableHeaders, unhoistableHeaders, signableHeaders, signingRegion, signingService } = options; + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region2 = signingRegion ?? await this.regionProvider(); + const { longDate, shortDate } = formatDate(signingDate); + if (expiresIn > MAX_PRESIGNED_TTL2) { + return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future"); + } + const scope = createScope2(shortDate, region2, signingService ?? this.service); + const request = moveHeadersToQuery2(prepareRequest2(originalRequest), { unhoistableHeaders }); + if (credentials.sessionToken) { + request.query[TOKEN_QUERY_PARAM2] = credentials.sessionToken; + } + request.query[ALGORITHM_QUERY_PARAM2] = ALGORITHM_IDENTIFIER2; + request.query[CREDENTIAL_QUERY_PARAM2] = `${credentials.accessKeyId}/${scope}`; + request.query[AMZ_DATE_QUERY_PARAM2] = longDate; + request.query[EXPIRES_QUERY_PARAM2] = expiresIn.toString(10); + const canonicalHeaders = getCanonicalHeaders2(request, unsignableHeaders, signableHeaders); + request.query[SIGNED_HEADERS_QUERY_PARAM2] = getCanonicalHeaderList(canonicalHeaders); + request.query[SIGNATURE_QUERY_PARAM2] = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region2, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, await getPayloadHash2(originalRequest, this.sha256))); + return request; + } + async sign(toSign, options) { + if (typeof toSign === "string") { + return this.signString(toSign, options); + } else if (toSign.headers && toSign.payload) { + return this.signEvent(toSign, options); + } else if (toSign.message) { + return this.signMessage(toSign, options); + } else { + return this.signRequest(toSign, options); + } + } + async signEvent({ headers, payload }, { signingDate = /* @__PURE__ */ new Date(), priorSignature, signingRegion, signingService }) { + const region2 = signingRegion ?? await this.regionProvider(); + const { shortDate, longDate } = formatDate(signingDate); + const scope = createScope2(shortDate, region2, signingService ?? this.service); + const hashedPayload = await getPayloadHash2({ headers: {}, body: payload }, this.sha256); + const hash = new this.sha256(); + hash.update(headers); + const hashedHeaders = toHex2(await hash.digest()); + const stringToSign = [ + EVENT_ALGORITHM_IDENTIFIER2, + longDate, + scope, + priorSignature, + hashedHeaders, + hashedPayload + ].join("\n"); + return this.signString(stringToSign, { signingDate, signingRegion: region2, signingService }); + } + async signMessage(signableMessage, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService }) { + const promise = this.signEvent({ + headers: this.headerMarshaller.format(signableMessage.message.headers), + payload: signableMessage.message.body + }, { + signingDate, + signingRegion, + signingService, + priorSignature: signableMessage.priorSignature + }); + return promise.then((signature) => { + return { message: signableMessage.message, signature }; + }); + } + async signString(stringToSign, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService } = {}) { + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region2 = signingRegion ?? await this.regionProvider(); + const { shortDate } = formatDate(signingDate); + const hash = new this.sha256(await this.getSigningKey(credentials, region2, shortDate, signingService)); + hash.update(toUint8Array2(stringToSign)); + return toHex2(await hash.digest()); + } + async signRequest(requestToSign, { signingDate = /* @__PURE__ */ new Date(), signableHeaders, unsignableHeaders, signingRegion, signingService } = {}) { + const credentials = await this.credentialProvider(); + this.validateResolvedCredentials(credentials); + const region2 = signingRegion ?? await this.regionProvider(); + const request = prepareRequest2(requestToSign); + const { longDate, shortDate } = formatDate(signingDate); + const scope = createScope2(shortDate, region2, signingService ?? this.service); + request.headers[AMZ_DATE_HEADER2] = longDate; + if (credentials.sessionToken) { + request.headers[TOKEN_HEADER2] = credentials.sessionToken; + } + const payloadHash = await getPayloadHash2(request, this.sha256); + if (!hasHeader2(SHA256_HEADER2, request.headers) && this.applyChecksum) { + request.headers[SHA256_HEADER2] = payloadHash; + } + const canonicalHeaders = getCanonicalHeaders2(request, unsignableHeaders, signableHeaders); + const signature = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region2, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, payloadHash)); + request.headers[AUTH_HEADER2] = `${ALGORITHM_IDENTIFIER2} Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${getCanonicalHeaderList(canonicalHeaders)}, Signature=${signature}`; + return request; + } + createCanonicalRequest(request, canonicalHeaders, payloadHash) { + const sortedHeaders = Object.keys(canonicalHeaders).sort(); + return `${request.method} +${this.getCanonicalPath(request)} +${getCanonicalQuery2(request)} +${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")} + +${sortedHeaders.join(";")} +${payloadHash}`; + } + async createStringToSign(longDate, credentialScope, canonicalRequest) { + const hash = new this.sha256(); + hash.update(toUint8Array2(canonicalRequest)); + const hashedRequest = await hash.digest(); + return `${ALGORITHM_IDENTIFIER2} +${longDate} +${credentialScope} +${toHex2(hashedRequest)}`; + } + getCanonicalPath({ path }) { + if (this.uriEscapePath) { + const normalizedPathSegments = []; + for (const pathSegment of path.split("/")) { + if (pathSegment?.length === 0) + continue; + if (pathSegment === ".") + continue; + if (pathSegment === "..") { + normalizedPathSegments.pop(); + } else { + normalizedPathSegments.push(pathSegment); + } + } + const normalizedPath = `${path?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path?.endsWith("/") ? "/" : ""}`; + const doubleEncoded = encodeURIComponent(normalizedPath); + return doubleEncoded.replace(/%2F/g, "/"); + } + return path; + } + async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) { + const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest); + const hash = new this.sha256(await keyPromise); + hash.update(toUint8Array2(stringToSign)); + return toHex2(await hash.digest()); + } + getSigningKey(credentials, region2, shortDate, service) { + return getSigningKey2(this.sha256, credentials, shortDate, region2, service || this.service); + } + validateResolvedCredentials(credentials) { + if (typeof credentials !== "object" || typeof credentials.accessKeyId !== "string" || typeof credentials.secretAccessKey !== "string") { + throw new Error("Resolved credential object is not valid"); + } + } + }; + var formatDate = (now2) => { + const longDate = iso86012(now2).replace(/[\-:]/g, ""); + return { + longDate, + shortDate: longDate.slice(0, 8) + }; + }; + var getCanonicalHeaderList = (headers) => Object.keys(headers).sort().join(";"); + + // src/voiceLambdaIamFetch.ts + var region = "us-east-2"; + var identityPoolId = "us-east-2:21ce1894-9a97-48ac-8741-b69f7eafea1c"; + function cognitoCredentials() { + if (!region || !identityPoolId) { + throw new Error( + "Missing AWS_REGION or COGNITO_IDENTITY_POOL_ID for voice Lambda signing." + ); + } + return fromCognitoIdentityPool({ + clientConfig: { region }, + identityPoolId + }); + } + var signerPromise = null; + function getSigner() { + if (!signerPromise) { + signerPromise = Promise.resolve( + new SignatureV42({ + credentials: cognitoCredentials(), + region, + service: "lambda", + sha256: Sha256, + applyChecksum: false + }) + ); + } + return signerPromise; + } + async function postVoiceLambdaWithIam(endpoint, body, jwtAccessToken) { + const url = new URL( + endpoint.startsWith("http") ? endpoint : `https://${endpoint}` + ); + const path = url.pathname && url.pathname.length > 0 ? url.pathname : "/"; + const headers = { + host: url.host, + "content-type": "application/json" + }; + if (jwtAccessToken) { + headers["x-oasis-authorization"] = `Bearer ${jwtAccessToken}`; + } + const req = new HttpRequest2({ + protocol: url.protocol, + hostname: url.hostname, + port: url.port ? parseInt(url.port, 10) : void 0, + method: "POST", + path, + headers, + body + }); + const signer = await getSigner(); + const signed = await signer.sign(req); + const portPart = signed.port != null && signed.port !== 80 && signed.port !== 443 ? `:${signed.port}` : ""; + const signedUrl = `${signed.protocol}//${signed.hostname}${portPart}${signed.path}`; + return fetch(signedUrl, { + method: signed.method, + headers: signed.headers, + body: signed.body + }); + } + + // src/awsSignedFetch.ts + var QuotaExceededError = class extends Error { + quota; + isQuotaError = true; + constructor(message, quota) { + super(message); + this.name = "QuotaExceededError"; + this.quota = quota; + } + }; + var normalizeEndpoint = (value) => String(value || "").trim().replace(/\/+$/, ""); + var assistantUrl = normalizeEndpoint("https://wvclepquxxczgrukfqyr.supabase.co/functions/v1/oasis-assist-test"); + var transcribeUrl = normalizeEndpoint("https://ic3fypkh4rz24odos4m3u5xsma0edmnn.lambda-url.us-east-2.on.aws/"); + var supabaseAuth2 = SupabaseAuth.getInstance(); + var endpointByOperation = { + assist: assistantUrl, + transcribe: transcribeUrl, + tts: transcribeUrl + }; + var endpointEnvByOperation = { + assist: "OASIS_ASSIST_URL", + transcribe: "OASIS_TRANSCRIBE_URL", + tts: "OASIS_TRANSCRIBE_URL" + }; + function getAssistantApiBase() { + return assistantUrl; + } + async function postSigned(op, payload) { + const endpoint = endpointByOperation[op]; + if (!endpoint) { + throw new Error( + `Endpoint not configured for operation "${op}". Missing ${endpointEnvByOperation[op]}.` + ); + } + const body = JSON.stringify({ op, ...payload }); + const session = await supabaseAuth2.getSession(); + const token = session?.access_token; + const requiresJwt = op !== "assist"; + if (requiresJwt && !token) { + throw new Error("Authentication required: No JWT found"); + } + const headers = { + "content-type": "application/json" + }; + if (token) { + headers.Authorization = `Bearer ${token}`; + } + const res = op === "transcribe" || op === "tts" ? await postVoiceLambdaWithIam(endpoint, body, token) : await fetch(endpoint, { method: "POST", headers, body }); + if (!res.ok) { + const errorBody = await res.text(); + if (res.status === 429 && op === "assist") { + try { + const parsed = JSON.parse(errorBody); + if (parsed.error === "quota_exceeded") { + throw new QuotaExceededError(parsed.message || "Usage limit reached.", parsed.quota); + } + } catch (e2) { + if (e2.isQuotaError) throw e2; + } + } + assistantLogger.error("transport", "Assistant backend error", { + op, + status: res.status, + errorBody + }); + throw new Error(`Assistant backend ${res.status} ${errorBody}`); + } + return res.json(); + } + + // src/proxyClient.ts + function getAssistLoopOptionsFromBuildEnv() { + const rawMax = String( + true ? "" : "" + ).trim(); + const rawRefine = String( + true ? "" : "" + ).trim(); + const refine = rawRefine === "1" || /^true$/i.test(rawRefine); + let max; + if (rawMax !== "") { + const n2 = parseInt(rawMax, 10); + if (Number.isFinite(n2) && n2 >= 1) { + max = Math.min(8, n2); + } + } + if (refine && (max == null || max < 2)) { + max = 3; + } + if (max == null && !refine) { + return void 0; + } + const out = {}; + if (max != null) { + out.max_inner_rounds = max; + } + if (refine) { + out.refine_after_route = true; + } + return Object.keys(out).length ? out : void 0; + } + var supabaseAuth3 = SupabaseAuth.getInstance(); + async function ensureAuthenticated() { + const isAuthenticated = await supabaseAuth3.isAuthenticated(); + if (!isAuthenticated) { + throw new Error("Authentication required: Please sign in to use voice features"); + } + } + async function assistRemote(system, messages, options, tools = [], generationConfig, assistLoop) { + return postSigned("assist", { + system, + messages, + options, + tools, + ...generationConfig ? { generation_config: generationConfig } : {}, + ...assistLoop?.max_inner_rounds != null ? { max_inner_rounds: assistLoop.max_inner_rounds } : {}, + ...assistLoop?.refine_after_route ? { refine_after_route: true } : {} + }); + } + async function transcribeAudio(audioBlob, options = {}) { + await ensureAuthenticated(); + const arrayBuffer = await audioBlob.arrayBuffer(); + const base64Audio = btoa( + new Uint8Array(arrayBuffer).reduce((data, byte) => data + String.fromCharCode(byte), "") + ); + const result = await postSigned("transcribe", { + audio: base64Audio, + mimeType: audioBlob.type, + ...options.language ? { language: options.language } : {}, + ...options.captureMeta ? { captureMeta: options.captureMeta } : {}, + ...options.source != null ? { source: options.source } : {}, + ...options.utteranceSeq != null ? { utteranceSeq: options.utteranceSeq } : {} + }); + return result; + } + async function textToSpeech(text2) { + await ensureAuthenticated(); + const result = await postSigned("tts", { text: text2 }); + const audioData = atob(result.audio); + const arrayBuffer = new Uint8Array(audioData.length); + for (let i2 = 0; i2 < audioData.length; i2++) { + arrayBuffer[i2] = audioData.charCodeAt(i2); + } + return new Blob([arrayBuffer], { type: result.mimeType || "audio/mpeg" }); + } + + // src/utils/routingUtils.ts + var CANCEL_RE = /^(?:no|cancel|nevermind|never\s+mind|stop)$/i; + function parseAmbiguityResolution(text2) { + const input = String(text2 || "").trim(); + if (!input) return null; + if (CANCEL_RE.test(input)) { + return "cancel"; + } + const hasTabGroup = /\btab\s*group\b/i.test(input); + const hasBookmarkFolder = /\bbookmark\s*folder\b/i.test(input); + if (hasTabGroup && hasBookmarkFolder) return null; + if (hasTabGroup) return "tab-group"; + if (hasBookmarkFolder) return "bookmark-folder"; + const hasGroupWord = /\bgroup\b/i.test(input); + const hasFolderWord = /\bfolder\b/i.test(input); + const hasTabWord = /\btab\b/i.test(input); + if (hasGroupWord && hasFolderWord) return null; + if (hasGroupWord) return "tab-group"; + if (hasFolderWord) return "bookmark-folder"; + if (hasTabWord) return "tab"; + return null; + } + function looksLikeNewActionCommand(text2) { + const input = String(text2 || ""); + const hasAction = /\b(?:open|close|delete|remove|create|make|new|add|save|move|put|rename|list|show|search|find|summarize|split|go\s+to|navigate|visit)\b/i.test( + input + ); + const hasObjectOrTarget = /\b(?:tab|tabs|group|folder|bookmark|window|history|memory|page|site|website|url|link)\b/i.test( + input + ) || /\bhttps?:\/\/[^\s]+\b|\b[a-z0-9.-]+\.[a-z]{2,}(?:\/[^\s]*)?\b/i.test( + input + ) || KNOWN_SITES_HINT_RE.test(input); + return hasAction && hasObjectOrTarget; + } + + // src/prompts/chatPrompt.ts + var CHAT_SYSTEM_PROMPT = `You are Oasis AI, a helpful and knowledgeable assistant integrated into the Oasis browser. You can help with ANYTHING - not just browser tasks. + +**Product naming:** The browser is Oasis (or Oasis Browser). Do not call it Firefox or imply the user is in Firefox unless you are quoting an external site or add-on name. + +**Your Capabilities:** +- Answer ANY question on any topic (science, history, coding, math, writing, etc.) +- Help with creative tasks (writing, brainstorming, explaining concepts) +- Provide advice and recommendations +- Assist with coding and technical problems +- Have casual conversations +- Format browser-command results into clean user-facing answers + +**Important:** You have access to the complete conversation history, including: +- All previous user requests +- Internal command traces and command results + +Treat command traces as internal context only. Never repeat raw tool payloads verbatim. + +**Response Guidelines:** +1. **Use Markdown inside the response field:** Format your answer using Markdown. + - Use **bold** for key terms or emphasis. + - Use bullet points or numbered lists for organized information. + - Use \`code blocks\` for code, URLs, or technical terms. + - Use headings for longer explanations. +2. **Be Helpful:** Answer questions thoroughly and accurately. If you don't know something, say so. +3. **Interpret Data:** If command context contains raw data, summarize it into human-readable prose inside the response field. Do not echo raw serialized payloads, IDs, or data dumps directly. +4. **Natural Tone:** Be friendly and conversational. Don't mention internal workings or "tool outputs". +5. **Context Aware:** Use the conversation history to provide relevant, contextual responses. +6. **No Trace Echo:** Never start a response by repeating command payload text, IDs, or serialized objects. + +**Formatting search_memory Results:** +When the command context contains search results (from search_memory), the data is structured JSON with: +- **summary**: A short description like "Found 5 results for 'Amazon'". +- **resultsBySource**: Results grouped by source (e.g., "history", "bookmark-folder", "tab"). +- **results**: Flat array of all matches with source, title, url, context, snippet. + +Present them grouped by source with clear headings. For example: + +**Browsing History** +- [Page Title](url) - snippet of matching content + +**Bookmark Folder: Research** +- [Saved Article](url) - snippet + +**Open Tabs** +- [Tab Title](url) - snippet + +If results are empty, say so naturally ("I couldn't find anything matching X in your history or bookmarks."). +If results come from a specific folder, mention the folder name. +When there are many results, highlight the top 3-5 most relevant and mention how many total were found. +Always make URLs clickable using Markdown link syntax. + +**Example - Internal Command Result:** +If the history shows: + - User: "list tabs" + - Internal command result: "["Google", "CNN"]" + +You should respond with the response field set to: +"Here are your open tabs: +- **Google** +- **CNN**" + +**Example - General Question:** +User: "What is machine learning?" +You should respond with a clear, helpful explanation inside the response field. + +Remember: You are a fully capable AI assistant. Help the user with whatever they need! + +**IMPORTANT \u2014 Output Format:** +Your ENTIRE reply must be a single valid JSON object \u2014 no text before or after it, no markdown fences around it. +The Markdown formatting described above goes inside the "response" string value, not at the top level. + +{"response":"","command_type":"","user_intent":""} + +command_type \u2014 what the user is asking you to DO: + info_retrieval, navigation, organization, content_transform, content_create, search, automation, system, help, other + +user_intent \u2014 the user's underlying goal: + learning, research, work, dev, marketing, shopping, personal, entertainment, meta, other + +Use "other" only when genuinely uncertain. Output ONLY the JSON object.`; + + // src/prompts/hiddenInstructions.ts + var SUMMARIZE_INSTRUCTION = `The content above is from a webpage that the user wants summarized. Please provide a clear, concise summary that: +1. Captures the main topic and key points +2. Uses bullet points for easy reading +3. Keeps it to 3-5 paragraphs max +4. Highlights any important facts, dates, or conclusions +Do NOT mention that you received page content or reference this instruction. Just provide the summary naturally.`; + var TOOL_OUTPUT_INSTRUCTION = "The command context above is internal trace data. Write a natural language response to the user's request using it, but never echo raw payload text, JSON, IDs, or serialized objects. Do NOT reference this instruction."; + var DEFAULT_INSTRUCTION = "Please respond to the user's message naturally and helpfully. Do NOT reference this instruction."; + function buildHiddenInstruction(ctx) { + if (ctx.hasSummarizeRequest) { + return SUMMARIZE_INSTRUCTION; + } + if (ctx.hasToolOutput) { + return TOOL_OUTPUT_INSTRUCTION; + } + return DEFAULT_INSTRUCTION; + } + + // src/prompts/routerPrompt.ts + function buildAssistRouterPrompt(commandNames) { + return [ + "You route the latest user request to one browser command.", + `Valid commands: ${commandNames.join(", ")}.`, + "For chained requests, you may call route_action_plan with actions[] (max 3) instead of a single command.", + "Return chat only when the latest user message is not a browser action.", + "When selecting a command, return only the command and JSON args.", + "Never invent command names outside the valid list.", + // CRITICAL: Clear distinction between search_history and search_memory + "SEARCH ROUTING RULES:", + "- search_history: ONLY for BROWSING HISTORY (pages the user visited in the past). Use for: 'what did I read', 'pages I visited', 'articles I browsed', 'what was that site about X', 'pull that article', 'find that page I visited', 'did I visit X'. Extract the topic as the query argument.", + "- search_memory: ONLY for BOOKMARKS, TABS, and BOOKMARK FOLDERS (things the user explicitly saved). Use for: 'search my bookmarks', 'what's in my folder', 'find in bookmarks', 'search bookmark folder X', 'do I have X bookmarked'. Supports folder and source args.", + "- search_memory does NOT search browsing history \u2014 use search_history instead.", + "- If the query mentions 'visited', 'browsed', 'read', 'looked at' (past tense) \u2192 search_history.", + "- If the query mentions 'bookmarks', 'folder', 'saved', 'tabs' \u2192 search_memory.", + "SPLIT VIEW:", + "- When the user wants split view, side-by-side tabs, two tabs at once, or a split screen of two pages in one window, prefer add_split_view (not chat). Use indices: [i,j] for two tab numbers, withIndex or withQuery to pair the current tab with another, or {} to split the current tab with a new tab.", + "- For removing split view or unsplitting, prefer remove_split_view.", + "For list/show requests, prefer list_* tools and avoid search_memory unless user explicitly asks to search.", + "For add/remove/delete/move requests, prefer mutation tools and keep destructive actions explicit.", + "Prefer open_url for explicit URLs/domains and web_search for plain-language queries.", + "For follow-ups like 'open it' after search results, prefer open_search_result with index (default 1).", + "If the user asks to inspect previous search results, use get_recent_search_results.", + "For ambiguous destructive/container targets, prefer safe commands like resolve_ambiguity instead of guessing." + ].join(" "); + } + + // src/assistant/agentGraphSupport.ts + function splitInternalArgs(args) { + const commandArgs = {}; + let chainNotice = null; + for (const [key, value] of Object.entries(args || {})) { + if (key === INTERNAL_CHAIN_NOTICE_ARG && typeof value === "string") { + chainNotice = value.trim() || null; + continue; + } + if (key.startsWith("__oasis")) { + continue; + } + commandArgs[key] = value; + } + return { commandArgs, chainNotice }; + } + function toAmbiguityPayload(routePending) { + return { + kind: routePending.kind || "container_target", + name: routePending.name, + query: routePending.query, + all: routePending.all, + choices: routePending.choices, + tabIndex: routePending.tabIndex, + verb: routePending.verb, + originalText: routePending.originalText, + description: routePending.kind === "close_delete_target" ? `Ambiguous close/delete target for "${routePending.name}"` : `Ambiguous container target for "${routePending.name}"` + }; + } + function setRoutePendingAmbiguity(routePending) { + setPendingAmbiguity(toAmbiguityPayload(routePending)); + assistantLogger.debug("router", "Ambiguity detected", { + name: routePending.name, + query: routePending.query || "", + all: !!routePending.all, + kind: routePending.kind || "container_target" + }); + } + + // src/assistant/agentSteps.ts + function createCommandToolAgent(command, deps) { + const { assistantWindow: assistantWindow2, messageId } = deps; + return async (state) => { + const recordStart = assistantWindow2.oasisRecordToolActionStart; + const recordUpdate = assistantWindow2.oasisRecordToolActionUpdate; + let actionId; + if (typeof recordStart === "function") { + actionId = recordStart(command.commandName, messageId); + } + const { commandArgs, chainNotice } = splitInternalArgs(state.args); + let result; + try { + result = await command.execute(commandArgs); + if (typeof recordUpdate === "function" && actionId) { + recordUpdate(actionId, "done"); + } + } catch (error) { + if (typeof recordUpdate === "function" && actionId) { + recordUpdate(actionId, "error"); + } + assistantLogger.error( + "graph", + `Command execution failed: ${command.commandName}`, + error + ); + result = { message: String(error) }; + } + if (result.requiresConfirmation) { + const remainingQueue = state.commandQueue.length > 1 ? state.commandQueue.slice(1) : []; + if (remainingQueue.length > 0) { + setContinuationQueue(remainingQueue); + } else { + clearContinuationQueue(); + } + assistantLogger.debug( + "graph", + `Command requires confirmation: ${command.commandName}` + ); + const confirmationMessage = String(result.message || "").trim(); + const toolResultPayload2 = { + kind: "tool_result", + commandName: command.commandName, + message: confirmationMessage + }; + return { + messages: [ + new AIMessage({ + content: confirmationMessage, + name: command.commandName, + additional_kwargs: { oasisToolResult: toolResultPayload2 } + }) + ], + lastWorker: command.commandName, + next: AGENT_END, + args: {}, + commandQueue: state.commandQueue + }; + } + const resultMessage = chainNotice ? `${chainNotice} +${result.message}` : result.message; + const toolResultPayload = { + kind: "tool_result", + commandName: command.commandName, + message: resultMessage + }; + return { + messages: [ + new AIMessage({ + content: resultMessage, + name: command.commandName, + additional_kwargs: { oasisToolResult: toolResultPayload } + }) + ], + lastWorker: command.commandName, + next: "supervisor", + args: {}, + commandQueue: state.commandQueue + }; + }; + } + + // src/utils/quotaUserMessage.ts + function formatQuotaExceededMessage(raw) { + const s2 = String(raw || "").trim().toLowerCase(); + if (!s2) { + return "You have reached your AI usage limit for this plan."; + } + if (s2.includes("daily_limit") || s2 === "daily_limit_exceeded") { + return "You have reached your daily AI usage limit. Your allocation resets every day."; + } + if (s2.includes("monthly_limit") || s2 === "monthly_limit_exceeded") { + return "You have reached your monthly AI usage limit. Your allocation resets at the start of your next billing cycle."; + } + if (s2.includes("quota_exceeded") || s2.includes("quota exceeded")) { + return "You have reached your AI usage limit for this plan."; + } + if (/^[a-z0-9_]+$/.test(String(raw || "").trim())) { + return "You have reached your AI usage limit for this plan."; + } + return String(raw || "").trim(); + } + + // src/utils/oasisCapabilitiesFaq.ts + var OASIS_CAPABILITIES_REPLY = `I'm Oasis AI, your assistant in this browser. Here's what I focus on: + +**Browser tasks (first and foremost)** +- **Tabs and navigation:** Open sites in new tabs, run web searches, and move around your windows. +- **Organization:** Create and manage tab groups, and work with your tabs in bulk when you ask. +- **Your data:** Search your browsing history and bookmarks. +- **The page you're reading:** Summarize, translate, or rework text on normal web pages you have open. (Built-in pages like the new tab page can't be summarized the same way\u2014open a regular website first.) + +**General help** +- Answer questions, brainstorm, explain ideas in plain language, and help you phrase something clearly. + +I don't take the place of a coding debugger or deep technical support. If you want something done in the browser, say what you're trying to do and I'll walk you through it. + +What would you like to try first?`; + function getOasisCapabilitiesReply(userText) { + const t2 = userText.trim().toLowerCase(); + if (t2.length < 12 || t2.length > 220) { + return null; + } + if (!/\bwhat\b/.test(t2)) { + return null; + } + if (!t2.includes("oasis") && !t2.includes("assistant")) { + return null; + } + const asksScope = /\bcan\b/.test(t2) || /\bdo\b/.test(t2) || /\bcapabilities\b/.test(t2) || /\bhelp (with|me)\b/.test(t2); + if (!asksScope) { + return null; + } + if (/\bwhat can i\b/.test(t2) && !t2.includes("you") && !t2.includes("assistant")) { + return null; + } + return OASIS_CAPABILITIES_REPLY; + } + + // src/assistant/messageUtils.ts + var TOOL_COMMAND_TYPE_MAP = { + open_url: "navigation", + navigate_tab: "navigation", + new_window: "navigation", + new_tab_to_right: "navigation", + open_bookmark_folder: "navigation", + open_search_result: "navigation", + close_tab: "organization", + create_tab_group: "organization", + delete_tab_group: "organization", + rename_tab_group: "organization", + add_tab_to_group: "organization", + remove_tab_from_group: "organization", + move_tab_to_new_window: "organization", + split_tabs: "organization", + add_split_view: "organization", + remove_split_view: "organization", + organize_windows: "organization", + create_bookmark_folder: "organization", + delete_bookmark_folder: "organization", + rename_bookmark_folder: "organization", + add_tab_to_bookmark_folder: "organization", + remove_tab_from_bookmark_folder: "organization", + list_tabs: "info_retrieval", + list_bookmark_folders: "info_retrieval", + list_tab_groups: "info_retrieval", + search_memory: "search", + get_recent_search_results: "search", + web_search: "search", + search_history: "search" + }; + function classifyToolAction(commandName) { + return { + command_type: TOOL_COMMAND_TYPE_MAP[commandName] ?? "other", + user_intent: "other", + input_tokens: null, + output_tokens: null + }; + } + function isRecord(value) { + return !!value && typeof value === "object"; + } + function asToolResultPayload(value) { + if (!isRecord(value)) { + return null; + } + const kind = value.kind; + const commandName = value.commandName; + const message = value.message; + if (kind !== "tool_result") { + return null; + } + if (typeof commandName !== "string" || !commandName.trim()) { + return null; + } + if (typeof message !== "string") { + return null; + } + return { + kind, + commandName, + message + }; + } + function getToolResultPayload(message) { + if (!message) { + return null; + } + const rawKwargs = message.additional_kwargs; + if (!isRecord(rawKwargs)) { + return null; + } + return asToolResultPayload(rawKwargs.oasisToolResult); + } + function msgText(m3) { + if (!m3) return ""; + const toolResult = getToolResultPayload(m3); + if (toolResult) { + return toolResult.message; + } + const c3 = m3.content; + if (typeof c3 === "string") return c3; + if (Array.isArray(c3)) { + return c3.map( + (v6) => typeof v6 === "string" ? v6 : typeof v6 === "object" && v6 && "text" in v6 ? String(v6.text || "") : "" + ).join(""); + } + return String(c3 ?? ""); + } + function toWire(messages) { + return messages.map((m3) => { + const role = m3._getType() === "human" ? "user" : "model"; + const toolResult = getToolResultPayload(m3); + if (toolResult) { + return { + role, + content: `Internal command result +Command: ${toolResult.commandName} +Result: ${toolResult.message}` + }; + } + return { role, content: msgText(m3) }; + }); + } + function extractChatContent(response) { + if (typeof response === "string") { + return response; + } + if (response && typeof response === "object" && "content" in response) { + return String(response.content ?? ""); + } + return ""; + } + var VALID_COMMAND_TYPES = /* @__PURE__ */ new Set([ + "info_retrieval", + "navigation", + "organization", + "content_transform", + "content_create", + "search", + "automation", + "system", + "help", + "other" + ]); + var VALID_USER_INTENTS = /* @__PURE__ */ new Set([ + "learning", + "research", + "work", + "dev", + "marketing", + "shopping", + "personal", + "entertainment", + "meta", + "other" + ]); + function extractTokenCountsFromUsageMetadata(usage) { + let inputTokens = null; + let outputTokens = null; + if (!isRecord(usage)) { + return { input_tokens: null, output_tokens: null }; + } + if (typeof usage.prompt_token_count === "number") { + inputTokens = usage.prompt_token_count; + } else if (typeof usage.promptTokenCount === "number") { + inputTokens = usage.promptTokenCount; + } + if (typeof usage.candidates_token_count === "number") { + outputTokens = usage.candidates_token_count; + } else if (typeof usage.candidatesTokenCount === "number") { + outputTokens = usage.candidatesTokenCount; + } + return { input_tokens: inputTokens, output_tokens: outputTokens }; + } + function extractTokenCountsFromAssistPayload(payload) { + if (!isRecord(payload)) { + return { input_tokens: null, output_tokens: null }; + } + return extractTokenCountsFromUsageMetadata(payload.usage_metadata); + } + function parseChatEnvelope(response) { + const defaultMeta = { + command_type: "other", + user_intent: "other", + input_tokens: null, + output_tokens: null + }; + const tokenCounts = extractTokenCountsFromAssistPayload(response); + const tokenMeta = { + input_tokens: tokenCounts.input_tokens, + output_tokens: tokenCounts.output_tokens + }; + if (!isRecord(response)) { + return { + text: extractChatContent(response), + meta: { ...defaultMeta, ...tokenMeta } + }; + } + const contentField = response.content; + if (isRecord(contentField)) { + return extractFromParsed(contentField, tokenMeta, defaultMeta); + } + if (typeof contentField !== "string" || !contentField.trim()) { + return { + text: extractChatContent(response), + meta: { ...defaultMeta, ...tokenMeta } + }; + } + let jsonStr = contentField.trim(); + const fenceMatch = jsonStr.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/); + if (fenceMatch) { + jsonStr = fenceMatch[1].trim(); + } + const direct = tryJsonParse(jsonStr); + if (direct !== null) { + return extractFromParsed(direct, tokenMeta, defaultMeta); + } + const repaired = jsonStr.replace(/\r\n/g, "\\n").replace(/\r/g, "\\n").replace(/\n/g, "\\n").replace(/\t/g, "\\t"); + const fromRepair = tryJsonParse(repaired); + if (fromRepair !== null) { + return extractFromParsed(fromRepair, tokenMeta, defaultMeta); + } + const regexResult = extractViaRegex(jsonStr, tokenMeta, defaultMeta); + if (regexResult !== null) { + return regexResult; + } + return { + text: jsonStr || contentField, + meta: { ...defaultMeta, ...tokenMeta } + }; + } + function tryJsonParse(str) { + try { + return JSON.parse(str); + } catch { + return null; + } + } + function extractFromParsed(parsed, tokenMeta, defaultMeta) { + if (!isRecord(parsed) || typeof parsed.response !== "string") { + return { + text: typeof parsed === "string" ? parsed : "", + meta: { ...defaultMeta, ...tokenMeta } + }; + } + const commandType = VALID_COMMAND_TYPES.has( + String(parsed.command_type ?? "") + ) ? parsed.command_type : "other"; + const userIntent = VALID_USER_INTENTS.has( + String(parsed.user_intent ?? "") + ) ? parsed.user_intent : "other"; + return { + text: parsed.response, + meta: { command_type: commandType, user_intent: userIntent, ...tokenMeta } + }; + } + function extractViaRegex(str, tokenMeta, defaultMeta) { + const responseMatch = str.match( + /"response"\s*:\s*"([\s\S]*?)"\s*,\s*"command_type"/ + ); + if (!responseMatch) { + return null; + } + const responseText = responseMatch[1].replace(/\\n/g, "\n").replace(/\\t/g, " ").replace(/\\"/g, '"').replace(/\\\\/g, "\\"); + const cmdMatch = str.match(/"command_type"\s*:\s*"([^"]+)"/); + const intentMatch = str.match(/"user_intent"\s*:\s*"([^"]+)"/); + const commandType = cmdMatch && VALID_COMMAND_TYPES.has(cmdMatch[1]) ? cmdMatch[1] : "other"; + const userIntent = intentMatch && VALID_USER_INTENTS.has(intentMatch[1]) ? intentMatch[1] : "other"; + return { + text: responseText || str, + meta: { command_type: commandType, user_intent: userIntent, ...tokenMeta } + }; + } + function stripLeadingEchoedPayload(value, payloads) { + let text2 = String(value || "").trim(); + if (!text2 || payloads.length === 0) { + return text2; + } + for (const payload of payloads) { + const candidate = String(payload || "").trim(); + if (!candidate) { + continue; + } + if (text2.startsWith(candidate)) { + if (text2.length === candidate.length) { + continue; + } + text2 = text2.slice(candidate.length).replace(/^[\s:.,;!-]+/, "").trim(); + break; + } + } + return text2; + } + function hasMessages(value) { + return !!value && typeof value === "object" && Array.isArray(value.messages); + } + + // src/assistant/extractLatestActionableText.ts + var ACTIONABLE_ENTITY_PATTERN = /(tab\s*group|group|tabs?|bookmark|folder|window|search|memory)/i; + var ACTIONABLE_VERB_PATTERN = /(delete|remove|create|make|new|add|save|move|put|list|open|close|rename|show|split|find|summarize)/i; + function extractLatestActionableText(messages) { + const latestUserMsg = [...messages].reverse().find((m3) => m3._getType() === "human"); + const latestTextRaw = msgText(latestUserMsg) || ""; + const lines = latestTextRaw.split(/\r?\n/).map((line) => line.trim()).filter(Boolean); + const commandLine = lines.find( + (line) => ACTIONABLE_ENTITY_PATTERN.test(line) && ACTIONABLE_VERB_PATTERN.test(line) + ) || latestTextRaw; + return { + latestTextRaw, + lines, + commandLine, + commandText: commandLine.toLowerCase(), + confirmationText: (lines[lines.length - 1] || latestTextRaw).trim() + }; + } + + // src/assistant/supervisorGates.ts + var CONFIRM_RE = /^(?:yes|confirm|do\s+it|go\s+ahead|approve|ok|okay)$/i; + var CANCEL_RE2 = /^(?:no|cancel|nevermind|don'?t|stop)$/i; + function resolvePendingConfirmationGate(params) { + const { confirmationText, pendingConfirmation, justRanConfirm } = params; + const confirmMatch = CONFIRM_RE.test(confirmationText); + const cancelMatch = CANCEL_RE2.test(confirmationText); + if ((confirmMatch || cancelMatch) && pendingConfirmation && !justRanConfirm) { + return { + kind: "route", + next: "confirm_action", + args: { confirmed: confirmMatch } + }; + } + if (pendingConfirmation) { + return { kind: "end" }; + } + return { kind: "none" }; + } + function resolvePendingAmbiguityGate(params) { + const { pendingAmbiguity, confirmationText, commandText, lastWorker } = params; + if (!pendingAmbiguity) { + return { kind: "none" }; + } + if (lastWorker === "resolve_ambiguity") { + return { kind: "route", next: "chat", args: {} }; + } + const resolution = parseAmbiguityResolution(confirmationText); + if (resolution) { + return { + kind: "route", + next: "resolve_ambiguity", + args: { target: resolution } + }; + } + const wordCount = confirmationText.split(/\s+/).filter(Boolean).length; + if (!looksLikeNewActionCommand(commandText) && wordCount <= 3) { + return { kind: "route", next: "resolve_ambiguity", args: {} }; + } + return { kind: "clear" }; + } + + // src/assistant/commandChain.ts + var CHAIN_VERBS = [ + "open", + "close", + "delete", + "remove", + "create", + "make", + "new", + "add", + "save", + "move", + "put", + "rename", + "list", + "show", + "search", + "find", + "summarize", + "split", + "organize", + "copy" + ]; + var CHAIN_VERB_PATTERN = CHAIN_VERBS.join("|"); + var CHAIN_CONNECTOR_RE = new RegExp( + `(?:\\s*;\\s*|\\s+(?:and\\s+then|then)\\s+(?=(?:please\\s+)?(?:${CHAIN_VERB_PATTERN})\\b)|\\s+and\\s+(?=(?:please\\s+)?(?:${CHAIN_VERB_PATTERN})\\b))`, + "i" + ); + var CHAIN_SPLIT_RE = new RegExp( + `\\s*;\\s*|\\s+(?:and\\s+then|then)\\s+(?=(?:please\\s+)?(?:${CHAIN_VERB_PATTERN})\\b)|\\s+and\\s+(?=(?:please\\s+)?(?:${CHAIN_VERB_PATTERN})\\b)`, + "gi" + ); + function looksLikeCommandChain(input) { + return CHAIN_CONNECTOR_RE.test(String(input || "").trim()); + } + function splitCommandChain(input, maxCommands = 3) { + const text2 = String(input || "").trim(); + if (!text2 || maxCommands < 1) { + return { commands: [], truncated: false }; + } + const parts = text2.split(CHAIN_SPLIT_RE).map((part) => part.trim()).filter(Boolean); + if (parts.length <= maxCommands) { + return { commands: parts, truncated: false }; + } + return { + commands: parts.slice(0, maxCommands), + truncated: true + }; + } + + // src/assistant/supervisorQueue.ts + function buildCommandQueuePlan(params) { + const { + existingQueue, + continuationQueue, + latestTextRaw, + commandLine, + lastWorker, + justRanTool, + maxCommands + } = params; + let commandQueue; + let source; + let truncated = false; + if (existingQueue.length > 0) { + commandQueue = [...existingQueue]; + source = "existing"; + } else if (lastWorker === "confirm_action" && continuationQueue.length > 0) { + commandQueue = [...continuationQueue]; + source = "continuation"; + } else { + const split = splitCommandChain(latestTextRaw || commandLine, maxCommands); + commandQueue = [...split.commands]; + truncated = split.truncated; + source = "parsed"; + } + if (commandQueue.length === 0 && commandLine) { + commandQueue = [commandLine]; + } + if (justRanTool && commandQueue.length > 1) { + commandQueue = commandQueue.slice(1); + } + const activeCommand = commandQueue[0] || commandLine; + if (!activeCommand) { + return null; + } + const truncationNotice = source === "parsed" && truncated ? `I can run up to ${maxCommands} commands per request, so I will run the first ${maxCommands}.` : null; + return { + commandQueue, + activeCommand, + source, + truncated, + truncationNotice + }; + } + function shouldClearContinuationQueue(params) { + const { + hasContinuation, + shouldResumeContinuation, + justRanTool, + commandText + } = params; + if (!hasContinuation || shouldResumeContinuation || justRanTool) { + return false; + } + return looksLikeNewActionCommand(commandText); + } + + // src/services/assistEndpointState.ts + var ASSIST_UNSUPPORTED_RETRY_MS = 6e4; + var endpointStates = /* @__PURE__ */ new Map(); + function normalizeEndpointKey(endpointKey) { + return String(endpointKey || "").trim().toLowerCase(); + } + function readEntry(endpointKey) { + const key = normalizeEndpointKey(endpointKey); + return endpointStates.get(key) || { + capability: "unknown", + unsupportedAt: 0 + }; + } + function writeEntry(endpointKey, entry) { + endpointStates.set(normalizeEndpointKey(endpointKey), entry); + } + function shouldAttemptAssist(endpointKey, now2 = Date.now()) { + const entry = readEntry(endpointKey); + if (entry.capability !== "unsupported") { + return true; + } + return now2 - entry.unsupportedAt >= ASSIST_UNSUPPORTED_RETRY_MS; + } + function markAssistSupported(endpointKey) { + writeEntry(endpointKey, { + capability: "supported", + unsupportedAt: 0 + }); + } + function markAssistUnsupported(endpointKey, now2 = Date.now()) { + writeEntry(endpointKey, { + capability: "unsupported", + unsupportedAt: now2 + }); + } + function getAssistCapability(endpointKey) { + return readEntry(endpointKey).capability; + } + + // src/assistant/plannedActions.ts + var PLAN_PREFIX = "__oasis_plan__:"; + function asRecord(value) { + if (!value || typeof value !== "object" || Array.isArray(value)) { + return null; + } + return value; + } + function normalizeAction(value, memberNameSet) { + const record = asRecord(value); + if (!record) { + return null; + } + const nextRaw = record.next; + const next = typeof nextRaw === "string" ? nextRaw.trim() : String(nextRaw || "").trim(); + if (!next || !memberNameSet.has(next)) { + return null; + } + const argsRecord = asRecord(record.args) || {}; + return { next, args: argsRecord }; + } + function parsePlannedActions(rawArgs, memberNameSet, maxActions) { + const rawActions = Array.isArray(rawArgs.actions) ? rawArgs.actions : []; + const actions = []; + for (const item of rawActions) { + const normalized = normalizeAction(item, memberNameSet); + if (!normalized) { + continue; + } + actions.push(normalized); + if (actions.length >= maxActions) { + break; + } + } + return actions; + } + function encodePlannedAction(action) { + return `${PLAN_PREFIX}${JSON.stringify(action)}`; + } + function decodePlannedAction(value) { + const text2 = String(value || "").trim(); + if (!text2.startsWith(PLAN_PREFIX)) { + return null; + } + try { + const parsed = JSON.parse(text2.slice(PLAN_PREFIX.length)); + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { + return null; + } + const next = String(parsed.next || "").trim(); + if (!next) { + return null; + } + const args = asRecord(parsed.args) || {}; + return { next, args }; + } catch { + return null; + } + } + + // src/assistant/supervisorAssist.ts + var PLAN_TOOL_NAME = "route_action_plan"; + var LIST_FAMILY_TOOLS = /* @__PURE__ */ new Set([ + "list_tabs", + "list_bookmark_folders", + "list_tab_groups" + ]); + var SEARCH_FAMILY_TOOLS = /* @__PURE__ */ new Set([ + "search_memory", + "search_history", + "get_recent_search_results", + "open_search_result" + ]); + var SEARCH_WEB_TOOL = "web_search"; + var MUTATION_FAMILY_TOOLS = /* @__PURE__ */ new Set([ + "add_tab_to_bookmark_folder", + "add_tab_to_group", + "remove_tab_from_bookmark_folder", + "remove_tab_from_group", + "create_bookmark_folder", + "delete_bookmark_folder", + "rename_bookmark_folder", + "open_bookmark_folder", + "create_tab_group", + "delete_tab_group", + "rename_tab_group", + "close_tab", + "move_tab_to_new_window", + "split_tabs", + "add_split_view", + "remove_split_view", + "confirm_action", + "resolve_ambiguity", + "new_window", + "organize_windows" + ]); + var SEARCH_WEB_HINT_RE = /\b(?:google|web|internet|online|bing|duckduckgo|search\s+the\s+web)\b/i; + var SEARCH_LOCAL_HINT_RE = /\b(?:bookmark|folder|hub|tab|tabs|group|groups|history|memory|saved|visited|recent\s+results?)\b/i; + var SEARCH_HISTORY_HINT_RE = /\b(?:visited|browsed|looked\s+at|read|viewed|pages?\s+i\s+(?:visited|read|browsed|looked\s+at|viewed)|articles?\s+i\s+(?:read|browsed|viewed)|sites?\s+i\s+(?:visited|browsed)|what\s+(?:was|did\s+i)|pull\s+that|get\s+that)\b/i; + var SEARCH_BOOKMARKS_HINT_RE = /\b(?:bookmark|bookmarks|folder|saved|bookmarked|in\s+(?:my\s+)?(?:bookmark\s+)?folder|what'?s\s+in)\b/i; + function constrainAssistRoutingForFamily(params) { + const { activeCommandText, assistOptions, assistTools } = params; + const family = classifyCommandFamily(activeCommandText); + const chainLike = looksLikeCommandChain(activeCommandText); + const allowPlanTool = chainLike; + const toResult = (options) => { + const deduped = []; + const seen = /* @__PURE__ */ new Set(); + for (const option of options) { + const name = String(option || "").trim(); + if (!name || seen.has(name)) { + continue; + } + seen.add(name); + deduped.push(name); + } + if (!seen.has("chat")) { + deduped.push("chat"); + seen.add("chat"); + } + const allowedSet = new Set(deduped.filter((option) => option !== "chat")); + const tools = assistTools.filter((tool) => allowedSet.has(tool.name)); + return { + family, + constrained: true, + options: deduped, + tools, + allowPlanTool + }; + }; + if (chainLike || family === "other") { + return { + family, + constrained: false, + options: [...assistOptions], + tools: [...assistTools], + allowPlanTool + }; + } + if (family === "list") { + return toResult( + assistOptions.filter( + (option) => option === "chat" || LIST_FAMILY_TOOLS.has(option) + ) + ); + } + if (family === "search") { + const hasWebHint = SEARCH_WEB_HINT_RE.test(activeCommandText); + const hasLocalHint = SEARCH_LOCAL_HINT_RE.test(activeCommandText); + const hasHistoryHint = SEARCH_HISTORY_HINT_RE.test(activeCommandText); + const hasBookmarksHint = SEARCH_BOOKMARKS_HINT_RE.test(activeCommandText); + const allowedTools = /* @__PURE__ */ new Set(); + if (hasHistoryHint && !hasBookmarksHint) { + allowedTools.add("search_history"); + allowedTools.add("get_recent_search_results"); + allowedTools.add("open_search_result"); + } else if (hasBookmarksHint && !hasHistoryHint) { + allowedTools.add("search_memory"); + allowedTools.add("get_recent_search_results"); + allowedTools.add("open_search_result"); + } else { + SEARCH_FAMILY_TOOLS.forEach((tool) => allowedTools.add(tool)); + } + if (hasWebHint || !hasLocalHint) { + allowedTools.add(SEARCH_WEB_TOOL); + } + return toResult( + assistOptions.filter( + (option) => option === "chat" || allowedTools.has(option) + ) + ); + } + if (family === "mutation") { + return toResult( + assistOptions.filter( + (option) => option === "chat" || MUTATION_FAMILY_TOOLS.has(option) + ) + ); + } + return { + family: "other", + constrained: false, + options: [...assistOptions], + tools: [...assistTools], + allowPlanTool + }; + } + function syncSubscriptionFromAssistRouterResponse(assist) { + const raw = assist; + if (isRecord(raw.usage_stats)) { + subscriptionService.updateFromAssistUsageStats( + raw.usage_stats + ); + return; + } + const tokens = extractTokenCountsFromAssistPayload(assist); + const hasTokens = tokens.input_tokens != null && tokens.input_tokens > 0 || tokens.output_tokens != null && tokens.output_tokens > 0; + if (!hasTokens) { + return; + } + subscriptionService.recordAssistRoutingTokens({ + command_type: "system", + user_intent: "other", + input_tokens: tokens.input_tokens, + output_tokens: tokens.output_tokens + }); + } + async function tryResolveAssistRoute(params) { + const { + endpointKey, + activeCommandText, + commandQueueLength, + messages, + assistRouterPrompt, + assistOptions, + assistTools, + memberNameSet, + maxPlanActions, + railroadMemoryBlock = "" + } = params; + const shouldTryAssistRouting = commandQueueLength <= 1 && looksLikeNewActionCommand(activeCommandText); + if (!shouldTryAssistRouting) { + return { kind: "none" }; + } + const constrained = constrainAssistRoutingForFamily({ + activeCommandText, + assistOptions, + assistTools + }); + const effectiveOptions = constrained.options; + const effectiveTools = constrained.tools; + const effectiveOptionSet = new Set(effectiveOptions); + const allowPlanTool = constrained.allowPlanTool; + const capability = getAssistCapability(endpointKey); + if (!shouldAttemptAssist(endpointKey)) { + if (capability === "unsupported") { + assistantLogger.debug( + "router", + "Assist endpoint currently cooling down." + ); + } + return { kind: "none" }; + } + try { + const assistMessages = toWire(messages.slice(-10)); + const optionsForAssist = allowPlanTool ? [...effectiveOptions, PLAN_TOOL_NAME] : effectiveOptions; + const toolsForAssist = allowPlanTool ? [ + ...effectiveTools, + { + name: PLAN_TOOL_NAME, + description: `Plan up to ${maxPlanActions} commands for chained requests. Args JSON: {"actions":[{"next":"","args":{...}}]}` + } + ] : effectiveTools; + const assistLoop = getAssistLoopOptionsFromBuildEnv(); + const routerSystem = assistRouterPrompt + (typeof railroadMemoryBlock === "string" ? railroadMemoryBlock : ""); + const assist = await assistRemote( + routerSystem, + assistMessages, + optionsForAssist, + toolsForAssist, + void 0, + assistLoop + ); + const innerRounds = typeof assist?.inner_rounds === "number" ? assist.inner_rounds : void 0; + if (innerRounds != null && innerRounds > 1) { + assistantLogger.debug("router", "Assist inner rounds", { innerRounds }); + } + if (assist?.quota) { + subscriptionService.updateFromQuota(assist.quota); + } + syncSubscriptionFromAssistRouterResponse(assist); + markAssistSupported(endpointKey); + const assistNext = typeof assist?.next === "string" ? assist.next.trim() : ""; + const assistArgs = isRecord(assist?.args) ? assist.args : {}; + if (allowPlanTool && assistNext === PLAN_TOOL_NAME) { + const actions = parsePlannedActions( + assistArgs, + memberNameSet, + maxPlanActions + ); + if (actions.length > 0) { + assistantLogger.debug("router", "Assist returned action plan", { + count: actions.length + }); + return { kind: "plan", actions }; + } + return { kind: "none" }; + } + if (assistNext && assistNext !== "chat" && !effectiveOptionSet.has(assistNext)) { + assistantLogger.debug( + "router", + "Assist route rejected by family policy", + { + assistNext, + family: constrained.family, + constrained: constrained.constrained + } + ); + return { kind: "none" }; + } + if (assistNext && assistNext !== "chat" && memberNameSet.has(assistNext)) { + assistantLogger.debug("router", `Assist route selected: ${assistNext}`); + return { kind: "tool", next: assistNext, args: assistArgs }; + } + if (assistNext === "chat") { + const content = typeof assist?.content === "string" ? assist.content.trim() : ""; + if (content) { + return { kind: "chat", content }; + } + } + return { kind: "none" }; + } catch (error) { + if (error instanceof QuotaExceededError || error.isQuotaError) { + if (error.quota) { + subscriptionService.updateFromQuota(error.quota); + } + return { + kind: "chat", + content: formatQuotaExceededMessage(error.message) + }; + } + const message = String(error || ""); + const assistUnsupported = /\b404\b|not found|post with\s*\{op:\s*"?assist"?\}/i.test(message); + if (assistUnsupported) { + markAssistUnsupported(endpointKey); + assistantLogger.warn( + "router", + "Assist endpoint unavailable, using fallback." + ); + } else { + assistantLogger.warn( + "router", + "Assist route failed, using fallback.", + error + ); + } + return { kind: "none" }; + } + } + + // src/assistant/toolResultPresenter.ts + function safeParseJson(value) { + try { + return JSON.parse(value); + } catch { + return null; + } + } + function toStringList(value) { + if (!Array.isArray(value)) { + return []; + } + return value.map((item) => typeof item === "string" ? item.trim() : "").filter(Boolean); + } + function toObjectList(value) { + if (!Array.isArray(value)) { + return []; + } + return value.filter( + (item) => !!item && typeof item === "object" && !Array.isArray(item) + ); + } + function formatLines(title, lines) { + if (lines.length === 0) { + return title; + } + return `${title} + +${lines.map((line) => `- ${line}`).join("\n")}`; + } + function formatListBookmarkFolders(message) { + const parsed = safeParseJson(message); + const rows = toStringList(parsed); + if (rows.length === 0) { + return message; + } + return formatLines("Here are your bookmark folders:", rows); + } + function formatListTabGroups(message) { + const parsed = safeParseJson(message); + const rows = toObjectList(parsed); + if (rows.length === 0) { + return message; + } + const lines = rows.map((row) => { + const name = typeof row.name === "string" ? row.name : "(unnamed)"; + const tabCount = typeof row.tabCount === "number" && Number.isFinite(row.tabCount) ? row.tabCount : 0; + const collapsed = row.collapsed === true ? "collapsed" : "expanded"; + return `${name} (${tabCount} tabs, ${collapsed})`; + }); + return formatLines("Here are your tab groups:", lines); + } + function extractJsonArrayTail(message) { + const colon = message.indexOf(":"); + if (colon < 0) { + return null; + } + const tail = message.slice(colon + 1).trim(); + if (!tail.startsWith("[")) { + return null; + } + return safeParseJson(tail); + } + function formatListTabs(message) { + const parsedTop = safeParseJson(message); + const strings = toStringList(parsedTop); + if (strings.length > 0) { + return formatLines("Here are your open tabs:", strings); + } + const tail = extractJsonArrayTail(message); + const rows = toObjectList(tail); + if (rows.length === 0) { + return message; + } + const containerMatch = message.match(/^Tabs in ([^:]+):/i); + const container = containerMatch?.[1]?.trim() || "the requested target"; + const lines = rows.map((row) => { + const title = typeof row.title === "string" ? row.title : "(untitled)"; + const url = typeof row.url === "string" ? row.url : ""; + return url ? `${title} (${url})` : title; + }); + return formatLines(`Here are the tabs in ${container}:`, lines); + } + function formatSearchResults(message) { + const parsed = safeParseJson(message); + if (!parsed || typeof parsed !== "object") { + return message; + } + const summary = typeof parsed.summary === "string" ? parsed.summary.trim() : "Search results:"; + const rows = toObjectList(parsed.results).slice(0, 10); + if (rows.length === 0) { + return summary || message; + } + const lines = rows.map((row) => { + const index2 = typeof row.index === "number" && Number.isFinite(row.index) ? row.index : void 0; + const title = typeof row.title === "string" ? row.title : "(untitled)"; + const url = typeof row.url === "string" ? row.url : ""; + const prefix = index2 != null ? `${index2}. ` : ""; + return url ? `${prefix}${title} (${url})` : `${prefix}${title}`; + }); + return formatLines(summary, lines); + } + function formatHistorySearchResults(message) { + const parsed = safeParseJson(message); + const rows = toObjectList(parsed); + if (rows.length === 0) { + return message; + } + const lines = rows.map((row) => { + const idx = typeof row.index === "number" ? `${row.index}. ` : ""; + const title = typeof row.title === "string" ? row.title : "(untitled)"; + const url = typeof row.url === "string" ? row.url : ""; + const relevance = typeof row.relevance === "string" ? ` (${row.relevance} match)` : ""; + const visited = typeof row.visited === "string" ? ` \u2014 visited ${row.visited}` : ""; + return url ? `${idx}[**${title}**](${url})${relevance}${visited}` : `${idx}**${title}**${relevance}${visited}`; + }); + return `Here's what I found in your browsing history: + +${lines.join("\n\n")}`; + } + function presentToolResult(payload) { + const message = String(payload.message || "").trim(); + if (!message) { + return "Done."; + } + switch (payload.commandName) { + case "list_bookmark_folders": + return formatListBookmarkFolders(message); + case "list_tab_groups": + return formatListTabGroups(message); + case "list_tabs": + return formatListTabs(message); + case "search_memory": + case "get_recent_search_results": + return formatSearchResults(message); + case "search_history": + return formatHistorySearchResults(message); + default: + return message; + } + } + + // src/assistant/graph.ts + var CHAT_GENERATION_CONFIG = { + responseMimeType: "application/json", + responseJsonSchema: { + type: "object", + properties: { + response: { + type: "string", + description: "The assistant's complete reply to the user. Use Markdown formatting: **bold**, bullet lists, `code blocks`, headings. Do NOT include raw JSON or internal data dumps." + }, + command_type: { + type: "string", + enum: [ + "info_retrieval", + "navigation", + "organization", + "content_transform", + "content_create", + "search", + "automation", + "system", + "help", + "other" + ], + description: "The action category: info_retrieval=answer a factual question, navigation=open/visit a URL or site, organization=manage tabs/bookmarks/groups, content_transform=summarize/translate/rewrite, content_create=write/generate new content, search=find in history/memory/web, automation=multi-step browser task, system=browser settings or preferences, help=how-to question about the assistant, other=none of the above." + }, + user_intent: { + type: "string", + enum: [ + "learning", + "research", + "work", + "dev", + "marketing", + "shopping", + "personal", + "entertainment", + "meta", + "other" + ], + description: "The user's underlying goal: learning=understand a topic, research=gather info for a decision, work=professional/business task, dev=coding or technical task, marketing=content or growth, shopping=buy or find products, personal=personal life task, entertainment=leisure/media/fun, meta=asking about the AI itself, other=none of the above." + } + }, + required: ["response", "command_type", "user_intent"] + } + }; + function buildAssistantGraph(commands2, assistantWindow2, messageId, assistToolDefs = [], options) { + const railroadMemoryBlock = String(options?.railroadMemoryBlock || ""); + const toolAgents = {}; + const memberNames = []; + for (const command of commands2) { + toolAgents[command.commandName] = createCommandToolAgent(command, { + assistantWindow: assistantWindow2, + messageId + }); + memberNames.push(command.commandName); + } + const memberNameSet = new Set(memberNames); + const assistTools = assistToolDefs.length > 0 ? assistToolDefs : commands2.map((command) => ({ + name: command.commandName, + description: command.description + })); + const assistOptions = [...memberNames, "chat"]; + const assistRouterPrompt = buildAssistRouterPrompt(memberNames); + const endpointKey = getAssistantApiBase(); + const chatNode = async (state) => { + const routerMessage = state.args?.routerMessage; + if (typeof routerMessage === "string" && routerMessage.trim()) { + return { + messages: [new AIMessage(routerMessage.trim())], + lastWorker: "chat", + commandQueue: [] + }; + } + const lastMsg = state.messages[state.messages.length - 1]; + const lastMsgText = msgText(lastMsg); + const toolPayload = getToolResultPayload(lastMsg); + const hasToolOutput = Boolean(toolPayload); + const hasSummarizeRequest = lastMsgText.includes("__SUMMARIZE_REQUEST__"); + if (toolPayload && !hasSummarizeRequest) { + return { + messages: [ + new AIMessage({ + content: presentToolResult(toolPayload), + additional_kwargs: { + oasisUsageMeta: classifyToolAction(toolPayload.commandName) + } + }) + ], + lastWorker: "chat", + commandQueue: [] + }; + } + const capabilitiesReply = getOasisCapabilitiesReply(lastMsgText); + if (capabilitiesReply) { + return { + messages: [new AIMessage(capabilitiesReply)], + lastWorker: "chat", + commandQueue: [] + }; + } + const hiddenInstruction = buildHiddenInstruction({ + hasSummarizeRequest, + hasToolOutput + }); + const messagesWithPrompt = [ + ...state.messages, + new HumanMessage(hiddenInstruction) + ]; + let res; + try { + res = await assistRemote( + CHAT_SYSTEM_PROMPT + railroadMemoryBlock, + toWire(messagesWithPrompt), + ["chat"], + [], + CHAT_GENERATION_CONFIG + ); + if (res?.quota) { + subscriptionService.updateFromQuota(res.quota); + } + } catch (error) { + assistantLogger.warn("chat", "Assist chat call failed.", error); + if (error instanceof QuotaExceededError || error.isQuotaError) { + if (error.quota) { + subscriptionService.updateFromQuota(error.quota); + } + return { + messages: [ + new AIMessage(formatQuotaExceededMessage(error.message)) + ], + lastWorker: "chat", + commandQueue: [] + }; + } + if (hasToolOutput) { + const fallback = String(msgText(lastMsg) || "").trim(); + return { + messages: [new AIMessage(fallback || "Done.")], + lastWorker: "chat", + commandQueue: [] + }; + } + return { + messages: [ + new AIMessage( + "I'm having trouble reaching the assistant service right now. Please try again." + ) + ], + lastWorker: "chat", + commandQueue: [] + }; + } + const { text: chatText, meta: usageMeta } = parseChatEnvelope(res); + const trimmedText = chatText.trim(); + if (!trimmedText) { + if (hasToolOutput) { + const fallback = String(msgText(lastMsg) || "").trim(); + return { + messages: [new AIMessage(fallback || "Done.")], + lastWorker: "chat", + commandQueue: [] + }; + } + return { + messages: [ + new AIMessage("I couldn't generate a response. Please try again.") + ], + lastWorker: "chat", + commandQueue: [] + }; + } + return { + messages: [ + new AIMessage({ + content: trimmedText, + additional_kwargs: { oasisUsageMeta: usageMeta } + }) + ], + lastWorker: "chat", + commandQueue: [] + }; + }; + const supervisorNode = async (state) => { + const { latestTextRaw, commandLine, commandText, confirmationText } = extractLatestActionableText(state.messages); + const justRanTool = memberNameSet.has(state.lastWorker); + const justRanConfirm = state.lastWorker === "confirm_action"; + const pendingConfirmation = getPendingConfirmation(); + const confirmationGate = resolvePendingConfirmationGate({ + confirmationText, + pendingConfirmation, + justRanConfirm + }); + if (confirmationGate.kind === "route") { + return { next: confirmationGate.next, args: confirmationGate.args }; + } + if (confirmationGate.kind === "end") { + return { next: AGENT_END, args: {} }; + } + const pendingAmbiguity = getPendingAmbiguity(); + const ambiguityGate = resolvePendingAmbiguityGate({ + pendingAmbiguity, + confirmationText, + commandText, + lastWorker: state.lastWorker + }); + if (ambiguityGate.kind === "route") { + return { next: ambiguityGate.next, args: ambiguityGate.args }; + } + if (ambiguityGate.kind === "clear") { + clearPendingAmbiguity(); + } + const pendingContinuationQueue = getContinuationQueue(); + const shouldResumeContinuation = state.lastWorker === "confirm_action" && pendingContinuationQueue.length > 0 && !getPendingConfirmation(); + if (shouldClearContinuationQueue({ + hasContinuation: pendingContinuationQueue.length > 0, + shouldResumeContinuation, + justRanTool, + commandText + })) { + clearContinuationQueue(); + } + if (justRanTool) { + if (state.commandQueue.length <= 1 && !shouldResumeContinuation) { + return { next: "chat", args: {}, commandQueue: [] }; + } + } + const continuationQueue = shouldResumeContinuation ? takeContinuationQueue() : []; + const hasQueuedCommands = state.commandQueue.length > 0 || continuationQueue.length > 0; + const topLevelActionText = commandLine.toLowerCase(); + const topLevelActionLike = looksLikeNewActionCommand(topLevelActionText); + if (!hasQueuedCommands && commandLine) { + const topLevelAssist = await tryResolveAssistRoute({ + endpointKey, + activeCommandText: topLevelActionText, + commandQueueLength: 1, + messages: state.messages, + assistRouterPrompt, + assistOptions, + assistTools, + memberNameSet, + maxPlanActions: MAX_NESTED_COMMANDS, + railroadMemoryBlock + }); + if (topLevelAssist.kind === "plan") { + const encodedQueue = topLevelAssist.actions.map( + (action) => encodePlannedAction(action) + ); + const first = topLevelAssist.actions[0]; + if (!first) { + return { next: "chat", args: {}, commandQueue: [] }; + } + return { + next: first.next, + args: first.args, + commandQueue: encodedQueue + }; + } + if (topLevelAssist.kind === "tool") { + const guardRoute = routeDeterministically(commandLine); + if (guardRoute.type === "tool" && guardRoute.next === "resolve_ambiguity" && guardRoute.pendingAmbiguity) { + setRoutePendingAmbiguity(guardRoute.pendingAmbiguity); + return { + next: guardRoute.next, + args: guardRoute.args, + commandQueue: [commandLine] + }; + } + return { + next: topLevelAssist.next, + args: topLevelAssist.args, + commandQueue: [commandLine] + }; + } + if (topLevelAssist.kind === "chat" && !topLevelActionLike) { + return { + next: "chat", + args: { routerMessage: topLevelAssist.content }, + commandQueue: [] + }; + } + } + const queuePlan = buildCommandQueuePlan({ + existingQueue: state.commandQueue, + continuationQueue, + latestTextRaw, + commandLine, + lastWorker: state.lastWorker, + justRanTool: justRanTool && state.commandQueue.length > 0, + maxCommands: MAX_NESTED_COMMANDS + }); + if (!queuePlan) { + return { next: "chat", args: {}, commandQueue: [] }; + } + const { commandQueue, activeCommand, truncationNotice } = queuePlan; + const applyNoticeToArgs = (args) => truncationNotice ? { ...args, [INTERNAL_CHAIN_NOTICE_ARG]: truncationNotice } : args; + const applyNoticeToMessage = (message) => truncationNotice ? `${truncationNotice} +${message}` : message; + const plannedAction = decodePlannedAction(activeCommand); + if (plannedAction) { + return { + next: plannedAction.next, + args: applyNoticeToArgs(plannedAction.args), + commandQueue + }; + } + const activeCommandText = activeCommand.toLowerCase(); + const actionLikeCommand = looksLikeNewActionCommand(activeCommandText); + const assistRoute = await tryResolveAssistRoute({ + endpointKey, + activeCommandText, + commandQueueLength: commandQueue.length, + messages: state.messages, + assistRouterPrompt, + assistOptions, + assistTools, + memberNameSet, + maxPlanActions: MAX_NESTED_COMMANDS, + railroadMemoryBlock + }); + if (assistRoute.kind === "plan") { + const encodedQueue = assistRoute.actions.map( + (action) => encodePlannedAction(action) + ); + const first = assistRoute.actions[0]; + if (first) { + return { + next: first.next, + args: applyNoticeToArgs(first.args), + commandQueue: encodedQueue + }; + } + } + const route = routeDeterministically(activeCommand); + if (assistRoute.kind === "tool") { + if (route.type === "tool" && route.next === "resolve_ambiguity" && route.pendingAmbiguity) { + setRoutePendingAmbiguity(route.pendingAmbiguity); + return { + next: route.next, + args: applyNoticeToArgs(route.args), + commandQueue + }; + } + return { + next: assistRoute.next, + args: applyNoticeToArgs(assistRoute.args), + commandQueue + }; + } + if (assistRoute.kind === "chat") { + if (actionLikeCommand) { + assistantLogger.debug( + "router", + "Ignoring assist chat response for action-like command" + ); + } else { + return { + next: "chat", + args: { routerMessage: applyNoticeToMessage(assistRoute.content) }, + commandQueue: [] + }; + } + } + if (route.type === "tool") { + if (route.pendingAmbiguity) { + setRoutePendingAmbiguity(route.pendingAmbiguity); + } + return { + next: route.next, + args: applyNoticeToArgs(route.args), + commandQueue + }; + } + if (route.type === "chat") { + return { + next: "chat", + args: { routerMessage: applyNoticeToMessage(route.message) }, + commandQueue: [] + }; + } + return { + next: "chat", + args: truncationNotice ? { routerMessage: truncationNotice } : {}, + commandQueue: [] + }; + }; + return { + stream(input, options2) { + const maxSteps = options2?.recursionLimit ?? ASSISTANT_RECURSION_LIMIT; + return streamAgentLoop({ + initialMessages: input.messages, + maxSteps, + supervisorNode, + chatNode, + toolAgents, + memberNames + }); + } + }; + } + + // src/shims/fs-promises-stub.mjs + async function unavailable() { + throw new Error("FileStorage is not available in the Oasis browser bundle"); + } + var readFile = unavailable; + var writeFile = unavailable; + var mkdir = unavailable; + var unlink = unavailable; + var access = unavailable; + var readdir = unavailable; + + // src/shims/path-stub.mjs + function join(...parts) { + return parts.filter(Boolean).join("/").replace(/\/+/g, "/"); + } + + // node_modules/yaml/browser/dist/index.js + var dist_exports = {}; + __export(dist_exports, { + Alias: () => Alias, + CST: () => cst_exports, + Composer: () => Composer, + Document: () => Document, + Lexer: () => Lexer, + LineCounter: () => LineCounter, + Pair: () => Pair, + Parser: () => Parser, + Scalar: () => Scalar, + Schema: () => Schema2, + YAMLError: () => YAMLError, + YAMLMap: () => YAMLMap, + YAMLParseError: () => YAMLParseError, + YAMLSeq: () => YAMLSeq, + YAMLWarning: () => YAMLWarning, + isAlias: () => isAlias, + isCollection: () => isCollection, + isDocument: () => isDocument, + isMap: () => isMap, + isNode: () => isNode3, + isPair: () => isPair, + isScalar: () => isScalar, + isSeq: () => isSeq, + parse: () => parse2, + parseAllDocuments: () => parseAllDocuments, + parseDocument: () => parseDocument, + stringify: () => stringify3, + visit: () => visit, + visitAsync: () => visitAsync + }); + + // node_modules/yaml/browser/dist/nodes/identity.js + var ALIAS = Symbol.for("yaml.alias"); + var DOC = Symbol.for("yaml.document"); + var MAP = Symbol.for("yaml.map"); + var PAIR = Symbol.for("yaml.pair"); + var SCALAR = Symbol.for("yaml.scalar"); + var SEQ = Symbol.for("yaml.seq"); + var NODE_TYPE2 = Symbol.for("yaml.node.type"); + var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE2] === ALIAS; + var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE2] === DOC; + var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE2] === MAP; + var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE2] === PAIR; + var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE2] === SCALAR; + var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE2] === SEQ; + function isCollection(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE2]) { + case MAP: + case SEQ: + return true; + } + return false; + } + function isNode3(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE2]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: + return true; + } + return false; + } + var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + + // node_modules/yaml/browser/dist/visit.js + var BREAK = Symbol("break visit"); + var SKIP = Symbol("skip children"); + var REMOVE = Symbol("remove node"); + function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + visit_(null, node, visitor_, Object.freeze([])); + } + visit.BREAK = BREAK; + visit.SKIP = SKIP; + visit.REMOVE = REMOVE; + function visit_(key, node, visitor, path) { + const ctrl = callVisitor(key, node, visitor, path); + if (isNode3(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visit_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i2 = 0; i2 < node.items.length; ++i2) { + const ci = visit_(i2, node.items[i2], visitor, path); + if (typeof ci === "number") + i2 = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i2, 1); + i2 -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = visit_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = visit_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; + } + async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + await visitAsync_(null, node, visitor_, Object.freeze([])); + } + visitAsync.BREAK = BREAK; + visitAsync.SKIP = SKIP; + visitAsync.REMOVE = REMOVE; + async function visitAsync_(key, node, visitor, path) { + const ctrl = await callVisitor(key, node, visitor, path); + if (isNode3(ctrl) || isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visitAsync_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i2 = 0; i2 < node.items.length; ++i2) { + const ci = await visitAsync_(i2, node.items[i2], visitor, path); + if (typeof ci === "number") + i2 = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i2, 1); + i2 -= 1; + } + } + } else if (isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; + } + function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; + } + function callVisitor(key, node, visitor, path) { + if (typeof visitor === "function") + return visitor(key, node, path); + if (isMap(node)) + return visitor.Map?.(key, node, path); + if (isSeq(node)) + return visitor.Seq?.(key, node, path); + if (isPair(node)) + return visitor.Pair?.(key, node, path); + if (isScalar(node)) + return visitor.Scalar?.(key, node, path); + if (isAlias(node)) + return visitor.Alias?.(key, node, path); + return void 0; + } + function replaceNode(key, path, node) { + const parent = path[path.length - 1]; + if (isCollection(parent)) { + parent.items[key] = node; + } else if (isPair(parent)) { + if (key === "key") + parent.key = node; + else + parent.value = node; + } else if (isDocument(parent)) { + parent.contents = node; + } else { + const pt = isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } + } + + // node_modules/yaml/browser/dist/doc/directives.js + var escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" + }; + var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); + var Directives = class _Directives { + constructor(yaml, tags) { + this.docStart = null; + this.docEnd = false; + this.yaml = Object.assign({}, _Directives.defaultYaml, yaml); + this.tags = Object.assign({}, _Directives.defaultTags, tags); + } + clone() { + const copy = new _Directives(this.yaml, this.tags); + copy.docStart = this.docStart; + return copy; + } + /** + * During parsing, get a Directives instance for the current document and + * update the stream state according to the current version's spec. + */ + atDocument() { + const res = new _Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: _Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, _Directives.defaultTags); + break; + } + return res; + } + /** + * @param onError - May be called even if the action was successful + * @returns `true` on success + */ + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" }; + this.tags = Object.assign({}, _Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version] = parts; + if (version === "1.1" || version === "1.2") { + this.yaml.version = version; + return true; + } else { + const isValid = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + /** + * Resolves a tag, matching handles to those defined in %TAG directives. + * + * @returns Resolved tag, which may also be the non-specific tag `'!'` or a + * `'!local'` tag, or `null` if unresolvable. + */ + tagName(source, onError) { + if (source === "!") + return "!"; + if (source[0] !== "!") { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") + onError("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } catch (error) { + onError(String(error)); + return null; + } + } + if (handle === "!") + return source; + onError(`Could not resolve tag: ${source}`); + return null; + } + /** + * Given a fully resolved tag, returns its printable string form, + * taking into account current tag prefixes and defaults. + */ + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc) { + const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && isNode3(doc.contents)) { + const tags = {}; + visit(doc.contents, (_key, node) => { + if (isNode3(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") + continue; + if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) + lines.push(`%TAG ${handle} ${prefix}`); + } + return lines.join("\n"); + } + }; + Directives.defaultYaml = { explicit: false, version: "1.2" }; + Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; + + // node_modules/yaml/browser/dist/doc/anchors.js + function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; + } + function anchorNames(root) { + const anchors = /* @__PURE__ */ new Set(); + visit(root, { + Value(_key, node) { + if (node.anchor) + anchors.add(node.anchor); + } + }); + return anchors; + } + function findNewAnchor(prefix, exclude) { + for (let i2 = 1; true; ++i2) { + const name = `${prefix}${i2}`; + if (!exclude.has(name)) + return name; + } + } + function createNodeAnchors(doc, prefix) { + const aliasObjects = []; + const sourceObjects = /* @__PURE__ */ new Map(); + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + prevAnchors ?? (prevAnchors = anchorNames(doc)); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + /** + * With circular references, the source node is only resolved after all + * of its child nodes are. This is why anchors are set only after all of + * the nodes have been created. + */ + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === "object" && ref.anchor && (isScalar(ref.node) || isCollection(ref.node))) { + ref.node.anchor = ref.anchor; + } else { + const error = new Error("Failed to resolve repeated object (this should not happen)"); + error.source = source; + throw error; + } + } + }, + sourceObjects + }; + } + + // node_modules/yaml/browser/dist/doc/applyReviver.js + function applyReviver(reviver, obj, key, val) { + if (val && typeof val === "object") { + if (Array.isArray(val)) { + for (let i2 = 0, len = val.length; i2 < len; ++i2) { + const v0 = val[i2]; + const v1 = applyReviver(reviver, val, String(i2), v0); + if (v1 === void 0) + delete val[i2]; + else if (v1 !== v0) + val[i2] = v1; + } + } else if (val instanceof Map) { + for (const k3 of Array.from(val.keys())) { + const v0 = val.get(k3); + const v1 = applyReviver(reviver, val, k3, v0); + if (v1 === void 0) + val.delete(k3); + else if (v1 !== v0) + val.set(k3, v1); + } + } else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === void 0) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } else { + for (const [k3, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k3, v0); + if (v1 === void 0) + delete val[k3]; + else if (v1 !== v0) + val[k3] = v1; + } + } + } + return reviver.call(obj, key, val); + } + + // node_modules/yaml/browser/dist/nodes/toJS.js + function toJS(value, arg, ctx) { + if (Array.isArray(value)) + return value.map((v6, i2) => toJS(v6, String(i2), ctx)); + if (value && typeof value.toJSON === "function") { + if (!ctx || !hasAnchor(value)) + return value.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: void 0 }; + ctx.anchors.set(value, data); + ctx.onCreate = (res2) => { + data.res = res2; + delete ctx.onCreate; + }; + const res = value.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value === "bigint" && !ctx?.keep) + return Number(value); + return value; + } + + // node_modules/yaml/browser/dist/nodes/Node.js + var NodeBase = class { + constructor(type) { + Object.defineProperty(this, NODE_TYPE2, { value: type }); + } + /** Create a copy of this node. */ + clone() { + const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy.range = this.range.slice(); + return copy; + } + /** A plain JavaScript representation of this node. */ + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!isDocument(doc)) + throw new TypeError("A document argument is required"); + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this, "", ctx); + if (typeof onAnchor === "function") + for (const { count: count3, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count3); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } + }; + + // node_modules/yaml/browser/dist/nodes/Alias.js + var Alias = class extends NodeBase { + constructor(source) { + super(ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { + set() { + throw new Error("Alias nodes cannot have tags"); + } + }); + } + /** + * Resolve the value of this alias within `doc`, finding the last + * instance of the `source` anchor before this node. + */ + resolve(doc, ctx) { + if (ctx?.maxAliasCount === 0) + throw new ReferenceError("Alias resolution is disabled"); + let nodes; + if (ctx?.aliasResolveCache) { + nodes = ctx.aliasResolveCache; + } else { + nodes = []; + visit(doc, { + Node: (_key, node) => { + if (isAlias(node) || hasAnchor(node)) + nodes.push(node); + } + }); + if (ctx) + ctx.aliasResolveCache = nodes; + } + let found = void 0; + for (const node of nodes) { + if (node === this) + break; + if (node.anchor === this.source) + found = node; + } + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const { anchors, doc, maxAliasCount } = ctx; + const source = this.resolve(doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + let data = anchors.get(source); + if (!data) { + toJS(source, null, ctx); + data = anchors.get(source); + } + if (data?.res === void 0) { + const msg = "This should not happen: Alias anchor was not resolved?"; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc, source, anchors); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + throw new ReferenceError(msg); + } + } + return data.res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; + } + }; + function getAliasCount(doc, node, anchors) { + if (isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors && source && anchors.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (isCollection(node)) { + let count3 = 0; + for (const item of node.items) { + const c3 = getAliasCount(doc, item, anchors); + if (c3 > count3) + count3 = c3; + } + return count3; + } else if (isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors); + const vc = getAliasCount(doc, node.value, anchors); + return Math.max(kc, vc); + } + return 1; + } + + // node_modules/yaml/browser/dist/nodes/Scalar.js + var isScalarValue = (value) => !value || typeof value !== "function" && typeof value !== "object"; + var Scalar = class extends NodeBase { + constructor(value) { + super(SCALAR); + this.value = value; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } + }; + Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; + Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; + Scalar.PLAIN = "PLAIN"; + Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; + Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; + + // node_modules/yaml/browser/dist/doc/createNode.js + var defaultTagPrefix = "tag:yaml.org,2002:"; + function findTagObject(value, tagName, tags) { + if (tagName) { + const match = tags.filter((t2) => t2.tag === tagName); + const tagObj = match.find((t2) => !t2.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find((t2) => t2.identify?.(value) && !t2.format); + } + function createNode(value, tagName, ctx) { + if (isDocument(value)) + value = value.contents; + if (isNode3(value)) + return value; + if (isPair(value)) { + const map2 = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx); + map2.items.push(value); + return map2; + } + if (value instanceof String || value instanceof Number || value instanceof Boolean || typeof BigInt !== "undefined" && value instanceof BigInt) { + value = value.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema4, sourceObjects } = ctx; + let ref = void 0; + if (aliasDuplicateObjects && value && typeof value === "object") { + ref = sourceObjects.get(value); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value)); + return new Alias(ref.anchor); + } else { + ref = { anchor: null, node: null }; + sourceObjects.set(value, ref); + } + } + if (tagName?.startsWith("!!")) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value, tagName, schema4.tags); + if (!tagObj) { + if (value && typeof value.toJSON === "function") { + value = value.toJSON(); + } + if (!value || typeof value !== "object") { + const node2 = new Scalar(value); + if (ref) + ref.node = node2; + return node2; + } + tagObj = value instanceof Map ? schema4[MAP] : Symbol.iterator in Object(value) ? schema4[SEQ] : schema4[MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value, ctx) : new Scalar(value); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; + } + + // node_modules/yaml/browser/dist/nodes/Collection.js + function collectionFromPath(schema4, path, value) { + let v6 = value; + for (let i2 = path.length - 1; i2 >= 0; --i2) { + const k3 = path[i2]; + if (typeof k3 === "number" && Number.isInteger(k3) && k3 >= 0) { + const a2 = []; + a2[k3] = v6; + v6 = a2; + } else { + v6 = /* @__PURE__ */ new Map([[k3, v6]]); + } + } + return createNode(v6, void 0, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema: schema4, + sourceObjects: /* @__PURE__ */ new Map() + }); + } + var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done; + var Collection = class extends NodeBase { + constructor(type, schema4) { + super(type); + Object.defineProperty(this, "schema", { + value: schema4, + configurable: true, + enumerable: false, + writable: true + }); + } + /** + * Create a copy of this collection. + * + * @param schema - If defined, overwrites the original's schema + */ + clone(schema4) { + const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema4) + copy.schema = schema4; + copy.items = copy.items.map((it) => isNode3(it) || isPair(it) ? it.clone(schema4) : it); + if (this.range) + copy.range = this.range.slice(); + return copy; + } + /** + * Adds a value to the collection. For `!!map` and `!!omap` the value must + * be a Pair instance or a `{ key, value }` object, which may not have a key + * that already exists in the map. + */ + addIn(path, value) { + if (isEmptyPath(path)) + this.add(value); + else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (isCollection(node)) + node.addIn(rest, value); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + /** + * Removes a value from the collection. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (isCollection(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + const [key, ...rest] = path; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && isScalar(node) ? node.value : node; + else + return isCollection(node) ? node.getIn(rest, keepScalar) : void 0; + } + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!isPair(node)) + return false; + const n2 = node.value; + return n2 == null || allowScalar && isScalar(n2) && n2.value == null && !n2.commentBefore && !n2.comment && !n2.tag; + }); + } + /** + * Checks if the collection includes a value with the key `key`. + */ + hasIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return isCollection(node) ? node.hasIn(rest) : false; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value) { + const [key, ...rest] = path; + if (rest.length === 0) { + this.set(key, value); + } else { + const node = this.get(key, true); + if (isCollection(node)) + node.setIn(rest, value); + else if (node === void 0 && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + }; + + // node_modules/yaml/browser/dist/stringify/stringifyComment.js + var stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, "#"); + function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; + } + var lineComment = (str, indent, comment) => str.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str.endsWith(" ") ? "" : " ") + comment; + + // node_modules/yaml/browser/dist/stringify/foldFlowLines.js + var FOLD_FLOW = "flow"; + var FOLD_BLOCK = "block"; + var FOLD_QUOTED = "quoted"; + function foldFlowLines(text2, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text2; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text2.length <= endStep) + return text2; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = void 0; + let prev = void 0; + let overflow = false; + let i2 = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i2 = consumeMoreIndentedLines(text2, i2, indent.length); + if (i2 !== -1) + end = i2 + endStep; + } + for (let ch; ch = text2[i2 += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i2; + switch (text2[i2 + 1]) { + case "x": + i2 += 3; + break; + case "u": + i2 += 5; + break; + case "U": + i2 += 9; + break; + default: + i2 += 1; + } + escEnd = i2; + } + if (ch === "\n") { + if (mode === FOLD_BLOCK) + i2 = consumeMoreIndentedLines(text2, i2, indent.length); + end = i2 + indent.length + endStep; + split = void 0; + } else { + if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { + const next = text2[i2 + 1]; + if (next && next !== " " && next !== "\n" && next !== " ") + split = i2; + } + if (i2 >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = void 0; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === " ") { + prev = ch; + ch = text2[i2 += 1]; + overflow = true; + } + const j3 = i2 > escEnd + 1 ? i2 - 2 : escStart - 1; + if (escapedFolds[j3]) + return text2; + folds.push(j3); + escapedFolds[j3] = true; + end = j3 + endStep; + split = void 0; + } else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text2; + if (onFold) + onFold(); + let res = text2.slice(0, folds[0]); + for (let i3 = 0; i3 < folds.length; ++i3) { + const fold = folds[i3]; + const end2 = folds[i3 + 1] || text2.length; + if (fold === 0) + res = ` +${indent}${text2.slice(0, end2)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text2[fold]}\\`; + res += ` +${indent}${text2.slice(fold + 1, end2)}`; + } + } + return res; + } + function consumeMoreIndentedLines(text2, i2, indent) { + let end = i2; + let start = i2 + 1; + let ch = text2[start]; + while (ch === " " || ch === " ") { + if (i2 < start + indent) { + ch = text2[++i2]; + } else { + do { + ch = text2[++i2]; + } while (ch && ch !== "\n"); + end = i2; + start = i2 + 1; + ch = text2[start]; + } + } + return end; + } + + // node_modules/yaml/browser/dist/stringify/stringifyString.js + var getFoldOptions = (ctx, isBlock2) => ({ + indentAtStart: isBlock2 ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth + }); + var containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str); + function lineLengthOverLimit(str, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str.length; + if (strLen <= limit) + return false; + for (let i2 = 0, start = 0; i2 < strLen; ++i2) { + if (str[i2] === "\n") { + if (i2 - start > limit) + return true; + start = i2 + 1; + if (strLen - start <= limit) + return false; + } + } + return true; + } + function doubleQuotedString(value, ctx) { + const json = JSON.stringify(value); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); + let str = ""; + let start = 0; + for (let i2 = 0, ch = json[i2]; ch; ch = json[++i2]) { + if (ch === " " && json[i2 + 1] === "\\" && json[i2 + 2] === "n") { + str += json.slice(start, i2) + "\\ "; + i2 += 1; + start = i2; + ch = "\\"; + } + if (ch === "\\") + switch (json[i2 + 1]) { + case "u": + { + str += json.slice(start, i2); + const code = json.substr(i2 + 2, 4); + switch (code) { + case "0000": + str += "\\0"; + break; + case "0007": + str += "\\a"; + break; + case "000b": + str += "\\v"; + break; + case "001b": + str += "\\e"; + break; + case "0085": + str += "\\N"; + break; + case "00a0": + str += "\\_"; + break; + case "2028": + str += "\\L"; + break; + case "2029": + str += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str += "\\x" + code.substr(2); + else + str += json.substr(i2, 6); + } + i2 += 5; + start = i2 + 1; + } + break; + case "n": + if (implicitKey || json[i2 + 2] === '"' || json.length < minMultiLineLength) { + i2 += 1; + } else { + str += json.slice(start, i2) + "\n\n"; + while (json[i2 + 2] === "\\" && json[i2 + 3] === "n" && json[i2 + 4] !== '"') { + str += "\n"; + i2 += 2; + } + str += indent; + if (json[i2 + 2] === " ") + str += "\\"; + i2 += 1; + start = i2 + 1; + } + break; + default: + i2 += 1; + } + } + str = start ? str + json.slice(start) : json; + return implicitKey ? str : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx, false)); + } + function singleQuotedString(value, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value.includes("\n") || /[ \t]\n|\n[ \t]/.test(value)) + return doubleQuotedString(value, ctx); + const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); + const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false)); + } + function quotedString(value, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value.includes('"'); + const hasSingle = value.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value, ctx); + } + var blockEndNewlines; + try { + blockEndNewlines = new RegExp("(^|(?\n"; + let chomp; + let endStart; + for (endStart = value.length; endStart > 0; --endStart) { + const ch = value[endStart - 1]; + if (ch !== "\n" && ch !== " " && ch !== " ") + break; + } + let end = value.substring(endStart); + const endNlPos = end.indexOf("\n"); + if (endNlPos === -1) { + chomp = "-"; + } else if (value === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) + onChompKeep(); + } else { + chomp = ""; + } + if (end) { + value = value.slice(0, -end.length); + if (end[end.length - 1] === "\n") + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0; startEnd < value.length; ++startEnd) { + const ch = value[startEnd]; + if (ch === " ") + startWithSpace = true; + else if (ch === "\n") + startNlPos = startEnd; + else + break; + } + let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value = value.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? "2" : "1"; + let header = (startWithSpace ? indentSize : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) + onComment(); + } + if (!literal) { + const foldedValue = value.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== "folded" && type !== Scalar.BLOCK_FOLDED) { + foldOptions.onOverflow = () => { + literalFallback = true; + }; + } + const body = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions); + if (!literalFallback) + return `>${header} +${indent}${body}`; + } + value = value.replace(/\n+/g, `$&${indent}`); + return `|${header} +${indent}${start}${value}${end}`; + } + function plainString(item, ctx, onComment, onChompKeep) { + const { type, value } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value.includes("\n") || inFlow && /[[\]{},]/.test(value)) { + return quotedString(value, ctx); + } + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) { + return implicitKey || inFlow || !value.includes("\n") ? quotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value.includes("\n")) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) { + return quotedString(value, ctx); + } + } + const str = value.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) + return quotedString(value, ctx); + } + return implicitKey ? str : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx, false)); + } + function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.BLOCK_FOLDED: + case Scalar.BLOCK_LITERAL: + return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t2 = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t2); + if (res === null) + throw new Error(`Unsupported default string type ${t2}`); + } + return res; + } + + // node_modules/yaml/browser/dist/stringify/stringify.js + function createStringifyContext(doc, options) { + const opt = Object.assign({ + blockQuote: true, + commentString: stringifyComment, + defaultKeyType: null, + defaultStringType: "PLAIN", + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: "false", + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: "null", + simpleKeys: false, + singleQuote: null, + trailingComma: false, + trueStr: "true", + verifyAliasOrder: true + }, doc.schema.toStringOptions, options); + let inFlow; + switch (opt.collectionStyle) { + case "block": + inFlow = false; + break; + case "flow": + inFlow = true; + break; + default: + inFlow = null; + } + return { + anchors: /* @__PURE__ */ new Set(), + doc, + flowCollectionPadding: opt.flowCollectionPadding ? " " : "", + indent: "", + indentStep: typeof opt.indent === "number" ? " ".repeat(opt.indent) : " ", + inFlow, + options: opt + }; + } + function getTagObject(tags, item) { + if (item.tag) { + const match = tags.filter((t2) => t2.tag === item.tag); + if (match.length > 0) + return match.find((t2) => t2.format === item.format) ?? match[0]; + } + let tagObj = void 0; + let obj; + if (isScalar(item)) { + obj = item.value; + let match = tags.filter((t2) => t2.identify?.(obj)); + if (match.length > 1) { + const testMatch = match.filter((t2) => t2.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = match.find((t2) => t2.format === item.format) ?? match.find((t2) => !t2.format); + } else { + obj = item; + tagObj = tags.find((t2) => t2.nodeClass && obj instanceof t2.nodeClass); + } + if (!tagObj) { + const name = obj?.constructor?.name ?? (obj === null ? "null" : typeof obj); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; + } + function stringifyProps(node, tagObj, { anchors, doc }) { + if (!doc.directives) + return ""; + const props = []; + const anchor = (isScalar(node) || isCollection(node)) && node.anchor; + if (anchor && anchorIsValid(anchor)) { + anchors.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(" "); + } + function stringify(item, ctx, onComment, onChompKeep) { + if (isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = void 0; + const node = isNode3(item) ? item : ctx.doc.createNode(item, { onTagObj: (o2) => tagObj = o2 }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : isScalar(node) ? stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str; + return isScalar(node) || str[0] === "{" || str[0] === "[" ? `${props} ${str}` : `${props} +${ctx.indent}${str}`; + } + + // node_modules/yaml/browser/dist/stringify/stringifyPair.js + function stringifyPair({ key, value }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = isNode3(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); + } + if (isCollection(key) || !isNode3(key) && typeof key === "object") { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key || keyComment && value == null && !ctx.inFlow || isCollection(key) || (isScalar(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str = stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value == null) { + if (keyCommentDone && onComment) + onComment(); + return str === "" ? "?" : explicitKey ? `? ${str}` : str; + } + } else if (allNullValues && !simpleKeys || value == null && explicitKey) { + str = `? ${str}`; + if (keyComment && !keyCommentDone) { + str += lineComment(str, ctx.indent, commentString(keyComment)); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str += lineComment(str, ctx.indent, commentString(keyComment)); + str = `? ${str} +${indent}:`; + } else { + str = `${str}:`; + if (keyComment) + str += lineComment(str, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (isNode3(value)) { + vsb = !!value.spaceBefore; + vcb = value.commentBefore; + valueComment = value.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value && typeof value === "object") + value = doc.createNode(value); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && isScalar(value)) + ctx.indentAtStart = str.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value) && !value.flow && !value.tag && !value.anchor) { + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify(value, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? "\n" : ""; + if (vcb) { + const cs = commentString(vcb); + ws += ` +${indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === "\n" && valueComment) + ws = "\n\n"; + } else { + ws += ` +${ctx.indent}`; + } + } else if (!explicitKey && isCollection(value)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf("\n"); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { + sp0 = valueStr.indexOf(" ", sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = ` +${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === "\n") { + ws = ""; + } + str += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } else if (valueComment && !valueCommentDone) { + str += lineComment(str, ctx.indent, commentString(valueComment)); + } else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str; + } + + // node_modules/yaml/browser/dist/log.js + function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") { + console.warn(warning); + } + } + + // node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js + var MERGE_KEY = "<<"; + var merge2 = { + identify: (value) => value === MERGE_KEY || typeof value === "symbol" && value.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY + }; + var isMergeKey = (ctx, key) => (merge2.identify(key) || isScalar(key) && (!key.type || key.type === Scalar.PLAIN) && merge2.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge2.tag && tag.default); + function addMergeToJSMap(ctx, map2, value) { + const source = resolveAliasValue(ctx, value); + if (isSeq(source)) + for (const it of source.items) + mergeValue(ctx, map2, it); + else if (Array.isArray(source)) + for (const it of source) + mergeValue(ctx, map2, it); + else + mergeValue(ctx, map2, source); + } + function mergeValue(ctx, map2, value) { + const source = resolveAliasValue(ctx, value); + if (!isMap(source)) + throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value2] of srcMap) { + if (map2 instanceof Map) { + if (!map2.has(key)) + map2.set(key, value2); + } else if (map2 instanceof Set) { + map2.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map2, key)) { + Object.defineProperty(map2, key, { + value: value2, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map2; + } + function resolveAliasValue(ctx, value) { + return ctx && isAlias(value) ? value.resolve(ctx.doc, ctx) : value; + } + + // node_modules/yaml/browser/dist/nodes/addPairToJSMap.js + function addPairToJSMap(ctx, map2, { key, value }) { + if (isNode3(key) && key.addToJSMap) + key.addToJSMap(ctx, map2, value); + else if (isMergeKey(ctx, key)) + addMergeToJSMap(ctx, map2, value); + else { + const jsKey = toJS(key, "", ctx); + if (map2 instanceof Map) { + map2.set(jsKey, toJS(value, jsKey, ctx)); + } else if (map2 instanceof Set) { + map2.add(jsKey); + } else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS(value, stringKey, ctx); + if (stringKey in map2) + Object.defineProperty(map2, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map2[stringKey] = jsValue; + } + } + return map2; + } + function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (isNode3(key) && ctx?.doc) { + const strCtx = createStringifyContext(ctx.doc, {}); + strCtx.anchors = /* @__PURE__ */ new Set(); + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); + } + + // node_modules/yaml/browser/dist/nodes/Pair.js + function createPair(key, value, ctx) { + const k3 = createNode(key, void 0, ctx); + const v6 = createNode(value, void 0, ctx); + return new Pair(k3, v6); + } + var Pair = class _Pair { + constructor(key, value = null) { + Object.defineProperty(this, NODE_TYPE2, { value: PAIR }); + this.key = key; + this.value = value; + } + clone(schema4) { + let { key, value } = this; + if (isNode3(key)) + key = key.clone(schema4); + if (isNode3(value)) + value = value.clone(schema4); + return new _Pair(key, value); + } + toJSON(_2, ctx) { + const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + return addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } + }; + + // node_modules/yaml/browser/dist/stringify/stringifyCollection.js + function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify4 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify4(collection, ctx, options); + } + function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; + const lines = []; + for (let i2 = 0; i2 < items.length; ++i2) { + const item = items[i2]; + let comment2 = null; + if (isNode3(item)) { + if (!chompKeep && item.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, item.commentBefore, chompKeep); + if (item.comment) + comment2 = item.comment; + } else if (isPair(item)) { + const ik = isNode3(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str2 = stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); + if (comment2) + str2 += lineComment(str2, itemIndent, commentString(comment2)); + if (chompKeep && comment2) + chompKeep = false; + lines.push(blockItemPrefix + str2); + } + let str; + if (lines.length === 0) { + str = flowChars.start + flowChars.end; + } else { + str = lines[0]; + for (let i2 = 1; i2 < lines.length; ++i2) { + const line = lines[i2]; + str += line ? ` +${indent}${line}` : "\n"; + } + } + if (comment) { + str += "\n" + indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str; + } + function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines = []; + for (let i2 = 0; i2 < items.length; ++i2) { + const item = items[i2]; + let comment = null; + if (isNode3(item)) { + if (item.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } else if (isPair(item)) { + const ik = isNode3(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = isNode3(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } else if (item.value == null && ik?.comment) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str = stringify(item, itemCtx, () => comment = null); + reqNewline || (reqNewline = lines.length > linesAtValue || str.includes("\n")); + if (i2 < items.length - 1) { + str += ","; + } else if (ctx.options.trailingComma) { + if (ctx.options.lineWidth > 0) { + reqNewline || (reqNewline = lines.reduce((sum, line) => sum + line.length + 2, 2) + (str.length + 2) > ctx.options.lineWidth); + } + if (reqNewline) { + str += ","; + } + } + if (comment) + str += lineComment(str, itemIndent, commentString(comment)); + lines.push(str); + linesAtValue = lines.length; + } + const { start, end } = flowChars; + if (lines.length === 0) { + return start + end; + } else { + if (!reqNewline) { + const len = lines.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str = start; + for (const line of lines) + str += line ? ` +${indentStep}${indent}${line}` : "\n"; + return `${str} +${indent}${end}`; + } else { + return `${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`; + } + } + } + function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = indentComment(commentString(comment), indent); + lines.push(ic.trimStart()); + } + } + + // node_modules/yaml/browser/dist/nodes/YAMLMap.js + function findPair(items, key) { + const k3 = isScalar(key) ? key.value : key; + for (const it of items) { + if (isPair(it)) { + if (it.key === key || it.key === k3) + return it; + if (isScalar(it.key) && it.key.value === k3) + return it; + } + } + return void 0; + } + var YAMLMap = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema4) { + super(MAP, schema4); + this.items = []; + } + /** + * A generic collection parsing method that can be extended + * to other node classes that inherit from YAMLMap + */ + static from(schema4, obj, ctx) { + const { keepUndefined, replacer } = ctx; + const map2 = new this(schema4); + const add = (key, value) => { + if (typeof replacer === "function") + value = replacer.call(obj, key, value); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value !== void 0 || keepUndefined) + map2.items.push(createPair(key, value, ctx)); + }; + if (obj instanceof Map) { + for (const [key, value] of obj) + add(key, value); + } else if (obj && typeof obj === "object") { + for (const key of Object.keys(obj)) + add(key, obj[key]); + } + if (typeof schema4.sortMapEntries === "function") { + map2.items.sort(schema4.sortMapEntries); + } + return map2; + } + /** + * Adds a value to the collection. + * + * @param overwrite - If not set `true`, using a key that is already in the + * collection will throw. Otherwise, overwrites the previous value. + */ + add(pair, overwrite) { + let _pair; + if (isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) { + _pair = new Pair(pair, pair?.value); + } else + _pair = new Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + if (isScalar(prev.value) && isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } else if (sortEntries) { + const i2 = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i2 === -1) + this.items.push(_pair); + else + this.items.splice(i2, 0, _pair); + } else { + this.items.push(_pair); + } + } + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it?.value; + return (!keepScalar && isScalar(node) ? node.value : node) ?? void 0; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value) { + this.add(new Pair(key, value), true); + } + /** + * @param ctx - Conversion context, originally set in Document#toJS() + * @param {Class} Type - If set, forces the returned collection type + * @returns Instance of Type, Map, or Object + */ + toJSON(_2, ctx, Type) { + const map2 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; + if (ctx?.onCreate) + ctx.onCreate(map2); + for (const item of this.items) + addPairToJSMap(ctx, map2, item); + return map2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { start: "{", end: "}" }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } + }; + + // node_modules/yaml/browser/dist/schema/common/map.js + var map = { + collection: "map", + default: true, + nodeClass: YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map2, onError) { + if (!isMap(map2)) + onError("Expected a mapping for this tag"); + return map2; + }, + createNode: (schema4, obj, ctx) => YAMLMap.from(schema4, obj, ctx) + }; + + // node_modules/yaml/browser/dist/nodes/YAMLSeq.js + var YAMLSeq = class extends Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema4) { + super(SEQ, schema4); + this.items = []; + } + add(value) { + this.items.push(value); + } + /** + * Removes a value from the collection. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + * + * @returns `true` if the item was found and removed. + */ + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return void 0; + const it = this.items[idx]; + return !keepScalar && isScalar(it) ? it.value : it; + } + /** + * Checks if the collection includes a value with the key `key`. + * + * `key` must contain a representation of an integer for this to succeed. + * It may be wrapped in a `Scalar`. + */ + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + /** + * Sets a value in this collection. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + * + * If `key` does not contain a representation of an integer, this will throw. + * It may be wrapped in a `Scalar`. + */ + set(key, value) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (isScalar(prev) && isScalarValue(value)) + prev.value = value; + else + this.items[idx] = value; + } + toJSON(_2, ctx) { + const seq2 = []; + if (ctx?.onCreate) + ctx.onCreate(seq2); + let i2 = 0; + for (const item of this.items) + seq2.push(toJS(item, String(i2++), ctx)); + return seq2; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { start: "[", end: "]" }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema4, obj, ctx) { + const { replacer } = ctx; + const seq2 = new this(schema4); + if (obj && Symbol.iterator in Object(obj)) { + let i2 = 0; + for (let it of obj) { + if (typeof replacer === "function") { + const key = obj instanceof Set ? it : String(i2++); + it = replacer.call(obj, key, it); + } + seq2.items.push(createNode(it, void 0, ctx)); + } + } + return seq2; + } + }; + function asItemIndex(key) { + let idx = isScalar(key) ? key.value : key; + if (idx && typeof idx === "string") + idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; + } + + // node_modules/yaml/browser/dist/schema/common/seq.js + var seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq2, onError) { + if (!isSeq(seq2)) + onError("Expected a sequence for this tag"); + return seq2; + }, + createNode: (schema4, obj, ctx) => YAMLSeq.from(schema4, obj, ctx) + }; + + // node_modules/yaml/browser/dist/schema/common/string.js + var string = { + identify: (value) => typeof value === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str) => str, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString(item, ctx, onComment, onChompKeep); + } + }; + + // node_modules/yaml/browser/dist/schema/common/null.js + var nullTag = { + identify: (value) => value == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar(null), + stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr + }; + + // node_modules/yaml/browser/dist/schema/core/bool.js + var boolTag = { + identify: (value) => typeof value === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: (str) => new Scalar(str[0] === "t" || str[0] === "T"), + stringify({ source, value }, ctx) { + if (source && boolTag.test.test(source)) { + const sv = source[0] === "t" || source[0] === "T"; + if (value === sv) + return source; + } + return value ? ctx.options.trueStr : ctx.options.falseStr; + } + }; + + // node_modules/yaml/browser/dist/stringify/stringifyNumber.js + function stringifyNumber({ format: format2, minFractionDigits, tag, value }) { + if (typeof value === "bigint") + return String(value); + const num = typeof value === "number" ? value : Number(value); + if (!isFinite(num)) + return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf"; + let n2 = Object.is(value, -0) ? "-0" : JSON.stringify(value); + if (!format2 && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n2) && !n2.includes("e")) { + let i2 = n2.indexOf("."); + if (i2 < 0) { + i2 = n2.length; + n2 += "."; + } + let d3 = minFractionDigits - (n2.length - i2 - 1); + while (d3-- > 0) + n2 += "0"; + } + return n2; + } + + // node_modules/yaml/browser/dist/schema/core/float.js + var floatNaN = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber + }; + var floatExp = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: (str) => parseFloat(str), + stringify(node) { + const num = Number(node.value); + return isFinite(num) ? num.toExponential() : stringifyNumber(node); + } + }; + var float = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str) { + const node = new Scalar(parseFloat(str)); + const dot = str.indexOf("."); + if (dot !== -1 && str[str.length - 1] === "0") + node.minFractionDigits = str.length - dot - 1; + return node; + }, + stringify: stringifyNumber + }; + + // node_modules/yaml/browser/dist/schema/core/int.js + var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value); + var intResolve = (str, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix); + function intStringify(node, radix, prefix) { + const { value } = node; + if (intIdentify(value) && value >= 0) + return prefix + value.toString(radix); + return stringifyNumber(node); + } + var intOct = { + identify: (value) => intIdentify(value) && value >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^0o[0-7]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt), + stringify: (node) => intStringify(node, 8, "0o") + }; + var int = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9]+$/, + resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt), + stringify: stringifyNumber + }; + var intHex = { + identify: (value) => intIdentify(value) && value >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^0x[0-9a-fA-F]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt), + stringify: (node) => intStringify(node, 16, "0x") + }; + + // node_modules/yaml/browser/dist/schema/core/schema.js + var schema = [ + map, + seq, + string, + nullTag, + boolTag, + intOct, + int, + intHex, + floatNaN, + floatExp, + float + ]; + + // node_modules/yaml/browser/dist/schema/json/schema.js + function intIdentify2(value) { + return typeof value === "bigint" || Number.isInteger(value); + } + var stringifyJSON = ({ value }) => JSON.stringify(value); + var jsonScalars = [ + { + identify: (value) => typeof value === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str) => str, + stringify: stringifyJSON + }, + { + identify: (value) => value == null, + createNode: () => new Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value) => typeof value === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true$|^false$/, + resolve: (str) => str === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify2, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10), + stringify: ({ value }) => intIdentify2(value) ? value.toString() : JSON.stringify(value) + }, + { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str) => parseFloat(str), + stringify: stringifyJSON + } + ]; + var jsonError = { + default: true, + tag: "", + test: /^/, + resolve(str, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str)}`); + return str; + } + }; + var schema2 = [map, seq].concat(jsonScalars, jsonError); + + // node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js + var binary = { + identify: (value) => value instanceof Uint8Array, + // Buffer inherits from Uint8Array + default: false, + tag: "tag:yaml.org,2002:binary", + /** + * Returns a Buffer in node and an Uint8Array in browsers + * + * To use the resulting buffer as an image, you'll want to do something like: + * + * const blob = new Blob([buffer], { type: 'image/jpeg' }) + * document.querySelector('#photo').src = URL.createObjectURL(blob) + */ + resolve(src, onError) { + if (typeof atob === "function") { + const str = atob(src.replace(/[\n\r]/g, "")); + const buffer = new Uint8Array(str.length); + for (let i2 = 0; i2 < str.length; ++i2) + buffer[i2] = str.charCodeAt(i2); + return buffer; + } else { + onError("This environment does not support reading binary tags; either Buffer or atob is required"); + return src; + } + }, + stringify({ comment, type, value }, ctx, onComment, onChompKeep) { + if (!value) + return ""; + const buf = value; + let str; + if (typeof btoa === "function") { + let s2 = ""; + for (let i2 = 0; i2 < buf.length; ++i2) + s2 += String.fromCharCode(buf[i2]); + str = btoa(s2); + } else { + throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); + } + type ?? (type = Scalar.BLOCK_LITERAL); + if (type !== Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n2 = Math.ceil(str.length / lineWidth); + const lines = new Array(n2); + for (let i2 = 0, o2 = 0; i2 < n2; ++i2, o2 += lineWidth) { + lines[i2] = str.substr(o2, lineWidth); + } + str = lines.join(type === Scalar.BLOCK_LITERAL ? "\n" : " "); + } + return stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep); + } + }; + + // node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js + function resolvePairs(seq2, onError) { + if (isSeq(seq2)) { + for (let i2 = 0; i2 < seq2.items.length; ++i2) { + let item = seq2.items[i2]; + if (isPair(item)) + continue; + else if (isMap(item)) { + if (item.items.length > 1) + onError("Each pair must have its own sequence indicator"); + const pair = item.items[0] || new Pair(new Scalar(null)); + if (item.commentBefore) + pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore} +${pair.key.commentBefore}` : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment ? `${item.comment} +${cn.comment}` : item.comment; + } + item = pair; + } + seq2.items[i2] = isPair(item) ? item : new Pair(item); + } + } else + onError("Expected a sequence for this tag"); + return seq2; + } + function createPairs(schema4, iterable, ctx) { + const { replacer } = ctx; + const pairs2 = new YAMLSeq(schema4); + pairs2.tag = "tag:yaml.org,2002:pairs"; + let i2 = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === "function") + it = replacer.call(iterable, String(i2++), it); + let key, value; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value = it[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value = it[key]; + } else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } else { + key = it; + } + pairs2.items.push(createPair(key, value, ctx)); + } + return pairs2; + } + var pairs = { + collection: "seq", + default: false, + tag: "tag:yaml.org,2002:pairs", + resolve: resolvePairs, + createNode: createPairs + }; + + // node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js + var YAMLOMap = class _YAMLOMap extends YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.prototype.set.bind(this); + this.tag = _YAMLOMap.tag; + } + /** + * If `ctx` is given, the return type is actually `Map`, + * but TypeScript won't allow widening the signature of a child method. + */ + toJSON(_2, ctx) { + if (!ctx) + return super.toJSON(_2); + const map2 = /* @__PURE__ */ new Map(); + if (ctx?.onCreate) + ctx.onCreate(map2); + for (const pair of this.items) { + let key, value; + if (isPair(pair)) { + key = toJS(pair.key, "", ctx); + value = toJS(pair.value, key, ctx); + } else { + key = toJS(pair, "", ctx); + } + if (map2.has(key)) + throw new Error("Ordered maps must not include duplicate keys"); + map2.set(key, value); + } + return map2; + } + static from(schema4, iterable, ctx) { + const pairs2 = createPairs(schema4, iterable, ctx); + const omap2 = new this(); + omap2.items = pairs2.items; + return omap2; + } + }; + YAMLOMap.tag = "tag:yaml.org,2002:omap"; + var omap = { + collection: "seq", + identify: (value) => value instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: "tag:yaml.org,2002:omap", + resolve(seq2, onError) { + const pairs2 = resolvePairs(seq2, onError); + const seenKeys = []; + for (const { key } of pairs2.items) { + if (isScalar(key)) { + if (seenKeys.includes(key.value)) { + onError(`Ordered maps must not include duplicate keys: ${key.value}`); + } else { + seenKeys.push(key.value); + } + } + } + return Object.assign(new YAMLOMap(), pairs2); + }, + createNode: (schema4, iterable, ctx) => YAMLOMap.from(schema4, iterable, ctx) + }; + + // node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js + function boolStringify({ value, source }, ctx) { + const boolObj = value ? trueTag : falseTag; + if (source && boolObj.test.test(source)) + return source; + return value ? ctx.options.trueStr : ctx.options.falseStr; + } + var trueTag = { + identify: (value) => value === true, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar(true), + stringify: boolStringify + }; + var falseTag = { + identify: (value) => value === false, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar(false), + stringify: boolStringify + }; + + // node_modules/yaml/browser/dist/schema/yaml-1.1/float.js + var floatNaN2 = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber + }; + var floatExp2 = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str) => parseFloat(str.replace(/_/g, "")), + stringify(node) { + const num = Number(node.value); + return isFinite(num) ? num.toExponential() : stringifyNumber(node); + } + }; + var float2 = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str) { + const node = new Scalar(parseFloat(str.replace(/_/g, ""))); + const dot = str.indexOf("."); + if (dot !== -1) { + const f3 = str.substring(dot + 1).replace(/_/g, ""); + if (f3[f3.length - 1] === "0") + node.minFractionDigits = f3.length; + } + return node; + }, + stringify: stringifyNumber + }; + + // node_modules/yaml/browser/dist/schema/yaml-1.1/int.js + var intIdentify3 = (value) => typeof value === "bigint" || Number.isInteger(value); + function intResolve2(str, offset, radix, { intAsBigInt }) { + const sign = str[0]; + if (sign === "-" || sign === "+") + offset += 1; + str = str.substring(offset).replace(/_/g, ""); + if (intAsBigInt) { + switch (radix) { + case 2: + str = `0b${str}`; + break; + case 8: + str = `0o${str}`; + break; + case 16: + str = `0x${str}`; + break; + } + const n3 = BigInt(str); + return sign === "-" ? BigInt(-1) * n3 : n3; + } + const n2 = parseInt(str, radix); + return sign === "-" ? -1 * n2 : n2; + } + function intStringify2(node, radix, prefix) { + const { value } = node; + if (intIdentify3(value)) { + const str = value.toString(radix); + return value < 0 ? "-" + prefix + str.substr(1) : prefix + str; + } + return stringifyNumber(node); + } + var intBin = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "BIN", + test: /^[-+]?0b[0-1_]+$/, + resolve: (str, _onError, opt) => intResolve2(str, 2, 2, opt), + stringify: (node) => intStringify2(node, 2, "0b") + }; + var intOct2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^[-+]?0[0-7_]+$/, + resolve: (str, _onError, opt) => intResolve2(str, 1, 8, opt), + stringify: (node) => intStringify2(node, 8, "0") + }; + var int2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str, _onError, opt) => intResolve2(str, 0, 10, opt), + stringify: stringifyNumber + }; + var intHex2 = { + identify: intIdentify3, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str, _onError, opt) => intResolve2(str, 2, 16, opt), + stringify: (node) => intStringify2(node, 16, "0x") + }; + + // node_modules/yaml/browser/dist/schema/yaml-1.1/set.js + var YAMLSet = class _YAMLSet extends YAMLMap { + constructor(schema4) { + super(schema4); + this.tag = _YAMLSet.tag; + } + add(key) { + let pair; + if (isPair(key)) + pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) + pair = new Pair(key.key, null); + else + pair = new Pair(key, null); + const prev = findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + /** + * If `keepPair` is `true`, returns the Pair matching `key`. + * Otherwise, returns the value of that Pair's key. + */ + get(key, keepPair) { + const pair = findPair(this.items, key); + return !keepPair && isPair(pair) ? isScalar(pair.key) ? pair.key.value : pair.key : pair; + } + set(key, value) { + if (typeof value !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`); + const prev = findPair(this.items, key); + if (prev && !value) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value) { + this.items.push(new Pair(key)); + } + } + toJSON(_2, ctx) { + return super.toJSON(_2, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); + } + static from(schema4, iterable, ctx) { + const { replacer } = ctx; + const set2 = new this(schema4); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value of iterable) { + if (typeof replacer === "function") + value = replacer.call(iterable, value, value); + set2.items.push(createPair(value, null, ctx)); + } + return set2; + } + }; + YAMLSet.tag = "tag:yaml.org,2002:set"; + var set = { + collection: "map", + identify: (value) => value instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: "tag:yaml.org,2002:set", + createNode: (schema4, iterable, ctx) => YAMLSet.from(schema4, iterable, ctx), + resolve(map2, onError) { + if (isMap(map2)) { + if (map2.hasAllNullValues(true)) + return Object.assign(new YAMLSet(), map2); + else + onError("Set items must all have null values"); + } else + onError("Expected a mapping for this tag"); + return map2; + } + }; + + // node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js + function parseSexagesimal(str, asBigInt) { + const sign = str[0]; + const parts = sign === "-" || sign === "+" ? str.substring(1) : str; + const num = (n2) => asBigInt ? BigInt(n2) : Number(n2); + const res = parts.replace(/_/g, "").split(":").reduce((res2, p2) => res2 * num(60) + num(p2), num(0)); + return sign === "-" ? num(-1) * res : res; + } + function stringifySexagesimal(node) { + let { value } = node; + let num = (n2) => n2; + if (typeof value === "bigint") + num = (n2) => BigInt(n2); + else if (isNaN(value) || !isFinite(value)) + return stringifyNumber(node); + let sign = ""; + if (value < 0) { + sign = "-"; + value *= num(-1); + } + const _60 = num(60); + const parts = [value % _60]; + if (value < 60) { + parts.unshift(0); + } else { + value = (value - parts[0]) / _60; + parts.unshift(value % _60); + if (value >= 60) { + value = (value - parts[0]) / _60; + parts.unshift(value); + } + } + return sign + parts.map((n2) => String(n2).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); + } + var intTime = { + identify: (value) => typeof value === "bigint" || Number.isInteger(value), + default: true, + tag: "tag:yaml.org,2002:int", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt), + stringify: stringifySexagesimal + }; + var floatTime = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: (str) => parseSexagesimal(str, false), + stringify: stringifySexagesimal + }; + var timestamp = { + identify: (value) => value instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part + // may be omitted altogether, resulting in a date format. In such a case, the time part is + // assumed to be 00:00:00Z (start of day, UTC). + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), + resolve(str) { + const match = str.match(timestamp.test); + if (!match) + throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second2] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date2 = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second2 || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d3 = parseSexagesimal(tz, false); + if (Math.abs(d3) < 30) + d3 *= 60; + date2 -= 6e4 * d3; + } + return new Date(date2); + }, + stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" + }; + + // node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js + var schema3 = [ + map, + seq, + string, + nullTag, + trueTag, + falseTag, + intBin, + intOct2, + int2, + intHex2, + floatNaN2, + floatExp2, + float2, + binary, + merge2, + omap, + pairs, + set, + intTime, + floatTime, + timestamp + ]; + + // node_modules/yaml/browser/dist/schema/tags.js + var schemas = /* @__PURE__ */ new Map([ + ["core", schema], + ["failsafe", [map, seq, string]], + ["json", schema2], + ["yaml11", schema3], + ["yaml-1.1", schema3] + ]); + var tagsByName = { + binary, + bool: boolTag, + float, + floatExp, + floatNaN, + floatTime, + int, + intHex, + intOct, + intTime, + map, + merge: merge2, + null: nullTag, + omap, + pairs, + seq, + set, + timestamp + }; + var coreKnownTags = { + "tag:yaml.org,2002:binary": binary, + "tag:yaml.org,2002:merge": merge2, + "tag:yaml.org,2002:omap": omap, + "tag:yaml.org,2002:pairs": pairs, + "tag:yaml.org,2002:set": set, + "tag:yaml.org,2002:timestamp": timestamp + }; + function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas.get(schemaName); + if (schemaTags && !customTags) { + return addMergeTag && !schemaTags.includes(merge2) ? schemaTags.concat(merge2) : schemaTags.slice(); + } + let tags = schemaTags; + if (!tags) { + if (Array.isArray(customTags)) + tags = []; + else { + const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + } + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags = tags.concat(tag); + } else if (typeof customTags === "function") { + tags = customTags(tags.slice()); + } + if (addMergeTag) + tags = tags.concat(merge2); + return tags.reduce((tags2, tag) => { + const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags2.includes(tagObj)) + tags2.push(tagObj); + return tags2; + }, []); + } + + // node_modules/yaml/browser/dist/schema/Schema.js + var sortMapEntriesByKey = (a2, b3) => a2.key < b3.key ? -1 : a2.key > b3.key ? 1 : 0; + var Schema2 = class _Schema { + constructor({ compat, customTags, merge: merge3, resolveKnownTags, schema: schema4, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) ? getTags(compat, "compat") : compat ? getTags(null, compat) : null; + this.name = typeof schema4 === "string" && schema4 || "core"; + this.knownTags = resolveKnownTags ? coreKnownTags : {}; + this.tags = getTags(customTags, this.name, merge3); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, MAP, { value: map }); + Object.defineProperty(this, SCALAR, { value: string }); + Object.defineProperty(this, SEQ, { value: seq }); + this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; + } + clone() { + const copy = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy.tags = this.tags.slice(); + return copy; + } + }; + + // node_modules/yaml/browser/dist/stringify/stringifyDocument.js + function stringifyDocument(doc, options) { + const lines = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc.directives) { + const dir = doc.directives.toString(doc); + if (dir) { + lines.push(dir); + hasDirectives = true; + } else if (doc.directives.docStart) + hasDirectives = true; + } + if (hasDirectives) + lines.push("---"); + const ctx = createStringifyContext(doc, options); + const { commentString } = ctx.options; + if (doc.commentBefore) { + if (lines.length !== 1) + lines.unshift(""); + const cs = commentString(doc.commentBefore); + lines.unshift(indentComment(cs, "")); + } + let chompKeep = false; + let contentComment = null; + if (doc.contents) { + if (isNode3(doc.contents)) { + if (doc.contents.spaceBefore && hasDirectives) + lines.push(""); + if (doc.contents.commentBefore) { + const cs = commentString(doc.contents.commentBefore); + lines.push(indentComment(cs, "")); + } + ctx.forceBlockIndent = !!doc.comment; + contentComment = doc.contents.comment; + } + const onChompKeep = contentComment ? void 0 : () => chompKeep = true; + let body = stringify(doc.contents, ctx, () => contentComment = null, onChompKeep); + if (contentComment) + body += lineComment(body, "", commentString(contentComment)); + if ((body[0] === "|" || body[0] === ">") && lines[lines.length - 1] === "---") { + lines[lines.length - 1] = `--- ${body}`; + } else + lines.push(body); + } else { + lines.push(stringify(doc.contents, ctx)); + } + if (doc.directives?.docEnd) { + if (doc.comment) { + const cs = commentString(doc.comment); + if (cs.includes("\n")) { + lines.push("..."); + lines.push(indentComment(cs, "")); + } else { + lines.push(`... ${cs}`); + } + } else { + lines.push("..."); + } + } else { + let dc = doc.comment; + if (dc && chompKeep) + dc = dc.replace(/^\n+/, ""); + if (dc) { + if ((!chompKeep || contentComment) && lines[lines.length - 1] !== "") + lines.push(""); + lines.push(indentComment(commentString(dc), "")); + } + } + return lines.join("\n") + "\n"; + } + + // node_modules/yaml/browser/dist/doc/Document.js + var Document = class _Document { + constructor(value, replacer, options) { + this.commentBefore = null; + this.comment = null; + this.errors = []; + this.warnings = []; + Object.defineProperty(this, NODE_TYPE2, { value: DOC }); + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const opt = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: "warn", + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: "1.2" + }, options); + this.options = opt; + let { version } = opt; + if (options?._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) + version = this.directives.yaml.version; + } else + this.directives = new Directives({ version }); + this.setSchema(version, options); + this.contents = value === void 0 ? null : this.createNode(value, _replacer, options); + } + /** + * Create a deep copy of this Document and its contents. + * + * Custom Node values that inherit from `Object` still refer to their original instances. + */ + clone() { + const copy = Object.create(_Document.prototype, { + [NODE_TYPE2]: { value: DOC } + }); + copy.commentBefore = this.commentBefore; + copy.comment = this.comment; + copy.errors = this.errors.slice(); + copy.warnings = this.warnings.slice(); + copy.options = Object.assign({}, this.options); + if (this.directives) + copy.directives = this.directives.clone(); + copy.schema = this.schema.clone(); + copy.contents = isNode3(this.contents) ? this.contents.clone(copy.schema) : this.contents; + if (this.range) + copy.range = this.range.slice(); + return copy; + } + /** Adds a value to the document. */ + add(value) { + if (assertCollection(this.contents)) + this.contents.add(value); + } + /** Adds a value to the document. */ + addIn(path, value) { + if (assertCollection(this.contents)) + this.contents.addIn(path, value); + } + /** + * Create a new `Alias` node, ensuring that the target `node` has the required anchor. + * + * If `node` already has an anchor, `name` is ignored. + * Otherwise, the `node.anchor` value will be set to `name`, + * or if an anchor with that name is already present in the document, + * `name` will be used as a prefix for a new unique anchor. + * If `name` is undefined, the generated anchor will use 'a' as a prefix. + */ + createAlias(node, name) { + if (!node.anchor) { + const prev = anchorNames(this); + node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + !name || prev.has(name) ? findNewAnchor(name || "a", prev) : name; + } + return new Alias(node.anchor); + } + createNode(value, replacer, options) { + let _replacer = void 0; + if (typeof replacer === "function") { + value = replacer.call({ "": value }, "", value); + _replacer = replacer; + } else if (Array.isArray(replacer)) { + const keyToStr = (v6) => typeof v6 === "number" || v6 instanceof String || v6 instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) + replacer = replacer.concat(asStr); + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + replacer = void 0; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors( + this, + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + anchorPrefix || "a" + ); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode(value, tag, ctx); + if (flow && isCollection(node)) + node.flow = true; + setAnchors(); + return node; + } + /** + * Convert a key and a value into a `Pair` using the current schema, + * recursively wrapping all values as `Scalar` or `Collection` nodes. + */ + createPair(key, value, options = {}) { + const k3 = this.createNode(key, null, options); + const v6 = this.createNode(value, null, options); + return new Pair(k3, v6); + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + /** + * Removes a value from the document. + * @returns `true` if the item was found and removed. + */ + deleteIn(path) { + if (isEmptyPath(path)) { + if (this.contents == null) + return false; + this.contents = null; + return true; + } + return assertCollection(this.contents) ? this.contents.deleteIn(path) : false; + } + /** + * Returns item at `key`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + get(key, keepScalar) { + return isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0; + } + /** + * Returns item at `path`, or `undefined` if not found. By default unwraps + * scalar values from their surrounding node; to disable set `keepScalar` to + * `true` (collections are always returned intact). + */ + getIn(path, keepScalar) { + if (isEmptyPath(path)) + return !keepScalar && isScalar(this.contents) ? this.contents.value : this.contents; + return isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : void 0; + } + /** + * Checks if the document includes a value with the key `key`. + */ + has(key) { + return isCollection(this.contents) ? this.contents.has(key) : false; + } + /** + * Checks if the document includes a value at `path`. + */ + hasIn(path) { + if (isEmptyPath(path)) + return this.contents !== void 0; + return isCollection(this.contents) ? this.contents.hasIn(path) : false; + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + set(key, value) { + if (this.contents == null) { + this.contents = collectionFromPath(this.schema, [key], value); + } else if (assertCollection(this.contents)) { + this.contents.set(key, value); + } + } + /** + * Sets a value in this document. For `!!set`, `value` needs to be a + * boolean to add/remove the item from the set. + */ + setIn(path, value) { + if (isEmptyPath(path)) { + this.contents = value; + } else if (this.contents == null) { + this.contents = collectionFromPath(this.schema, Array.from(path), value); + } else if (assertCollection(this.contents)) { + this.contents.setIn(path, value); + } + } + /** + * Change the YAML version and schema used by the document. + * A `null` version disables support for directives, explicit tags, anchors, and aliases. + * It also requires the `schema` option to be given as a `Schema` instance value. + * + * Overrides all previously set schema options. + */ + setSchema(version, options = {}) { + if (typeof version === "number") + version = String(version); + let opt; + switch (version) { + case "1.1": + if (this.directives) + this.directives.yaml.version = "1.1"; + else + this.directives = new Directives({ version: "1.1" }); + opt = { resolveKnownTags: false, schema: "yaml-1.1" }; + break; + case "1.2": + case "next": + if (this.directives) + this.directives.yaml.version = version; + else + this.directives = new Directives({ version }); + opt = { resolveKnownTags: true, schema: "core" }; + break; + case null: + if (this.directives) + delete this.directives; + opt = null; + break; + default: { + const sv = JSON.stringify(version); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + if (options.schema instanceof Object) + this.schema = options.schema; + else if (opt) + this.schema = new Schema2(Object.assign(opt, options)); + else + throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + // json & jsonArg are only used from toJSON() + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: /* @__PURE__ */ new Map(), + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS(this.contents, jsonArg ?? "", ctx); + if (typeof onAnchor === "function") + for (const { count: count3, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count3); + return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res; + } + /** + * A JSON representation of the document `contents`. + * + * @param jsonArg Used by `JSON.stringify` to indicate the array index or + * property name. + */ + toJSON(jsonArg, onAnchor) { + return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); + } + /** A YAML representation of the document. */ + toString(options = {}) { + if (this.errors.length > 0) + throw new Error("Document with errors cannot be stringified"); + if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s2 = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s2}`); + } + return stringifyDocument(this, options); + } + }; + function assertCollection(contents) { + if (isCollection(contents)) + return true; + throw new Error("Expected a YAML collection as document contents"); + } + + // node_modules/yaml/browser/dist/errors.js + var YAMLError = class extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } + }; + var YAMLParseError = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLParseError", pos, code, message); + } + }; + var YAMLWarning = class extends YAMLError { + constructor(pos, code, message) { + super("YAMLWarning", pos, code, message); + } + }; + var prettifyError = (src, lc) => (error) => { + if (error.pos[0] === -1) + return; + error.linePos = error.pos.map((pos) => lc.linePos(pos)); + const { line, col } = error.linePos[0]; + error.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = "\u2026" + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) + lineStr = lineStr.substring(0, 79) + "\u2026"; + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) + prev = prev.substring(0, 79) + "\u2026\n"; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count3 = 1; + const end = error.linePos[1]; + if (end?.line === line && end.col > col) { + count3 = Math.max(1, Math.min(end.col - col, 80 - ci)); + } + const pointer = " ".repeat(ci) + "^".repeat(count3); + error.message += `: + +${lineStr} +${pointer} +`; + } + }; + + // node_modules/yaml/browser/dist/compose/resolve-props.js + function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ""; + let commentSep = ""; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") + onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + reqSpace = false; + } + if (tab) { + if (atNewline && token.type !== "comment" && token.type !== "newline") { + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + } + tab = null; + } + switch (token.type) { + case "space": + if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes(" ")) { + tab = token; + } + hasSpace = true; + break; + case "comment": { + if (!hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = token.source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += commentSep + cb; + commentSep = ""; + atNewline = false; + break; + } + case "newline": + if (atNewline) { + if (comment) + comment += token.source; + else if (!found || indicator !== "seq-item-ind") + spaceBefore = true; + } else + commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) + newlineAfterProp = token; + hasSpace = true; + break; + case "anchor": + if (anchor) + onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); + if (token.source.endsWith(":")) + onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); + anchor = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case "tag": { + if (tag) + onError(token, "MULTIPLE_TAGS", "A node can have at most one tag"); + tag = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + } + case indicator: + if (anchor || tag) + onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); + if (found) + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); + found = token; + atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; + hasSpace = false; + break; + case "comma": + if (flow) { + if (comma) + onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + // else fallthrough + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last2 = tokens[tokens.length - 1]; + const end = last2 ? last2.offset + last2.source.length : offset; + if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) { + onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + } + if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq")) + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + anchor, + tag, + newlineAfterProp, + end, + start: start ?? end + }; + } + + // node_modules/yaml/browser/dist/compose/util-contains-newline.js + function containsNewline(key) { + if (!key) + return null; + switch (key.type) { + case "alias": + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + if (key.source.includes("\n")) + return true; + if (key.end) { + for (const st of key.end) + if (st.type === "newline") + return true; + } + return false; + case "flow-collection": + for (const it of key.items) { + for (const st of it.start) + if (st.type === "newline") + return true; + if (it.sep) { + for (const st of it.sep) + if (st.type === "newline") + return true; + } + if (containsNewline(it.key) || containsNewline(it.value)) + return true; + } + return false; + default: + return true; + } + } + + // node_modules/yaml/browser/dist/compose/util-flow-indent-check.js + function flowIndentCheck(indent, fc, onError) { + if (fc?.type === "flow-collection") { + const end = fc.end[0]; + if (end.indent === indent && (end.source === "]" || end.source === "}") && containsNewline(fc)) { + const msg = "Flow end indicator should be more indented than parent"; + onError(end, "BAD_INDENT", msg, true); + } + } + } + + // node_modules/yaml/browser/dist/compose/util-map-includes.js + function mapIncludes(ctx, items, search3) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) + return false; + const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a2, b3) => a2 === b3 || isScalar(a2) && isScalar(b3) && a2.value === b3.value; + return items.some((pair) => isEqual(pair.key, search3)); + } + + // node_modules/yaml/browser/dist/compose/resolve-block-map.js + var startColMsg = "All mapping items must start at the same column"; + function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bm, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLMap; + const map2 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start, key, sep, value } = collItem; + const keyProps = resolveProps(start, { + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: bm.indent, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === "block-seq") + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); + else if ("indent" in key && key.indent !== bm.indent) + onError(offset, "BAD_INDENT", startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) { + if (map2.comment) + map2.comment += "\n" + keyProps.comment; + else + map2.comment = keyProps.comment; + } + continue; + } + if (keyProps.newlineAfterProp || containsNewline(key)) { + onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); + } + } else if (keyProps.found?.indent !== bm.indent) { + onError(offset, "BAD_INDENT", startColMsg); + } + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key ? composeNode2(ctx, key, keyProps, onError) : composeEmptyNode2(ctx, keyStart, start, null, keyProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, key, onError); + ctx.atKey = false; + if (mapIncludes(ctx, map2.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + const valueProps = resolveProps(sep ?? [], { + indicator: "map-value-ind", + next: value, + offset: keyNode.range[2], + onError, + parentIndent: bm.indent, + startOnNewline: !key || key.type === "block-scalar" + }); + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if (value?.type === "block-map" && !valueProps.hasNewline) + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); + if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) + onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); + } + const valueNode = value ? composeNode2(ctx, value, valueProps, onError) : composeEmptyNode2(ctx, offset, sep, null, valueProps, onError); + if (ctx.schema.compat) + flowIndentCheck(bm.indent, value, onError); + offset = valueNode.range[2]; + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map2.items.push(pair); + } else { + if (implicitKey) + onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); + if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map2.items.push(pair); + } + } + if (commentEnd && commentEnd < offset) + onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); + map2.range = [bm.offset, offset, commentEnd ?? offset]; + return map2; + } + + // node_modules/yaml/browser/dist/compose/resolve-block-seq.js + function resolveBlockSeq({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bs, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLSeq; + const seq2 = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start, value } of bs.items) { + const props = resolveProps(start, { + indicator: "seq-item-ind", + next: value, + offset, + onError, + parentIndent: bs.indent, + startOnNewline: true + }); + if (!props.found) { + if (props.anchor || props.tag || value) { + if (value?.type === "block-seq") + onError(props.end, "BAD_INDENT", "All sequence items must start at the same column"); + else + onError(offset, "MISSING_CHAR", "Sequence item without - indicator"); + } else { + commentEnd = props.end; + if (props.comment) + seq2.comment = props.comment; + continue; + } + } + const node = value ? composeNode2(ctx, value, props, onError) : composeEmptyNode2(ctx, props.end, start, null, props, onError); + if (ctx.schema.compat) + flowIndentCheck(bs.indent, value, onError); + offset = node.range[2]; + seq2.items.push(node); + } + seq2.range = [bs.offset, offset, commentEnd ?? offset]; + return seq2; + } + + // node_modules/yaml/browser/dist/compose/resolve-end.js + function resolveEnd(end, offset, reqSpace, onError) { + let comment = ""; + if (end) { + let hasSpace = false; + let sep = ""; + for (const token of end) { + const { source, type } = token; + switch (type) { + case "space": + hasSpace = true; + break; + case "comment": { + if (reqSpace && !hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += sep + cb; + sep = ""; + break; + } + case "newline": + if (comment) + sep += source; + hasSpace = true; + break; + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); + } + offset += source.length; + } + } + return { comment, offset }; + } + + // node_modules/yaml/browser/dist/compose/resolve-flow-collection.js + var blockMsg = "Block collections are not allowed within flow collections"; + var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); + function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, fc, onError, tag) { + const isMap2 = fc.start.source === "{"; + const fcName = isMap2 ? "flow map" : "flow sequence"; + const NodeClass = tag?.nodeClass ?? (isMap2 ? YAMLMap : YAMLSeq); + const coll = new NodeClass(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = fc.offset + fc.start.source.length; + for (let i2 = 0; i2 < fc.items.length; ++i2) { + const collItem = fc.items[i2]; + const { start, key, sep, value } = collItem; + const props = resolveProps(start, { + flow: fcName, + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value) { + if (i2 === 0 && props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + else if (i2 < fc.items.length - 1) + onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); + if (props.comment) { + if (coll.comment) + coll.comment += "\n" + props.comment; + else + coll.comment = props.comment; + } + offset = props.end; + continue; + } + if (!isMap2 && ctx.options.strict && containsNewline(key)) + onError( + key, + // checked by containsNewline() + "MULTILINE_IMPLICIT_KEY", + "Implicit keys of flow sequence pairs need to be on a single line" + ); + } + if (i2 === 0) { + if (props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + } else { + if (!props.comma) + onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ""; + loop: for (const st of start) { + switch (st.type) { + case "comma": + case "space": + break; + case "comment": + prevItemComment = st.source.substring(1); + break loop; + default: + break loop; + } + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (isPair(prev)) + prev = prev.value ?? prev.key; + if (prev.comment) + prev.comment += "\n" + prevItemComment; + else + prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap2 && !sep && !props.found) { + const valueNode = value ? composeNode2(ctx, value, props, onError) : composeEmptyNode2(ctx, props.end, sep, null, props, onError); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock(value)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else { + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key ? composeNode2(ctx, key, props, onError) : composeEmptyNode2(ctx, keyStart, start, null, props, onError); + if (isBlock(key)) + onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg); + ctx.atKey = false; + const valueProps = resolveProps(sep ?? [], { + flow: fcName, + indicator: "map-value-ind", + next: value, + offset: keyNode.range[2], + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap2 && !props.found && ctx.options.strict) { + if (sep) + for (const st of sep) { + if (st === valueProps.found) + break; + if (st.type === "newline") { + onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + break; + } + } + if (props.start < valueProps.found.offset - 1024) + onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); + } + } else if (value) { + if ("source" in value && value.source?.[0] === ":") + onError(value, "MISSING_CHAR", `Missing space after : in ${fcName}`); + else + onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); + } + const valueNode = value ? composeNode2(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep, null, valueProps, onError) : null; + if (valueNode) { + if (isBlock(value)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += "\n" + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + if (isMap2) { + const map2 = coll; + if (mapIncludes(ctx, map2.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + map2.items.push(pair); + } else { + const map2 = new YAMLMap(ctx.schema); + map2.flow = true; + map2.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map2.range = [keyNode.range[0], endRange[1], endRange[2]]; + coll.items.push(map2); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap2 ? "}" : "]"; + const [ce2, ...ee] = fc.end; + let cePos = offset; + if (ce2?.source === expectedEnd) + cePos = ce2.offset + ce2.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); + if (ce2 && ce2.source.length !== 1) + ee.unshift(ce2); + } + if (ee.length > 0) { + const end = resolveEnd(ee, cePos, ctx.options.strict, onError); + if (end.comment) { + if (coll.comment) + coll.comment += "\n" + end.comment; + else + coll.comment = end.comment; + } + coll.range = [fc.offset, cePos, end.offset]; + } else { + coll.range = [fc.offset, cePos, cePos]; + } + return coll; + } + + // node_modules/yaml/browser/dist/compose/compose-collection.js + function resolveCollection(CN2, ctx, token, onError, tagName, tag) { + const coll = token.type === "block-map" ? resolveBlockMap(CN2, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq(CN2, ctx, token, onError, tag) : resolveFlowCollection(CN2, ctx, token, onError, tag); + const Coll = coll.constructor; + if (tagName === "!" || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) + coll.tag = tagName; + return coll; + } + function composeCollection(CN2, ctx, token, props, onError) { + const tagToken = props.tag; + const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)); + if (token.type === "block-seq") { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; + if (lastProp && (!nl || nl.offset < lastProp.offset)) { + const message = "Missing newline after block sequence props"; + onError(lastProp, "MISSING_CHAR", message); + } + } + const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; + if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.tagName && expType === "seq") { + return resolveCollection(CN2, ctx, token, onError, tagName); + } + let tag = ctx.schema.tags.find((t2) => t2.tag === tagName && t2.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt?.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } else { + if (kt) { + onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true); + } else { + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); + } + return resolveCollection(CN2, ctx, token, onError, tagName); + } + } + const coll = resolveCollection(CN2, ctx, token, onError, tagName, tag); + const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll; + const node = isNode3(res) ? res : new Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag?.format) + node.format = tag.format; + return node; + } + + // node_modules/yaml/browser/dist/compose/resolve-block-scalar.js + function resolveBlockScalar(ctx, scalar, onError) { + const start = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); + if (!header) + return { value: "", type: null, comment: "", range: [start, start, start] }; + const type = header.mode === ">" ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL; + const lines = scalar.source ? splitLines(scalar.source) : []; + let chompStart = lines.length; + for (let i2 = lines.length - 1; i2 >= 0; --i2) { + const content = lines[i2][1]; + if (content === "" || content === "\r") + chompStart = i2; + else + break; + } + if (chompStart === 0) { + const value2 = header.chomp === "+" && lines.length > 0 ? "\n".repeat(Math.max(1, lines.length - 1)) : ""; + let end2 = start + header.length; + if (scalar.source) + end2 += scalar.source.length; + return { value: value2, type, comment: header.comment, range: [start, end2, end2] }; + } + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i2 = 0; i2 < chompStart; ++i2) { + const [indent, content] = lines[i2]; + if (content === "" || content === "\r") { + if (header.indent === 0 && indent.length > trimIndent) + trimIndent = indent.length; + } else { + if (indent.length < trimIndent) { + const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"; + onError(offset + indent.length, "MISSING_CHAR", message); + } + if (header.indent === 0) + trimIndent = indent.length; + contentStart = i2; + if (trimIndent === 0 && !ctx.atRoot) { + const message = "Block scalar values in collections must be indented"; + onError(offset, "BAD_INDENT", message); + } + break; + } + offset += indent.length + content.length + 1; + } + for (let i2 = lines.length - 1; i2 >= chompStart; --i2) { + if (lines[i2][0].length > trimIndent) + chompStart = i2 + 1; + } + let value = ""; + let sep = ""; + let prevMoreIndented = false; + for (let i2 = 0; i2 < contentStart; ++i2) + value += lines[i2][0].slice(trimIndent) + "\n"; + for (let i2 = contentStart; i2 < chompStart; ++i2) { + let [indent, content] = lines[i2]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === "\r"; + if (crlf) + content = content.slice(0, -1); + if (content && indent.length < trimIndent) { + const src = header.indent ? "explicit indentation indicator" : "first line"; + const message = `Block scalar lines must not be less indented than their ${src}`; + onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); + indent = ""; + } + if (type === Scalar.BLOCK_LITERAL) { + value += sep + indent.slice(trimIndent) + content; + sep = "\n"; + } else if (indent.length > trimIndent || content[0] === " ") { + if (sep === " ") + sep = "\n"; + else if (!prevMoreIndented && sep === "\n") + sep = "\n\n"; + value += sep + indent.slice(trimIndent) + content; + sep = "\n"; + prevMoreIndented = true; + } else if (content === "") { + if (sep === "\n") + value += "\n"; + else + sep = "\n"; + } else { + value += sep + content; + sep = " "; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case "-": + break; + case "+": + for (let i2 = chompStart; i2 < lines.length; ++i2) + value += "\n" + lines[i2][0].slice(trimIndent); + if (value[value.length - 1] !== "\n") + value += "\n"; + break; + default: + value += "\n"; + } + const end = start + header.length + scalar.source.length; + return { value, type, comment: header.comment, range: [start, end, end] }; + } + function parseBlockScalarHeader({ offset, props }, strict, onError) { + if (props[0].type !== "block-scalar-header") { + onError(props[0], "IMPOSSIBLE", "Block scalar header not found"); + return null; + } + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ""; + let error = -1; + for (let i2 = 1; i2 < source.length; ++i2) { + const ch = source[i2]; + if (!chomp && (ch === "-" || ch === "+")) + chomp = ch; + else { + const n2 = Number(ch); + if (!indent && n2) + indent = n2; + else if (error === -1) + error = offset + i2; + } + } + if (error !== -1) + onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ""; + let length = source.length; + for (let i2 = 1; i2 < props.length; ++i2) { + const token = props[i2]; + switch (token.type) { + case "space": + hasSpace = true; + // fallthrough + case "newline": + length += token.source.length; + break; + case "comment": + if (strict && !hasSpace) { + const message = "Comments must be separated from other tokens by white space characters"; + onError(token, "MISSING_CHAR", message); + } + length += token.source.length; + comment = token.source.substring(1); + break; + case "error": + onError(token, "UNEXPECTED_TOKEN", token.message); + length += token.source.length; + break; + /* istanbul ignore next should not happen */ + default: { + const message = `Unexpected token in block scalar header: ${token.type}`; + onError(token, "UNEXPECTED_TOKEN", message); + const ts = token.source; + if (ts && typeof ts === "string") + length += ts.length; + } + } + } + return { mode, indent, chomp, comment, length }; + } + function splitLines(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m3 = first.match(/^( *)/); + const line0 = m3?.[1] ? [m3[1], first.slice(m3[1].length)] : ["", first]; + const lines = [line0]; + for (let i2 = 1; i2 < split.length; i2 += 2) + lines.push([split[i2], split[i2 + 1]]); + return lines; + } + + // node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js + function resolveFlowScalar(scalar, strict, onError) { + const { offset, type, source, end } = scalar; + let _type; + let value; + const _onError = (rel, code, msg) => onError(offset + rel, code, msg); + switch (type) { + case "scalar": + _type = Scalar.PLAIN; + value = plainValue(source, _onError); + break; + case "single-quoted-scalar": + _type = Scalar.QUOTE_SINGLE; + value = singleQuotedValue(source, _onError); + break; + case "double-quoted-scalar": + _type = Scalar.QUOTE_DOUBLE; + value = doubleQuotedValue(source, _onError); + break; + /* istanbul ignore next should not happen */ + default: + onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); + return { + value: "", + type: null, + comment: "", + range: [offset, offset + source.length, offset + source.length] + }; + } + const valueEnd = offset + source.length; + const re2 = resolveEnd(end, valueEnd, strict, onError); + return { + value, + type: _type, + comment: re2.comment, + range: [offset, valueEnd, re2.offset] + }; + } + function plainValue(source, onError) { + let badChar = ""; + switch (source[0]) { + /* istanbul ignore next should not happen */ + case " ": + badChar = "a tab character"; + break; + case ",": + badChar = "flow indicator character ,"; + break; + case "%": + badChar = "directive indicator character %"; + break; + case "|": + case ">": { + badChar = `block scalar indicator ${source[0]}`; + break; + } + case "@": + case "`": { + badChar = `reserved character ${source[0]}`; + break; + } + } + if (badChar) + onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); + return foldLines(source); + } + function singleQuotedValue(source, onError) { + if (source[source.length - 1] !== "'" || source.length === 1) + onError(source.length, "MISSING_CHAR", "Missing closing 'quote"); + return foldLines(source.slice(1, -1)).replace(/''/g, "'"); + } + function foldLines(source) { + let first, line; + try { + first = new RegExp("(.*?)(? wsStart ? source.slice(wsStart, i2 + 1) : ch; + } else { + res += ch; + } + } + if (source[source.length - 1] !== '"' || source.length === 1) + onError(source.length, "MISSING_CHAR", 'Missing closing "quote'); + return res; + } + function foldNewline(source, offset) { + let fold = ""; + let ch = source[offset + 1]; + while (ch === " " || ch === " " || ch === "\n" || ch === "\r") { + if (ch === "\r" && source[offset + 2] !== "\n") + break; + if (ch === "\n") + fold += "\n"; + offset += 1; + ch = source[offset + 1]; + } + if (!fold) + fold = " "; + return { fold, offset }; + } + var escapeCodes = { + "0": "\0", + // null character + a: "\x07", + // bell character + b: "\b", + // backspace + e: "\x1B", + // escape character + f: "\f", + // form feed + n: "\n", + // line feed + r: "\r", + // carriage return + t: " ", + // horizontal tab + v: "\v", + // vertical tab + N: "\x85", + // Unicode next line + _: "\xA0", + // Unicode non-breaking space + L: "\u2028", + // Unicode line separator + P: "\u2029", + // Unicode paragraph separator + " ": " ", + '"': '"', + "/": "/", + "\\": "\\", + " ": " " + }; + function parseCharCode(source, offset, length, onError) { + const cc = source.substr(offset, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + try { + return String.fromCodePoint(code); + } catch { + const raw = source.substr(offset - 2, length + 2); + onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`); + return raw; + } + } + + // node_modules/yaml/browser/dist/compose/compose-scalar.js + function composeScalar(ctx, token, tagToken, onError) { + const { value, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar(ctx, token, onError) : resolveFlowScalar(token, ctx.options.strict, onError); + const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) { + tag = ctx.schema[SCALAR]; + } else if (tagName) + tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError); + else if (token.type === "scalar") + tag = findScalarTagByTest(ctx, value, token, onError); + else + tag = ctx.schema[SCALAR]; + let scalar; + try { + const res = tag.resolve(value, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); + scalar = isScalar(res) ? res : new Scalar(res); + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); + scalar = new Scalar(value); + } + scalar.range = range; + scalar.source = value; + if (type) + scalar.type = type; + if (tagName) + scalar.tag = tagName; + if (tag.format) + scalar.format = tag.format; + if (comment) + scalar.comment = comment; + return scalar; + } + function findScalarTagByName(schema4, value, tagName, tagToken, onError) { + if (tagName === "!") + return schema4[SCALAR]; + const matchWithTest = []; + for (const tag of schema4.tags) { + if (!tag.collection && tag.tag === tagName) { + if (tag.default && tag.test) + matchWithTest.push(tag); + else + return tag; + } + } + for (const tag of matchWithTest) + if (tag.test?.test(value)) + return tag; + const kt = schema4.knownTags[tagName]; + if (kt && !kt.collection) { + schema4.tags.push(Object.assign({}, kt, { default: false, test: void 0 })); + return kt; + } + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); + return schema4[SCALAR]; + } + function findScalarTagByTest({ atKey, directives, schema: schema4 }, value, token, onError) { + const tag = schema4.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value)) || schema4[SCALAR]; + if (schema4.compat) { + const compat = schema4.compat.find((tag2) => tag2.default && tag2.test?.test(value)) ?? schema4[SCALAR]; + if (tag.tag !== compat.tag) { + const ts = directives.tagString(tag.tag); + const cs = directives.tagString(compat.tag); + const msg = `Value may be parsed as either ${ts} or ${cs}`; + onError(token, "TAG_RESOLVE_FAILED", msg, true); + } + } + return tag; + } + + // node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js + function emptyScalarPosition(offset, before, pos) { + if (before) { + pos ?? (pos = before.length); + for (let i2 = pos - 1; i2 >= 0; --i2) { + let st = before[i2]; + switch (st.type) { + case "space": + case "comment": + case "newline": + offset -= st.source.length; + continue; + } + st = before[++i2]; + while (st?.type === "space") { + offset += st.source.length; + st = before[++i2]; + } + break; + } + } + return offset; + } + + // node_modules/yaml/browser/dist/compose/compose-node.js + var CN = { composeNode, composeEmptyNode }; + function composeNode(ctx, token, props, onError) { + const atKey = ctx.atKey; + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case "alias": + node = composeAlias(ctx, token, onError); + if (anchor || tag) + onError(token, "ALIAS_PROPS", "An alias node must not specify any properties"); + break; + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "block-scalar": + node = composeScalar(ctx, token, tag, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + case "block-map": + case "block-seq": + case "flow-collection": + try { + node = composeCollection(CN, ctx, token, props, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + onError(token, "RESOURCE_EXHAUSTION", message); + } + break; + default: { + const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`; + onError(token, "UNEXPECTED_TOKEN", message); + isSrcToken = false; + } + } + node ?? (node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError)); + if (anchor && node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + if (atKey && ctx.options.stringKeys && (!isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) { + const msg = "With stringKeys, all keys must be strings"; + onError(tag ?? token, "NON_STRING_KEY", msg); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + if (token.type === "scalar" && token.source === "") + node.comment = comment; + else + node.commentBefore = comment; + } + if (ctx.options.keepSourceTokens && isSrcToken) + node.srcToken = token; + return node; + } + function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) { + const token = { + type: "scalar", + offset: emptyScalarPosition(offset, before, pos), + indent: -1, + source: "" + }; + const node = composeScalar(ctx, token, tag, onError); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end; + } + return node; + } + function composeAlias({ options }, { offset, source, end }, onError) { + const alias = new Alias(source.substring(1)); + if (alias.source === "") + onError(offset, "BAD_ALIAS", "Alias cannot be an empty string"); + if (alias.source.endsWith(":")) + onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); + const valueEnd = offset + source.length; + const re2 = resolveEnd(end, valueEnd, options.strict, onError); + alias.range = [offset, valueEnd, re2.offset]; + if (re2.comment) + alias.comment = re2.comment; + return alias; + } + + // node_modules/yaml/browser/dist/compose/compose-doc.js + function composeDoc(options, directives, { offset, start, value, end }, onError) { + const opts = Object.assign({ _directives: directives }, options); + const doc = new Document(void 0, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc.directives, + options: doc.options, + schema: doc.schema + }; + const props = resolveProps(start, { + indicator: "doc-start", + next: value ?? end?.[0], + offset, + onError, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc.directives.docStart = true; + if (value && (value.type === "block-map" || value.type === "block-seq") && !props.hasNewline) + onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); + } + doc.contents = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError); + const contentEnd = doc.contents.range[2]; + const re2 = resolveEnd(end, contentEnd, false, onError); + if (re2.comment) + doc.comment = re2.comment; + doc.range = [offset, contentEnd, re2.offset]; + return doc; + } + + // node_modules/yaml/browser/dist/compose/composer.js + function getErrorPos(src) { + if (typeof src === "number") + return [src, src + 1]; + if (Array.isArray(src)) + return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === "string" ? source.length : 1)]; + } + function parsePrelude(prelude) { + let comment = ""; + let atComment = false; + let afterEmptyLine = false; + for (let i2 = 0; i2 < prelude.length; ++i2) { + const source = prelude[i2]; + switch (source[0]) { + case "#": + comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " "); + atComment = true; + afterEmptyLine = false; + break; + case "%": + if (prelude[i2 + 1]?.[0] !== "#") + i2 += 1; + atComment = false; + break; + default: + if (!atComment) + afterEmptyLine = true; + atComment = false; + } + } + return { comment, afterEmptyLine }; + } + var Composer = class { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) + this.warnings.push(new YAMLWarning(pos, code, message)); + else + this.errors.push(new YAMLParseError(pos, code, message)); + }; + this.directives = new Directives({ version: options.version || "1.2" }); + this.options = options; + } + decorate(doc, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + if (comment) { + const dc = doc.contents; + if (afterDoc) { + doc.comment = doc.comment ? `${doc.comment} +${comment}` : comment; + } else if (afterEmptyLine || doc.directives.docStart || !dc) { + doc.commentBefore = comment; + } else if (isCollection(dc) && !dc.flow && dc.items.length > 0) { + let it = dc.items[0]; + if (isPair(it)) + it = it.key; + const cb = it.commentBefore; + it.commentBefore = cb ? `${comment} +${cb}` : comment; + } else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment} +${cb}` : comment; + } + } + if (afterDoc) { + Array.prototype.push.apply(doc.errors, this.errors); + Array.prototype.push.apply(doc.warnings, this.warnings); + } else { + doc.errors = this.errors; + doc.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + /** + * Current stream status information. + * + * Mostly useful at the end of input for an empty stream. + */ + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + /** + * Compose tokens into documents. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) + yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + /** Advance the composer by one CST token. */ + *next(token) { + switch (token.type) { + case "directive": + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, "BAD_DIRECTIVE", message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case "document": { + const doc = composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc.directives.docStart) + this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); + this.decorate(doc, false); + if (this.doc) + yield this.doc; + this.doc = doc; + this.atDirectives = false; + break; + } + case "byte-order-mark": + case "space": + break; + case "comment": + case "newline": + this.prelude.push(token.source); + break; + case "error": { + const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; + const error = new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); + if (this.atDirectives || !this.doc) + this.errors.push(error); + else + this.doc.errors.push(error); + break; + } + case "doc-end": { + if (!this.doc) { + const msg = "Unexpected doc-end without preceding document"; + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg)); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc} +${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: + this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); + } + } + /** + * Call at end of input to yield any remaining document. + * + * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. + * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. + */ + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc = new Document(void 0, opts); + if (this.atDirectives) + this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); + doc.range = [0, endOffset, endOffset]; + this.decorate(doc, false); + yield doc; + } + } + }; + + // node_modules/yaml/browser/dist/parse/cst.js + var cst_exports = {}; + __export(cst_exports, { + BOM: () => BOM, + DOCUMENT: () => DOCUMENT, + FLOW_END: () => FLOW_END, + SCALAR: () => SCALAR2, + createScalarToken: () => createScalarToken, + isCollection: () => isCollection2, + isScalar: () => isScalar2, + prettyToken: () => prettyToken, + resolveAsScalar: () => resolveAsScalar, + setScalarValue: () => setScalarValue, + stringify: () => stringify2, + tokenType: () => tokenType, + visit: () => visit2 + }); + + // node_modules/yaml/browser/dist/parse/cst-scalar.js + function resolveAsScalar(token, strict = true, onError) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError) + onError(offset, code, message); + else + throw new YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return resolveFlowScalar(token, strict, _onError); + case "block-scalar": + return resolveBlockScalar({ options: { strict } }, token, _onError); + } + } + return null; + } + function createScalarToken(value, context) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context; + const source = stringifyString({ type, value }, { + implicitKey, + indent: indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + const end = context.end ?? [ + { type: "newline", offset: -1, indent, source: "\n" } + ]; + switch (source[0]) { + case "|": + case ">": { + const he2 = source.indexOf("\n"); + const head = source.substring(0, he2); + const body = source.substring(he2 + 1) + "\n"; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, end)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + return { type: "block-scalar", offset, indent, props, source: body }; + } + case '"': + return { type: "double-quoted-scalar", offset, indent, source, end }; + case "'": + return { type: "single-quoted-scalar", offset, indent, source, end }; + default: + return { type: "scalar", offset, indent, source, end }; + } + } + function setScalarValue(token, value, context = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context; + let indent = "indent" in token ? token.indent : null; + if (afterKey && typeof indent === "number") + indent += 2; + if (!type) + switch (token.type) { + case "single-quoted-scalar": + type = "QUOTE_SINGLE"; + break; + case "double-quoted-scalar": + type = "QUOTE_DOUBLE"; + break; + case "block-scalar": { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; + break; + } + default: + type = "PLAIN"; + } + const source = stringifyString({ type, value }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + switch (source[0]) { + case "|": + case ">": + setBlockScalarValue(token, source); + break; + case '"': + setFlowScalarValue(token, source, "double-quoted-scalar"); + break; + case "'": + setFlowScalarValue(token, source, "single-quoted-scalar"); + break; + default: + setFlowScalarValue(token, source, "scalar"); + } + } + function setBlockScalarValue(token, source) { + const he2 = source.indexOf("\n"); + const head = source.substring(0, he2); + const body = source.substring(he2 + 1) + "\n"; + if (token.type === "block-scalar") { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + header.source = head; + token.source = body; + } else { + const { offset } = token; + const indent = "indent" in token ? token.indent : -1; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0)) + props.push({ type: "newline", offset: -1, indent, source: "\n" }); + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type: "block-scalar", indent, props, source: body }); + } + } + function addEndtoBlockProps(props, end) { + if (end) + for (const st of end) + switch (st.type) { + case "space": + case "comment": + props.push(st); + break; + case "newline": + props.push(st); + return true; + } + return false; + } + function setFlowScalarValue(token, source, type) { + switch (token.type) { + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + token.type = type; + token.source = source; + break; + case "block-scalar": { + const end = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === "block-scalar-header") + oa -= token.props[0].source.length; + for (const tok of end) + tok.offset += oa; + delete token.props; + Object.assign(token, { type, source, end }); + break; + } + case "block-map": + case "block-seq": { + const offset = token.offset + source.length; + const nl = { type: "newline", offset, indent: token.indent, source: "\n" }; + delete token.items; + Object.assign(token, { type, source, end: [nl] }); + break; + } + default: { + const indent = "indent" in token ? token.indent : -1; + const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type, indent, source, end }); + } + } + } + + // node_modules/yaml/browser/dist/parse/cst-stringify.js + var stringify2 = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst); + function stringifyToken(token) { + switch (token.type) { + case "block-scalar": { + let res = ""; + for (const tok of token.props) + res += stringifyToken(tok); + return res + token.source; + } + case "block-map": + case "block-seq": { + let res = ""; + for (const item of token.items) + res += stringifyItem(item); + return res; + } + case "flow-collection": { + let res = token.start.source; + for (const item of token.items) + res += stringifyItem(item); + for (const st of token.end) + res += st.source; + return res; + } + case "document": { + let res = stringifyItem(token); + if (token.end) + for (const st of token.end) + res += st.source; + return res; + } + default: { + let res = token.source; + if ("end" in token && token.end) + for (const st of token.end) + res += st.source; + return res; + } + } + } + function stringifyItem({ start, key, sep, value }) { + let res = ""; + for (const st of start) + res += st.source; + if (key) + res += stringifyToken(key); + if (sep) + for (const st of sep) + res += st.source; + if (value) + res += stringifyToken(value); + return res; + } + + // node_modules/yaml/browser/dist/parse/cst-visit.js + var BREAK2 = Symbol("break visit"); + var SKIP2 = Symbol("skip children"); + var REMOVE2 = Symbol("remove item"); + function visit2(cst, visitor) { + if ("type" in cst && cst.type === "document") + cst = { start: cst.start, value: cst.value }; + _visit(Object.freeze([]), cst, visitor); + } + visit2.BREAK = BREAK2; + visit2.SKIP = SKIP2; + visit2.REMOVE = REMOVE2; + visit2.itemAtPath = (cst, path) => { + let item = cst; + for (const [field, index2] of path) { + const tok = item?.[field]; + if (tok && "items" in tok) { + item = tok.items[index2]; + } else + return void 0; + } + return item; + }; + visit2.parentCollection = (cst, path) => { + const parent = visit2.itemAtPath(cst, path.slice(0, -1)); + const field = path[path.length - 1][0]; + const coll = parent?.[field]; + if (coll && "items" in coll) + return coll; + throw new Error("Parent collection not found"); + }; + function _visit(path, item, visitor) { + let ctrl = visitor(item, path); + if (typeof ctrl === "symbol") + return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i2 = 0; i2 < token.items.length; ++i2) { + const ci = _visit(Object.freeze(path.concat([[field, i2]])), token.items[i2], visitor); + if (typeof ci === "number") + i2 = ci - 1; + else if (ci === BREAK2) + return BREAK2; + else if (ci === REMOVE2) { + token.items.splice(i2, 1); + i2 -= 1; + } + } + if (typeof ctrl === "function" && field === "key") + ctrl = ctrl(item, path); + } + } + return typeof ctrl === "function" ? ctrl(item, path) : ctrl; + } + + // node_modules/yaml/browser/dist/parse/cst.js + var BOM = "\uFEFF"; + var DOCUMENT = ""; + var FLOW_END = ""; + var SCALAR2 = ""; + var isCollection2 = (token) => !!token && "items" in token; + var isScalar2 = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); + function prettyToken(token) { + switch (token) { + case BOM: + return ""; + case DOCUMENT: + return ""; + case FLOW_END: + return ""; + case SCALAR2: + return ""; + default: + return JSON.stringify(token); + } + } + function tokenType(source) { + switch (source) { + case BOM: + return "byte-order-mark"; + case DOCUMENT: + return "doc-mode"; + case FLOW_END: + return "flow-error-end"; + case SCALAR2: + return "scalar"; + case "---": + return "doc-start"; + case "...": + return "doc-end"; + case "": + case "\n": + case "\r\n": + return "newline"; + case "-": + return "seq-item-ind"; + case "?": + return "explicit-key-ind"; + case ":": + return "map-value-ind"; + case "{": + return "flow-map-start"; + case "}": + return "flow-map-end"; + case "[": + return "flow-seq-start"; + case "]": + return "flow-seq-end"; + case ",": + return "comma"; + } + switch (source[0]) { + case " ": + case " ": + return "space"; + case "#": + return "comment"; + case "%": + return "directive-line"; + case "*": + return "alias"; + case "&": + return "anchor"; + case "!": + return "tag"; + case "'": + return "single-quoted-scalar"; + case '"': + return "double-quoted-scalar"; + case "|": + case ">": + return "block-scalar-header"; + } + return null; + } + + // node_modules/yaml/browser/dist/parse/lexer.js + function isEmpty(ch) { + switch (ch) { + case void 0: + case " ": + case "\n": + case "\r": + case " ": + return true; + default: + return false; + } + } + var hexDigits = new Set("0123456789ABCDEFabcdef"); + var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); + var flowIndicatorChars = new Set(",[]{}"); + var invalidAnchorChars = new Set(" ,[]{}\n\r "); + var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); + var Lexer = class { + constructor() { + this.atEnd = false; + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + this.buffer = ""; + this.flowKey = false; + this.flowLevel = 0; + this.indentNext = 0; + this.indentValue = 0; + this.lineEndPos = null; + this.next = null; + this.pos = 0; + } + /** + * Generate YAML tokens from the `source` string. If `incomplete`, + * a part of the last line may be left as a buffer for the next call. + * + * @returns A generator of lexical tokens + */ + *lex(source, incomplete = false) { + if (source) { + if (typeof source !== "string") + throw TypeError("source is not a string"); + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next = this.next ?? "stream"; + while (next && (incomplete || this.hasChars(1))) + next = yield* this.parseNext(next); + } + atLineEnd() { + let i2 = this.pos; + let ch = this.buffer[i2]; + while (ch === " " || ch === " ") + ch = this.buffer[++i2]; + if (!ch || ch === "#" || ch === "\n") + return true; + if (ch === "\r") + return this.buffer[i2 + 1] === "\n"; + return false; + } + charAt(n2) { + return this.buffer[this.pos + n2]; + } + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === " ") + ch = this.buffer[++indent + offset]; + if (ch === "\r") { + const next = this.buffer[indent + offset + 1]; + if (next === "\n" || !next && !this.atEnd) + return offset + indent + 1; + } + return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; + } + if (ch === "-" || ch === ".") { + const dt = this.buffer.substr(offset, 3); + if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3])) + return -1; + } + return offset; + } + getLine() { + let end = this.lineEndPos; + if (typeof end !== "number" || end !== -1 && end < this.pos) { + end = this.buffer.indexOf("\n", this.pos); + this.lineEndPos = end; + } + if (end === -1) + return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === "\r") + end -= 1; + return this.buffer.substring(this.pos, end); + } + hasChars(n2) { + return this.pos + n2 <= this.buffer.length; + } + setNext(state) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state; + return null; + } + peek(n2) { + return this.buffer.substr(this.pos, n2); + } + *parseNext(next) { + switch (next) { + case "stream": + return yield* this.parseStream(); + case "line-start": + return yield* this.parseLineStart(); + case "block-start": + return yield* this.parseBlockStart(); + case "doc": + return yield* this.parseDocument(); + case "flow": + return yield* this.parseFlowCollection(); + case "quoted-scalar": + return yield* this.parseQuotedScalar(); + case "block-scalar": + return yield* this.parseBlockScalar(); + case "plain-scalar": + return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) + return this.setNext("stream"); + if (line[0] === BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === "%") { + let dirEnd = line.length; + let cs = line.indexOf("#"); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === " " || ch === " ") { + dirEnd = cs - 1; + break; + } else { + cs = line.indexOf("#", cs + 1); + } + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === " " || ch === " ") + dirEnd -= 1; + else + break; + } + const n2 = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n2); + this.pushNewline(); + return "stream"; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return "stream"; + } + yield DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) + return this.setNext("line-start"); + if (ch === "-" || ch === ".") { + if (!this.atEnd && !this.hasChars(4)) + return this.setNext("line-start"); + const s2 = this.peek(3); + if ((s2 === "---" || s2 === "...") && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s2 === "---" ? "doc" : "stream"; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) + this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) + return this.setNext("block-start"); + if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) { + const n2 = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n2; + return yield* this.parseBlockStart(); + } + return "doc"; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) + return this.setNext("doc"); + let n2 = yield* this.pushIndicators(); + switch (line[n2]) { + case "#": + yield* this.pushCount(line.length - n2); + // fallthrough + case void 0: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + return "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "doc"; + case '"': + case "'": + return yield* this.parseQuotedScalar(); + case "|": + case ">": + n2 += yield* this.parseBlockScalarHeader(); + n2 += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n2); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: + return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } else { + sp = 0; + } + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) + return this.setNext("flow"); + if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) { + const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"); + if (!atFlowEndMarker) { + this.flowLevel = 0; + yield FLOW_END; + return yield* this.parseLineStart(); + } + } + let n2 = 0; + while (line[n2] === ",") { + n2 += yield* this.pushCount(1); + n2 += yield* this.pushSpaces(true); + this.flowKey = false; + } + n2 += yield* this.pushIndicators(); + switch (line[n2]) { + case void 0: + return "flow"; + case "#": + yield* this.pushCount(line.length - n2); + return "flow"; + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? "flow" : "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "flow"; + case '"': + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ":": { + const next = this.charAt(1); + if (this.flowKey || isEmpty(next) || next === ",") { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return "flow"; + } + } + // fallthrough + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote = this.charAt(0); + let end = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") { + while (end !== -1 && this.buffer[end + 1] === "'") + end = this.buffer.indexOf("'", end + 2); + } else { + while (end !== -1) { + let n2 = 0; + while (this.buffer[end - 1 - n2] === "\\") + n2 += 1; + if (n2 % 2 === 0) + break; + end = this.buffer.indexOf('"', end + 1); + } + } + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf("\n", this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = qb.indexOf("\n", cs); + } + if (nl !== -1) { + end = nl - (qb[nl - 1] === "\r" ? 2 : 1); + } + } + if (end === -1) { + if (!this.atEnd) + return this.setNext("quoted-scalar"); + end = this.buffer.length; + } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? "flow" : "doc"; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i2 = this.pos; + while (true) { + const ch = this.buffer[++i2]; + if (ch === "+") + this.blockScalarKeep = true; + else if (ch > "0" && ch <= "9") + this.blockScalarIndent = Number(ch) - 1; + else if (ch !== "-") + break; + } + return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#"); + } + *parseBlockScalar() { + let nl = this.pos - 1; + let indent = 0; + let ch; + loop: for (let i3 = this.pos; ch = this.buffer[i3]; ++i3) { + switch (ch) { + case " ": + indent += 1; + break; + case "\n": + nl = i3; + indent = 0; + break; + case "\r": { + const next = this.buffer[i3 + 1]; + if (!next && !this.atEnd) + return this.setNext("block-scalar"); + if (next === "\n") + break; + } + // fallthrough + default: + break loop; + } + } + if (!ch && !this.atEnd) + return this.setNext("block-scalar"); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) + this.indentNext = indent; + else { + this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); + } + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = this.buffer.indexOf("\n", cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) + return this.setNext("block-scalar"); + nl = this.buffer.length; + } + } + let i2 = nl + 1; + ch = this.buffer[i2]; + while (ch === " ") + ch = this.buffer[++i2]; + if (ch === " ") { + while (ch === " " || ch === " " || ch === "\r" || ch === "\n") + ch = this.buffer[++i2]; + nl = i2 - 1; + } else if (!this.blockScalarKeep) { + do { + let i3 = nl - 1; + let ch2 = this.buffer[i3]; + if (ch2 === "\r") + ch2 = this.buffer[--i3]; + const lastChar = i3; + while (ch2 === " ") + ch2 = this.buffer[--i3]; + if (ch2 === "\n" && i3 >= this.pos && i3 + 1 + indent > lastChar) + nl = i3; + else + break; + } while (true); + } + yield SCALAR2; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i2 = this.pos - 1; + let ch; + while (ch = this.buffer[++i2]) { + if (ch === ":") { + const next = this.buffer[i2 + 1]; + if (isEmpty(next) || inFlow && flowIndicatorChars.has(next)) + break; + end = i2; + } else if (isEmpty(ch)) { + let next = this.buffer[i2 + 1]; + if (ch === "\r") { + if (next === "\n") { + i2 += 1; + ch = "\n"; + next = this.buffer[i2 + 1]; + } else + end = i2; + } + if (next === "#" || inFlow && flowIndicatorChars.has(next)) + break; + if (ch === "\n") { + const cs = this.continueScalar(i2 + 1); + if (cs === -1) + break; + i2 = Math.max(i2, cs - 2); + } + } else { + if (inFlow && flowIndicatorChars.has(ch)) + break; + end = i2; + } + } + if (!ch && !this.atEnd) + return this.setNext("plain-scalar"); + yield SCALAR2; + yield* this.pushToIndex(end + 1, true); + return inFlow ? "flow" : "doc"; + } + *pushCount(n2) { + if (n2 > 0) { + yield this.buffer.substr(this.pos, n2); + this.pos += n2; + return n2; + } + return 0; + } + *pushToIndex(i2, allowEmpty) { + const s2 = this.buffer.slice(this.pos, i2); + if (s2) { + yield s2; + this.pos += s2.length; + return s2.length; + } else if (allowEmpty) + yield ""; + return 0; + } + *pushIndicators() { + switch (this.charAt(0)) { + case "!": + return (yield* this.pushTag()) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators()); + case "&": + return (yield* this.pushUntil(isNotAnchorChar)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators()); + case "-": + // this is an error + case "?": + // this is an error outside flow collections + case ":": { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) { + if (!inFlow) + this.indentNext = this.indentValue + 1; + else if (this.flowKey) + this.flowKey = false; + return (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators()); + } + } + } + return 0; + } + *pushTag() { + if (this.charAt(1) === "<") { + let i2 = this.pos + 2; + let ch = this.buffer[i2]; + while (!isEmpty(ch) && ch !== ">") + ch = this.buffer[++i2]; + return yield* this.pushToIndex(ch === ">" ? i2 + 1 : i2, false); + } else { + let i2 = this.pos + 1; + let ch = this.buffer[i2]; + while (ch) { + if (tagChars.has(ch)) + ch = this.buffer[++i2]; + else if (ch === "%" && hexDigits.has(this.buffer[i2 + 1]) && hexDigits.has(this.buffer[i2 + 2])) { + ch = this.buffer[i2 += 3]; + } else + break; + } + return yield* this.pushToIndex(i2, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === "\n") + return yield* this.pushCount(1); + else if (ch === "\r" && this.charAt(1) === "\n") + return yield* this.pushCount(2); + else + return 0; + } + *pushSpaces(allowTabs) { + let i2 = this.pos - 1; + let ch; + do { + ch = this.buffer[++i2]; + } while (ch === " " || allowTabs && ch === " "); + const n2 = i2 - this.pos; + if (n2 > 0) { + yield this.buffer.substr(this.pos, n2); + this.pos = i2; + } + return n2; + } + *pushUntil(test) { + let i2 = this.pos; + let ch = this.buffer[i2]; + while (!test(ch)) + ch = this.buffer[++i2]; + return yield* this.pushToIndex(i2, false); + } + }; + + // node_modules/yaml/browser/dist/parse/line-counter.js + var LineCounter = class { + constructor() { + this.lineStarts = []; + this.addNewLine = (offset) => this.lineStarts.push(offset); + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = low + high >> 1; + if (this.lineStarts[mid] < offset) + low = mid + 1; + else + high = mid; + } + if (this.lineStarts[low] === offset) + return { line: low + 1, col: 1 }; + if (low === 0) + return { line: 0, col: offset }; + const start = this.lineStarts[low - 1]; + return { line: low, col: offset - start + 1 }; + }; + } + }; + + // node_modules/yaml/browser/dist/parse/parser.js + function includesToken(list, type) { + for (let i2 = 0; i2 < list.length; ++i2) + if (list[i2].type === type) + return true; + return false; + } + function findNonEmptyIndex(list) { + for (let i2 = 0; i2 < list.length; ++i2) { + switch (list[i2].type) { + case "space": + case "comment": + case "newline": + break; + default: + return i2; + } + } + return -1; + } + function isFlowToken(token) { + switch (token?.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "flow-collection": + return true; + default: + return false; + } + } + function getPrevProps(parent) { + switch (parent.type) { + case "document": + return parent.start; + case "block-map": { + const it = parent.items[parent.items.length - 1]; + return it.sep ?? it.start; + } + case "block-seq": + return parent.items[parent.items.length - 1].start; + /* istanbul ignore next should not happen */ + default: + return []; + } + } + function getFirstKeyStartProps(prev) { + if (prev.length === 0) + return []; + let i2 = prev.length; + loop: while (--i2 >= 0) { + switch (prev[i2].type) { + case "doc-start": + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + case "newline": + break loop; + } + } + while (prev[++i2]?.type === "space") { + } + return prev.splice(i2, prev.length); + } + function fixFlowSeqItems(fc) { + if (fc.start.type === "flow-seq-start") { + for (const it of fc.items) { + if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) { + if (it.key) + it.value = it.key; + delete it.key; + if (isFlowToken(it.value)) { + if (it.value.end) + Array.prototype.push.apply(it.value.end, it.sep); + else + it.value.end = it.sep; + } else + Array.prototype.push.apply(it.start, it.sep); + delete it.sep; + } + } + } + } + var Parser = class { + /** + * @param onNewLine - If defined, called separately with the start position of + * each new line (in `parse()`, including the start of input). + */ + constructor(onNewLine) { + this.atNewLine = true; + this.atScalar = false; + this.indent = 0; + this.offset = 0; + this.onKeyLine = false; + this.stack = []; + this.source = ""; + this.type = ""; + this.lexer = new Lexer(); + this.onNewLine = onNewLine; + } + /** + * Parse `source` as a YAML stream. + * If `incomplete`, a part of the last line may be left as a buffer for the next call. + * + * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. + * + * @returns A generator of tokens representing each directive, document, and other structure. + */ + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) + this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) + yield* this.next(lexeme); + if (!incomplete) + yield* this.end(); + } + /** + * Advance the parser by the `source` of one lexical token. + */ + *next(source) { + this.source = source; + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; + } + const type = tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ type: "error", offset: this.offset, message, source }); + this.offset += source.length; + } else if (type === "scalar") { + this.atNewLine = false; + this.atScalar = true; + this.type = "scalar"; + } else { + this.type = type; + yield* this.step(); + switch (type) { + case "newline": + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) + this.onNewLine(this.offset + source.length); + break; + case "space": + if (this.atNewLine && source[0] === " ") + this.indent += source.length; + break; + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + if (this.atNewLine) + this.indent += source.length; + break; + case "doc-mode": + case "flow-error-end": + return; + default: + this.atNewLine = false; + } + this.offset += source.length; + } + } + /** Call at end of input to push out any remaining constructions */ + *end() { + while (this.stack.length > 0) + yield* this.pop(); + } + get sourceToken() { + const st = { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + return st; + } + *step() { + const top = this.peek(1); + if (this.type === "doc-end" && top?.type !== "doc-end") { + while (this.stack.length > 0) + yield* this.pop(); + this.stack.push({ + type: "doc-end", + offset: this.offset, + source: this.source + }); + return; + } + if (!top) + return yield* this.stream(); + switch (top.type) { + case "document": + return yield* this.document(top); + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return yield* this.scalar(top); + case "block-scalar": + return yield* this.blockScalar(top); + case "block-map": + return yield* this.blockMap(top); + case "block-seq": + return yield* this.blockSequence(top); + case "flow-collection": + return yield* this.flowCollection(top); + case "doc-end": + return yield* this.documentEnd(top); + } + yield* this.pop(); + } + peek(n2) { + return this.stack[this.stack.length - n2]; + } + *pop(error) { + const token = error ?? this.stack.pop(); + if (!token) { + const message = "Tried to pop an empty stack"; + yield { type: "error", offset: this.offset, source: "", message }; + } else if (this.stack.length === 0) { + yield token; + } else { + const top = this.peek(1); + if (token.type === "block-scalar") { + token.indent = "indent" in top ? top.indent : 0; + } else if (token.type === "flow-collection" && top.type === "document") { + token.indent = 0; + } + if (token.type === "flow-collection") + fixFlowSeqItems(token); + switch (top.type) { + case "document": + top.value = token; + break; + case "block-scalar": + top.props.push(token); + break; + case "block-map": { + const it = top.items[top.items.length - 1]; + if (it.value) { + top.items.push({ start: [], key: token, sep: [] }); + this.onKeyLine = true; + return; + } else if (it.sep) { + it.value = token; + } else { + Object.assign(it, { key: token, sep: [] }); + this.onKeyLine = !it.explicitKey; + return; + } + break; + } + case "block-seq": { + const it = top.items[top.items.length - 1]; + if (it.value) + top.items.push({ start: [], value: token }); + else + it.value = token; + break; + } + case "flow-collection": { + const it = top.items[top.items.length - 1]; + if (!it || it.value) + top.items.push({ start: [], key: token, sep: [] }); + else if (it.sep) + it.value = token; + else + Object.assign(it, { key: token, sep: [] }); + return; + } + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { + const last2 = token.items[token.items.length - 1]; + if (last2 && !last2.sep && !last2.value && last2.start.length > 0 && findNonEmptyIndex(last2.start) === -1 && (token.indent === 0 || last2.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { + if (top.type === "document") + top.end = last2.start; + else + top.items.push({ start: last2.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case "directive-line": + yield { type: "directive", offset: this.offset, source: this.source }; + return; + case "byte-order-mark": + case "space": + case "comment": + case "newline": + yield this.sourceToken; + return; + case "doc-mode": + case "doc-start": { + const doc = { + type: "document", + offset: this.offset, + start: [] + }; + if (this.type === "doc-start") + doc.start.push(this.sourceToken); + this.stack.push(doc); + return; + } + } + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc) { + if (doc.value) + return yield* this.lineEnd(doc); + switch (this.type) { + case "doc-start": { + if (findNonEmptyIndex(doc.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } else + doc.start.push(this.sourceToken); + return; + } + case "anchor": + case "tag": + case "space": + case "comment": + case "newline": + doc.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc); + if (bv) + this.stack.push(bv); + else { + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + } + *scalar(scalar) { + if (this.type === "map-value-ind") { + const prev = getPrevProps(this.peek(2)); + const start = getFirstKeyStartProps(prev); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } else + sep = [this.sourceToken]; + const map2 = { + type: "block-map", + offset: scalar.offset, + indent: scalar.indent, + items: [{ start, key: scalar, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map2; + } else + yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case "space": + case "comment": + case "newline": + scalar.props.push(this.sourceToken); + return; + case "scalar": + scalar.source = this.source; + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + yield* this.pop(); + break; + /* istanbul ignore next should not happen */ + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map2) { + const it = map2.items[map2.items.length - 1]; + switch (this.type) { + case "newline": + this.onKeyLine = false; + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last2 = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last2?.type === "comment") + end?.push(this.sourceToken); + else + map2.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "space": + case "comment": + if (it.value) { + map2.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + if (this.atIndentedComment(it.start, map2.indent)) { + const prev = map2.items[map2.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + Array.prototype.push.apply(end, it.start); + end.push(this.sourceToken); + map2.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map2.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map2.indent; + const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind"; + let start = []; + if (atNextItem && it.sep && !it.value) { + const nl = []; + for (let i2 = 0; i2 < it.sep.length; ++i2) { + const st = it.sep[i2]; + switch (st.type) { + case "newline": + nl.push(i2); + break; + case "space": + break; + case "comment": + if (st.indent > map2.indent) + nl.length = 0; + break; + default: + nl.length = 0; + } + } + if (nl.length >= 2) + start = it.sep.splice(nl[1]); + } + switch (this.type) { + case "anchor": + case "tag": + if (atNextItem || it.value) { + start.push(this.sourceToken); + map2.items.push({ start }); + this.onKeyLine = true; + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "explicit-key-ind": + if (!it.sep && !it.explicitKey) { + it.start.push(this.sourceToken); + it.explicitKey = true; + } else if (atNextItem || it.value) { + start.push(this.sourceToken); + map2.items.push({ start, explicitKey: true }); + } else { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken], explicitKey: true }] + }); + } + this.onKeyLine = true; + return; + case "map-value-ind": + if (it.explicitKey) { + if (!it.sep) { + if (includesToken(it.start, "newline")) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else { + const start2 = getFirstKeyStartProps(it.start); + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key: null, sep: [this.sourceToken] }] + }); + } + } else if (it.value) { + map2.items.push({ start: [], key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) { + const start2 = getFirstKeyStartProps(it.start); + const key = it.key; + const sep = it.sep; + sep.push(this.sourceToken); + delete it.key; + delete it.sep; + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key, sep }] + }); + } else if (start.length > 0) { + it.sep = it.sep.concat(start, this.sourceToken); + } else { + it.sep.push(this.sourceToken); + } + } else { + if (!it.sep) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else if (it.value || atNextItem) { + map2.items.push({ start, key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [], key: null, sep: [this.sourceToken] }] + }); + } else { + it.sep.push(this.sourceToken); + } + } + this.onKeyLine = true; + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs = this.flowScalar(this.type); + if (atNextItem || it.value) { + map2.items.push({ start, key: fs, sep: [] }); + this.onKeyLine = true; + } else if (it.sep) { + this.stack.push(fs); + } else { + Object.assign(it, { key: fs, sep: [] }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map2); + if (bv) { + if (bv.type === "block-seq") { + if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) { + yield* this.pop({ + type: "error", + offset: this.offset, + message: "Unexpected block-seq-ind on same line with key", + source: this.source + }); + return; + } + } else if (atMapIndent) { + map2.items.push({ start }); + } + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq2) { + const it = seq2.items[seq2.items.length - 1]; + switch (this.type) { + case "newline": + if (it.value) { + const end = "end" in it.value ? it.value.end : void 0; + const last2 = Array.isArray(end) ? end[end.length - 1] : void 0; + if (last2?.type === "comment") + end?.push(this.sourceToken); + else + seq2.items.push({ start: [this.sourceToken] }); + } else + it.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it.value) + seq2.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it.start, seq2.indent)) { + const prev = seq2.items[seq2.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + Array.prototype.push.apply(end, it.start); + end.push(this.sourceToken); + seq2.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + case "anchor": + case "tag": + if (it.value || this.indent <= seq2.indent) + break; + it.start.push(this.sourceToken); + return; + case "seq-item-ind": + if (this.indent !== seq2.indent) + break; + if (it.value || includesToken(it.start, "seq-item-ind")) + seq2.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + } + if (this.indent > seq2.indent) { + const bv = this.startBlockValue(seq2); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it = fc.items[fc.items.length - 1]; + if (this.type === "flow-error-end") { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top?.type === "flow-collection"); + } else if (fc.end.length === 0) { + switch (this.type) { + case "comma": + case "explicit-key-ind": + if (!it || it.sep) + fc.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + case "map-value-ind": + if (!it || it.value) + fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + Object.assign(it, { key: null, sep: [this.sourceToken] }); + return; + case "space": + case "comment": + case "newline": + case "anchor": + case "tag": + if (!it || it.value) + fc.items.push({ start: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + it.start.push(this.sourceToken); + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs = this.flowScalar(this.type); + if (!it || it.value) + fc.items.push({ start: [], key: fs, sep: [] }); + else if (it.sep) + this.stack.push(fs); + else + Object.assign(it, { key: fs, sep: [] }); + return; + } + case "flow-map-end": + case "flow-seq-end": + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + if (bv) + this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } else { + const parent = this.peek(2); + if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { + yield* this.pop(); + yield* this.step(); + } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map2 = { + type: "block-map", + offset: fc.offset, + indent: fc.indent, + items: [{ start, key: fc, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map2; + } else { + yield* this.lineEnd(fc); + } + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf("\n") + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf("\n", nl) + 1; + } + } + return { + type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return this.flowScalar(this.type); + case "block-scalar-header": + return { + type: "block-scalar", + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: "" + }; + case "flow-map-start": + case "flow-seq-start": + return { + type: "flow-collection", + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case "seq-item-ind": + return { + type: "block-seq", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case "explicit-key-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + start.push(this.sourceToken); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, explicitKey: true }] + }; + } + case "map-value-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }; + } + } + return null; + } + atIndentedComment(start, indent) { + if (this.type !== "comment") + return false; + if (this.indent <= indent) + return false; + return start.every((st) => st.type === "newline" || st.type === "space"); + } + *documentEnd(docEnd) { + if (this.type !== "doc-mode") { + if (docEnd.end) + docEnd.end.push(this.sourceToken); + else + docEnd.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case "comma": + case "doc-start": + case "doc-end": + case "flow-seq-end": + case "flow-map-end": + case "map-value-ind": + yield* this.pop(); + yield* this.step(); + break; + case "newline": + this.onKeyLine = false; + // fallthrough + case "space": + case "comment": + default: + if (token.end) + token.end.push(this.sourceToken); + else + token.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + }; + + // node_modules/yaml/browser/dist/public-api.js + function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + const lineCounter = options.lineCounter || prettyErrors && new LineCounter() || null; + return { lineCounter, prettyErrors }; + } + function parseAllDocuments(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + const docs = Array.from(composer.compose(parser.parse(source))); + if (prettyErrors && lineCounter) + for (const doc of docs) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + if (docs.length > 0) + return docs; + return Object.assign([], { empty: true }, composer.streamInfo()); + } + function parseDocument(source, options = {}) { + const { lineCounter, prettyErrors } = parseOptions(options); + const parser = new Parser(lineCounter?.addNewLine); + const composer = new Composer(options); + let doc = null; + for (const _doc of composer.compose(parser.parse(source), true, source.length)) { + if (!doc) + doc = _doc; + else if (doc.options.logLevel !== "silent") { + doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); + break; + } + } + if (prettyErrors && lineCounter) { + doc.errors.forEach(prettifyError(source, lineCounter)); + doc.warnings.forEach(prettifyError(source, lineCounter)); + } + return doc; + } + function parse2(src, reviver, options) { + let _reviver = void 0; + if (typeof reviver === "function") { + _reviver = reviver; + } else if (options === void 0 && reviver && typeof reviver === "object") { + options = reviver; + } + const doc = parseDocument(src, options); + if (!doc) + return null; + doc.warnings.forEach((warning) => warn(doc.options.logLevel, warning)); + if (doc.errors.length > 0) { + if (doc.options.logLevel !== "silent") + throw doc.errors[0]; + else + doc.errors = []; + } + return doc.toJS(Object.assign({ reviver: _reviver }, options)); + } + function stringify3(value, replacer, options) { + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === void 0 && replacer) { + options = replacer; + } + if (typeof options === "string") + options = options.length; + if (typeof options === "number") { + const indent = Math.round(options); + options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent }; + } + if (value === void 0) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) + return void 0; + } + if (isDocument(value) && !_replacer) + return value.toString(options); + return new Document(value, _replacer, options).toString(options); + } + + // node_modules/yaml/browser/index.js + var browser_default = dist_exports; + + // node_modules/railroad-memory/dist/chunk-QP7H5BKJ.mjs + var FileStorage = class { + directory; + format; + constructor(options = {}) { + this.directory = options.directory || "./railroad-sessions"; + this.format = options.format || "yaml"; + } + getFilePath(sessionId) { + const ext = this.format === "yaml" ? "yaml" : "json"; + return join(this.directory, `${sessionId}.${ext}`); + } + async load(sessionId) { + const filePath = this.getFilePath(sessionId); + try { + const content = await readFile(filePath, "utf-8"); + if (this.format === "yaml") { + return browser_default.parse(content); + } else { + return JSON.parse(content); + } + } catch (error) { + if (error.code === "ENOENT") { + return null; + } + throw error; + } + } + async save(state) { + await mkdir(this.directory, { recursive: true }); + const filePath = this.getFilePath(state.sessionId); + let content; + if (this.format === "yaml") { + content = browser_default.stringify(state, { indent: 2 }); + } else { + content = JSON.stringify(state, null, 2); + } + await writeFile(filePath, content, "utf-8"); + } + async delete(sessionId) { + const filePath = this.getFilePath(sessionId); + try { + await unlink(filePath); + } catch (error) { + if (error.code !== "ENOENT") { + throw error; + } + } + } + async exists(sessionId) { + const filePath = this.getFilePath(sessionId); + try { + await access(filePath); + return true; + } catch { + return false; + } + } + async list() { + try { + const files = await readdir(this.directory); + const ext = this.format === "yaml" ? ".yaml" : ".json"; + return files.filter((f3) => f3.endsWith(ext)).map((f3) => f3.replace(ext, "")); + } catch { + return []; + } + } + }; + var MemoryStorage = class { + store = /* @__PURE__ */ new Map(); + async load(sessionId) { + return this.store.get(sessionId) || null; + } + async save(state) { + this.store.set(state.sessionId, JSON.parse(JSON.stringify(state))); + } + async delete(sessionId) { + this.store.delete(sessionId); + } + async exists(sessionId) { + return this.store.has(sessionId); + } + async list() { + return Array.from(this.store.keys()); + } + /** Clear all sessions (useful for testing) */ + clear() { + this.store.clear(); + } + }; + function createStorage(options) { + if (typeof options === "string") { + if (options === "memory") { + return new MemoryStorage(); + } else if (options === "file") { + return new FileStorage(); + } + } + if (typeof options === "object") { + if ("load" in options && "save" in options) { + return options; + } + if ("type" in options) { + if (options.type === "memory") { + return new MemoryStorage(); + } else if (options.type === "file") { + return new FileStorage({ + directory: options.directory, + format: options.format + }); + } + } + } + return new FileStorage(); + } + var TEMPORAL_KEYWORDS = [ + "when", + "date", + "time", + "first", + "last", + "before", + "after", + "ago", + "yesterday", + "today", + "week", + "month", + "year", + "recently" + ]; + function generateId() { + return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; + } + function now() { + return (/* @__PURE__ */ new Date()).toISOString(); + } + var Railroad = class { + sessionId; + storage; + state = null; + initialized = false; + constructor(options) { + if (typeof options === "string") { + this.sessionId = options; + this.storage = new FileStorage(); + } else { + this.sessionId = options.sessionId; + this.storage = options.storage ? createStorage(options.storage) : new FileStorage(); + } + } + /** + * Initialize the session - loads existing or creates new + */ + async init(options) { + if (this.initialized) return; + const existing = await this.storage.load(this.sessionId); + if (existing) { + this.state = existing; + } else { + this.state = { + sessionId: this.sessionId, + createdAt: now(), + updatedAt: now(), + user: options?.initialUser || {}, + memories: [], + decisions: [], + currentContext: void 0, + stats: { + totalTokens: 0, + messageCount: 0 + } + }; + await this.save(); + } + this.initialized = true; + } + /** + * Ensure session is initialized + */ + async ensureInit() { + if (!this.initialized) { + await this.init(); + } + } + /** + * Save current state to storage + */ + async save() { + if (!this.state) return; + this.state.updatedAt = now(); + await this.storage.save(this.state); + } + // ============================================================ + // USER PROFILE + // ============================================================ + /** + * Get current user profile + */ + async getUser() { + await this.ensureInit(); + return { ...this.state.user }; + } + /** + * Update user profile (merges with existing) + */ + async updateUser(updates) { + await this.ensureInit(); + this.state.user = { ...this.state.user, ...updates }; + await this.save(); + } + /** + * Set user profile (replaces existing) + */ + async setUser(user) { + await this.ensureInit(); + this.state.user = user; + await this.save(); + } + // ============================================================ + // MEMORIES + // ============================================================ + /** + * Add one or more memories + */ + async remember(facts, options) { + await this.ensureInit(); + const factArray = Array.isArray(facts) ? facts : [facts]; + const newMemories = []; + for (const content of factArray) { + const memory = { + id: generateId(), + content, + category: options?.category, + importance: options?.importance, + createdAt: now() + }; + this.state.memories.push(memory); + newMemories.push(memory); + } + await this.save(); + return newMemories; + } + /** + * Get all memories, optionally filtered + */ + async getMemories(query) { + await this.ensureInit(); + let memories = [...this.state.memories]; + if (query?.category) { + memories = memories.filter((m3) => m3.category === query.category); + } + if (query?.minImportance !== void 0) { + memories = memories.filter( + (m3) => (m3.importance || 0) >= query.minImportance + ); + } + if (query?.search) { + const searchLower = query.search.toLowerCase(); + memories = memories.filter( + (m3) => m3.content.toLowerCase().includes(searchLower) + ); + } + if (query?.limit) { + memories = memories.slice(-query.limit); + } + return memories; + } + /** + * Get memory count + */ + async getMemoryCount() { + await this.ensureInit(); + return this.state.memories.length; + } + /** + * Clear all memories (use with caution) + */ + async clearMemories() { + await this.ensureInit(); + this.state.memories = []; + await this.save(); + } + // ============================================================ + // ADVANCED MEMORY - Hierarchical Storage + // ============================================================ + /** + * Add a raw session (kept verbatim for high fidelity) + * Recent sessions are kept raw, older ones should be compressed to facts + */ + async addRawSession(content, options) { + await this.ensureInit(); + const maxSessions = options?.maxSessions ?? 5; + if (!this.state.recentRaw) { + this.state.recentRaw = []; + } + const rawSession = { + sessionNumber: options?.sessionNumber ?? this.state.recentRaw.length + 1, + date: options?.date ?? now(), + content: content.length > 4e3 ? content.slice(0, 4e3) : content, + createdAt: now() + }; + this.state.recentRaw.push(rawSession); + if (this.state.recentRaw.length > maxSessions) { + this.state.recentRaw = this.state.recentRaw.slice(-maxSessions); + } + this.state.sessionsProcessed = (this.state.sessionsProcessed ?? 0) + 1; + await this.save(); + return rawSession; + } + /** + * Get recent raw sessions + */ + async getRawSessions(limit) { + await this.ensureInit(); + const sessions = this.state.recentRaw ?? []; + return limit ? sessions.slice(-limit) : [...sessions]; + } + // ============================================================ + // ADVANCED MEMORY - Timeline Indexing + // ============================================================ + /** + * Add an event to the timeline + */ + async addTimelineEvent(date2, event, entity) { + await this.ensureInit(); + if (!this.state.timeline) { + this.state.timeline = {}; + } + const timelineEvent = { + id: generateId(), + date: date2, + event, + entity, + createdAt: now() + }; + if (!this.state.timeline[date2]) { + this.state.timeline[date2] = []; + } + this.state.timeline[date2].push(timelineEvent); + await this.save(); + return timelineEvent; + } + /** + * Get timeline events, optionally filtered by date range + */ + async getTimeline(options) { + await this.ensureInit(); + const timeline = this.state.timeline ?? {}; + if (!options) { + return { ...timeline }; + } + const filtered = {}; + for (const [date2, events] of Object.entries(timeline)) { + if (options.startDate && date2 < options.startDate) continue; + if (options.endDate && date2 > options.endDate) continue; + let filteredEvents = events; + if (options.entity) { + filteredEvents = events.filter((e2) => e2.entity === options.entity); + } + if (filteredEvents.length > 0) { + filtered[date2] = filteredEvents; + } + } + return filtered; + } + // ============================================================ + // ADVANCED MEMORY - Entity Tracking + // ============================================================ + /** + * Track facts about an entity (person, place, thing) + */ + async trackEntity(name, facts, type = "other") { + await this.ensureInit(); + if (!this.state.entities) { + this.state.entities = {}; + } + if (!this.state.entityNames) { + this.state.entityNames = []; + } + const factArray = Array.isArray(facts) ? facts : [facts]; + if (this.state.entities[name]) { + this.state.entities[name].facts.push(...factArray); + this.state.entities[name].lastUpdated = now(); + } else { + this.state.entities[name] = { + name, + type, + facts: factArray, + lastUpdated: now() + }; + if (!this.state.entityNames.includes(name)) { + this.state.entityNames.push(name); + } + } + await this.save(); + return this.state.entities[name]; + } + /** + * Get facts about an entity + */ + async getEntity(name) { + await this.ensureInit(); + return this.state.entities?.[name] ?? null; + } + /** + * Get all tracked entities + */ + async getEntities() { + await this.ensureInit(); + return { ...this.state.entities ?? {} }; + } + /** + * Search for entities mentioned in text + */ + async findMentionedEntities(text2) { + await this.ensureInit(); + const textLower = text2.toLowerCase(); + const mentioned = []; + for (const name of this.state.entityNames ?? []) { + if (textLower.includes(name.toLowerCase())) { + const entity = this.state.entities?.[name]; + if (entity) { + mentioned.push(entity); + } + } + } + return mentioned; + } + // ============================================================ + // ADVANCED MEMORY - Question-Aware Retrieval + // ============================================================ + /** + * Get context optimized for a specific question + * Analyzes the question to determine what context is most relevant + */ + async getContextForQuestion(question, options) { + await this.ensureInit(); + const qLower = question.toLowerCase(); + const parts = []; + const includeRaw = options?.includeRaw ?? true; + const includeTimeline = options?.includeTimeline ?? true; + const includeEntities = options?.includeEntities ?? true; + const maxRecentSessions = options?.maxRecentSessions ?? 5; + const maxFacts = options?.maxFacts ?? 60; + if (includeRaw) { + const rawSessions = this.state.recentRaw ?? []; + if (rawSessions.length > 0) { + parts.push("## RECENT CONVERSATIONS (verbatim)"); + for (const session of rawSessions.slice(-maxRecentSessions)) { + parts.push(session.content); + } + parts.push(""); + } + } + const isTemporalQuestion = TEMPORAL_KEYWORDS.some( + (kw) => qLower.includes(kw) + ); + if (includeTimeline && isTemporalQuestion) { + const timeline = this.state.timeline ?? {}; + if (Object.keys(timeline).length > 0) { + parts.push("## TIMELINE OF EVENTS"); + const sortedDates = Object.keys(timeline).sort(); + for (const date2 of sortedDates) { + parts.push(`${date2}:`); + for (const event of timeline[date2]) { + const prefix = event.entity ? `${event.entity}: ` : ""; + parts.push(` - ${prefix}${event.event}`); + } + } + parts.push(""); + } + } + if (includeEntities) { + const mentionedEntities = await this.findMentionedEntities(question); + for (const entity of mentionedEntities) { + parts.push(`## ABOUT ${entity.name.toUpperCase()}`); + for (const fact of entity.facts) { + parts.push(` - ${fact}`); + } + parts.push(""); + } + } + const memories = this.state.memories ?? []; + if (memories.length > 0) { + parts.push("## ALL EXTRACTED FACTS"); + for (const memory of memories.slice(-maxFacts)) { + parts.push(` - ${memory.content}`); + } + } + return parts.join("\n"); + } + /** + * Detect if this is a temporal question + */ + isTemporalQuestion(question) { + const qLower = question.toLowerCase(); + return TEMPORAL_KEYWORDS.some((kw) => qLower.includes(kw)); + } + // ============================================================ + // DECISIONS + // ============================================================ + /** + * Track a decision + */ + async decide(decision, context) { + await this.ensureInit(); + const newDecision = { + id: generateId(), + content: decision, + context, + createdAt: now() + }; + this.state.decisions.push(newDecision); + await this.save(); + return newDecision; + } + /** + * Get all decisions + */ + async getDecisions() { + await this.ensureInit(); + return [...this.state.decisions]; + } + // ============================================================ + // CONTEXT + // ============================================================ + /** + * Set current conversation context + */ + async setContext(context) { + await this.ensureInit(); + this.state.currentContext = context; + await this.save(); + } + /** + * Get current conversation context + */ + async getCurrentContext() { + await this.ensureInit(); + return this.state.currentContext; + } + /** + * Get full context object for injection into LLM + */ + async getContext() { + await this.ensureInit(); + const state = this.state; + const context = { + sessionId: state.sessionId, + user: { ...state.user }, + memories: [...state.memories], + decisions: [...state.decisions], + currentContext: state.currentContext, + stats: { + totalTokens: state.stats.totalTokens, + messageCount: state.stats.messageCount, + memoryCount: state.memories.length, + decisionCount: state.decisions.length + }, + toPrompt() { + const lines = []; + if (Object.keys(context.user).length > 0) { + lines.push("## User Profile"); + for (const [key, value] of Object.entries(context.user)) { + lines.push(`- ${key}: ${value}`); + } + lines.push(""); + } + if (context.memories.length > 0) { + lines.push("## Memories"); + for (const memory of context.memories) { + lines.push(`- ${memory.content}`); + } + lines.push(""); + } + if (context.decisions.length > 0) { + lines.push("## Decisions"); + for (const decision of context.decisions) { + lines.push(`- ${decision.content}`); + } + lines.push(""); + } + if (context.currentContext) { + lines.push(`## Current Context`); + lines.push(context.currentContext); + } + return lines.join("\n"); + }, + toYAML() { + return browser_default.stringify({ + user: context.user, + memories: context.memories.map((m3) => m3.content), + decisions: context.decisions.map((d3) => d3.content), + currentContext: context.currentContext + }); + }, + toJSON() { + return JSON.stringify( + { + user: context.user, + memories: context.memories, + decisions: context.decisions, + currentContext: context.currentContext, + stats: context.stats + }, + null, + 2 + ); + } + }; + return context; + } + // ============================================================ + // STATS & TRACKING + // ============================================================ + /** + * Record tokens used (for tracking) + */ + async addTokens(count3) { + await this.ensureInit(); + this.state.stats.totalTokens += count3; + await this.save(); + } + /** + * Increment message count + */ + async incrementMessageCount() { + await this.ensureInit(); + this.state.stats.messageCount += 1; + await this.save(); + } + /** + * Get current stats + */ + async getStats() { + await this.ensureInit(); + return { + ...this.state.stats, + memoryCount: this.state.memories.length, + decisionCount: this.state.decisions.length + }; + } + // ============================================================ + // EXTRACTION HELPERS + // ============================================================ + /** + * Process an extraction result from LLM + * This is a convenience method for handling structured LLM output + */ + async processExtraction(result) { + await this.ensureInit(); + if (result.userUpdates) { + await this.updateUser(result.userUpdates); + } + if (result.newMemories && result.newMemories.length > 0) { + await this.remember(result.newMemories); + } + if (result.newDecisions && result.newDecisions.length > 0) { + for (const decision of result.newDecisions) { + await this.decide(decision); + } + } + if (result.currentContext) { + await this.setContext(result.currentContext); + } + } + /** + * Get the system prompt for memory extraction + * Use this to instruct your LLM to return structured output + */ + static getExtractionPrompt() { + return `You are having an ongoing conversation. Your memory persists between messages. + +CRITICAL RULES: +1. Reference the user by name when known +2. Use facts from memory naturally in responses +3. Extract new facts worth remembering +4. Track decisions and commitments + +Your response MUST be valid JSON: +{ + "response": "Your natural conversational response", + "userUpdates": {"key": "value"} or null, + "newMemories": ["fact 1", "fact 2"] or [], + "newDecisions": ["decision 1"] or [], + "currentContext": "Brief summary of current discussion" +}`; + } + /** + * Get advanced extraction prompt that includes timeline and entity tracking + * Use this for better accuracy with temporal and multi-entity conversations + */ + static getAdvancedExtractionPrompt(speakerA, speakerB, sessionDate) { + return `Extract information from this conversation on ${sessionDate}. + +Return JSON: +{ + "facts_about_${speakerA}": ["fact1", "fact2"], + "facts_about_${speakerB}": ["fact1", "fact2"], + "dated_events": [ + {"date": "YYYY-MM-DD or relative date", "event": "description", "who": "${speakerA} or ${speakerB}"} + ], + "people_mentioned": ["name1", "name2"], + "places_mentioned": ["place1"], + "things_mentioned": ["thing1"] +} + +IMPORTANT: For dates, convert relative references: +- "yesterday" on ${sessionDate} = actual date +- "last week" = approximate date +- "two months ago" = approximate date + +JSON only:`; + } + /** + * Get prompt for answering questions with verification loop support + * Use this when answering questions about the conversation history + */ + static getAnswerPrompt(context, question) { + return `Answer this question using the context below. + +${context} + +QUESTION: ${question} + +INSTRUCTIONS: +1. Search ALL sections carefully (recent conversations, timeline, facts) +2. For date questions, check the TIMELINE section +3. For "who/what" questions, check the FACTS section +4. Be specific with names and dates +5. If unsure, give your best guess based on available info + +Answer:`; + } + /** + * Get verification prompt for when first answer is "I don't know" + * This implements the verification loop for better accuracy + */ + static getVerificationPrompt(context, question) { + return `The previous answer was "I don't know" but let's try again. + +CONTEXT: +${context} + +QUESTION: ${question} + +Look more carefully: +1. Check if ANY partial information exists +2. Check for related facts that might answer indirectly +3. Look for context clues + +If you find ANY relevant information, use it. Only say "I don't know" if truly nothing is relevant. + +Answer:`; + } + // ============================================================ + // SESSION MANAGEMENT + // ============================================================ + /** + * Get raw session state + */ + async getState() { + await this.ensureInit(); + return JSON.parse(JSON.stringify(this.state)); + } + /** + * Delete this session + */ + async destroy() { + await this.storage.delete(this.sessionId); + this.state = null; + this.initialized = false; + } + /** + * Check if session exists in storage + */ + async exists() { + return this.storage.exists(this.sessionId); + } + /** + * Get session ID + */ + getSessionId() { + return this.sessionId; + } + // ============================================================ + // PRUNING + // ============================================================ + /** + * Prune memories to keep context size manageable + * Returns pruned state without modifying the session + */ + async getPrunedContext(config) { + await this.ensureInit(); + const { pruneMemories: pruneMemories2, DEFAULT_PRUNING_CONFIG: DEFAULT_PRUNING_CONFIG2 } = await Promise.resolve().then(() => (init_pruning_5FCWCEIC(), pruning_5FCWCEIC_exports)); + const mergedConfig = { ...DEFAULT_PRUNING_CONFIG2, ...config }; + return pruneMemories2(this.state.memories, mergedConfig); + } + /** + * Get context formatted with pruning applied + * Use this for long-running sessions where memory has grown large + */ + async getPrunedPrompt(config) { + const prunedState = await this.getPrunedContext(config); + const { formatPrunedStateForPrompt: formatPrunedStateForPrompt2 } = await Promise.resolve().then(() => (init_pruning_5FCWCEIC(), pruning_5FCWCEIC_exports)); + const memorySection = formatPrunedStateForPrompt2(prunedState); + const lines = []; + const user = this.state.user; + if (Object.keys(user).length > 0) { + lines.push("## User Profile"); + for (const [key, value] of Object.entries(user)) { + lines.push(`- ${key}: ${value}`); + } + lines.push(""); + } + lines.push(memorySection); + if (this.state.decisions.length > 0) { + lines.push("## Key Decisions"); + for (const decision of this.state.decisions.slice(-20)) { + lines.push(`- ${decision.content}`); + } + lines.push(""); + } + if (this.state.currentContext) { + lines.push("## Current Context"); + lines.push(this.state.currentContext); + } + return lines.join("\n"); + } + /** + * Estimate token count for current context + */ + async estimateContextTokens() { + await this.ensureInit(); + const { estimateTokens: estimateTokens2, pruneMemories: pruneMemories2, DEFAULT_PRUNING_CONFIG: DEFAULT_PRUNING_CONFIG2 } = await Promise.resolve().then(() => (init_pruning_5FCWCEIC(), pruning_5FCWCEIC_exports)); + const rawTokens = this.state.memories.reduce( + (sum, m3) => sum + Math.ceil(m3.content.length / 4), + 0 + ); + const prunedState = pruneMemories2(this.state.memories, DEFAULT_PRUNING_CONFIG2); + const prunedEstimate = estimateTokens2(prunedState); + return { + raw: rawTokens, + pruned: prunedEstimate.total + }; + } + /** + * Mark a memory as accessed (for reinforcement learning) + */ + async touchMemory(memoryId) { + await this.ensureInit(); + const memory = this.state.memories.find((m3) => m3.id === memoryId); + if (memory) { + memory.lastAccessed = now(); + memory.accessCount = (memory.accessCount || 0) + 1; + await this.save(); + } + } + /** + * Boost importance of memories matching a search term + */ + async reinforceMemories(searchTerm, boost = 1) { + await this.ensureInit(); + const searchLower = searchTerm.toLowerCase(); + let reinforced = 0; + for (const memory of this.state.memories) { + if (memory.content.toLowerCase().includes(searchLower)) { + memory.importance = Math.min(10, (memory.importance || 5) + boost); + memory.lastAccessed = now(); + memory.accessCount = (memory.accessCount || 0) + 1; + reinforced++; + } + } + if (reinforced > 0) { + await this.save(); + } + return reinforced; + } + /** + * Archive old memories (move to separate storage, reduce active set) + */ + async archiveOldMemories(daysOld = 30) { + await this.ensureInit(); + const cutoff = /* @__PURE__ */ new Date(); + cutoff.setDate(cutoff.getDate() - daysOld); + const toArchive = []; + const toKeep = []; + for (const memory of this.state.memories) { + const createdAt = new Date(memory.createdAt); + if (createdAt > cutoff || (memory.importance || 5) >= 8) { + toKeep.push(memory); + } else { + toArchive.push(memory); + } + } + if (toArchive.length > 0) { + const archiveState = { + sessionId: this.sessionId, + archivedAt: now(), + memories: toArchive + }; + const archivePath = `${this.sessionId}_archive_${Date.now()}`; + await this.storage.save({ + ...this.state, + sessionId: archivePath, + memories: toArchive + }); + } + this.state.memories = toKeep; + await this.save(); + return { + archived: toArchive.length, + remaining: toKeep.length + }; + } + }; + + // node_modules/railroad-memory/dist/browser.mjs + init_chunk_NM4NC7ZM(); + async function createSession(sessionId, options = {}) { + let storage; + if (!options.storage || options.storage === "localStorage") { + storage = new LocalStorageAdapter({ prefix: options.prefix }); + } else if (options.storage === "memory") { + storage = new MemoryStorage(); + } else if (options.storage === "sessionStorage") { + const { SessionStorageAdapter: SessionStorageAdapter2 } = await Promise.resolve().then(() => (init_browser_storage_NM532BJM(), browser_storage_NM532BJM_exports)); + storage = new SessionStorageAdapter2({ prefix: options.prefix }); + } else if (options.storage === "indexedDB") { + const { IndexedDBAdapter: IndexedDBAdapter2 } = await Promise.resolve().then(() => (init_browser_storage_NM532BJM(), browser_storage_NM532BJM_exports)); + const idbStorage = new IndexedDBAdapter2(); + await idbStorage.init(); + storage = idbStorage; + } else { + storage = options.storage; + } + const session = new Railroad({ + sessionId, + storage + }); + await session.init(); + if (options.initialUser) { + await session.updateUser(options.initialUser); + } + return session; + } + + // src/services/railroadMemory.ts + var sessionCache = /* @__PURE__ */ new Map(); + var extractionTurnCounts = /* @__PURE__ */ new Map(); + var RAILROAD_EXTRACTION_GEN_CONFIG = { + responseMimeType: "application/json", + responseJsonSchema: { + type: "object", + properties: { + response: { + type: "string", + description: "Brief acknowledgment; may be empty." + }, + newMemories: { + type: "array", + items: { type: "string" }, + description: "Standalone facts to remember for future turns." + }, + newDecisions: { + type: "array", + items: { type: "string" } + }, + currentContext: { type: "string" }, + userUpdates: { type: "object" } + }, + required: ["response"] + } + }; + function railroadExtractionInterval() { + const raw = String( + true ? "" : "" + ).trim(); + if (raw === "0") { + return 0; + } + if (raw === "") { + return 4; + } + const n2 = parseInt(raw, 10); + if (!Number.isFinite(n2) || n2 < 1) { + return 4; + } + return Math.min(64, n2); + } + function parseExtractionObject(text2) { + const t2 = text2.trim(); + if (!t2) { + return null; + } + try { + const o2 = JSON.parse(t2); + if (o2 && typeof o2 === "object" && !Array.isArray(o2)) { + return o2; + } + } catch { + } + return null; + } + function sessionKeyFromWindow(win) { + const raw = win.oasisRailroadSessionKey; + if (typeof raw !== "string") { + return null; + } + const k3 = raw.trim(); + return k3.length > 0 ? k3 : null; + } + function invalidateRailroadSessionCache() { + sessionCache.clear(); + extractionTurnCounts.clear(); + } + async function getOrCreateSession(key) { + let p2 = sessionCache.get(key); + if (!p2) { + p2 = createSession(key, { storage: "indexedDB" }); + sessionCache.set(key, p2); + } + return p2; + } + async function getRailroadForWindow(win) { + const key = sessionKeyFromWindow(win); + if (!key) { + return null; + } + try { + return await getOrCreateSession(key); + } catch (e2) { + assistantLogger.warn("railroad", "Session init failed", e2); + return null; + } + } + async function getRailroadMemoryPromptBlock(win) { + const rr = await getRailroadForWindow(win); + if (!rr) { + return ""; + } + try { + const block = await rr.getPrunedPrompt(); + const t2 = String(block || "").trim(); + if (!t2) { + return ""; + } + return ` + +## Long-term memory (Railroad) +${t2} +`; + } catch (e2) { + assistantLogger.warn("railroad", "getPrunedPrompt failed", e2); + return ""; + } + } + async function recordRailroadTurn(win, userText, assistantMarkdown) { + const rr = await getRailroadForWindow(win); + if (!rr) { + return; + } + const u4 = String(userText || "").trim(); + const a2 = String(assistantMarkdown || "").trim(); + if (!u4 && !a2) { + return; + } + try { + await rr.addRawSession(`User: +${u4} + +Assistant: +${a2}`); + await rr.incrementMessageCount(); + } catch (e2) { + assistantLogger.warn("railroad", "addRawSession failed", e2); + } + } + function maybeRunRailroadStructuredExtraction(win, userText, assistantMarkdown) { + void runRailroadStructuredExtractionMaybe(win, userText, assistantMarkdown); + } + async function runRailroadStructuredExtractionMaybe(win, userText, assistantMarkdown) { + const interval = railroadExtractionInterval(); + if (interval === 0) { + return; + } + const key = sessionKeyFromWindow(win); + if (!key) { + return; + } + const rr = await getRailroadForWindow(win); + if (!rr) { + return; + } + const prev = extractionTurnCounts.get(key) ?? 0; + const next = prev + 1; + extractionTurnCounts.set(key, next); + if (next % interval !== 0) { + return; + } + const u4 = String(userText || "").trim(); + const a2 = String(assistantMarkdown || "").trim(); + if (!u4 && !a2) { + return; + } + const block = `USER: +${u4} + +ASSISTANT: +${a2}`.slice(0, 12e4); + try { + const system = Railroad.getExtractionPrompt(); + const res = await assistRemote( + system, + [{ role: "user", content: block }], + ["chat"], + [], + RAILROAD_EXTRACTION_GEN_CONFIG + ); + const { text: text2 } = parseChatEnvelope(res); + const parsed = parseExtractionObject(text2); + if (!parsed || typeof parsed.response !== "string") { + assistantLogger.debug("railroad", "extraction: no valid JSON payload"); + return; + } + await rr.processExtraction({ + response: parsed.response, + newMemories: Array.isArray(parsed.newMemories) ? parsed.newMemories.filter((x3) => typeof x3 === "string") : void 0, + newDecisions: Array.isArray(parsed.newDecisions) ? parsed.newDecisions.filter((x3) => typeof x3 === "string") : void 0, + currentContext: typeof parsed.currentContext === "string" ? parsed.currentContext : void 0, + userUpdates: parsed.userUpdates && typeof parsed.userUpdates === "object" && !Array.isArray(parsed.userUpdates) ? parsed.userUpdates : void 0 + }); + assistantLogger.debug("railroad", "extraction: processExtraction applied"); + } catch (e2) { + assistantLogger.warn("railroad", "structured extraction failed", e2); + } + } + + // src/assistant/session.ts + function createFallbackSessionStore() { + let messages = []; + const CAP = 24; + return { + get messages() { + return [...messages]; + }, + addTurn(user, assistant) { + messages.push(user, assistant); + if (messages.length > CAP) { + messages.splice(0, messages.length - CAP); + } + }, + clear() { + messages = []; + }, + setSession(nextMessages) { + messages = [...nextMessages]; + if (messages.length > CAP) { + messages.splice(0, messages.length - CAP); + } + } + }; + } + function importAssistantSession(assistantWindow2) { + if (!assistantWindow2.ChromeUtils?.importESModule) { + assistantLogger.warn( + "session", + "ChromeUtils unavailable, using fallback session store." + ); + return createFallbackSessionStore(); + } + try { + const mod = assistantWindow2.ChromeUtils.importESModule( + "chrome://browser/content/assistant/AssistantSession.sys.mjs" + ); + const importedSession = mod.AssistantSession; + if (importedSession) { + assistantLogger.info("session", "Imported AssistantSession singleton."); + return importedSession; + } + assistantLogger.warn( + "session", + "AssistantSession export missing, using fallback session store." + ); + return createFallbackSessionStore(); + } catch (error) { + assistantLogger.error( + "session", + "Failed to import AssistantSession singleton.", + error + ); + return createFallbackSessionStore(); + } + } + function installSessionObserver(assistantWindow2) { + try { + const services = assistantWindow2.Services; + if (!services?.obs) { + return; + } + const observer = { + observe: (_subject, topic, _data2) => { + if (topic === "oasis-session-updated") { + try { + assistantWindow2.dispatchEvent( + new CustomEvent(OASIS_EVENT_HISTORY_UPDATE) + ); + } catch { + } + } + } + }; + services.obs.addObserver(observer, "oasis-session-updated", false); + } catch (error) { + assistantLogger.error( + "session", + "Failed to install session observer.", + error + ); + } + } + function hydrateSessionMessages(session) { + return session.messages.map((m3) => { + const message = m3 || {}; + if (typeof message._getType === "function") { + return message; + } + if (message.type === "human") { + return new HumanMessage(msgText(message)); + } + if (message.type === "ai") { + return new AIMessage(msgText(message)); + } + return new HumanMessage(msgText(message)); + }); + } + function createAssistantSessionController(assistantWindow2) { + const session = importAssistantSession(assistantWindow2); + installSessionObserver(assistantWindow2); + function getCurrentSessionMessages() { + return hydrateSessionMessages(session); + } + function pushCurrentTurn(user, assistant) { + session.addTurn( + { type: "human", content: user }, + { type: "ai", content: assistant } + ); + } + function syncSessionFromPlainTurns(turns) { + session.setSession( + turns.map((t2) => ({ + type: t2.type, + content: t2.content + })) + ); + } + function resetAssistantSession2() { + session.clear(); + try { + assistantWindow2.dispatchEvent( + new CustomEvent(OASIS_EVENT_HISTORY_UPDATE) + ); + } catch { + } + } + function getAssistantHistory2() { + return getCurrentSessionMessages(); + } + return { + getCurrentSessionMessages, + pushCurrentTurn, + resetAssistantSession: resetAssistantSession2, + getAssistantHistory: getAssistantHistory2, + syncSessionFromPlainTurns + }; + } + + // src/utils/streamGuards.ts + var STREAM_GUARD_DEFAULTS = { + maxStreamSteps: 36, + maxSameStepStreak: 8 + }; + function createStreamGuardState() { + return { + stepCount: 0, + previousStepName: "", + sameStepStreak: 0 + }; + } + function advanceStreamGuard(state, stepName) { + const nextStepCount = state.stepCount + 1; + if (stepName === state.previousStepName) { + return { + stepCount: nextStepCount, + previousStepName: state.previousStepName, + sameStepStreak: state.sameStepStreak + 1 + }; + } + return { + stepCount: nextStepCount, + previousStepName: stepName, + sameStepStreak: 1 + }; + } + function shouldStopForStreamGuard(state, config = STREAM_GUARD_DEFAULTS) { + return state.stepCount > config.maxStreamSteps || state.sameStepStreak > config.maxSameStepStreak; + } + + // src/assistant/stream.ts + function extractMessageText(msg) { + if (typeof msg?.content === "string") { + return msg.content; + } + if (Array.isArray(msg?.content)) { + return msg.content.map((c3) => { + if (typeof c3 === "string") { + return c3; + } + if (typeof c3 === "object" && c3 && "text" in c3) { + const value = c3.text; + if (value != null) { + return String(value); + } + } + if (typeof c3 === "object" && c3 && "type" in c3 && c3.type === "text" && "text" in c3) { + return String(c3.text ?? ""); + } + return String(c3 ?? ""); + }).join(""); + } + if (msg?.content != null) { + return String(msg.content); + } + return ""; + } + async function consumeAssistantGraphStream(args) { + const { + stream, + prompt, + onChunk, + inputType, + toolCommandNames, + pushCurrentTurn, + trackUsage + } = args; + let combinedSessionString = ""; + let toolOutputBuffer = ""; + let isSaved = false; + let hasEmittedUserMessage = false; + const recentToolPayloads = []; + let toolMessageCount = 0; + let emittedChars = 0; + let guardTriggered = false; + let lastUsageMeta; + let streamGuardState = createStreamGuardState(); + for await (const state of stream) { + if ("__end__" in state) { + if (combinedSessionString && !isSaved) { + pushCurrentTurn(prompt, combinedSessionString); + trackUsage(inputType, lastUsageMeta); + isSaved = true; + } + break; + } + const step = Object.entries(state).find(([k3]) => k3 !== "__end"); + const stepValue = step?.[1]; + const stepName = step?.[0] || "unknown"; + streamGuardState = advanceStreamGuard(streamGuardState, stepName); + if (shouldStopForStreamGuard(streamGuardState, STREAM_GUARD_DEFAULTS)) { + guardTriggered = true; + assistantLogger.warn("stream", "Stream guard triggered.", { + stepCount: streamGuardState.stepCount, + stepName, + sameStepStreak: streamGuardState.sameStepStreak + }); + if (!hasEmittedUserMessage) { + onChunk(`${STREAM_GUARD_MESSAGE} +`); + combinedSessionString = STREAM_GUARD_MESSAGE; + hasEmittedUserMessage = true; + } + break; + } + if (!hasMessages(stepValue) || !stepValue.messages) { + continue; + } + const messages = stepValue.messages; + for (const rawMessage of messages) { + const msg = rawMessage; + const text2 = extractMessageText(msg); + if (!text2) { + continue; + } + const kwargs = msg.additional_kwargs; + if (isRecord(kwargs) && isRecord(kwargs.oasisUsageMeta)) { + const newMeta = kwargs.oasisUsageMeta; + if (!lastUsageMeta) { + lastUsageMeta = newMeta; + } else { + lastUsageMeta = { + command_type: lastUsageMeta.command_type !== "other" && newMeta.command_type === "other" ? lastUsageMeta.command_type : newMeta.command_type, + user_intent: lastUsageMeta.user_intent !== "other" && newMeta.user_intent === "other" ? lastUsageMeta.user_intent : newMeta.user_intent, + input_tokens: newMeta.input_tokens ?? lastUsageMeta.input_tokens, + output_tokens: newMeta.output_tokens ?? lastUsageMeta.output_tokens + }; + } + } + const msgName = typeof msg.name === "string" ? msg.name ?? "" : ""; + const toolResult = getToolResultPayload(msg); + const isToolNodeMessage = toolCommandNames.has(stepName) || toolCommandNames.has(msgName) || !!toolResult; + if (isToolNodeMessage) { + toolMessageCount += 1; + const payloadText = toolResult?.message || text2; + toolOutputBuffer += `${payloadText} +`; + const payload = String(payloadText || "").trim(); + if (payload) { + recentToolPayloads.unshift(payload); + if (recentToolPayloads.length > 8) { + recentToolPayloads.pop(); + } + } + continue; + } + const sanitizedText = stripLeadingEchoedPayload( + String(text2 || "").trim(), + recentToolPayloads + ); + if (!sanitizedText) { + continue; + } + const newContent = `${sanitizedText} +`; + onChunk(newContent); + combinedSessionString += newContent; + emittedChars += newContent.length; + hasEmittedUserMessage = true; + } + } + if (!hasEmittedUserMessage && toolOutputBuffer) { + const sanitizedFallback = stripLeadingEchoedPayload( + String(toolOutputBuffer || "").trim(), + recentToolPayloads + ); + if (sanitizedFallback) { + const friendlyMessage = sanitizedFallback.endsWith("\n") ? sanitizedFallback : `${sanitizedFallback} +`; + onChunk(friendlyMessage); + combinedSessionString = friendlyMessage; + hasEmittedUserMessage = true; + emittedChars += friendlyMessage.length; + } + } + if (combinedSessionString && !isSaved) { + pushCurrentTurn(prompt, combinedSessionString); + trackUsage(inputType, lastUsageMeta); + } + assistantLogger.debug("stream", "Run summary", { + steps: streamGuardState.stepCount, + sameStepStreak: streamGuardState.sameStepStreak, + guardTriggered, + emittedChars, + toolMessageCount + }); + return combinedSessionString || "(no output)"; + } + + // src/prompts/voicePrompt.ts + var VOICE_SCOPE_AND_RECOVERY = `Scope and recovery (voice input \u2014 applies to every reply): +- You are primarily an Oasis browsing assistant. Treat what you heard as a command or question about tabs, windows, search, navigation, or page content unless the user clearly asks for general conversation with no browser angle. +- Do not refer to the product as Firefox; the browser is Oasis. +- If a request does not map safely to a browser action or tool, give ONE short clarification (for example: "Say the site name to open, or say 'search X on Google'"). Do not pivot into long empathy, therapy-style, or storytelling replies. +- If the transcript looks fragmentary, nonsensical, or unrelated to browsing, do not invent a personal situation or backstory. Ask them to repeat, or suggest one concrete browser-focused phrase they can try. +`; + var VOICE_REPLY_ADDENDUM = `${VOICE_SCOPE_AND_RECOVERY} +You are the user's personal voice assistant in Oasis. Be warm and clear, but stay task-oriented. + +Voice and spoken delivery (this will be read by text-to-speech): +- Sound conversational: vary rhythm, use short and medium sentences, and connect ideas the way people talk ("So the main idea is\u2026", "Here's why that matters\u2026"). +- When explaining something, teach in layers: start with a simple takeaway, then add nuance if useful. Do not sound like you are reading a numbered list aloud unless the user asked for steps. +- Avoid robotic patterns: do not say "Item one, item two", do not over-use "Additionally" or "Furthermore", and do not read markdown symbols or formatting cues. +- Do not read bullet characters or headings as words; rephrase as flowing speech. +- For code, URLs, or file paths: give a short spoken summary unless the user explicitly asked for exact text; spell critical tokens slowly only when needed. +- Keep answers focused for listening; offer to go deeper if the topic is large. + +`; + var VOICE_CHAT_TEXT_REPLY_ADDENDUM = `${VOICE_SCOPE_AND_RECOVERY} +You are replying in the chat sidebar as text (nothing will be read aloud). The user spoke their message via the voice orb. + +- Use markdown when it helps (short lists, links, **bold** for emphasis). +- Be concise but complete; they may glance at the chat while continuing the conversation. +- Use your tools when they help fulfill the request. + +`; + + // src/services/voiceInput.ts + function eventBlob(event) { + const data = event.data; + return data instanceof Blob ? data : null; + } + var VoiceInputService = class { + mediaRecorder = null; + audioChunks = []; + stream = null; + composerUtteranceSeq = 0; + activeComposerSeq = 0; + async startRecording() { + try { + this.stream = await navigator.mediaDevices.getUserMedia({ + audio: { + echoCancellation: true, + noiseSuppression: true, + autoGainControl: true + } + }); + this.composerUtteranceSeq += 1; + this.activeComposerSeq = this.composerUtteranceSeq; + const audioTracks = this.stream.getAudioTracks(); + const mimeType = this.getSupportedMimeType(); + assistantLogger.debug("voice-input", "recording_started", { + utteranceSeq: this.activeComposerSeq, + mimeType: mimeType || "(browser default)", + tracks: audioTracks.map((t2) => { + let deviceId = ""; + try { + deviceId = t2.getSettings?.().deviceId ?? ""; + } catch { + } + return { label: t2.label || "", deviceId }; + }) + }); + this.mediaRecorder = mimeType ? new MediaRecorder(this.stream, { mimeType }) : new MediaRecorder(this.stream); + this.audioChunks = []; + this.mediaRecorder.ondataavailable = (event) => { + const blob = eventBlob(event); + if (blob && blob.size > 0) { + this.audioChunks.push(blob); + } + }; + this.mediaRecorder.start(); + } catch (error) { + assistantLogger.error("voice-input", "Error starting recording", error); + throw new Error("Failed to access microphone. Please check permissions."); + } + } + async stopRecording() { + return new Promise((resolve, reject) => { + if (!this.mediaRecorder) { + reject(new Error("No active recording")); + return; + } + const seq2 = this.activeComposerSeq; + this.mediaRecorder.onstop = async () => { + try { + if (this.stream) { + this.stream.getTracks().forEach((track) => track.stop()); + } + const mimeType = this.mediaRecorder?.mimeType || "audio/webm"; + const audioBlob = new Blob(this.audioChunks, { type: mimeType }); + assistantLogger.debug("voice-input", "sending_transcribe", { + utteranceSeq: seq2, + chunkCount: this.audioChunks.length, + blobBytes: audioBlob.size, + mimeType + }); + const result = await transcribeAudio(audioBlob, { + source: "composer", + utteranceSeq: seq2 + }); + resolve(result.transcript || ""); + } catch (error) { + assistantLogger.error( + "voice-input", + "Error transcribing audio", + error + ); + reject(error); + } finally { + this.mediaRecorder = null; + this.audioChunks = []; + this.stream = null; + } + }; + this.mediaRecorder.stop(); + }); + } + isRecording() { + return this.mediaRecorder?.state === "recording"; + } + cancelRecording() { + assistantLogger.debug("voice-input", "recording_cancelled", { + utteranceSeq: this.activeComposerSeq + }); + if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") { + this.mediaRecorder.stop(); + } + if (this.stream) { + this.stream.getTracks().forEach((track) => track.stop()); + } + this.mediaRecorder = null; + this.audioChunks = []; + this.stream = null; + } + getSupportedMimeType() { + const types = [ + "audio/webm;codecs=opus", + "audio/webm", + "audio/ogg;codecs=opus", + "audio/mp4" + ]; + for (const type of types) { + if (MediaRecorder.isTypeSupported(type)) { + return type; + } + } + return ""; + } + }; + var voiceInput_default = new VoiceInputService(); + + // src/utils/voiceVadDebounce.ts + function advanceVadSpeechDebounce(streak, speechFrame, debounceFrames) { + if (!speechFrame) { + return { streak: 0, commit: false }; + } + const next = streak + 1; + if (next >= debounceFrames) { + return { streak: 0, commit: true }; + } + return { streak: next, commit: false }; + } + + // src/utils/voiceUtteranceGuards.ts + var MIN_AUTO_TRANSCRIPT_LENGTH = 5; + var SHORT_TRANSCRIPT_ALLOWLIST = /^(no|yes|ok|tab|stop|undo|redo|back|refresh|forward|close)$/i; + function shouldDiscardAutoTranscript(transcript, manualStop) { + if (manualStop) { + return false; + } + const t2 = transcript.replace(/\s+/g, " ").trim(); + if (t2.length === 0) { + return false; + } + if (t2.length >= MIN_AUTO_TRANSCRIPT_LENGTH) { + return false; + } + if (SHORT_TRANSCRIPT_ALLOWLIST.test(t2)) { + return false; + } + return true; + } + + // src/services/voiceAgent.ts + var TTS_STOP_EVENT = "oasis-tts-stop"; + var MAX_TTS_CHARS = 2e3; + var TARGET_TRANSCRIBE_SAMPLE_RATE = 16e3; + var PRE_ROLL_MS = 1200; + var MAX_CAPTURE_HISTORY_MS = 12e3; + var MANUAL_FLUSH_LOOKBACK_MS = 2800; + var VAD_THRESHOLD_MULTIPLIER = 2; + var VAD_MIN_THRESHOLD = 0.01; + var VAD_MAX_THRESHOLD = 0.045; + var VAD_SILENCE_MS = 1250; + var VAD_SPEECH_ON_FRAMES = 2; + var VAD_MIN_UTTERANCE_MS = 240; + var RECORDER_SLICE_MS = 160; + var PRECISE_START_RMS_THRESHOLD = 0.014; + var ECHO_GUARD_MS_AFTER_TTS = 700; + var ECHO_GUARD_MS_AFTER_TTS_INTERRUPT = 450; + var ECHO_GUARD_MS_AFTER_TEXT_REPLY = 180; + var AUTO_MIN_UTTERANCE_BYTES_PRECISE = 800; + var MANUAL_STOP_MIN_UTTERANCE_MS = 120; + var MANUAL_STOP_MIN_UTTERANCE_BYTES = 120; + var MIN_UTTERANCE_BYTES = 400; + var VAD_SPEECH_DEBOUNCE_FRAMES = 3; + function eventBlob2(event) { + const data = event.data; + return data instanceof Blob ? data : null; + } + function nowMs() { + return globalThis.performance?.now() ?? Date.now(); + } + function clamp(value, min, max) { + return Math.min(max, Math.max(min, value)); + } + var VOICE_CAPTURE_MODE_STORAGE_KEY = "oasis.voice.captureMode"; + var VOICE_SPOKEN_REPLIES_STORAGE_KEY = "oasis.voice.orbSpokenReplies"; + function readStoredCaptureMode() { + try { + const ls = globalThis.localStorage; + if (!ls) return "continuous"; + const v6 = ls.getItem(VOICE_CAPTURE_MODE_STORAGE_KEY); + if (v6 === "precise") return "precise"; + } catch { + } + return "continuous"; + } + function readStoredVoiceSpokenReplies() { + try { + const ls = globalThis.localStorage; + if (!ls) return true; + const v6 = ls.getItem(VOICE_SPOKEN_REPLIES_STORAGE_KEY); + if (v6 === "0" || v6 === "false") return false; + } catch { + } + return true; + } + function randomAssistantMessageId() { + try { + return crypto.randomUUID(); + } catch { + return `va-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`; + } + } + function transcribeFailureUserMessage(error) { + const s2 = String(error); + if (s2.includes("403") || s2.includes("Forbidden")) { + return "Voice could not reach the transcription service (access denied). See browser/base/content/assistant/VOICE_INPUT_SETUP.md or ask your admin to check AWS IAM and the Lambda URL."; + } + if (/Authentication required/i.test(s2)) { + return "Please sign in to use voice. Voice transcription needs an authenticated Oasis session."; + } + return "Could not transcribe audio. Check your connection and try again."; + } + function normalizeTextForSpeech(text2) { + const normalized = text2.replace(/<[^>]*>/g, "").replace(/^[\t ]*[-*+]\s+/gm, "").replace(/^[\t ]*\d+\.\s+/gm, "").replace(/[#*_`~\[\]()>|]/g, "").replace(/[–—]+/g, ", ").replace(/\s*:\s*/g, ": ").replace(/\s*;\s*/g, "; ").replace(/\n{2,}/g, ". ").replace(/\n/g, " ").replace(/([.,!?;:])([^\s])/g, "$1 $2").replace(/\s{2,}/g, " ").trim().slice(0, MAX_TTS_CHARS).trim(); + if (!normalized) { + return ""; + } + if (!/[.!?]$/.test(normalized)) { + return `${normalized}.`; + } + return normalized; + } + function summarizeUrlForSpeech(value) { + try { + const parsed = new URL(value); + const host = parsed.hostname.replace(/^www\./i, ""); + if (!host) { + return "that page"; + } + return host; + } catch { + return "that page"; + } + } + function makeSpeechFriendlyReply(text2) { + const raw = String(text2 || "").trim(); + if (!raw) { + return ""; + } + const missingUrl = "Okay. Tell me the website you'd like me to open."; + const missingQuery = "Okay. What should I search for?"; + if (/^Missing 'url' argument\.?$/i.test(raw)) { + return missingUrl; + } + if (/^Missing 'query' argument\.?$/i.test(raw)) { + return missingQuery; + } + if (/^Opened URL in a new tab:/i.test(raw)) { + return "Done. I've opened that in a new tab."; + } + if (/^Opened web search for/i.test(raw)) { + return "I've opened a web search."; + } + if (/^Opened a new tab to the right of:/i.test(raw)) { + return "I've opened a new tab."; + } + if (/^Cannot open URL/i.test(raw) || /^Cannot open web search/i.test(raw) || /^Browser UI not available\.?$/i.test(raw)) { + return "I can't open a new tab right now."; + } + const openedUrlMatch = raw.match( + /^(?:Opened URL in a new tab|Successfully opened URL|Opened in new tab):\s+(.+)$/i + ); + if (openedUrlMatch) { + return `Done. I've opened ${summarizeUrlForSpeech(openedUrlMatch[1])} in a new tab.`; + } + const searchMatch = raw.match( + /^Opened web search for "?(.+?)"? in a new tab\.?$/i + ); + if (searchMatch) { + return `Sure. I opened a web search for ${searchMatch[1]}.`; + } + const tabActionRewrites = [ + [/^Closed tab:/i, "Closed that tab."], + [/^Reloaded tab:/i, "Reloaded that tab."], + [/^Pinned tab:/i, "Pinned that tab."], + [/^Unpinned tab:/i, "Unpinned that tab."], + [/^Moved tab to start:/i, "Moved that tab to the start."], + [/^Moved tab to end:/i, "Moved that tab to the end."], + [/^Duplicated tab:/i, "Duplicated that tab."], + [/^Bookmarked tab:/i, "Bookmarked that tab."], + [/^Selected all tabs in this window\.?$/i, "Selected all tabs in this window."], + [/^Closed \d+ duplicate tab\(s\)\.?$/i, "Closed the duplicate tabs."], + [/^Closed \d+ tab\(s\) to the right\.?$/i, "Closed the tabs to the right."], + [/^Closed \d+ tab\(s\) to the left\.?$/i, "Closed the tabs to the left."], + [/^Closed \d+ other tab\(s\)\.?$/i, "Closed the other tabs."] + ]; + for (const [pattern, replacement] of tabActionRewrites) { + if (pattern.test(raw)) { + return replacement; + } + } + const shortened = raw.replace(/https?:\/\/\S+/gi, (url) => summarizeUrlForSpeech(url)); + const sentenceMatch = shortened.match(/^([^.!?]+[.!?])(?:\s+.*)?$/s); + if (sentenceMatch && sentenceMatch[1].length < shortened.length) { + return sentenceMatch[1].trim(); + } + return shortened; + } + var VoiceAgentService = class { + state = "idle"; + listeners = /* @__PURE__ */ new Set(); + mediaRecorder = null; + recorderMimeType = ""; + recorderStartedAt = 0; + chunkTimeline = []; + micStream = null; + ttsAudio = null; + ttsObjectUrl = null; + aborted = false; + runAssistant = null; + preferredListeningSource = "handsfree"; + listeningSourceActive = null; + audioContext = null; + micSource = null; + analyser = null; + vadData = null; + pcmProcessor = null; + pcmSink = null; + pcmTimeline = []; + audioLoopId = 0; + audioLoopRunning = false; + ttsAnalyser = null; + ttsAnalyserData = null; + mediaElementSource = null; + speechActive = false; + speechOnFrames = 0; + silenceMs = 0; + utteranceStartTime = 0; + utteranceBufferStartMs = 0; + recentSpeechDetectedAt = 0; + peakSpeechRms = 0; + currentVadThreshold = VAD_MIN_THRESHOLD; + ambientNoiseFloor = 0; + ambientSampleCount = 0; + lastVadFrameMs = 0; + finishUtterancePromise = null; + ttsRequestId = 0; + activeSpeakCleanup = null; + captureMode = readStoredCaptureMode(); + speechPrimeFrames = 0; + vadSpeechStreakFrames = 0; + voiceSpokenRepliesEnabled = readStoredVoiceSpokenReplies(); + constructor() { + window.addEventListener( + TTS_STOP_EVENT, + this.handleExternalTtsStop + ); + } + setRunAssistant(fn) { + this.runAssistant = fn; + } + getListeningSource() { + return this.listeningSourceActive; + } + getUserSpeaking() { + return this.speechActive; + } + getCaptureMode() { + return this.captureMode; + } + setCaptureMode(mode) { + this.captureMode = mode; + try { + globalThis.localStorage?.setItem(VOICE_CAPTURE_MODE_STORAGE_KEY, mode); + } catch { + } + assistantLogger.warn("voice", "capture mode set", { mode }); + } + getVoiceSpokenRepliesEnabled() { + return this.voiceSpokenRepliesEnabled; + } + setVoiceSpokenRepliesEnabled(enabled) { + this.voiceSpokenRepliesEnabled = enabled; + try { + globalThis.localStorage?.setItem( + VOICE_SPOKEN_REPLIES_STORAGE_KEY, + enabled ? "1" : "0" + ); + } catch { + } + assistantLogger.warn("voice", "orb spoken replies", { enabled }); + } + on(listener) { + this.listeners.add(listener); + return () => { + this.listeners.delete(listener); + }; + } + getState() { + return this.state; + } + handleExternalTtsStop = (event) => { + if (event.detail?.source === "voice-agent") { + return; + } + this.stopSpeaking(); + }; + emit(event) { + for (const listener of this.listeners) { + try { + listener(event); + } catch { + } + } + } + setState(nextState, listeningSource) { + this.state = nextState; + if (nextState === "listening" && listeningSource) { + this.listeningSourceActive = listeningSource; + this.emit({ type: "state", state: nextState, listeningSource }); + return; + } + if (nextState !== "listening") { + this.listeningSourceActive = null; + } + this.emit({ type: "state", state: nextState }); + } + emitVad(userSpeaking) { + this.emit({ type: "vad", userSpeaking }); + } + emitListeningPhase(phase) { + this.emit({ type: "listening_phase", phase }); + } + setMicTracksEnabled(enabled) { + const tracks = this.micStream?.getAudioTracks() ?? []; + tracks.forEach((track) => { + track.enabled = enabled; + }); + } + getAudioConstraints() { + const supported = navigator.mediaDevices?.getSupportedConstraints?.() || {}; + const constraints = { + echoCancellation: true, + noiseSuppression: true, + autoGainControl: true + }; + if (supported.channelCount) { + constraints.channelCount = { ideal: 1 }; + } + if (supported.sampleRate) { + constraints.sampleRate = { ideal: TARGET_TRANSCRIBE_SAMPLE_RATE }; + } + if (supported.sampleSize) { + constraints.sampleSize = { ideal: 16 }; + } + if ("suppressLocalAudioPlayback" in supported && supported.suppressLocalAudioPlayback) { + constraints.suppressLocalAudioPlayback = true; + } + return constraints; + } + async startConversation(listeningSource = "handsfree") { + if (this.state !== "idle") { + return; + } + this.aborted = false; + this.preferredListeningSource = listeningSource; + if (!navigator.mediaDevices?.getUserMedia) { + this.emit({ + type: "error", + message: "Microphone is not available in this page." + }); + return; + } + try { + this.micStream = await navigator.mediaDevices.getUserMedia({ + audio: this.getAudioConstraints() + }); + } catch { + if (this.aborted) { + return; + } + this.emit({ type: "error", message: "Microphone access denied." }); + return; + } + if (this.aborted) { + this.releaseMic(); + return; + } + this.setupAnalyser(); + if (!this.analyser || !this.audioContext) { + this.releaseAudioContext(); + this.releaseMic(); + this.emit({ + type: "error", + message: "Could not start audio analysis." + }); + return; + } + if (this.audioContext.state === "suspended") { + try { + await this.audioContext.resume(); + } catch (error) { + assistantLogger.error("voice-agent", "AudioContext.resume failed", error); + this.releaseAudioContext(); + this.releaseMic(); + this.emit({ + type: "error", + message: "Tap the microphone button to enable listening." + }); + return; + } + } + this.setMicTracksEnabled(true); + this.resetListeningCalibration(); + this.setState("listening", listeningSource); + const captureStarted = await this.startContinuousCapture(); + if (!captureStarted) { + this.releaseAudioContext(); + this.releaseMic(); + this.setState("idle"); + this.emit({ + type: "error", + message: "Could not start microphone capture." + }); + return; + } + try { + const track = this.micStream.getAudioTracks()[0]; + assistantLogger.info("voice-agent", "Microphone capture started", { + mimeType: this.recorderMimeType, + settings: track?.getSettings?.() || null + }); + } catch { + } + this.ensureAudioLoop(); + this.emitListeningPhase("capturing"); + this.speechPrimeFrames = 0; + } + setupAnalyser() { + if (!this.micStream) { + return; + } + try { + this.audioContext = new AudioContext(); + const source = this.audioContext.createMediaStreamSource(this.micStream); + this.micSource = source; + this.analyser = this.audioContext.createAnalyser(); + this.analyser.fftSize = 1024; + this.analyser.smoothingTimeConstant = 0.65; + source.connect(this.analyser); + this.vadData = new Uint8Array(this.analyser.fftSize); + const processor = this.audioContext.createScriptProcessor(4096, 1, 1); + const sink = this.audioContext.createGain(); + sink.gain.value = 0; + processor.onaudioprocess = (event) => { + const audioEvent = event; + if (this.state !== "listening" || this.aborted) { + return; + } + const input = audioEvent.inputBuffer; + const sampleRate = input.sampleRate || this.audioContext?.sampleRate || 48e3; + if (!sampleRate || input.length <= 0) { + return; + } + const mono = new Float32Array(input.length); + const channels = Math.max(1, input.numberOfChannels); + for (let channel = 0; channel < channels; channel++) { + const data = input.getChannelData(channel); + for (let index2 = 0; index2 < data.length; index2++) { + mono[index2] += data[index2] / channels; + } + } + const endMs = nowMs(); + const durationMs = mono.length / sampleRate * 1e3; + this.pcmTimeline.push({ + samples: mono, + startMs: endMs - durationMs, + endMs, + sampleRate + }); + this.trimPcmTimeline(endMs); + }; + source.connect(processor); + processor.connect(sink); + sink.connect(this.audioContext.destination); + this.pcmProcessor = processor; + this.pcmSink = sink; + } catch (error) { + assistantLogger.error("voice-agent", "Analyser setup failed", error); + } + } + resetListeningCalibration() { + this.speechActive = false; + this.speechOnFrames = 0; + this.speechPrimeFrames = 0; + this.vadSpeechStreakFrames = 0; + this.silenceMs = 0; + this.utteranceStartTime = 0; + this.utteranceBufferStartMs = 0; + this.recentSpeechDetectedAt = 0; + this.peakSpeechRms = 0; + this.ambientNoiseFloor = 0; + this.ambientSampleCount = 0; + this.currentVadThreshold = VAD_MIN_THRESHOLD; + this.emitVad(false); + } + computeRms() { + if (!this.analyser || !this.vadData) { + return 0; + } + this.analyser.getByteTimeDomainData(this.vadData); + let sum = 0; + for (let index2 = 0; index2 < this.vadData.length; index2++) { + const value = (this.vadData[index2] - 128) / 128; + sum += value * value; + } + return Math.sqrt(sum / this.vadData.length); + } + computeRmsFromAnalyser(analyser, data) { + analyser.getByteTimeDomainData(data); + let sum = 0; + for (let index2 = 0; index2 < data.length; index2++) { + const value = (data[index2] - 128) / 128; + sum += value * value; + } + return Math.sqrt(sum / data.length); + } + normalizeLevel(rms) { + return Math.min(1, Math.max(0, rms * 7)); + } + observeAmbientNoise(rms) { + if (this.speechActive) { + return; + } + const sample = this.ambientSampleCount === 0 ? rms : this.ambientNoiseFloor * 0.92 + rms * 0.08; + this.ambientNoiseFloor = sample; + this.ambientSampleCount += 1; + const derivedThreshold = Math.max( + sample * VAD_THRESHOLD_MULTIPLIER, + sample + 6e-3 + ); + this.currentVadThreshold = clamp( + derivedThreshold, + VAD_MIN_THRESHOLD, + VAD_MAX_THRESHOLD + ); + } + emitAudioLevels() { + let mic = 0; + let tts = 0; + if (this.state === "listening" && this.analyser) { + mic = this.normalizeLevel(this.computeRms()); + } else if (this.state === "speaking" && this.ttsAnalyser && this.ttsAnalyserData) { + tts = this.normalizeLevel( + this.computeRmsFromAnalyser(this.ttsAnalyser, this.ttsAnalyserData) + ); + } + this.emit({ type: "audio_level", mic, tts }); + } + ensureAudioLoop() { + if (this.audioLoopRunning) { + return; + } + this.audioLoopRunning = true; + this.lastVadFrameMs = nowMs(); + const tick = () => { + if (!this.audioLoopRunning || this.aborted) { + return; + } + this.emitAudioLevels(); + if (this.state === "listening") { + const now2 = nowMs(); + const dt = Math.min(120, now2 - this.lastVadFrameMs); + this.lastVadFrameMs = now2; + const rms = this.computeRms(); + this.observeAmbientNoise(rms); + const speech = rms > this.currentVadThreshold; + const primeSpeech = rms > PRECISE_START_RMS_THRESHOLD; + if (this.captureMode === "precise") { + if (speech) { + this.recentSpeechDetectedAt = now2; + this.peakSpeechRms = Math.max(this.peakSpeechRms, rms); + this.silenceMs = 0; + } + if (!this.speechActive) { + if (primeSpeech) { + const next = advanceVadSpeechDebounce( + this.vadSpeechStreakFrames, + true, + VAD_SPEECH_DEBOUNCE_FRAMES + ); + this.vadSpeechStreakFrames = next.streak; + if (next.commit) { + this.beginUtteranceRecording(now2, rms); + } + } else { + this.vadSpeechStreakFrames = 0; + } + } + } else if (speech) { + this.recentSpeechDetectedAt = now2; + this.peakSpeechRms = Math.max(this.peakSpeechRms, rms); + this.silenceMs = 0; + this.speechOnFrames += 1; + if (!this.speechActive && this.speechOnFrames >= VAD_SPEECH_ON_FRAMES) { + this.beginUtteranceRecording(now2, rms); + } + } else { + this.speechOnFrames = 0; + if (this.speechActive) { + this.silenceMs += dt; + if (this.silenceMs >= VAD_SILENCE_MS) { + void this.finishUtteranceRecording(); + } + } + } + } + this.audioLoopId = requestAnimationFrame(tick); + }; + this.audioLoopId = requestAnimationFrame(tick); + } + stopAudioLoop() { + this.audioLoopRunning = false; + if (this.audioLoopId) { + cancelAnimationFrame(this.audioLoopId); + this.audioLoopId = 0; + } + } + trimChunkTimeline(now2 = nowMs()) { + const keepSince = this.utteranceBufferStartMs ? Math.max( + this.utteranceBufferStartMs - RECORDER_SLICE_MS, + now2 - MAX_CAPTURE_HISTORY_MS + ) : now2 - PRE_ROLL_MS; + this.chunkTimeline = this.chunkTimeline.filter( + (chunk) => chunk.timestampMs >= keepSince + ); + } + trimPcmTimeline(now2 = nowMs()) { + const keepSince = this.utteranceBufferStartMs ? Math.max( + this.utteranceBufferStartMs - RECORDER_SLICE_MS, + now2 - MAX_CAPTURE_HISTORY_MS + ) : now2 - PRE_ROLL_MS; + this.pcmTimeline = this.pcmTimeline.filter((chunk) => chunk.endMs >= keepSince); + } + async startContinuousCapture() { + if (!this.micStream) { + return false; + } + if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") { + return true; + } + const mimeType = this.pickMimeType(); + let recorder = null; + try { + recorder = new MediaRecorder( + this.micStream, + mimeType ? { mimeType, audioBitsPerSecond: 64e3 } : { audioBitsPerSecond: 64e3 } + ); + } catch { + try { + recorder = new MediaRecorder( + this.micStream, + mimeType ? { mimeType } : {} + ); + } catch (error) { + assistantLogger.error("voice-agent", "MediaRecorder failed", error); + return false; + } + } + this.chunkTimeline = []; + this.pcmTimeline = []; + this.mediaRecorder = recorder; + this.recorderMimeType = recorder.mimeType || mimeType || "audio/webm"; + this.recorderStartedAt = nowMs(); + recorder.ondataavailable = (event) => { + const blob = eventBlob2(event); + if (!blob || blob.size <= 0) { + return; + } + this.chunkTimeline.push({ + blob, + timestampMs: nowMs() + }); + this.trimChunkTimeline(); + }; + try { + recorder.start(RECORDER_SLICE_MS); + return true; + } catch (error) { + assistantLogger.error("voice-agent", "MediaRecorder.start failed", error); + this.mediaRecorder = null; + return false; + } + } + async stopContinuousCapture() { + const recorder = this.mediaRecorder; + this.mediaRecorder = null; + if (!recorder || recorder.state === "inactive") { + return; + } + await new Promise((resolve) => { + const handleStop = () => { + resolve(); + }; + recorder.addEventListener("stop", handleStop, { once: true }); + try { + recorder.stop(); + } catch { + resolve(); + } + }); + } + beginUtteranceRecording(now2, rms) { + this.speechActive = true; + this.utteranceStartTime = now2; + this.utteranceBufferStartMs = Math.max( + this.recorderStartedAt, + now2 - PRE_ROLL_MS + ); + this.peakSpeechRms = Math.max(this.peakSpeechRms, rms); + this.emitVad(true); + } + resolveUtteranceStartMs(forceFlush) { + if (this.utteranceBufferStartMs > 0) { + return this.utteranceBufferStartMs; + } + if (!forceFlush || this.chunkTimeline.length === 0) { + return 0; + } + if (this.recentSpeechDetectedAt <= 0 && this.speechOnFrames === 0 && !this.speechActive) { + return 0; + } + const latestTimestamp = this.chunkTimeline[this.chunkTimeline.length - 1]?.timestampMs || nowMs(); + return Math.max( + this.recorderStartedAt, + latestTimestamp - MANUAL_FLUSH_LOOKBACK_MS + ); + } + buildUtteranceBlob(startMs) { + const selectedChunks = this.chunkTimeline.filter((chunk) => chunk.timestampMs >= startMs - RECORDER_SLICE_MS).map((chunk) => chunk.blob); + const mimeType = this.recorderMimeType || "audio/webm"; + return new Blob(selectedChunks, { type: mimeType }); + } + buildUtterancePcm(startMs) { + const selected = this.pcmTimeline.filter( + (chunk) => chunk.endMs >= startMs - RECORDER_SLICE_MS + ); + if (selected.length === 0) { + return null; + } + const sampleRate = selected[0]?.sampleRate || this.audioContext?.sampleRate || 48e3; + const trimmedChunks = []; + let totalLength = 0; + for (const chunk of selected) { + let startIndex = 0; + if (chunk.startMs < startMs && chunk.endMs > startMs) { + startIndex = Math.max( + 0, + Math.min( + chunk.samples.length, + Math.floor((startMs - chunk.startMs) / 1e3 * chunk.sampleRate) + ) + ); + } else if (chunk.endMs <= startMs) { + continue; + } + const slice = chunk.samples.subarray(startIndex); + if (slice.length === 0) { + continue; + } + trimmedChunks.push(new Float32Array(slice)); + totalLength += slice.length; + } + if (totalLength === 0) { + return null; + } + const samples = new Float32Array(totalLength); + let offset = 0; + for (const chunk of trimmedChunks) { + samples.set(chunk, offset); + offset += chunk.length; + } + return { samples, sampleRate }; + } + resetUtteranceState() { + this.speechActive = false; + this.silenceMs = 0; + this.speechOnFrames = 0; + this.utteranceStartTime = 0; + this.utteranceBufferStartMs = 0; + this.peakSpeechRms = 0; + this.emitVad(false); + } + finishUtteranceRecording(forceFlush = false, manualStop = false) { + if (this.finishUtterancePromise) { + return this.finishUtterancePromise; + } + const promise = this.finishUtteranceRecordingInternal( + forceFlush, + manualStop + ).finally(() => { + if (this.finishUtterancePromise === promise) { + this.finishUtterancePromise = null; + } + }); + this.finishUtterancePromise = promise; + return promise; + } + async finishUtteranceRecordingInternal(forceFlush = false, manualStop = false) { + const startMs = this.resolveUtteranceStartMs(forceFlush); + if (!startMs) { + this.resetUtteranceState(); + return; + } + const durationMs = Math.max(0, nowMs() - startMs); + const rms = this.peakSpeechRms || void 0; + await this.stopContinuousCapture(); + if (this.aborted) { + this.chunkTimeline = []; + this.pcmTimeline = []; + this.resetUtteranceState(); + return; + } + const audioBlob = this.buildUtteranceBlob(startMs); + const pcm = this.buildUtterancePcm(startMs); + this.chunkTimeline = []; + this.pcmTimeline = []; + this.resetUtteranceState(); + if (this.aborted) { + return; + } + const minMs = manualStop ? MANUAL_STOP_MIN_UTTERANCE_MS : VAD_MIN_UTTERANCE_MS; + const minBytes = manualStop ? MANUAL_STOP_MIN_UTTERANCE_BYTES : this.captureMode === "precise" ? AUTO_MIN_UTTERANCE_BYTES_PRECISE : MIN_UTTERANCE_BYTES; + if (durationMs < minMs || audioBlob.size < minBytes) { + if (manualStop) { + this.emit({ + type: "error", + message: "Recording was too short to transcribe. Hold the mic a moment longer, then tap the orb again." + }); + } + if (!this.aborted) { + this.resumeListeningAfterTurn(); + } + return; + } + await this.processUtteranceBlob(audioBlob, { durationMs, rms }, pcm, manualStop); + } + buildRawUtteranceBlob(audioBlob, details) { + const mimeType = audioBlob.type || this.recorderMimeType || "audio/webm"; + if (audioBlob.size < 256) { + return null; + } + return { + blob: audioBlob, + captureMeta: { + preprocessed: false, + mimeType, + durationMs: details.durationMs, + ...typeof details.rms === "number" ? { rms: details.rms } : {} + } + }; + } + async prepareUtteranceBlob(audioBlob, details, pcm) { + if (!pcm) { + assistantLogger.warn( + "voice-agent", + "PCM audio was unavailable; falling back to recorded audio upload", + { + originalMimeType: audioBlob.type || this.recorderMimeType || "audio/webm", + durationMs: details.durationMs + } + ); + return this.buildRawUtteranceBlob(audioBlob, details); + } + try { + const processedBlob = await this.preprocessPcmUtterance( + pcm.samples, + pcm.sampleRate + ); + if (!processedBlob || processedBlob.size < 256) { + assistantLogger.warn( + "voice-agent", + "PCM preprocessing produced no usable WAV; falling back to recorded audio upload", + { + originalMimeType: audioBlob.type || this.recorderMimeType || "audio/webm", + durationMs: details.durationMs, + pcmSampleRate: pcm.sampleRate, + pcmSamples: pcm.samples.length + } + ); + return this.buildRawUtteranceBlob(audioBlob, details); + } + return { + blob: processedBlob, + captureMeta: { + preprocessed: true, + mimeType: processedBlob.type || "audio/wav", + durationMs: details.durationMs, + ...typeof details.rms === "number" ? { rms: details.rms } : {}, + sampleRateHz: TARGET_TRANSCRIBE_SAMPLE_RATE, + channels: 1 + } + }; + } catch (error) { + assistantLogger.warn( + "voice-agent", + "Audio preprocessing failed; falling back to recorded audio upload", + error + ); + return this.buildRawUtteranceBlob(audioBlob, details); + } + } + async preprocessPcmUtterance(mono, sampleRate) { + if (!mono.length || !sampleRate) { + return null; + } + const frameCount = Math.max( + 1, + Math.ceil(mono.length / sampleRate * TARGET_TRANSCRIBE_SAMPLE_RATE) + ); + const offline = new OfflineAudioContext( + 1, + frameCount, + TARGET_TRANSCRIBE_SAMPLE_RATE + ); + const inputBuffer = offline.createBuffer(1, mono.length, sampleRate); + inputBuffer.copyToChannel(mono, 0); + const source = offline.createBufferSource(); + source.buffer = inputBuffer; + const highPass = offline.createBiquadFilter(); + highPass.type = "highpass"; + highPass.frequency.value = 85; + highPass.Q.value = 0.707; + const compressor = offline.createDynamicsCompressor(); + compressor.threshold.value = -24; + compressor.knee.value = 18; + compressor.ratio.value = 3; + compressor.attack.value = 3e-3; + compressor.release.value = 0.25; + source.connect(highPass); + highPass.connect(compressor); + compressor.connect(offline.destination); + source.start(0); + const rendered = await offline.startRendering(); + return this.encodeWavBlob(rendered); + } + encodeWavBlob(buffer) { + const samples = buffer.getChannelData(0); + let peak = 0; + for (let index2 = 0; index2 < samples.length; index2++) { + peak = Math.max(peak, Math.abs(samples[index2])); + } + const gain = peak > 0 ? Math.min(4, 0.92 / peak) : 1; + const bytesPerSample = 2; + const dataLength = samples.length * bytesPerSample; + const wav = new ArrayBuffer(44 + dataLength); + const view = new DataView(wav); + const writeAscii = (offset2, text2) => { + for (let index2 = 0; index2 < text2.length; index2++) { + view.setUint8(offset2 + index2, text2.charCodeAt(index2)); + } + }; + writeAscii(0, "RIFF"); + view.setUint32(4, 36 + dataLength, true); + writeAscii(8, "WAVE"); + writeAscii(12, "fmt "); + view.setUint32(16, 16, true); + view.setUint16(20, 1, true); + view.setUint16(22, 1, true); + view.setUint32(24, buffer.sampleRate, true); + view.setUint32(28, buffer.sampleRate * bytesPerSample, true); + view.setUint16(32, bytesPerSample, true); + view.setUint16(34, 16, true); + writeAscii(36, "data"); + view.setUint32(40, dataLength, true); + let offset = 44; + for (let index2 = 0; index2 < samples.length; index2++) { + const sample = clamp(samples[index2] * gain, -1, 1); + view.setInt16( + offset, + sample < 0 ? sample * 32768 : sample * 32767, + true + ); + offset += bytesPerSample; + } + return new Blob([wav], { type: "audio/wav" }); + } + async processUtteranceBlob(audioBlob, details, pcm, manualStop = false) { + if (this.aborted) { + return; + } + this.setState("transcribing"); + try { + const prepared = await this.prepareUtteranceBlob(audioBlob, details, pcm); + if (!prepared) { + this.emit({ + type: "error", + message: "I couldn't process that audio. Please try again." + }); + this.resumeListeningAfterTurn(); + return; + } + assistantLogger.info("voice-agent", "Audio preprocessing succeeded", { + ...prepared.captureMeta, + originalMimeType: audioBlob.type || this.recorderMimeType || "audio/webm" + }); + assistantLogger.info("voice-agent", "Submitting utterance for transcription", { + ...prepared.captureMeta, + originalMimeType: audioBlob.type || this.recorderMimeType || "audio/webm" + }); + const { transcript } = await transcribeAudio(prepared.blob, { + captureMeta: prepared.captureMeta + }); + if (!transcript || this.aborted) { + this.resumeListeningAfterTurn(); + return; + } + if (shouldDiscardAutoTranscript(transcript, manualStop)) { + this.emit({ + type: "error", + message: "That was too short to interpret. Say a bit more, or tap the orb when you are done." + }); + this.resumeListeningAfterTurn(); + return; + } + this.emit({ type: "userTranscript", text: transcript }); + await this.runTurn(transcript); + } catch (error) { + assistantLogger.error("voice-agent", "Transcription failed", error); + this.emit({ type: "error", message: transcribeFailureUserMessage(error) }); + this.resumeListeningAfterTurn(); + } + } + async startListening(options) { + if (this.state === "idle") { + await this.startConversation(options?.source || "user"); + } + } + async finishListening() { + if (this.state !== "listening") { + return; + } + await this.finishUtteranceRecording(true, true); + } + resumeListeningAfterTurn(echoGuardMs = 0) { + void this.resumeListeningAfterTurnInternal(echoGuardMs); + } + async resumeListeningAfterTurnInternal(echoGuardMs = 0) { + if (this.aborted) { + return; + } + if (this.preferredListeningSource === "user") { + this.setState("idle"); + return; + } + if (echoGuardMs > 0) { + this.emitListeningPhase("echo_guard"); + await new Promise((resolve) => { + setTimeout(resolve, echoGuardMs); + }); + if (this.aborted) { + return; + } + } + this.lastVadFrameMs = nowMs(); + this.resetListeningCalibration(); + this.setMicTracksEnabled(true); + if (this.audioContext?.state === "suspended") { + try { + await this.audioContext.resume(); + } catch (error) { + assistantLogger.error("voice-agent", "AudioContext.resume failed", error); + if (!this.aborted) { + this.stop(); + this.emit({ + type: "error", + message: "Tap the microphone button to enable listening." + }); + } + return; + } + } + const started = await this.startContinuousCapture(); + if (!started) { + if (!this.aborted) { + this.stop(); + this.emit({ + type: "error", + message: "Could not restart microphone capture." + }); + } + return; + } + if (this.aborted) { + return; + } + this.setState("listening", this.preferredListeningSource); + this.ensureAudioLoop(); + this.emitListeningPhase("capturing"); + this.speechPrimeFrames = 0; + } + async runTurn(transcript) { + if (!this.runAssistant) { + this.emit({ type: "error", message: "Assistant not connected." }); + this.resumeListeningAfterTurn(); + return; + } + const useSpoken = this.voiceSpokenRepliesEnabled; + const win = globalThis; + this.setState("thinking"); + this.setMicTracksEnabled(false); + let aiMessageId; + if (!useSpoken && typeof win.oasisVoiceAssistantTurnBegin === "function") { + try { + aiMessageId = win.oasisVoiceAssistantTurnBegin(transcript); + } catch { + aiMessageId = void 0; + } + } + if (!useSpoken && !aiMessageId) { + aiMessageId = randomAssistantMessageId(); + } + const onChunk = (chunk) => { + if (!useSpoken && aiMessageId && win.oasisVoiceAssistantStreamChunk) { + try { + win.oasisVoiceAssistantStreamChunk(aiMessageId, chunk); + } catch { + } + } + }; + const voiceDelivery = useSpoken ? "spoken" : "text_chat"; + let fullResponse = ""; + try { + fullResponse = await this.runAssistant( + transcript, + onChunk, + "voice", + aiMessageId, + voiceDelivery + ); + } catch (error) { + assistantLogger.error("voice-agent", "Assistant failed", error); + this.emit({ type: "error", message: "Assistant error." }); + this.resumeListeningAfterTurn(); + return; + } + if (this.aborted || !fullResponse.trim()) { + this.emit({ type: "turn_done" }); + this.resumeListeningAfterTurn(); + return; + } + if (useSpoken) { + this.setState("speaking"); + try { + await this.speak(fullResponse); + } catch (error) { + assistantLogger.error("voice-agent", "TTS failed", error); + } + if (typeof win.oasisVoiceSpokenTurnMirror === "function") { + try { + win.oasisVoiceSpokenTurnMirror(transcript, fullResponse); + } catch { + } + } + this.emit({ type: "assistant_reply_text", text: fullResponse }); + this.emit({ type: "turn_done" }); + this.resumeListeningAfterTurn(ECHO_GUARD_MS_AFTER_TTS); + return; + } + this.emit({ type: "turn_done" }); + this.resumeListeningAfterTurn(ECHO_GUARD_MS_AFTER_TEXT_REPLY); + } + async speak(text2) { + const plain = normalizeTextForSpeech(makeSpeechFriendlyReply(text2)); + if (!plain) { + return; + } + const requestId = ++this.ttsRequestId; + window.dispatchEvent( + new CustomEvent(TTS_STOP_EVENT, { + detail: { source: "voice-agent" } + }) + ); + try { + const blob = await textToSpeech(plain); + if (this.aborted || requestId !== this.ttsRequestId || this.state !== "speaking") { + return; + } + const url = URL.createObjectURL(blob); + this.ttsObjectUrl = url; + return new Promise((resolve) => { + let settled = false; + const finish = () => { + if (settled) { + return; + } + settled = true; + if (this.activeSpeakCleanup === finish) { + this.activeSpeakCleanup = null; + } + this.cleanupAudio(); + resolve(); + }; + const audio = new Audio(url); + this.ttsAudio = audio; + this.activeSpeakCleanup = finish; + this.disconnectTtsGraph(); + if (this.audioContext) { + try { + const source = this.audioContext.createMediaElementSource(audio); + const analyser = this.audioContext.createAnalyser(); + analyser.fftSize = 512; + analyser.smoothingTimeConstant = 0.55; + source.connect(analyser); + analyser.connect(this.audioContext.destination); + this.mediaElementSource = source; + this.ttsAnalyser = analyser; + this.ttsAnalyserData = new Uint8Array(analyser.fftSize); + } catch (error) { + assistantLogger.error("voice-agent", "TTS audio graph failed", error); + this.disconnectTtsGraph(); + } + } + audio.onended = finish; + audio.onerror = finish; + void audio.play().catch(finish); + }); + } catch { + if (requestId === this.ttsRequestId) { + this.activeSpeakCleanup = null; + } + this.cleanupAudio(); + } + } + disconnectTtsGraph() { + if (this.mediaElementSource) { + try { + this.mediaElementSource.disconnect(); + } catch { + } + this.mediaElementSource = null; + } + if (this.ttsAnalyser) { + try { + this.ttsAnalyser.disconnect(); + } catch { + } + this.ttsAnalyser = null; + } + this.ttsAnalyserData = null; + } + stop() { + this.aborted = true; + this.preferredListeningSource = "handsfree"; + this.ttsRequestId += 1; + this.stopAudioLoop(); + const finish = this.activeSpeakCleanup; + this.activeSpeakCleanup = null; + if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") { + try { + this.mediaRecorder.stop(); + } catch { + } + } + this.mediaRecorder = null; + this.chunkTimeline = []; + this.recorderMimeType = ""; + this.resetUtteranceState(); + this.releaseAudioContext(); + this.releaseMic(); + if (finish) { + finish(); + } else { + this.cleanupAudio(); + } + this.setState("idle"); + } + stopSpeaking() { + this.ttsRequestId += 1; + const finish = this.activeSpeakCleanup; + this.activeSpeakCleanup = null; + if (finish) { + finish(); + } else { + this.cleanupAudio(); + } + if (this.state === "speaking") { + this.emit({ type: "turn_done" }); + this.resumeListeningAfterTurn(ECHO_GUARD_MS_AFTER_TTS_INTERRUPT); + } + } + releaseAudioContext() { + if (this.micSource) { + try { + this.micSource.disconnect(); + } catch { + } + this.micSource = null; + } + if (this.pcmProcessor) { + try { + this.pcmProcessor.disconnect(); + } catch { + } + this.pcmProcessor.onaudioprocess = null; + this.pcmProcessor = null; + } + if (this.pcmSink) { + try { + this.pcmSink.disconnect(); + } catch { + } + this.pcmSink = null; + } + if (this.audioContext) { + try { + void this.audioContext.close(); + } catch { + } + this.audioContext = null; + } + this.analyser = null; + this.vadData = null; + this.pcmTimeline = []; + } + releaseMic() { + if (this.micStream) { + this.micStream.getTracks().forEach((track) => track.stop()); + this.micStream = null; + } + } + cleanupAudio() { + this.disconnectTtsGraph(); + if (this.ttsAudio) { + this.ttsAudio.pause(); + this.ttsAudio = null; + } + if (this.ttsObjectUrl) { + URL.revokeObjectURL(this.ttsObjectUrl); + this.ttsObjectUrl = null; + } + } + pickMimeType() { + const types = [ + "audio/webm;codecs=opus", + "audio/webm", + "audio/ogg;codecs=opus", + "audio/ogg", + "audio/mp4" + ]; + for (const type of types) { + if (MediaRecorder.isTypeSupported(type)) { + return type; + } + } + return ""; + } + }; + var voiceAgent = new VoiceAgentService(); + var voiceAgent_default = voiceAgent; + + // src/assistant.ts + var supabaseAuth4 = SupabaseAuth.getInstance(); + var assistantWindow = window; + assistantWindow.supabaseAuth = supabaseAuth4; + assistantWindow.subscriptionService = subscriptionService; + assistantWindow.voiceInputService = voiceInput_default; + assistantWindow.textToSpeech = textToSpeech; + assistantWindow.marked = d; + assistantWindow.DOMPurify = purify; + var aw = assistantWindow; + aw.oasisSetOAuthCallbackBaseUrl = (url) => supabaseAuth4.setOAuthCallbackBaseUrl(url); + aw.oasisGetOAuthCallbackBaseUrl = () => supabaseAuth4.getOAuthCallbackBaseUrl(); + var sessionController = createAssistantSessionController(assistantWindow); + var oasisCapabilitiesMarkdownCache = null; + function getOasisCapabilitiesMarkdown() { + if (oasisCapabilitiesMarkdownCache == null) { + const { assistTools } = createAssistantCommandsRegistry(); + oasisCapabilitiesMarkdownCache = buildCapabilitiesOverviewMarkdown(assistTools); + } + return oasisCapabilitiesMarkdownCache; + } + assistantWindow.getOasisCapabilitiesMarkdown = getOasisCapabilitiesMarkdown; + function oasisPushLocalChatTurn(userText, assistantMarkdown) { + sessionController.pushCurrentTurn(userText, assistantMarkdown); + try { + assistantWindow.dispatchEvent(new CustomEvent(OASIS_EVENT_HISTORY_UPDATE)); + } catch { + } + } + assistantWindow.oasisPushLocalChatTurn = oasisPushLocalChatTurn; + function resetAssistantSession() { + sessionController.resetAssistantSession(); + } + assistantWindow.resetAssistantSession = resetAssistantSession; + function getAssistantHistory() { + return sessionController.getAssistantHistory(); + } + assistantWindow.getAssistantHistory = getAssistantHistory; + function oasisSyncSessionFromPlainTurns(turns) { + sessionController.syncSessionFromPlainTurns(turns); + } + assistantWindow.oasisSyncSessionFromPlainTurns = oasisSyncSessionFromPlainTurns; + function oasisSetRailroadSessionKey(key) { + if (key == null || key === "") { + assistantWindow.oasisRailroadSessionKey = void 0; + } else { + assistantWindow.oasisRailroadSessionKey = key; + } + invalidateRailroadSessionCache(); + } + assistantWindow.oasisSetRailroadSessionKey = oasisSetRailroadSessionKey; + async function runAssistantStream(prompt, onChunk, inputType = "text", messageId, voiceDelivery = "spoken") { + const isAuthenticated = await supabaseAuth4.isAuthenticated(); + const { commands: commands2, toolCommandNames, assistTools } = createAssistantCommandsRegistry(); + const railroadMemoryBlock = await getRailroadMemoryPromptBlock(assistantWindow); + const graph = buildAssistantGraph( + commands2, + assistantWindow, + messageId, + assistTools, + { railroadMemoryBlock } + ); + const sessionHistory = sessionController.getCurrentSessionMessages(); + const voiceSystemAddendum = inputType === "voice" ? voiceDelivery === "text_chat" ? VOICE_CHAT_TEXT_REPLY_ADDENDUM : VOICE_REPLY_ADDENDUM : null; + const stream = await graph.stream( + { + messages: [ + ...sessionHistory, + ...voiceSystemAddendum ? [new SystemMessage(voiceSystemAddendum)] : [], + new HumanMessage({ content: prompt }) + ] + }, + { recursionLimit: ASSISTANT_RECURSION_LIMIT } + ); + const combined = await consumeAssistantGraphStream({ + stream, + prompt, + onChunk, + inputType, + toolCommandNames, + pushCurrentTurn: sessionController.pushCurrentTurn, + trackUsage: (nextInputType, meta) => { + if (isAuthenticated) { + subscriptionService.trackUsage(nextInputType, void 0, meta); + } + } + }); + void recordRailroadTurn(assistantWindow, prompt, combined); + maybeRunRailroadStructuredExtraction(assistantWindow, prompt, combined); + return combined; + } + assistantWindow.runAssistantStream = runAssistantStream; + voiceAgent_default.setRunAssistant(runAssistantStream); + assistantWindow.voiceAgent = voiceAgent_default; +})(); +/*! @license DOMPurify 3.3.1 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.3.1/LICENSE */ +/*! Bundled license information: + +tslib/tslib.es6.js: + (*! ***************************************************************************** + 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. + ***************************************************************************** *) + +@langchain/core/dist/utils/fast-json-patch/src/helpers.js: + (*! + * https://github.com/Starcounter-Jack/JSON-Patch + * (c) 2017-2022 Joachim Wester + * MIT licensed + *) + +@langchain/core/dist/utils/fast-json-patch/src/duplex.js: + (*! + * https://github.com/Starcounter-Jack/JSON-Patch + * (c) 2013-2021 Joachim Wester + * MIT license + *) +*/ diff --git a/browser/base/content/assistant/assistant.css b/browser/base/content/assistant/assistant.css new file mode 100644 index 0000000000000..a7a1f3a1d2c31 --- /dev/null +++ b/browser/base/content/assistant/assistant.css @@ -0,0 +1,8 @@ + +/* Basic Markdown styles */ +.ai-message strong { font-weight: bold; } +.ai-message em { font-style: italic; } +.ai-message code { background: #f4f4f4; padding: 2px 4px; border-radius: 3px; font-family: monospace; } +.ai-message pre { background: #f4f4f4; padding: 8px; border-radius: 5px; overflow-x: auto; } +.ai-message ul, .ai-message ol { margin-left: 20px; } +.ai-message a { color: #007acc; text-decoration: underline; } diff --git a/browser/base/content/assistant/assistant.ui.js b/browser/base/content/assistant/assistant.ui.js new file mode 100644 index 0000000000000..a3cc3c3a7dc67 --- /dev/null +++ b/browser/base/content/assistant/assistant.ui.js @@ -0,0 +1,866 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +// Privileged shim - runs in chrome (privileged) context +// This file acts as the bridge between the privileged Firefox environment and the content-based Preact UI. + +(function () { + const Services = + window.Services || + ChromeUtils.import("resource://gre/modules/Services.jsm").Services; + + function normalizeAssistantOpenTabUrl(url) { + if (!url) { + return url; + } + if (/^[a-z][a-z0-9+.-]*:/i.test(url)) { + return url; + } + if (/^https?:\/\//i.test(url)) { + return url; + } + return `https://${url}`; + } + + const OASIS_ASSISTANT_THEME_PREF = "browser.oasis.assistant.theme"; + const OASIS_ASSISTANT_THEME_IDS = new Set([ + "default", + "traditional-light", + "neutral-light", + "clean-light", + "warm-light", + "ide-light", + "vs-light", + "light-modern", + "light-plus", + "quiet-light", + "solarized-light", + "traditional-dark", + "violet-dark", + "forest-dark", + "slate-dark", + "high-contrast", + "cool-dark", + "midnight-dark", + "vs-dark", + "dark-modern", + "dark-plus", + "abyss", + "kimbie-dark", + "monokai", + ]); + + function normalizeAssistantThemeId(id) { + return typeof id === "string" && OASIS_ASSISTANT_THEME_IDS.has(id) + ? id + : "default"; + } + + window.assistantBridge = { + openTab(url) { + try { + const fixed = normalizeAssistantOpenTabUrl(url); + try { + const win = Services.wm.getMostRecentWindow("navigator:browser"); + if (win?.openTrustedLinkIn) { + win.openTrustedLinkIn(fixed, "tab"); + return true; + } + if (win?.openWebLinkIn) { + win.openWebLinkIn(fixed, "tab", {}); + return true; + } + if (win?.gBrowser?.addTrustedTab) { + win.gBrowser.selectedTab = win.gBrowser.addTrustedTab(fixed, { + inBackground: false, + }); + return true; + } + if (win?.gBrowser) { + win.gBrowser.selectedTab = win.gBrowser.addTab(fixed, { + triggeringPrincipal: + Services.scriptSecurityManager.getSystemPrincipal(), + inBackground: false, + }); + return true; + } + } catch (e) { + console.warn( + "assistantBridge: failed to open tab via browser window", + e + ); + } + const opened = window.open(fixed); + return !!opened; + } catch (e) { + console.error("assistantBridge.openTab error", e); + return false; + } + }, + postOasisOverlayChromeMessage(data) { + try { + if (!data || typeof data !== "object") { + return false; + } + const win = Services.wm.getMostRecentWindow("navigator:browser"); + if (!win) { + return false; + } + const overlayBrowser = win.document.getElementById( + "oasis-assistant-overlay-browser" + ); + const sidebarBrowser = win.SidebarController?.browser; + const isOverlayChild = + overlayBrowser?.contentWindow && + overlayBrowser.contentWindow === window; + const isSidebarChild = + sidebarBrowser?.contentWindow && + sidebarBrowser.contentWindow === window; + if (!isOverlayChild && !isSidebarChild) { + return false; + } + let origin = ""; + try { + origin = String(window.location.origin || ""); + } catch (e) { + void e; + } + const ev = new win.MessageEvent("message", { + bubbles: false, + cancelable: false, + data, + origin, + source: window, + ports: [], + }); + win.dispatchEvent(ev); + return true; + } catch (e) { + console.warn("assistantBridge.postOasisOverlayChromeMessage", e); + return false; + } + }, + runOasisAssistantLayoutToggle() { + try { + const win = Services.wm.getMostRecentWindow("navigator:browser"); + const sc = win?.SidebarController; + if (!win || !sc || typeof sc.show !== "function") { + return false; + } + const overlayBrowser = win.document.getElementById( + "oasis-assistant-overlay-browser" + ); + const sidebarBrowser = sc.browser; + const inOverlay = + overlayBrowser?.contentWindow && + overlayBrowser.contentWindow === window; + const inSidebar = + sidebarBrowser?.contentWindow && + sidebarBrowser.contentWindow === window; + if (!inOverlay && !inSidebar) { + return false; + } + if (typeof sc._switchOasisAssistantLayout !== "function") { + return false; + } + return sc._switchOasisAssistantLayout(); + } catch (e) { + console.warn("assistantBridge.runOasisAssistantLayoutToggle", e); + return false; + } + }, + getAssistantTheme() { + try { + const v = Services.prefs.getStringPref( + OASIS_ASSISTANT_THEME_PREF, + "default" + ); + return normalizeAssistantThemeId(v); + } catch (e) { + void e; + return "default"; + } + }, + setAssistantTheme(id) { + try { + const next = normalizeAssistantThemeId(id); + Services.prefs.setStringPref(OASIS_ASSISTANT_THEME_PREF, next); + } catch (e) { + void e; + } + }, + async getAssistantHistory() { + try { + const HIST_USERNAME = "oasis_assistant_history"; + const logins = Services.logins.findLogins( + LOGIN_HOSTNAME, + null, + LOGIN_REALM + ); + const entry = logins.find(l => l.username === HIST_USERNAME); + if (entry) { + try { + return JSON.parse(entry.password); + } catch (e) { + void e; + } + } + } catch (e) { + console.error("assistantBridge.getAssistantHistory error", e); + } + return null; + }, + async setAssistantHistory(history) { + try { + const HIST_USERNAME = "oasis_assistant_history"; + // Remove any existing history entry + try { + const logins = Services.logins.findLogins( + LOGIN_HOSTNAME, + null, + LOGIN_REALM + ); + for (const l of logins) { + if (l.username === HIST_USERNAME) { + Services.logins.removeLogin(l); + } + } + } catch (e) { + // Non-fatal + } + + const loginInfo = new Components.Constructor( + "@mozilla.org/login-manager/loginInfo;1", + Ci.nsILoginInfo, + "init" + )( + LOGIN_HOSTNAME, + null, + LOGIN_REALM, + HIST_USERNAME, + JSON.stringify(history || []), + "", + "" + ); + await Services.logins.addLoginAsync(loginInfo); + // Notify any UI instances that history changed + try { + window.dispatchEvent(new CustomEvent("oasis-history-update")); + } catch (e) { + void e; + } + } catch (e) { + console.error("assistantBridge.setAssistantHistory error", e); + } + }, + getAuthState() { + return window.oasisAuthState || { isAuthenticated: false, user: null }; + }, + getOnboardingStatus() { + try { + return { + guidedFlowEnabled: Services.prefs.getBoolPref( + "browser.oasis.onboarding.guidedFlowEnabled", + true + ), + migrationCompleted: Services.prefs.getBoolPref( + "browser.oasis.onboarding.migrationCompleted", + false + ), + postMigrationTipShown: Services.prefs.getBoolPref( + "browser.oasis.onboarding.postMigrationTipShown", + false + ), + checklistDismissed: Services.prefs.getBoolPref( + "browser.oasis.onboarding.checklistDismissed", + false + ), + oauthAttemptStarted: Services.prefs.getBoolPref( + "browser.oasis.onboarding.oauthAttemptStarted", + false + ), + importOptOut: Services.prefs.getBoolPref( + "browser.oasis.onboarding.importOptOut", + false + ), + firstAiTurnComplete: Services.prefs.getBoolPref( + "browser.oasis.onboarding.firstAiTurnComplete", + false + ), + welcomeCompleted: Services.prefs.getBoolPref( + "browser.oasis.welcome.completed", + false + ), + }; + } catch (e) { + console.error("assistantBridge.getOnboardingStatus error", e); + return { + guidedFlowEnabled: true, + migrationCompleted: false, + postMigrationTipShown: false, + checklistDismissed: false, + oauthAttemptStarted: false, + importOptOut: false, + firstAiTurnComplete: false, + welcomeCompleted: false, + }; + } + }, + markOauthSignInStarted() { + try { + Services.prefs.setBoolPref( + "browser.oasis.onboarding.oauthAttemptStarted", + true + ); + } catch (e) { + void e; + } + }, + dismissOnboardingChecklist() { + try { + Services.prefs.setBoolPref( + "browser.oasis.onboarding.checklistDismissed", + true + ); + } catch (e) { + void e; + } + }, + markImportOptOut() { + try { + if ( + Services.prefs.getBoolPref( + "browser.oasis.onboarding.importOptOut", + false + ) + ) { + return; + } + Services.prefs.setBoolPref( + "browser.oasis.onboarding.importOptOut", + true + ); + window.dispatchEvent(new CustomEvent("oasis-onboarding-update")); + } catch (e) { + void e; + } + }, + markFirstAiTurnComplete() { + try { + if ( + Services.prefs.getBoolPref( + "browser.oasis.onboarding.firstAiTurnComplete", + false + ) + ) { + return; + } + Services.prefs.setBoolPref( + "browser.oasis.onboarding.firstAiTurnComplete", + true + ); + window.dispatchEvent(new CustomEvent("oasis-onboarding-update")); + } catch (e) { + void e; + } + }, + openImportBrowserData() { + try { + const win = Services.wm.getMostRecentWindow("navigator:browser"); + if (!win) { + return false; + } + const { MigrationUtils } = ChromeUtils.importESModule( + "resource:///modules/MigrationUtils.sys.mjs" + ); + void MigrationUtils.showMigrationWizard(win, { + entrypoint: MigrationUtils.MIGRATION_ENTRYPOINTS.UNKNOWN, + }); + return true; + } catch (e) { + console.error("assistantBridge.openImportBrowserData error", e); + return false; + } + }, + }; +})(); + +// Expose global helpers for existing UI code that expects `window.getAssistantHistory` / `window.setAssistantHistory` +try { + if (typeof window.getAssistantHistory !== "function") { + window.getAssistantHistory = function () { + try { + if ( + window.assistantBridge && + typeof window.assistantBridge.getAssistantHistory === "function" + ) { + return window.assistantBridge.getAssistantHistory(); + } + } catch (e) { + console.error("window.getAssistantHistory error", e); + } + return null; + }; + } + + if (typeof window.setAssistantHistory !== "function") { + window.setAssistantHistory = async function (history) { + try { + if ( + window.assistantBridge && + typeof window.assistantBridge.setAssistantHistory === "function" + ) { + return await window.assistantBridge.setAssistantHistory(history); + } + } catch (e) { + console.error("window.setAssistantHistory error", e); + } + return undefined; + }; + } +} catch (e) { + console.error("Failed to expose assistant history globals", e); +} + +const MIXPANEL_TOKEN = "4a23d4890cf107ac290b2d5e878e2561"; + +// --- Dynamic Loader for Preact Bundle --- +(function () { + try { + const ASSISTANT_CONTENT_BASE = "chrome://browser/content/assistant/"; + const bundleSrc = ASSISTANT_CONTENT_BASE + "dist/assistant.ui.bundle.js"; + const cssSrc = ASSISTANT_CONTENT_BASE + "dist/assistant.ui.bundle.css"; + + const link = document.createElement("link"); + link.rel = "stylesheet"; + link.href = cssSrc; + document.head.appendChild(link); + + const script = document.createElement("script"); + script.src = bundleSrc; + script.async = false; + script.onerror = e => + console.error("assistant: Failed to load Preact UI bundle", e); + document.head.appendChild(script); + + // Create Root Element if it doesn't exist + // The Preact app mounts to 'assistant-preact-root' + if (!document.getElementById("assistant-preact-root")) { + const root = document.createElement("div"); + root.id = "assistant-preact-root"; + document.body.appendChild(root); + } + } catch (e) { + console.error("assistant: dynamic loader failed", e); + } +})(); + +// --- Mixpanel Tracking --- +let __oasisAnonId = null; +function oasisAnalyticsDisabled() { + try { + return typeof Cu !== "undefined" && Cu.isInAutomation; + } catch (e) { + void e; + return false; + } +} +function getDistinctId() { + try { + const key = "oasis_anon_distinct_id"; + const existing = sessionStorage.getItem(key); + if (existing) { + return existing; + } + const v = + crypto && crypto.randomUUID ? crypto.randomUUID() : String(Math.random()); + sessionStorage.setItem(key, v); + return v; + } catch (e) { + if (!__oasisAnonId) { + __oasisAnonId = + crypto && crypto.randomUUID + ? crypto.randomUUID() + : String(Math.random()); + } + return __oasisAnonId; + } +} +function mpTrack(event, props = {}) { + if (oasisAnalyticsDisabled()) { + return; + } + const distinct = + window.oasisAuthState?.user?.id || + window.oasisAuthState?.user?.email || + getDistinctId(); + const body = [ + { + event, + properties: { + token: MIXPANEL_TOKEN, + distinct_id: distinct, + authenticated: !!window.oasisAuthState?.isAuthenticated, + user_email: window.oasisAuthState?.user?.email || null, + user_id: window.oasisAuthState?.user?.id || null, + ...props, + }, + }, + ]; + try { + const data = btoa(JSON.stringify(body)); + fetch("https://api.mixpanel.com/track?ip=1", { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: "data=" + encodeURIComponent(data), + keepalive: true, + }).catch(() => {}); + } catch (e) { + void e; + } +} +function mpIdentify(user) { + if (oasisAnalyticsDisabled()) { + return; + } + const distinct = user?.id || user?.email || getDistinctId(); + const body = [ + { + $token: MIXPANEL_TOKEN, + $distinct_id: distinct, + $set: { + $email: user?.email || undefined, + }, + }, + ]; + try { + const data = btoa(JSON.stringify(body)); + fetch("https://api.mixpanel.com/engage#profile-set", { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: "data=" + encodeURIComponent(data), + keepalive: true, + }).catch(() => {}); + } catch (e) { + void e; + } +} +window.mpTrack = mpTrack; +window.mpIdentify = mpIdentify; + +mpTrack("assistant_ui_loaded_preact"); + +// --- Auth State Management & Secure Storage --- +// SupabaseAuth should be available from assistant.bundle.js + +const LOGIN_HOSTNAME = "https://kahana.co"; +const LOGIN_REALM = "Oasis Assistant"; +const LOGIN_USERNAME = "oasis_assistant_session"; +const OAUTH_HANDOFF_COOKIE_NAME = "oasis_assistant_handoff"; +const ASSISTANT_OAUTH_TARGET = "assistant"; + +let assistantOAuthHandoffInFlight = false; + +function readAssistantOAuthHandoffEntry() { + if (!Services?.cookies) { + return null; + } + try { + let latest = null; + for (const cookie of Services.cookies.cookies) { + if (cookie.name !== OAUTH_HANDOFF_COOKIE_NAME) { + continue; + } + try { + const payload = JSON.parse(decodeURIComponent(cookie.value)); + const timestamp = payload?.timestamp || 0; + const handoffTarget = payload.handoff_target || payload.target; + if (handoffTarget && handoffTarget !== ASSISTANT_OAUTH_TARGET) { + continue; + } + if (!latest || timestamp > (latest.payload?.timestamp || 0)) { + latest = { cookie, payload }; + } + } catch (e) { + console.error("Assistant: Failed to parse OAuth handoff cookie:", e); + } + } + return latest; + } catch (e) { + console.error("Assistant: Failed to read OAuth handoff cookies:", e); + } + return null; +} + +function clearAssistantHandoffCookie(cookie) { + if (!Services?.cookies || !cookie) { + return; + } + try { + Services.cookies.remove( + cookie.host, + cookie.name, + cookie.path, + cookie.originAttributes || {} + ); + } catch (e) { + console.error("Assistant: Failed to clear OAuth handoff cookie:", e); + } +} + +function dispatchAssistantAuthError(message) { + try { + window.dispatchEvent( + new CustomEvent("oasis-auth-error", { + detail: { description: message, error: message }, + }) + ); + } catch (e) {} +} + +function openOasisWelcomeIfNeededAfterAssistantAuth() { + try { + const { OasisWelcomeManager, navigatePostAuthLanding } = + ChromeUtils.importESModule( + "resource:///modules/oasiswelcome/OasisWelcomeManager.sys.mjs" + ); + const win = Services.wm.getMostRecentWindow("navigator:browser"); + if (!win) { + return; + } + if (OasisWelcomeManager?.shouldShowAboutWelcomePage?.()) { + OasisWelcomeManager.openWelcomePage(win); + return; + } + if (typeof navigatePostAuthLanding === "function") { + navigatePostAuthLanding(win); + } + } catch (e) { + console.warn("Assistant: could not navigate after sign-in:", e); + } +} + +async function tryConsumeAssistantOAuthHandoffCookie() { + if (assistantOAuthHandoffInFlight) { + return; + } + if (window.oasisAuthState?.isAuthenticated) { + return; + } + if (!window.supabaseAuth?.handleOAuthCallbackData) { + return; + } + const entry = readAssistantOAuthHandoffEntry(); + if (!entry) { + return; + } + assistantOAuthHandoffInFlight = true; + try { + const { cookie, payload } = entry; + if (payload.error) { + clearAssistantHandoffCookie(cookie); + dispatchAssistantAuthError( + payload.description || payload.error || "OAuth sign-in failed" + ); + return; + } + const result = await window.supabaseAuth.handleOAuthCallbackData(payload); + clearAssistantHandoffCookie(cookie); + if (!result?.success) { + dispatchAssistantAuthError( + result?.error || "Failed to complete OAuth sign-in" + ); + } else { + openOasisWelcomeIfNeededAfterAssistantAuth(); + } + } catch (e) { + console.error("Assistant OAuth handoff failed:", e); + clearAssistantHandoffCookie(entry.cookie); + dispatchAssistantAuthError( + e instanceof Error ? e.message : "OAuth handoff failed" + ); + } finally { + assistantOAuthHandoffInFlight = false; + } +} + +function startAssistantOAuthHandoffPolling() { + window.setInterval(() => { + void tryConsumeAssistantOAuthHandoffCookie(); + }, 1500); +} + +// Secure Storage Functions (Privileged) +async function securelySaveSession(session) { + if (!session || !session.access_token) { + return; + } + try { + const logins = Services.logins.findLogins( + LOGIN_HOSTNAME, + null, + LOGIN_REALM + ); + for (const login of logins) { + if (login.username === LOGIN_USERNAME) { + Services.logins.removeLogin(login); + } + } + + const loginInfo = new Components.Constructor( + "@mozilla.org/login-manager/loginInfo;1", + Ci.nsILoginInfo, + "init" + )( + LOGIN_HOSTNAME, + null, + LOGIN_REALM, + LOGIN_USERNAME, + JSON.stringify({ + access_token: session.access_token, + refresh_token: session.refresh_token, + expires_at: session.expires_at, + user: session.user, + }), + "", + "" + ); + await Services.logins.addLoginAsync(loginInfo); + } catch (e) { + console.error("Failed to save session securely:", e); + } +} + +async function securelyLoadSession() { + try { + const logins = Services.logins.findLogins( + LOGIN_HOSTNAME, + null, + LOGIN_REALM + ); + const login = logins.find(l => l.username === LOGIN_USERNAME); + + if (login) { + const sessionData = JSON.parse(login.password); + + if (window.supabaseAuth && window.supabaseAuth.supabase) { + const { data, error } = + await window.supabaseAuth.supabase.auth.setSession({ + access_token: sessionData.access_token, + refresh_token: sessionData.refresh_token, + }); + + if (!error && data.session) { + return data.session; + } + void error; + securelyClearSession(); + } + } + } catch (e) { + console.error("Failed to load secure session:", e); + } + return null; +} + +function securelyClearSession() { + try { + const logins = Services.logins.findLogins( + LOGIN_HOSTNAME, + null, + LOGIN_REALM + ); + for (const login of logins) { + if (login.username === LOGIN_USERNAME) { + Services.logins.removeLogin(login); + } + } + } catch (e) { + console.error("Failed to clear secure session:", e); + } +} + +// Initial Auth Check +async function checkCurrentAuthStatus() { + const restoredSession = await securelyLoadSession(); + + if (restoredSession) { + updateGlobalAuthState(true, restoredSession.user); + + // Verify with Supabase and ensure internal state matches + if (window.supabaseAuth && window.supabaseAuth.supabase) { + try { + const { + data: { user }, + error, + } = await window.supabaseAuth.supabase.auth.getUser(); + if (error || !user) { + void error; + securelyClearSession(); + updateGlobalAuthState(false); + } else { + // Update session in storage if it changed (e.g. refreshed) + const { + data: { session }, + } = await window.supabaseAuth.supabase.auth.getSession(); + if (session) { + securelySaveSession(session); + } + } + } catch (e) { + console.error("Oasis: Error verifying restored session:", e); + } + } + return; + } + + if (window.supabaseAuth && window.supabaseAuth.supabase) { + try { + const { + data: { user }, + error, + } = await window.supabaseAuth.supabase.auth.getUser(); + if (user && !error) { + updateGlobalAuthState(true, user); + } else { + updateGlobalAuthState(false); + } + } catch (e) { + console.error("Oasis: Error checking Supabase status:", e); + updateGlobalAuthState(false); + } + } else { + updateGlobalAuthState(false); + } +} + +function updateGlobalAuthState(authenticated, user = null) { + window.oasisAuthState = { isAuthenticated: authenticated, user }; + // Notify UI (Preact) of the change + try { + window.dispatchEvent( + new CustomEvent("oasis-auth-update", { detail: window.oasisAuthState }) + ); + } catch (e) {} +} + +// Subscribe to Supabase auth state changes +if (window.supabaseAuth) { + window.supabaseAuth.onAuthStateChange(authState => { + if (authState.isAuthenticated && authState.session) { + securelySaveSession(authState.session); + updateGlobalAuthState(true, authState.user); + } else if (!authState.isAuthenticated) { + // Only clear if we were previously logged in to avoid clearing during initial restoration race + if (window.oasisAuthState?.isAuthenticated) { + securelyClearSession(); + updateGlobalAuthState(false); + } + } + }); +} + +// Start Auth Check immediately +checkCurrentAuthStatus(); +startAssistantOAuthHandoffPolling(); diff --git a/browser/base/content/assistant/assistant.xhtml b/browser/base/content/assistant/assistant.xhtml new file mode 100644 index 0000000000000..063be37e0a734 --- /dev/null +++ b/browser/base/content/assistant/assistant.xhtml @@ -0,0 +1,19 @@ + + + + + + Assistant + + + +
    + + + + + + + + + \ No newline at end of file diff --git a/browser/base/content/assistant/auth-callback.html b/browser/base/content/assistant/auth-callback.html new file mode 100644 index 0000000000000..9ebfb8c06880c --- /dev/null +++ b/browser/base/content/assistant/auth-callback.html @@ -0,0 +1,156 @@ + + + + + + Oasis Browser - Authentication Callback + + + +
    +
    +
    Processing authentication...
    +
    +
    + + + + diff --git a/browser/base/content/assistant/auth-guard.js b/browser/base/content/assistant/auth-guard.js new file mode 100644 index 0000000000000..7a81bba1ebf86 --- /dev/null +++ b/browser/base/content/assistant/auth-guard.js @@ -0,0 +1,26 @@ +// Lightweight auth guard for assistant entrypoints. +(function() { + "use strict"; + + if (window.__oasisAuthGuardInstalled) { + return; + } + window.__oasisAuthGuardInstalled = true; + + function isAuthenticated() { + const authState = window.oasisAuthState; + return !!(authState && authState.isAuthenticated); + } + + const originalRunAssistantStream = window.runAssistantStream; + if (typeof originalRunAssistantStream !== "function") { + return; + } + + window.runAssistantStream = async function(...args) { + if (!isAuthenticated()) { + throw new Error("Authentication required: Please sign in to use the AI assistant"); + } + return await originalRunAssistantStream.apply(this, args); + }; +})(); diff --git a/browser/base/content/assistant/bootstrap.js b/browser/base/content/assistant/bootstrap.js new file mode 100644 index 0000000000000..d7fcac016e34a --- /dev/null +++ b/browser/base/content/assistant/bootstrap.js @@ -0,0 +1,69 @@ +// Runs in the chrome-privileged browser window. +// Wires up the assistant button to toggle the assistant sidebar via command +(function () { + window.addEventListener( + "load", + function () { + window.oasisSetOverlayOAuthCallbackBaseUrl = function (url) { + try { + if ( + window.SidebarController + ?.setOasisAssistantOverlayOAuthCallbackBaseUrl + ) { + return window.SidebarController.setOasisAssistantOverlayOAuthCallbackBaseUrl( + url + ); + } + } catch (e) { + console.error("Failed to set overlay OAuth callback base URL:", e); + } + return "https://kahana.co"; + }; + + window.oasisGetOverlayOAuthCallbackBaseUrl = function () { + try { + if ( + window.SidebarController + ?.getOasisAssistantOverlayOAuthCallbackBaseUrl + ) { + return window.SidebarController.getOasisAssistantOverlayOAuthCallbackBaseUrl(); + } + } catch (e) { + console.error("Failed to get overlay OAuth callback base URL:", e); + } + return "https://kahana.co"; + }; + + const assistantToggle = document.getElementById("assistant-button"); + + if (assistantToggle) { + // Use the command system to toggle the sidebar + assistantToggle.setAttribute("command", "viewOasisAssistantSidebar"); + + // Also handle direct clicks as fallback + assistantToggle.addEventListener("click", function () { + // If the command attribute doesn't work, manually execute the command + const command = "viewOasisAssistantSidebar"; + const commandElement = document.getElementById(command); + + if ( + commandElement && + typeof commandElement.doCommand === "function" + ) { + commandElement.doCommand(); + } else { + // Fallback: try to access SidebarController directly + try { + if (window.SidebarController?.show) { + window.SidebarController.show(command); + } + } catch (e) { + console.error("Failed to open assistant sidebar:", e); + } + } + }); + } + }, + { once: true } + ); +})(); diff --git a/browser/base/content/assistant/build/.env.defaults b/browser/base/content/assistant/build/.env.defaults new file mode 100644 index 0000000000000..3af6891cff8cb --- /dev/null +++ b/browser/base/content/assistant/build/.env.defaults @@ -0,0 +1,8 @@ +OASIS_ASSIST_URL=https://wvclepquxxczgrukfqyr.supabase.co/functions/v1/oasis-assist-test +OASIS_TRANSCRIBE_URL=https://ic3fypkh4rz24odos4m3u5xsma0edmnn.lambda-url.us-east-2.on.aws/ +AWS_REGION=us-east-2 +COGNITO_IDENTITY_POOL_ID=us-east-2:21ce1894-9a97-48ac-8741-b69f7eafea1c +SUPABASE_URL=https://wvclepquxxczgrukfqyr.supabase.co +SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Ind2Y2xlcHF1eHhjemdydWtmcXlyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTUwODU5OTksImV4cCI6MjA3MDY2MTk5OX0.T-hZ_8QxtVnOt0mtCY_Zch87SYEcsyQZwnvvFAtZiNY +# Optional: Railroad structured extraction via assist every N turns (default 4 if unset in esbuild). Use 0 to disable. +# OASIS_RAILROAD_EXTRACTION_INTERVAL=4 diff --git a/browser/base/content/assistant/build/.gitignore b/browser/base/content/assistant/build/.gitignore new file mode 100644 index 0000000000000..1383dcf813b62 --- /dev/null +++ b/browser/base/content/assistant/build/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +package-lock.json +tests/tmp*.mjs +.env.local diff --git a/browser/base/content/assistant/build/esbuild.config.mjs b/browser/base/content/assistant/build/esbuild.config.mjs new file mode 100644 index 0000000000000..6e29d114b08a6 --- /dev/null +++ b/browser/base/content/assistant/build/esbuild.config.mjs @@ -0,0 +1,58 @@ +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import esbuild from "esbuild"; +import dotenv from "dotenv"; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +dotenv.config({ path: ".env.defaults", quiet: true }); +dotenv.config({ path: ".env.local", override: true, quiet: true }); + +function requireEnv(name) { + const value = process.env[name]; + if (typeof value !== "string" || !value.trim()) { + throw new Error( + `Missing required env var ${name}. Set it in build/.env.defaults, build/.env.local, or shell env.` + ); + } + return value.trim(); +} + +const OASIS_ASSIST_URL = requireEnv("OASIS_ASSIST_URL"); +const OASIS_TRANSCRIBE_URL = requireEnv("OASIS_TRANSCRIBE_URL"); +const AWS_REGION = requireEnv("AWS_REGION"); +const COGNITO_IDENTITY_POOL_ID = requireEnv("COGNITO_IDENTITY_POOL_ID"); +const SUPABASE_URL = requireEnv("SUPABASE_URL"); +const SUPABASE_ANON_KEY = requireEnv("SUPABASE_ANON_KEY"); + +await esbuild.build({ + entryPoints: ["./src/assistant.ts"], + bundle: true, + platform: "browser", + format: "iife", + target: "es2022", + outfile: "../assistant.bundle.js", + sourcemap: false, + logLevel: "info", + alias: { + "fs/promises": path.join(__dirname, "src/shims/fs-promises-stub.mjs"), + path: path.join(__dirname, "src/shims/path-stub.mjs"), + }, + define: { + "process.env.OASIS_ASSIST_URL": JSON.stringify(OASIS_ASSIST_URL), + "process.env.OASIS_TRANSCRIBE_URL": JSON.stringify(OASIS_TRANSCRIBE_URL), + "process.env.AWS_REGION": JSON.stringify(AWS_REGION), + "process.env.COGNITO_IDENTITY_POOL_ID": JSON.stringify(COGNITO_IDENTITY_POOL_ID), + "process.env.SUPABASE_URL": JSON.stringify(SUPABASE_URL), + "process.env.SUPABASE_ANON_KEY": JSON.stringify(SUPABASE_ANON_KEY), + "process.env.OASIS_ASSIST_MAX_INNER_ROUNDS": JSON.stringify( + process.env.OASIS_ASSIST_MAX_INNER_ROUNDS || "" + ), + "process.env.OASIS_ASSIST_REFINE_AFTER_ROUTE": JSON.stringify( + process.env.OASIS_ASSIST_REFINE_AFTER_ROUTE || "" + ), + "process.env.OASIS_RAILROAD_EXTRACTION_INTERVAL": JSON.stringify( + process.env.OASIS_RAILROAD_EXTRACTION_INTERVAL || "" + ), + }, +}); diff --git a/browser/base/content/assistant/build/package-lock.json b/browser/base/content/assistant/build/package-lock.json new file mode 100644 index 0000000000000..85206754f26a8 --- /dev/null +++ b/browser/base/content/assistant/build/package-lock.json @@ -0,0 +1,4456 @@ +{ + "name": "assistant-bundle", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "assistant-bundle", + "dependencies": { + "@aws-crypto/sha256-js": "^5.2.0", + "@aws-sdk/client-s3": "^3.896.0", + "@aws-sdk/credential-provider-cognito-identity": "^3.901.0", + "@aws-sdk/protocol-http": "^3.370.0", + "@aws-sdk/signature-v4": "^3.370.0", + "@huggingface/transformers": "^3.4.0", + "@langchain/core": "^0.3.72", + "@orama/orama": "^3.1.0", + "@supabase/supabase-js": "^2.45.4", + "idb": "^8.0.3", + "minisearch": "^7.2.0", + "railroad-memory": "^0.2.1", + "zod": "^3.25.76" + }, + "devDependencies": { + "dotenv": "^17.2.1", + "esbuild": "^0.25.9", + "typescript": "^5.5.4" + } + }, + "node_modules/@aws-crypto/crc32": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/crc32/-/crc32-5.2.0.tgz", + "integrity": "sha512-nLbCWqQNgUiwwtFsen1AdzAtvuLRsQS8rYgMuxCrdKf9kOssamGLuPwyTY9wyYblNr9+1XM8v6zoDTPPSIeANg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-crypto/crc32c": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/crc32c/-/crc32c-5.2.0.tgz", + "integrity": "sha512-+iWb8qaHLYKrNvGRbiYRHSdKRWhto5XlZUEBwDjYNf+ly5SVYG6zEoYIdxvf5R3zyeP16w4PLBn3rH1xc74Rag==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/sha1-browser": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/sha1-browser/-/sha1-browser-5.2.0.tgz", + "integrity": "sha512-OH6lveCFfcDjX4dbAvCFSYUjJZjDr/3XJ3xHtjn3Oj5b9RjojQo8npoLeA/bNwkOkrSQ0wgrHzXk4tDRxGKJeg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/supports-web-crypto": "^5.2.0", + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "@aws-sdk/util-locate-window": "^3.0.0", + "@smithy/util-utf8": "^2.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/sha1-browser/node_modules/@smithy/is-array-buffer": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-2.2.0.tgz", + "integrity": "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha1-browser/node_modules/@smithy/util-buffer-from": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-2.2.0.tgz", + "integrity": "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha1-browser/node_modules/@smithy/util-utf8": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz", + "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha256-browser": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/sha256-browser/-/sha256-browser-5.2.0.tgz", + "integrity": "sha512-AXfN/lGotSQwu6HNcEsIASo7kWXZ5HYWvfOmSNKDsEqC4OashTp8alTmaz+F7TC2L083SFv5RdB+qU3Vs1kZqw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-js": "^5.2.0", + "@aws-crypto/supports-web-crypto": "^5.2.0", + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "@aws-sdk/util-locate-window": "^3.0.0", + "@smithy/util-utf8": "^2.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/sha256-browser/node_modules/@smithy/is-array-buffer": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-2.2.0.tgz", + "integrity": "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha256-browser/node_modules/@smithy/util-buffer-from": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-2.2.0.tgz", + "integrity": "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha256-browser/node_modules/@smithy/util-utf8": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz", + "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/sha256-js": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/sha256-js/-/sha256-js-5.2.0.tgz", + "integrity": "sha512-FFQQyu7edu4ufvIZ+OadFpHHOt+eSTBaYaki44c+akjg7qZg9oOQeLlk77F6tSYqjDAFClrHJk9tMf0HdVyOvA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/util": "^5.2.0", + "@aws-sdk/types": "^3.222.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@aws-crypto/supports-web-crypto": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/supports-web-crypto/-/supports-web-crypto-5.2.0.tgz", + "integrity": "sha512-iAvUotm021kM33eCdNfwIN//F77/IADDSs58i+MDaOqFrVjZo9bAal0NK7HurRuWLLpF1iLX7gbWrjHjeo+YFg==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/util": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/util/-/util-5.2.0.tgz", + "integrity": "sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.222.0", + "@smithy/util-utf8": "^2.0.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-crypto/util/node_modules/@smithy/is-array-buffer": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-2.2.0.tgz", + "integrity": "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/util/node_modules/@smithy/util-buffer-from": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-2.2.0.tgz", + "integrity": "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz", + "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^2.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-cognito-identity/-/client-cognito-identity-3.901.0.tgz", + "integrity": "sha512-cDJ+npYeAiS9u/52RwR0AHgneEF+rnyxiYm4d/c4FTI6xTQId3hSD0zdK0EgZ1wfoMk0/+5Ft6mYk0V6JN+cbQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.901.0", + "@aws-sdk/credential-provider-node": "3.901.0", + "@aws-sdk/middleware-host-header": "3.901.0", + "@aws-sdk/middleware-logger": "3.901.0", + "@aws-sdk/middleware-recursion-detection": "3.901.0", + "@aws-sdk/middleware-user-agent": "3.901.0", + "@aws-sdk/region-config-resolver": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@aws-sdk/util-endpoints": "3.901.0", + "@aws-sdk/util-user-agent-browser": "3.901.0", + "@aws-sdk/util-user-agent-node": "3.901.0", + "@smithy/config-resolver": "^4.3.0", + "@smithy/core": "^3.14.0", + "@smithy/fetch-http-handler": "^5.3.0", + "@smithy/hash-node": "^4.2.0", + "@smithy/invalid-dependency": "^4.2.0", + "@smithy/middleware-content-length": "^4.2.0", + "@smithy/middleware-endpoint": "^4.3.0", + "@smithy/middleware-retry": "^4.4.0", + "@smithy/middleware-serde": "^4.2.0", + "@smithy/middleware-stack": "^4.2.0", + "@smithy/node-config-provider": "^4.3.0", + "@smithy/node-http-handler": "^4.3.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/smithy-client": "^4.7.0", + "@smithy/types": "^4.6.0", + "@smithy/url-parser": "^4.2.0", + "@smithy/util-base64": "^4.2.0", + "@smithy/util-body-length-browser": "^4.2.0", + "@smithy/util-body-length-node": "^4.2.0", + "@smithy/util-defaults-mode-browser": "^4.2.0", + "@smithy/util-defaults-mode-node": "^4.2.0", + "@smithy/util-endpoints": "^3.2.0", + "@smithy/util-middleware": "^4.2.0", + "@smithy/util-retry": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/client-sso": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.901.0.tgz", + "integrity": "sha512-sGyDjjkJ7ppaE+bAKL/Q5IvVCxtoyBIzN+7+hWTS/mUxWJ9EOq9238IqmVIIK6sYNIzEf9yhobfMARasPYVTNg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.901.0", + "@aws-sdk/middleware-host-header": "3.901.0", + "@aws-sdk/middleware-logger": "3.901.0", + "@aws-sdk/middleware-recursion-detection": "3.901.0", + "@aws-sdk/middleware-user-agent": "3.901.0", + "@aws-sdk/region-config-resolver": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@aws-sdk/util-endpoints": "3.901.0", + "@aws-sdk/util-user-agent-browser": "3.901.0", + "@aws-sdk/util-user-agent-node": "3.901.0", + "@smithy/config-resolver": "^4.3.0", + "@smithy/core": "^3.14.0", + "@smithy/fetch-http-handler": "^5.3.0", + "@smithy/hash-node": "^4.2.0", + "@smithy/invalid-dependency": "^4.2.0", + "@smithy/middleware-content-length": "^4.2.0", + "@smithy/middleware-endpoint": "^4.3.0", + "@smithy/middleware-retry": "^4.4.0", + "@smithy/middleware-serde": "^4.2.0", + "@smithy/middleware-stack": "^4.2.0", + "@smithy/node-config-provider": "^4.3.0", + "@smithy/node-http-handler": "^4.3.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/smithy-client": "^4.7.0", + "@smithy/types": "^4.6.0", + "@smithy/url-parser": "^4.2.0", + "@smithy/util-base64": "^4.2.0", + "@smithy/util-body-length-browser": "^4.2.0", + "@smithy/util-body-length-node": "^4.2.0", + "@smithy/util-defaults-mode-browser": "^4.2.0", + "@smithy/util-defaults-mode-node": "^4.2.0", + "@smithy/util-endpoints": "^3.2.0", + "@smithy/util-middleware": "^4.2.0", + "@smithy/util-retry": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/core": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.901.0.tgz", + "integrity": "sha512-brKAc3y64tdhyuEf+OPIUln86bRTqkLgb9xkd6kUdIeA5+qmp/N6amItQz+RN4k4O3kqkCPYnAd3LonTKluobw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.901.0", + "@aws-sdk/xml-builder": "3.901.0", + "@smithy/core": "^3.14.0", + "@smithy/node-config-provider": "^4.3.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/signature-v4": "^5.3.0", + "@smithy/smithy-client": "^4.7.0", + "@smithy/types": "^4.6.0", + "@smithy/util-base64": "^4.2.0", + "@smithy/util-middleware": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/credential-provider-env": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.901.0.tgz", + "integrity": "sha512-5hAdVl3tBuARh3zX5MLJ1P/d+Kr5kXtDU3xm1pxUEF4xt2XkEEpwiX5fbkNkz2rbh3BCt2gOHsAbh6b3M7n+DA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/credential-provider-http": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.901.0.tgz", + "integrity": "sha512-Ggr7+0M6QZEsrqRkK7iyJLf4LkIAacAxHz9c4dm9hnDdU7vqrlJm6g73IxMJXWN1bIV7IxfpzB11DsRrB/oNjQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@smithy/fetch-http-handler": "^5.3.0", + "@smithy/node-http-handler": "^4.3.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/smithy-client": "^4.7.0", + "@smithy/types": "^4.6.0", + "@smithy/util-stream": "^4.4.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/credential-provider-ini": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.901.0.tgz", + "integrity": "sha512-zxadcDS0hNJgv8n4hFYJNOXyfjaNE1vvqIiF/JzZSQpSSYXzCd+WxXef5bQh+W3giDtRUmkvP5JLbamEFjZKyw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.901.0", + "@aws-sdk/credential-provider-env": "3.901.0", + "@aws-sdk/credential-provider-http": "3.901.0", + "@aws-sdk/credential-provider-process": "3.901.0", + "@aws-sdk/credential-provider-sso": "3.901.0", + "@aws-sdk/credential-provider-web-identity": "3.901.0", + "@aws-sdk/nested-clients": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@smithy/credential-provider-imds": "^4.2.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/shared-ini-file-loader": "^4.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/credential-provider-node": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.901.0.tgz", + "integrity": "sha512-dPuFzMF7L1s/lQyT3wDxqLe82PyTH+5o1jdfseTEln64LJMl0ZMWaKX/C1UFNDxaTd35Cgt1bDbjjAWHMiKSFQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/credential-provider-env": "3.901.0", + "@aws-sdk/credential-provider-http": "3.901.0", + "@aws-sdk/credential-provider-ini": "3.901.0", + "@aws-sdk/credential-provider-process": "3.901.0", + "@aws-sdk/credential-provider-sso": "3.901.0", + "@aws-sdk/credential-provider-web-identity": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@smithy/credential-provider-imds": "^4.2.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/shared-ini-file-loader": "^4.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/credential-provider-process": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.901.0.tgz", + "integrity": "sha512-/IWgmgM3Cl1wTdJA5HqKMAojxLkYchh5kDuphApxKhupLu6Pu0JBOHU8A5GGeFvOycyaVwosod6zDduINZxe+A==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/shared-ini-file-loader": "^4.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/credential-provider-sso": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.901.0.tgz", + "integrity": "sha512-SjmqZQHmqFSET7+6xcZgtH7yEyh5q53LN87GqwYlJZ6KJ5oNw11acUNEhUOL1xTSJEvaWqwTIkS2zqrzLcM9bw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/client-sso": "3.901.0", + "@aws-sdk/core": "3.901.0", + "@aws-sdk/token-providers": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/shared-ini-file-loader": "^4.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/credential-provider-web-identity": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.901.0.tgz", + "integrity": "sha512-NYjy/6NLxH9m01+pfpB4ql8QgAorJcu8tw69kzHwUd/ql6wUDTbC7HcXqtKlIwWjzjgj2BKL7j6SyFapgCuafA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.901.0", + "@aws-sdk/nested-clients": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/shared-ini-file-loader": "^4.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-host-header": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-host-header/-/middleware-host-header-3.901.0.tgz", + "integrity": "sha512-yWX7GvRmqBtbNnUW7qbre3GvZmyYwU0WHefpZzDTYDoNgatuYq6LgUIQ+z5C04/kCRoFkAFrHag8a3BXqFzq5A==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.901.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-logger": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.901.0.tgz", + "integrity": "sha512-UoHebjE7el/tfRo8/CQTj91oNUm+5Heus5/a4ECdmWaSCHCS/hXTsU3PTTHAY67oAQR8wBLFPfp3mMvXjB+L2A==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.901.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-recursion-detection": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.901.0.tgz", + "integrity": "sha512-Wd2t8qa/4OL0v/oDpCHHYkgsXJr8/ttCxrvCKAt0H1zZe2LlRhY9gpDVKqdertfHrHDj786fOvEQA28G1L75Dg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.901.0", + "@aws/lambda-invoke-store": "^0.0.1", + "@smithy/protocol-http": "^5.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/middleware-user-agent": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.901.0.tgz", + "integrity": "sha512-Zby4F03fvD9xAgXGPywyk4bC1jCbnyubMEYChLYohD+x20ULQCf+AimF/Btn7YL+hBpzh1+RmqmvZcx+RgwgNQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@aws-sdk/util-endpoints": "3.901.0", + "@smithy/core": "^3.14.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/nested-clients": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.901.0.tgz", + "integrity": "sha512-feAAAMsVwctk2Tms40ONybvpfJPLCmSdI+G+OTrNpizkGLNl6ik2Ng2RzxY6UqOfN8abqKP/DOUj1qYDRDG8ag==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.901.0", + "@aws-sdk/middleware-host-header": "3.901.0", + "@aws-sdk/middleware-logger": "3.901.0", + "@aws-sdk/middleware-recursion-detection": "3.901.0", + "@aws-sdk/middleware-user-agent": "3.901.0", + "@aws-sdk/region-config-resolver": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@aws-sdk/util-endpoints": "3.901.0", + "@aws-sdk/util-user-agent-browser": "3.901.0", + "@aws-sdk/util-user-agent-node": "3.901.0", + "@smithy/config-resolver": "^4.3.0", + "@smithy/core": "^3.14.0", + "@smithy/fetch-http-handler": "^5.3.0", + "@smithy/hash-node": "^4.2.0", + "@smithy/invalid-dependency": "^4.2.0", + "@smithy/middleware-content-length": "^4.2.0", + "@smithy/middleware-endpoint": "^4.3.0", + "@smithy/middleware-retry": "^4.4.0", + "@smithy/middleware-serde": "^4.2.0", + "@smithy/middleware-stack": "^4.2.0", + "@smithy/node-config-provider": "^4.3.0", + "@smithy/node-http-handler": "^4.3.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/smithy-client": "^4.7.0", + "@smithy/types": "^4.6.0", + "@smithy/url-parser": "^4.2.0", + "@smithy/util-base64": "^4.2.0", + "@smithy/util-body-length-browser": "^4.2.0", + "@smithy/util-body-length-node": "^4.2.0", + "@smithy/util-defaults-mode-browser": "^4.2.0", + "@smithy/util-defaults-mode-node": "^4.2.0", + "@smithy/util-endpoints": "^3.2.0", + "@smithy/util-middleware": "^4.2.0", + "@smithy/util-retry": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/region-config-resolver": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.901.0.tgz", + "integrity": "sha512-7F0N888qVLHo4CSQOsnkZ4QAp8uHLKJ4v3u09Ly5k4AEStrSlFpckTPyUx6elwGL+fxGjNE2aakK8vEgzzCV0A==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.901.0", + "@smithy/node-config-provider": "^4.3.0", + "@smithy/types": "^4.6.0", + "@smithy/util-config-provider": "^4.2.0", + "@smithy/util-middleware": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/token-providers": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.901.0.tgz", + "integrity": "sha512-pJEr1Ggbc/uVTDqp9IbNu9hdr0eQf3yZix3s4Nnyvmg4xmJSGAlbPC9LrNr5u3CDZoc8Z9CuLrvbP4MwYquNpQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.901.0", + "@aws-sdk/nested-clients": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/shared-ini-file-loader": "^4.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/types": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.901.0.tgz", + "integrity": "sha512-FfEM25hLEs4LoXsLXQ/q6X6L4JmKkKkbVFpKD4mwfVHtRVQG6QxJiCPcrkcPISquiy6esbwK2eh64TWbiD60cg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-endpoints": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.901.0.tgz", + "integrity": "sha512-5nZP3hGA8FHEtKvEQf4Aww5QZOkjLW1Z+NixSd+0XKfHvA39Ah5sZboScjLx0C9kti/K3OGW1RCx5K9Zc3bZqg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.901.0", + "@smithy/types": "^4.6.0", + "@smithy/url-parser": "^4.2.0", + "@smithy/util-endpoints": "^3.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-user-agent-browser": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.901.0.tgz", + "integrity": "sha512-Ntb6V/WFI21Ed4PDgL/8NSfoZQQf9xzrwNgiwvnxgAl/KvAvRBgQtqj5gHsDX8Nj2YmJuVoHfH9BGjL9VQ4WNg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.901.0", + "@smithy/types": "^4.6.0", + "bowser": "^2.11.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/util-user-agent-node": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.901.0.tgz", + "integrity": "sha512-l59KQP5TY7vPVUfEURc7P5BJKuNg1RSsAKBQW7LHLECXjLqDUbo2SMLrexLBEoArSt6E8QOrIN0C8z/0Xk0jYw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/middleware-user-agent": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@smithy/node-config-provider": "^4.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "aws-crt": ">=1.0.0" + }, + "peerDependenciesMeta": { + "aws-crt": { + "optional": true + } + } + }, + "node_modules/@aws-sdk/client-cognito-identity/node_modules/@aws-sdk/xml-builder": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.901.0.tgz", + "integrity": "sha512-pxFCkuAP7Q94wMTNPAwi6hEtNrp/BdFf+HOrIEeFQsk4EoOmpKY3I6S+u6A9Wg295J80Kh74LqDWM22ux3z6Aw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "fast-xml-parser": "5.2.5", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-s3": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-s3/-/client-s3-3.896.0.tgz", + "integrity": "sha512-UETVuMLQRqgrWxTnavotY0TlB/jaR9sL3hkIFPx4KtjmigNBdwRaiVfOuTnIXKd+w9RPINYG//nnrK+5gIyZkA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha1-browser": "5.2.0", + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.896.0", + "@aws-sdk/credential-provider-node": "3.896.0", + "@aws-sdk/middleware-bucket-endpoint": "3.893.0", + "@aws-sdk/middleware-expect-continue": "3.893.0", + "@aws-sdk/middleware-flexible-checksums": "3.896.0", + "@aws-sdk/middleware-host-header": "3.893.0", + "@aws-sdk/middleware-location-constraint": "3.893.0", + "@aws-sdk/middleware-logger": "3.893.0", + "@aws-sdk/middleware-recursion-detection": "3.893.0", + "@aws-sdk/middleware-sdk-s3": "3.896.0", + "@aws-sdk/middleware-ssec": "3.893.0", + "@aws-sdk/middleware-user-agent": "3.896.0", + "@aws-sdk/region-config-resolver": "3.893.0", + "@aws-sdk/signature-v4-multi-region": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@aws-sdk/util-endpoints": "3.895.0", + "@aws-sdk/util-user-agent-browser": "3.893.0", + "@aws-sdk/util-user-agent-node": "3.896.0", + "@aws-sdk/xml-builder": "3.894.0", + "@smithy/config-resolver": "^4.2.2", + "@smithy/core": "^3.12.0", + "@smithy/eventstream-serde-browser": "^4.1.1", + "@smithy/eventstream-serde-config-resolver": "^4.2.1", + "@smithy/eventstream-serde-node": "^4.1.1", + "@smithy/fetch-http-handler": "^5.2.1", + "@smithy/hash-blob-browser": "^4.1.1", + "@smithy/hash-node": "^4.1.1", + "@smithy/hash-stream-node": "^4.1.1", + "@smithy/invalid-dependency": "^4.1.1", + "@smithy/md5-js": "^4.1.1", + "@smithy/middleware-content-length": "^4.1.1", + "@smithy/middleware-endpoint": "^4.2.4", + "@smithy/middleware-retry": "^4.3.0", + "@smithy/middleware-serde": "^4.1.1", + "@smithy/middleware-stack": "^4.1.1", + "@smithy/node-config-provider": "^4.2.2", + "@smithy/node-http-handler": "^4.2.1", + "@smithy/protocol-http": "^5.2.1", + "@smithy/smithy-client": "^4.6.4", + "@smithy/types": "^4.5.0", + "@smithy/url-parser": "^4.1.1", + "@smithy/util-base64": "^4.1.0", + "@smithy/util-body-length-browser": "^4.1.0", + "@smithy/util-body-length-node": "^4.1.0", + "@smithy/util-defaults-mode-browser": "^4.1.4", + "@smithy/util-defaults-mode-node": "^4.1.4", + "@smithy/util-endpoints": "^3.1.2", + "@smithy/util-middleware": "^4.1.1", + "@smithy/util-retry": "^4.1.2", + "@smithy/util-stream": "^4.3.2", + "@smithy/util-utf8": "^4.1.0", + "@smithy/util-waiter": "^4.1.1", + "@smithy/uuid": "^1.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/client-sso": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/client-sso/-/client-sso-3.896.0.tgz", + "integrity": "sha512-mpE3mrNili1dcvEvxaYjyoib8HlRXkb2bY5a3WeK++KObFY+HUujKtgQmiNSRX5YwQszm//fTrmGMmv9zpMcKg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.896.0", + "@aws-sdk/middleware-host-header": "3.893.0", + "@aws-sdk/middleware-logger": "3.893.0", + "@aws-sdk/middleware-recursion-detection": "3.893.0", + "@aws-sdk/middleware-user-agent": "3.896.0", + "@aws-sdk/region-config-resolver": "3.893.0", + "@aws-sdk/types": "3.893.0", + "@aws-sdk/util-endpoints": "3.895.0", + "@aws-sdk/util-user-agent-browser": "3.893.0", + "@aws-sdk/util-user-agent-node": "3.896.0", + "@smithy/config-resolver": "^4.2.2", + "@smithy/core": "^3.12.0", + "@smithy/fetch-http-handler": "^5.2.1", + "@smithy/hash-node": "^4.1.1", + "@smithy/invalid-dependency": "^4.1.1", + "@smithy/middleware-content-length": "^4.1.1", + "@smithy/middleware-endpoint": "^4.2.4", + "@smithy/middleware-retry": "^4.3.0", + "@smithy/middleware-serde": "^4.1.1", + "@smithy/middleware-stack": "^4.1.1", + "@smithy/node-config-provider": "^4.2.2", + "@smithy/node-http-handler": "^4.2.1", + "@smithy/protocol-http": "^5.2.1", + "@smithy/smithy-client": "^4.6.4", + "@smithy/types": "^4.5.0", + "@smithy/url-parser": "^4.1.1", + "@smithy/util-base64": "^4.1.0", + "@smithy/util-body-length-browser": "^4.1.0", + "@smithy/util-body-length-node": "^4.1.0", + "@smithy/util-defaults-mode-browser": "^4.1.4", + "@smithy/util-defaults-mode-node": "^4.1.4", + "@smithy/util-endpoints": "^3.1.2", + "@smithy/util-middleware": "^4.1.1", + "@smithy/util-retry": "^4.1.2", + "@smithy/util-utf8": "^4.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/core": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.896.0.tgz", + "integrity": "sha512-uJaoyWKeGNyCyeI+cIJrD7LEB4iF/W8/x2ij7zg32OFpAAJx96N34/e+XSKp/xkJpO5FKiBOskKLnHeUsJsAPA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.893.0", + "@aws-sdk/xml-builder": "3.894.0", + "@smithy/core": "^3.12.0", + "@smithy/node-config-provider": "^4.2.2", + "@smithy/property-provider": "^4.1.1", + "@smithy/protocol-http": "^5.2.1", + "@smithy/signature-v4": "^5.2.1", + "@smithy/smithy-client": "^4.6.4", + "@smithy/types": "^4.5.0", + "@smithy/util-base64": "^4.1.0", + "@smithy/util-middleware": "^4.1.1", + "@smithy/util-utf8": "^4.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-cognito-identity": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-cognito-identity/-/credential-provider-cognito-identity-3.901.0.tgz", + "integrity": "sha512-irVFwiiEC+JRFQTZwI7264LOGXRjqdp3AvmqiEmmZS0+sJsEaF65prCs+nzw6J1WqQ6IZKClKKQsH7x8FfOPrQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/client-cognito-identity": "3.901.0", + "@aws-sdk/types": "3.901.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-cognito-identity/node_modules/@aws-sdk/types": { + "version": "3.901.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.901.0.tgz", + "integrity": "sha512-FfEM25hLEs4LoXsLXQ/q6X6L4JmKkKkbVFpKD4mwfVHtRVQG6QxJiCPcrkcPISquiy6esbwK2eh64TWbiD60cg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-env": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.896.0.tgz", + "integrity": "sha512-Cnqhupdkp825ICySrz4QTI64Nq3AmUAscPW8dueanni0avYBDp7RBppX4H0+6icqN569B983XNfQ0YSImQhfhg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@smithy/property-provider": "^4.1.1", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-http": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.896.0.tgz", + "integrity": "sha512-CN0fTCKCUA1OTSx1c76o8XyJCy2WoI/av3J8r8mL6GmxTerhLRyzDy/MwxzPjTYPoL+GLEg6V4a9fRkWj1hBUA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@smithy/fetch-http-handler": "^5.2.1", + "@smithy/node-http-handler": "^4.2.1", + "@smithy/property-provider": "^4.1.1", + "@smithy/protocol-http": "^5.2.1", + "@smithy/smithy-client": "^4.6.4", + "@smithy/types": "^4.5.0", + "@smithy/util-stream": "^4.3.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-ini": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.896.0.tgz", + "integrity": "sha512-+rbYG98czzwZLTYHJasK+VBjnIeXk73mRpZXHvaa4kDNxBezdN2YsoGNpLlPSxPdbpq18LY3LRtkdFTaT6DIQA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.896.0", + "@aws-sdk/credential-provider-env": "3.896.0", + "@aws-sdk/credential-provider-http": "3.896.0", + "@aws-sdk/credential-provider-process": "3.896.0", + "@aws-sdk/credential-provider-sso": "3.896.0", + "@aws-sdk/credential-provider-web-identity": "3.896.0", + "@aws-sdk/nested-clients": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@smithy/credential-provider-imds": "^4.1.2", + "@smithy/property-provider": "^4.1.1", + "@smithy/shared-ini-file-loader": "^4.2.0", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-node": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.896.0.tgz", + "integrity": "sha512-J0Jm+56MNngk1PIyqoJFf5FC2fjA4CYXlqODqNRDtid7yk7HB9W3UTtvxofmii5KJOLcHGNPdGnHWKkUc+xYgw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/credential-provider-env": "3.896.0", + "@aws-sdk/credential-provider-http": "3.896.0", + "@aws-sdk/credential-provider-ini": "3.896.0", + "@aws-sdk/credential-provider-process": "3.896.0", + "@aws-sdk/credential-provider-sso": "3.896.0", + "@aws-sdk/credential-provider-web-identity": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@smithy/credential-provider-imds": "^4.1.2", + "@smithy/property-provider": "^4.1.1", + "@smithy/shared-ini-file-loader": "^4.2.0", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-process": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.896.0.tgz", + "integrity": "sha512-UfWVMQPZy7dus40c4LWxh5vQ+I51z0q4vf09Eqas5848e9DrGRG46GYIuc/gy+4CqEypjbg/XNMjnZfGLHxVnQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@smithy/property-provider": "^4.1.1", + "@smithy/shared-ini-file-loader": "^4.2.0", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-sso": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.896.0.tgz", + "integrity": "sha512-77Te8WrVdLABKlv7QyetXP6aYEX1UORiahLA1PXQb/p66aFBw18Xc6JiN/6zJ4RqdyV1Xr9rwYBwGYua93ANIA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/client-sso": "3.896.0", + "@aws-sdk/core": "3.896.0", + "@aws-sdk/token-providers": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@smithy/property-provider": "^4.1.1", + "@smithy/shared-ini-file-loader": "^4.2.0", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/credential-provider-web-identity": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.896.0.tgz", + "integrity": "sha512-gwMwZWumo+V0xJplO8j2HIb1TfPsF9fbcRGXS0CanEvjg4fF2Xs1pOQl2oCw3biPZpxHB0plNZjqSF2eneGg9g==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.896.0", + "@aws-sdk/nested-clients": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@smithy/property-provider": "^4.1.1", + "@smithy/shared-ini-file-loader": "^4.2.0", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/eventstream-codec": { + "version": "3.370.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/eventstream-codec/-/eventstream-codec-3.370.0.tgz", + "integrity": "sha512-PiaDMum7TNsIE3DGECSsNYwibBIPN2/e13BJbTwi6KgVx8BV2mYA3kQkaUDiy++tEpzN81Nh5OPTFVb7bvgYYg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/crc32": "3.0.0", + "@aws-sdk/types": "3.370.0", + "@aws-sdk/util-hex-encoding": "3.310.0", + "tslib": "^2.5.0" + } + }, + "node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/crc32": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/crc32/-/crc32-3.0.0.tgz", + "integrity": "sha512-IzSgsrxUcsrejQbPVilIKy16kAT52EwB6zSaI+M3xxIhKh5+aldEyvI+z6erM7TCLB2BJsFrtHjp6/4/sr+3dA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/util": "^3.0.0", + "@aws-sdk/types": "^3.222.0", + "tslib": "^1.11.1" + } + }, + "node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "license": "0BSD" + }, + "node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/util": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@aws-crypto/util/-/util-3.0.0.tgz", + "integrity": "sha512-2OJlpeJpCR48CC8r+uKVChzs9Iungj9wkZrl8Z041DWEWvyIHILYKCPNzJghKsivj+S3mLo6BVc7mBNzdxA46w==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "^3.222.0", + "@aws-sdk/util-utf8-browser": "^3.0.0", + "tslib": "^1.11.1" + } + }, + "node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-crypto/util/node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "license": "0BSD" + }, + "node_modules/@aws-sdk/eventstream-codec/node_modules/@aws-sdk/types": { + "version": "3.370.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.370.0.tgz", + "integrity": "sha512-8PGMKklSkRKjunFhzM2y5Jm0H2TBu7YRNISdYzXLUHKSP9zlMEYagseKVdmox0zKHf1LXVNuSlUV2b6SRrieCQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^1.1.0", + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/eventstream-codec/node_modules/@smithy/types": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-1.2.0.tgz", + "integrity": "sha512-z1r00TvBqF3dh4aHhya7nz1HhvCg4TRmw51fjMrh5do3h+ngSstt/yKlNbHeb9QxJmFbmN8KEVSWgb1bRvfEoA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/is-array-buffer": { + "version": "3.310.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/is-array-buffer/-/is-array-buffer-3.310.0.tgz", + "integrity": "sha512-urnbcCR+h9NWUnmOtet/s4ghvzsidFmspfhYaHAmSRdy9yDjdjBJMFjjsn85A1ODUktztm+cVncXjQ38WCMjMQ==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/middleware-bucket-endpoint": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-bucket-endpoint/-/middleware-bucket-endpoint-3.893.0.tgz", + "integrity": "sha512-H+wMAoFC73T7M54OFIezdHXR9/lH8TZ3Cx1C3MEBb2ctlzQrVCd8LX8zmOtcGYC8plrRwV+8rNPe0FMqecLRew==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.893.0", + "@aws-sdk/util-arn-parser": "3.893.0", + "@smithy/node-config-provider": "^4.2.2", + "@smithy/protocol-http": "^5.2.1", + "@smithy/types": "^4.5.0", + "@smithy/util-config-provider": "^4.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-expect-continue": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-expect-continue/-/middleware-expect-continue-3.893.0.tgz", + "integrity": "sha512-PEZkvD6k0X9sacHkvkVF4t2QyQEAzd35OJ2bIrjWCfc862TwukMMJ1KErRmQ1WqKXHKF4L0ed5vtWaO/8jVLNA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.893.0", + "@smithy/protocol-http": "^5.2.1", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-flexible-checksums": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-flexible-checksums/-/middleware-flexible-checksums-3.896.0.tgz", + "integrity": "sha512-bB3W/IFG7HNNziACOp1aZVGGnrIahXc0PxZoU055JirEGQtDFIU1ZD7S9zLKmy9FFUvQsAeRL9nDFHbx8cwx/w==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/crc32": "5.2.0", + "@aws-crypto/crc32c": "5.2.0", + "@aws-crypto/util": "5.2.0", + "@aws-sdk/core": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@smithy/is-array-buffer": "^4.1.0", + "@smithy/node-config-provider": "^4.2.2", + "@smithy/protocol-http": "^5.2.1", + "@smithy/types": "^4.5.0", + "@smithy/util-middleware": "^4.1.1", + "@smithy/util-stream": "^4.3.2", + "@smithy/util-utf8": "^4.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-host-header": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-host-header/-/middleware-host-header-3.893.0.tgz", + "integrity": "sha512-qL5xYRt80ahDfj9nDYLhpCNkDinEXvjLe/Qen/Y/u12+djrR2MB4DRa6mzBCkLkdXDtf0WAoW2EZsNCfGrmOEQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.893.0", + "@smithy/protocol-http": "^5.2.1", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-location-constraint": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-location-constraint/-/middleware-location-constraint-3.893.0.tgz", + "integrity": "sha512-MlbBc7Ttb1ekbeeeFBU4DeEZOLb5s0Vl4IokvO17g6yJdLk4dnvZro9zdXl3e7NXK+kFxHRBFZe55p/42mVgDA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.893.0", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-logger": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.893.0.tgz", + "integrity": "sha512-ZqzMecjju5zkBquSIfVfCORI/3Mge21nUY4nWaGQy+NUXehqCGG4W7AiVpiHGOcY2cGJa7xeEkYcr2E2U9U0AA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.893.0", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-recursion-detection": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.893.0.tgz", + "integrity": "sha512-H7Zotd9zUHQAr/wr3bcWHULYhEeoQrF54artgsoUGIf/9emv6LzY89QUccKIxYd6oHKNTrTyXm9F0ZZrzXNxlg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.893.0", + "@aws/lambda-invoke-store": "^0.0.1", + "@smithy/protocol-http": "^5.2.1", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-sdk-s3": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-s3/-/middleware-sdk-s3-3.896.0.tgz", + "integrity": "sha512-hlPu/AZ5Afa4ZafP+aXIjRtKm7BX57lurA+TJ+7nXm1Az8Du3Sg2tZXP2/GfqTztLIFQYj/Jy5smkJ0+1HNAPQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@aws-sdk/util-arn-parser": "3.893.0", + "@smithy/core": "^3.12.0", + "@smithy/node-config-provider": "^4.2.2", + "@smithy/protocol-http": "^5.2.1", + "@smithy/signature-v4": "^5.2.1", + "@smithy/smithy-client": "^4.6.4", + "@smithy/types": "^4.5.0", + "@smithy/util-config-provider": "^4.1.0", + "@smithy/util-middleware": "^4.1.1", + "@smithy/util-stream": "^4.3.2", + "@smithy/util-utf8": "^4.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-ssec": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-ssec/-/middleware-ssec-3.893.0.tgz", + "integrity": "sha512-e4ccCiAnczv9mMPheKjgKxZQN473mcup+3DPLVNnIw5GRbQoDqPSB70nUzfORKZvM7ar7xLMPxNR8qQgo1C8Rg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.893.0", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/middleware-user-agent": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.896.0.tgz", + "integrity": "sha512-so/3tZH34YIeqG/QJgn5ZinnmHRdXV1ehsj4wVUrezL/dVW86jfwIkQIwpw8roOC657UoUf91c9FDhCxs3J5aQ==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@aws-sdk/util-endpoints": "3.895.0", + "@smithy/core": "^3.12.0", + "@smithy/protocol-http": "^5.2.1", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/nested-clients": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.896.0.tgz", + "integrity": "sha512-KaHALB6DIXScJL/ExmonADr3jtTV6dpOHoEeTRSskJ/aW+rhZo7kH8SLmrwOT/qX8d5tza17YyR/oRkIKY6Eaw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "3.896.0", + "@aws-sdk/middleware-host-header": "3.893.0", + "@aws-sdk/middleware-logger": "3.893.0", + "@aws-sdk/middleware-recursion-detection": "3.893.0", + "@aws-sdk/middleware-user-agent": "3.896.0", + "@aws-sdk/region-config-resolver": "3.893.0", + "@aws-sdk/types": "3.893.0", + "@aws-sdk/util-endpoints": "3.895.0", + "@aws-sdk/util-user-agent-browser": "3.893.0", + "@aws-sdk/util-user-agent-node": "3.896.0", + "@smithy/config-resolver": "^4.2.2", + "@smithy/core": "^3.12.0", + "@smithy/fetch-http-handler": "^5.2.1", + "@smithy/hash-node": "^4.1.1", + "@smithy/invalid-dependency": "^4.1.1", + "@smithy/middleware-content-length": "^4.1.1", + "@smithy/middleware-endpoint": "^4.2.4", + "@smithy/middleware-retry": "^4.3.0", + "@smithy/middleware-serde": "^4.1.1", + "@smithy/middleware-stack": "^4.1.1", + "@smithy/node-config-provider": "^4.2.2", + "@smithy/node-http-handler": "^4.2.1", + "@smithy/protocol-http": "^5.2.1", + "@smithy/smithy-client": "^4.6.4", + "@smithy/types": "^4.5.0", + "@smithy/url-parser": "^4.1.1", + "@smithy/util-base64": "^4.1.0", + "@smithy/util-body-length-browser": "^4.1.0", + "@smithy/util-body-length-node": "^4.1.0", + "@smithy/util-defaults-mode-browser": "^4.1.4", + "@smithy/util-defaults-mode-node": "^4.1.4", + "@smithy/util-endpoints": "^3.1.2", + "@smithy/util-middleware": "^4.1.1", + "@smithy/util-retry": "^4.1.2", + "@smithy/util-utf8": "^4.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/protocol-http": { + "version": "3.370.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/protocol-http/-/protocol-http-3.370.0.tgz", + "integrity": "sha512-MfZCgSsVmir+4kJps7xT0awOPNi+swBpcVp9ZtAP7POduUVV6zVLurMNLXsppKsErggssD5E9HUgQFs5w06U4Q==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.370.0", + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/protocol-http/node_modules/@aws-sdk/types": { + "version": "3.370.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.370.0.tgz", + "integrity": "sha512-8PGMKklSkRKjunFhzM2y5Jm0H2TBu7YRNISdYzXLUHKSP9zlMEYagseKVdmox0zKHf1LXVNuSlUV2b6SRrieCQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^1.1.0", + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/protocol-http/node_modules/@smithy/types": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-1.2.0.tgz", + "integrity": "sha512-z1r00TvBqF3dh4aHhya7nz1HhvCg4TRmw51fjMrh5do3h+ngSstt/yKlNbHeb9QxJmFbmN8KEVSWgb1bRvfEoA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/region-config-resolver": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.893.0.tgz", + "integrity": "sha512-/cJvh3Zsa+Of0Zbg7vl9wp/kZtdb40yk/2+XcroAMVPO9hPvmS9r/UOm6tO7FeX4TtkRFwWaQJiTZTgSdsPY+Q==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.893.0", + "@smithy/node-config-provider": "^4.2.2", + "@smithy/types": "^4.5.0", + "@smithy/util-config-provider": "^4.1.0", + "@smithy/util-middleware": "^4.1.1", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/signature-v4": { + "version": "3.370.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4/-/signature-v4-3.370.0.tgz", + "integrity": "sha512-Mh++NJiXoBxMzz4d8GQPNB37nqjS1gsVwjKoSAWFE67sjgsjb8D5JWRCm9CinqPoXi2iN57+1DcQalTDKQGc0A==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/eventstream-codec": "3.370.0", + "@aws-sdk/is-array-buffer": "3.310.0", + "@aws-sdk/types": "3.370.0", + "@aws-sdk/util-hex-encoding": "3.310.0", + "@aws-sdk/util-middleware": "3.370.0", + "@aws-sdk/util-uri-escape": "3.310.0", + "@aws-sdk/util-utf8": "3.310.0", + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/signature-v4-multi-region": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.896.0.tgz", + "integrity": "sha512-txiQDEZXL9tlNP8mbnNaDtuHBYc/FCqaZ8Y76qnfM3o6CTIn0t0tTAlnx1CyFe4EaikVBgQuZvj5KfNA8PmlzA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/middleware-sdk-s3": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@smithy/protocol-http": "^5.2.1", + "@smithy/signature-v4": "^5.2.1", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/signature-v4/node_modules/@aws-sdk/types": { + "version": "3.370.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.370.0.tgz", + "integrity": "sha512-8PGMKklSkRKjunFhzM2y5Jm0H2TBu7YRNISdYzXLUHKSP9zlMEYagseKVdmox0zKHf1LXVNuSlUV2b6SRrieCQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^1.1.0", + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/signature-v4/node_modules/@smithy/types": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-1.2.0.tgz", + "integrity": "sha512-z1r00TvBqF3dh4aHhya7nz1HhvCg4TRmw51fjMrh5do3h+ngSstt/yKlNbHeb9QxJmFbmN8KEVSWgb1bRvfEoA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/token-providers": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.896.0.tgz", + "integrity": "sha512-WBoD+RY7tUfW9M+wGrZ2vdveR+ziZOjGHWFY3lcGnDvI8KE+fcSccEOTxgJBNBS5Z8B+WHKU2sZjb+Z7QqGwjw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/core": "3.896.0", + "@aws-sdk/nested-clients": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@smithy/property-provider": "^4.1.1", + "@smithy/shared-ini-file-loader": "^4.2.0", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/types": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.893.0.tgz", + "integrity": "sha512-Aht1nn5SnA0N+Tjv0dzhAY7CQbxVtmq1bBR6xI0MhG7p2XYVh1wXuKTzrldEvQWwA3odOYunAfT9aBiKZx9qIg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/util-arn-parser": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-arn-parser/-/util-arn-parser-3.893.0.tgz", + "integrity": "sha512-u8H4f2Zsi19DGnwj5FSZzDMhytYF/bCh37vAtBsn3cNDL3YG578X5oc+wSX54pM3tOxS+NY7tvOAo52SW7koUA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/util-buffer-from": { + "version": "3.310.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-buffer-from/-/util-buffer-from-3.310.0.tgz", + "integrity": "sha512-i6LVeXFtGih5Zs8enLrt+ExXY92QV25jtEnTKHsmlFqFAuL3VBeod6boeMXkN2p9lbSVVQ1sAOOYZOHYbYkntw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/is-array-buffer": "3.310.0", + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/util-endpoints": { + "version": "3.895.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.895.0.tgz", + "integrity": "sha512-MhxBvWbwxmKknuggO2NeMwOVkHOYL98pZ+1ZRI5YwckoCL3AvISMnPJgfN60ww6AIXHGpkp+HhpFdKOe8RHSEg==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.893.0", + "@smithy/types": "^4.5.0", + "@smithy/url-parser": "^4.1.1", + "@smithy/util-endpoints": "^3.1.2", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/util-hex-encoding": { + "version": "3.310.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-hex-encoding/-/util-hex-encoding-3.310.0.tgz", + "integrity": "sha512-sVN7mcCCDSJ67pI1ZMtk84SKGqyix6/0A1Ab163YKn+lFBQRMKexleZzpYzNGxYzmQS6VanP/cfU7NiLQOaSfA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/util-locate-window": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-locate-window/-/util-locate-window-3.893.0.tgz", + "integrity": "sha512-T89pFfgat6c8nMmpI8eKjBcDcgJq36+m9oiXbcUzeU55MP9ZuGgBomGjGnHaEyF36jenW9gmg3NfZDm0AO2XPg==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws-sdk/util-middleware": { + "version": "3.370.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-middleware/-/util-middleware-3.370.0.tgz", + "integrity": "sha512-Jvs9FZHaQznWGLkRel3PFEP93I1n0Kp6356zxYHk3LIOmjpzoob3R+v96mzyN+dZrnhPdPubYS41qbU2F9lROg==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/util-uri-escape": { + "version": "3.310.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-uri-escape/-/util-uri-escape-3.310.0.tgz", + "integrity": "sha512-drzt+aB2qo2LgtDoiy/3sVG8w63cgLkqFIa2NFlGpUgHFWTXkqtbgf4L5QdjRGKWhmZsnqkbtL7vkSWEcYDJ4Q==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/util-user-agent-browser": { + "version": "3.893.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.893.0.tgz", + "integrity": "sha512-PE9NtbDBW6Kgl1bG6A5fF3EPo168tnkj8TgMcT0sg4xYBWsBpq0bpJZRh+Jm5Bkwiw9IgTCLjEU7mR6xWaMB9w==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/types": "3.893.0", + "@smithy/types": "^4.5.0", + "bowser": "^2.11.0", + "tslib": "^2.6.2" + } + }, + "node_modules/@aws-sdk/util-user-agent-node": { + "version": "3.896.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.896.0.tgz", + "integrity": "sha512-jegizucAwoxyBddKl0kRGNEgRHcfGuMeyhP1Nf+wIUmHz/9CxobIajqcVk/KRNLdZY5mSn7YG2VtP3z0BcBb0w==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/middleware-user-agent": "3.896.0", + "@aws-sdk/types": "3.893.0", + "@smithy/node-config-provider": "^4.2.2", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "aws-crt": ">=1.0.0" + }, + "peerDependenciesMeta": { + "aws-crt": { + "optional": true + } + } + }, + "node_modules/@aws-sdk/util-utf8": { + "version": "3.310.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-utf8/-/util-utf8-3.310.0.tgz", + "integrity": "sha512-DnLfFT8uCO22uOJc0pt0DsSNau1GTisngBCDw8jQuWT5CqogMJu4b/uXmwEqfj8B3GX6Xsz8zOd6JpRlPftQoA==", + "license": "Apache-2.0", + "dependencies": { + "@aws-sdk/util-buffer-from": "3.310.0", + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@aws-sdk/util-utf8-browser": { + "version": "3.259.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/util-utf8-browser/-/util-utf8-browser-3.259.0.tgz", + "integrity": "sha512-UvFa/vR+e19XookZF8RzFZBrw2EUkQWxiBW0yYQAhvk3C+QVGl0H3ouca8LDBlBfQKXwmW3huo/59H8rwb1wJw==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.3.1" + } + }, + "node_modules/@aws-sdk/xml-builder": { + "version": "3.894.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.894.0.tgz", + "integrity": "sha512-E6EAMc9dT1a2DOdo4zyOf3fp5+NJ2wI+mcm7RaW1baFIWDwcb99PpvWoV7YEiK7oaBDshuOEGWKUSYXdW+JYgA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.5.0", + "fast-xml-parser": "5.2.5", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@aws/lambda-invoke-store": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.0.1.tgz", + "integrity": "sha512-ORHRQ2tmvnBXc8t/X9Z8IcSbBA4xTLKuN873FopzklHMeqBst7YG0d+AX97inkvDX+NChYtSr+qGfcqGFaI8Zw==", + "license": "Apache-2.0", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@cfworker/json-schema": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@cfworker/json-schema/-/json-schema-4.1.1.tgz", + "integrity": "sha512-gAmrUZSGtKc3AiBL71iNWxDsyUC5uMaKKGdvzYsBoTW/xi42JQHl7eKV2OYzCUqvc+D2RCcf7EXY2iCyFIk6og==", + "license": "MIT" + }, + "node_modules/@emnapi/runtime": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.8.1.tgz", + "integrity": "sha512-mehfKSMWjjNol8659Z8KxEMrdSJDDot5SXMq00dM8BN4o+CLNXQ0xH2V7EchNHV4RmbZLmmPdEaXZc5H2FXmDg==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.9.tgz", + "integrity": "sha512-OaGtL73Jck6pBKjNIe24BnFE6agGl+6KxDtTfHhy1HmhthfKouEcOhqpSL64K4/0WCtbKFLOdzD/44cJ4k9opA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.9.tgz", + "integrity": "sha512-5WNI1DaMtxQ7t7B6xa572XMXpHAaI/9Hnhk8lcxF4zVN4xstUgTlvuGDorBguKEnZO70qwEcLpfifMLoxiPqHQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.9.tgz", + "integrity": "sha512-IDrddSmpSv51ftWslJMvl3Q2ZT98fUSL2/rlUXuVqRXHCs5EUF1/f+jbjF5+NG9UffUDMCiTyh8iec7u8RlTLg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.9.tgz", + "integrity": "sha512-I853iMZ1hWZdNllhVZKm34f4wErd4lMyeV7BLzEExGEIZYsOzqDWDf+y082izYUE8gtJnYHdeDpN/6tUdwvfiw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.9.tgz", + "integrity": "sha512-XIpIDMAjOELi/9PB30vEbVMs3GV1v2zkkPnuyRRURbhqjyzIINwj+nbQATh4H9GxUgH1kFsEyQMxwiLFKUS6Rg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.9.tgz", + "integrity": "sha512-jhHfBzjYTA1IQu8VyrjCX4ApJDnH+ez+IYVEoJHeqJm9VhG9Dh2BYaJritkYK3vMaXrf7Ogr/0MQ8/MeIefsPQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.9.tgz", + "integrity": "sha512-z93DmbnY6fX9+KdD4Ue/H6sYs+bhFQJNCPZsi4XWJoYblUqT06MQUdBCpcSfuiN72AbqeBFu5LVQTjfXDE2A6Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.9.tgz", + "integrity": "sha512-mrKX6H/vOyo5v71YfXWJxLVxgy1kyt1MQaD8wZJgJfG4gq4DpQGpgTB74e5yBeQdyMTbgxp0YtNj7NuHN0PoZg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.9.tgz", + "integrity": "sha512-HBU2Xv78SMgaydBmdor38lg8YDnFKSARg1Q6AT0/y2ezUAKiZvc211RDFHlEZRFNRVhcMamiToo7bDx3VEOYQw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.9.tgz", + "integrity": "sha512-BlB7bIcLT3G26urh5Dmse7fiLmLXnRlopw4s8DalgZ8ef79Jj4aUcYbk90g8iCa2467HX8SAIidbL7gsqXHdRw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.9.tgz", + "integrity": "sha512-e7S3MOJPZGp2QW6AK6+Ly81rC7oOSerQ+P8L0ta4FhVi+/j/v2yZzx5CqqDaWjtPFfYz21Vi1S0auHrap3Ma3A==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.9.tgz", + "integrity": "sha512-Sbe10Bnn0oUAB2AalYztvGcK+o6YFFA/9829PhOCUS9vkJElXGdphz0A3DbMdP8gmKkqPmPcMJmJOrI3VYB1JQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.9.tgz", + "integrity": "sha512-YcM5br0mVyZw2jcQeLIkhWtKPeVfAerES5PvOzaDxVtIyZ2NUBZKNLjC5z3/fUlDgT6w89VsxP2qzNipOaaDyA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.9.tgz", + "integrity": "sha512-++0HQvasdo20JytyDpFvQtNrEsAgNG2CY1CLMwGXfFTKGBGQT3bOeLSYE2l1fYdvML5KUuwn9Z8L1EWe2tzs1w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.9.tgz", + "integrity": "sha512-uNIBa279Y3fkjV+2cUjx36xkx7eSjb8IvnL01eXUKXez/CBHNRw5ekCGMPM0BcmqBxBcdgUWuUXmVWwm4CH9kg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.9.tgz", + "integrity": "sha512-Mfiphvp3MjC/lctb+7D287Xw1DGzqJPb/J2aHHcHxflUo+8tmN/6d4k6I2yFR7BVo5/g7x2Monq4+Yew0EHRIA==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.9.tgz", + "integrity": "sha512-iSwByxzRe48YVkmpbgoxVzn76BXjlYFXC7NvLYq+b+kDjyyk30J0JY47DIn8z1MO3K0oSl9fZoRmZPQI4Hklzg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.9.tgz", + "integrity": "sha512-9jNJl6FqaUG+COdQMjSCGW4QiMHH88xWbvZ+kRVblZsWrkXlABuGdFJ1E9L7HK+T0Yqd4akKNa/lO0+jDxQD4Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.9.tgz", + "integrity": "sha512-RLLdkflmqRG8KanPGOU7Rpg829ZHu8nFy5Pqdi9U01VYtG9Y0zOG6Vr2z4/S+/3zIyOxiK6cCeYNWOFR9QP87g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.9.tgz", + "integrity": "sha512-YaFBlPGeDasft5IIM+CQAhJAqS3St3nJzDEgsgFixcfZeyGPCd6eJBWzke5piZuZ7CtL656eOSYKk4Ls2C0FRQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.9.tgz", + "integrity": "sha512-1MkgTCuvMGWuqVtAvkpkXFmtL8XhWy+j4jaSO2wxfJtilVCi0ZE37b8uOdMItIHz4I6z1bWWtEX4CJwcKYLcuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.9.tgz", + "integrity": "sha512-4Xd0xNiMVXKh6Fa7HEJQbrpP3m3DDn43jKxMjxLLRjWnRsfxjORYJlXPO4JNcXtOyfajXorRKY9NkOpTHptErg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.9.tgz", + "integrity": "sha512-WjH4s6hzo00nNezhp3wFIAfmGZ8U7KtrJNlFMRKxiI9mxEK1scOMAaa9i4crUtu+tBr+0IN6JCuAcSBJZfnphw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.9.tgz", + "integrity": "sha512-mGFrVJHmZiRqmP8xFOc6b84/7xa5y5YvR1x8djzXpJBSv/UsNK6aqec+6JDjConTgvvQefdGhFDAs2DLAds6gQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.9.tgz", + "integrity": "sha512-b33gLVU2k11nVx1OhX3C8QQP6UHQK4ZtN56oFWvVXvz2VkDoe6fbG8TOgHFxEvqeqohmRnIHe5A1+HADk4OQww==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.9.tgz", + "integrity": "sha512-PPOl1mi6lpLNQxnGoyAfschAodRFYXJ+9fs6WHXz7CSWKbOqiMZsubC+BQsVKuul+3vKLuwTHsS2c2y9EoKwxQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@huggingface/jinja": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/@huggingface/jinja/-/jinja-0.5.5.tgz", + "integrity": "sha512-xRlzazC+QZwr6z4ixEqYHo9fgwhTZ3xNSdljlKfUFGZSdlvt166DljRELFUfFytlYOYvo3vTisA/AFOuOAzFQQ==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@huggingface/transformers": { + "version": "3.8.1", + "resolved": "https://registry.npmjs.org/@huggingface/transformers/-/transformers-3.8.1.tgz", + "integrity": "sha512-tsTk4zVjImqdqjS8/AOZg2yNLd1z9S5v+7oUPpXaasDRwEDhB+xnglK1k5cad26lL5/ZIaeREgWWy0bs9y9pPA==", + "license": "Apache-2.0", + "dependencies": { + "@huggingface/jinja": "^0.5.3", + "onnxruntime-node": "1.21.0", + "onnxruntime-web": "1.22.0-dev.20250409-89f8206ba4", + "sharp": "^0.34.1" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz", + "integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz", + "integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz", + "integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz", + "integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz", + "integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==", + "cpu": [ + "arm" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz", + "integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.4.tgz", + "integrity": "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==", + "cpu": [ + "ppc64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.2.4.tgz", + "integrity": "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==", + "cpu": [ + "riscv64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.4.tgz", + "integrity": "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==", + "cpu": [ + "s390x" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz", + "integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz", + "integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz", + "integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz", + "integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==", + "cpu": [ + "arm" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz", + "integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.5.tgz", + "integrity": "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==", + "cpu": [ + "ppc64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.34.5.tgz", + "integrity": "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==", + "cpu": [ + "riscv64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.5.tgz", + "integrity": "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==", + "cpu": [ + "s390x" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz", + "integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz", + "integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz", + "integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.5.tgz", + "integrity": "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.7.0" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz", + "integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.5.tgz", + "integrity": "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==", + "cpu": [ + "ia32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz", + "integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@isaacs/fs-minipass": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz", + "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==", + "license": "ISC", + "dependencies": { + "minipass": "^7.0.4" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@langchain/core": { + "version": "0.3.72", + "resolved": "https://registry.npmjs.org/@langchain/core/-/core-0.3.72.tgz", + "integrity": "sha512-WsGWVZYnlKffj2eEfDocPNiaTRoxyYiLSQdQ7oxZvxGZBqo/90vpjbC33UGK1uPNBM4kT+pkdaol/MnvKUh8TQ==", + "license": "MIT", + "dependencies": { + "@cfworker/json-schema": "^4.0.2", + "ansi-styles": "^5.0.0", + "camelcase": "6", + "decamelize": "1.2.0", + "js-tiktoken": "^1.0.12", + "langsmith": "^0.3.46", + "mustache": "^4.2.0", + "p-queue": "^6.6.2", + "p-retry": "4", + "uuid": "^10.0.0", + "zod": "^3.25.32", + "zod-to-json-schema": "^3.22.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@orama/orama": { + "version": "3.1.18", + "resolved": "https://registry.npmjs.org/@orama/orama/-/orama-3.1.18.tgz", + "integrity": "sha512-a61ljmRVVyG5MC/698C8/FfFDw5a8LOIvyOLW5fztgUXqUpc1jOfQzOitSCbge657OgXXThmY3Tk8fpiDb4UcA==", + "license": "Apache-2.0", + "engines": { + "node": ">= 20.0.0" + } + }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.4.tgz", + "integrity": "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.0.tgz", + "integrity": "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.0.tgz", + "integrity": "sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ==", + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.1", + "@protobufjs/inquire": "^1.1.0" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/inquire": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.0.tgz", + "integrity": "sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.0.tgz", + "integrity": "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==", + "license": "BSD-3-Clause" + }, + "node_modules/@smithy/abort-controller": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/abort-controller/-/abort-controller-4.2.0.tgz", + "integrity": "sha512-PLUYa+SUKOEZtXFURBu/CNxlsxfaFGxSBPcStL13KpVeVWIfdezWyDqkz7iDLmwnxojXD0s5KzuB5HGHvt4Aeg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/chunked-blob-reader": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@smithy/chunked-blob-reader/-/chunked-blob-reader-5.1.0.tgz", + "integrity": "sha512-a36AtR7Q7XOhRPt6F/7HENmTWcB8kN7mDJcOFM/+FuKO6x88w8MQJfYCufMWh4fGyVkPjUh3Rrz/dnqFQdo6OQ==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/chunked-blob-reader-native": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@smithy/chunked-blob-reader-native/-/chunked-blob-reader-native-4.1.0.tgz", + "integrity": "sha512-Bnv0B3nSlfB2mPO0WgM49I/prl7+kamF042rrf3ezJ3Z4C7csPYvyYgZfXTGXwXfj1mAwDWjE/ybIf49PzFzvA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-base64": "^4.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/config-resolver": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/@smithy/config-resolver/-/config-resolver-4.3.0.tgz", + "integrity": "sha512-9oH+n8AVNiLPK/iK/agOsoWfrKZ3FGP3502tkksd6SRsKMYiu7AFX0YXo6YBADdsAj7C+G/aLKdsafIJHxuCkQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/node-config-provider": "^4.3.0", + "@smithy/types": "^4.6.0", + "@smithy/util-config-provider": "^4.2.0", + "@smithy/util-middleware": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/core": { + "version": "3.14.0", + "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.14.0.tgz", + "integrity": "sha512-XJ4z5FxvY/t0Dibms/+gLJrI5niRoY0BCmE02fwmPcRYFPI4KI876xaE79YGWIKnEslMbuQPsIEsoU/DXa0DoA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/middleware-serde": "^4.2.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/types": "^4.6.0", + "@smithy/util-base64": "^4.2.0", + "@smithy/util-body-length-browser": "^4.2.0", + "@smithy/util-middleware": "^4.2.0", + "@smithy/util-stream": "^4.4.0", + "@smithy/util-utf8": "^4.2.0", + "@smithy/uuid": "^1.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/credential-provider-imds": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.2.0.tgz", + "integrity": "sha512-SOhFVvFH4D5HJZytb0bLKxCrSnwcqPiNlrw+S4ZXjMnsC+o9JcUQzbZOEQcA8yv9wJFNhfsUiIUKiEnYL68Big==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/node-config-provider": "^4.3.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/types": "^4.6.0", + "@smithy/url-parser": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/eventstream-codec": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-codec/-/eventstream-codec-4.1.1.tgz", + "integrity": "sha512-PwkQw1hZwHTQB6X5hSUWz2OSeuj5Z6enWuAqke7DgWoP3t6vg3ktPpqPz3Erkn6w+tmsl8Oss6nrgyezoea2Iw==", + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/crc32": "5.2.0", + "@smithy/types": "^4.5.0", + "@smithy/util-hex-encoding": "^4.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/eventstream-serde-browser": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-browser/-/eventstream-serde-browser-4.1.1.tgz", + "integrity": "sha512-Q9QWdAzRaIuVkefupRPRFAasaG/droBqn1feiMnmLa+LLEUG45pqX1+FurHFmlqiCfobB3nUlgoJfeXZsr7MPA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/eventstream-serde-universal": "^4.1.1", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/eventstream-serde-config-resolver": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-config-resolver/-/eventstream-serde-config-resolver-4.2.1.tgz", + "integrity": "sha512-oSUkF9zDN9zcOUBMtxp8RewJlh71E9NoHWU8jE3hU9JMYCsmW4assVTpgic/iS3/dM317j6hO5x18cc3XrfvEw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/eventstream-serde-node": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-node/-/eventstream-serde-node-4.1.1.tgz", + "integrity": "sha512-tn6vulwf/ScY0vjhzptSJuDJJqlhNtUjkxJ4wiv9E3SPoEqTEKbaq6bfqRO7nvhTG29ALICRcvfFheOUPl8KNA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/eventstream-serde-universal": "^4.1.1", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/eventstream-serde-universal": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-universal/-/eventstream-serde-universal-4.1.1.tgz", + "integrity": "sha512-uLOAiM/Dmgh2CbEXQx+6/ssK7fbzFhd+LjdyFxXid5ZBCbLHTFHLdD/QbXw5aEDsLxQhgzDxLLsZhsftAYwHJA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/eventstream-codec": "^4.1.1", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/fetch-http-handler": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.3.0.tgz", + "integrity": "sha512-BG3KSmsx9A//KyIfw+sqNmWFr1YBUr+TwpxFT7yPqAk0yyDh7oSNgzfNH7pS6OC099EGx2ltOULvumCFe8bcgw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/protocol-http": "^5.3.0", + "@smithy/querystring-builder": "^4.2.0", + "@smithy/types": "^4.6.0", + "@smithy/util-base64": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/hash-blob-browser": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@smithy/hash-blob-browser/-/hash-blob-browser-4.1.1.tgz", + "integrity": "sha512-avAtk++s1e/1VODf+rg7c9R2pB5G9y8yaJaGY4lPZI2+UIqVyuSDMikWjeWfBVmFZ3O7NpDxBbUCyGhThVUKWQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/chunked-blob-reader": "^5.1.0", + "@smithy/chunked-blob-reader-native": "^4.1.0", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/hash-node": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/hash-node/-/hash-node-4.2.0.tgz", + "integrity": "sha512-ugv93gOhZGysTctZh9qdgng8B+xO0cj+zN0qAZ+Sgh7qTQGPOJbMdIuyP89KNfUyfAqFSNh5tMvC+h2uCpmTtA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "@smithy/util-buffer-from": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/hash-stream-node": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@smithy/hash-stream-node/-/hash-stream-node-4.1.1.tgz", + "integrity": "sha512-3ztT4pV0Moazs3JAYFdfKk11kYFDo4b/3R3+xVjIm6wY9YpJf+xfz+ocEnNKcWAdcmSMqi168i2EMaKmJHbJMA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.5.0", + "@smithy/util-utf8": "^4.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/invalid-dependency": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/invalid-dependency/-/invalid-dependency-4.2.0.tgz", + "integrity": "sha512-ZmK5X5fUPAbtvRcUPtk28aqIClVhbfcmfoS4M7UQBTnDdrNxhsrxYVv0ZEl5NaPSyExsPWqL4GsPlRvtlwg+2A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/is-array-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-4.2.0.tgz", + "integrity": "sha512-DZZZBvC7sjcYh4MazJSGiWMI2L7E0oCiRHREDzIxi/M2LY79/21iXt6aPLHge82wi5LsuRF5A06Ds3+0mlh6CQ==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/md5-js": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@smithy/md5-js/-/md5-js-4.1.1.tgz", + "integrity": "sha512-MvWXKK743BuHjr/hnWuT6uStdKEaoqxHAQUvbKJPPZM5ZojTNFI5D+47BoQfBE5RgGlRRty05EbWA+NXDv+hIA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.5.0", + "@smithy/util-utf8": "^4.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/middleware-content-length": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/middleware-content-length/-/middleware-content-length-4.2.0.tgz", + "integrity": "sha512-6ZAnwrXFecrA4kIDOcz6aLBhU5ih2is2NdcZtobBDSdSHtE9a+MThB5uqyK4XXesdOCvOcbCm2IGB95birTSOQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/protocol-http": "^5.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/middleware-endpoint": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/@smithy/middleware-endpoint/-/middleware-endpoint-4.3.0.tgz", + "integrity": "sha512-jFVjuQeV8TkxaRlcCNg0GFVgg98tscsmIrIwRFeC74TIUyLE3jmY9xgc1WXrPQYRjQNK3aRoaIk6fhFRGOIoGw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.14.0", + "@smithy/middleware-serde": "^4.2.0", + "@smithy/node-config-provider": "^4.3.0", + "@smithy/shared-ini-file-loader": "^4.3.0", + "@smithy/types": "^4.6.0", + "@smithy/url-parser": "^4.2.0", + "@smithy/util-middleware": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/middleware-retry": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/@smithy/middleware-retry/-/middleware-retry-4.4.0.tgz", + "integrity": "sha512-yaVBR0vQnOnzex45zZ8ZrPzUnX73eUC8kVFaAAbn04+6V7lPtxn56vZEBBAhgS/eqD6Zm86o6sJs6FuQVoX5qg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/node-config-provider": "^4.3.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/service-error-classification": "^4.2.0", + "@smithy/smithy-client": "^4.7.0", + "@smithy/types": "^4.6.0", + "@smithy/util-middleware": "^4.2.0", + "@smithy/util-retry": "^4.2.0", + "@smithy/uuid": "^1.1.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/middleware-serde": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/middleware-serde/-/middleware-serde-4.2.0.tgz", + "integrity": "sha512-rpTQ7D65/EAbC6VydXlxjvbifTf4IH+sADKg6JmAvhkflJO2NvDeyU9qsWUNBelJiQFcXKejUHWRSdmpJmEmiw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/protocol-http": "^5.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/middleware-stack": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/middleware-stack/-/middleware-stack-4.2.0.tgz", + "integrity": "sha512-G5CJ//eqRd9OARrQu9MK1H8fNm2sMtqFh6j8/rPozhEL+Dokpvi1Og+aCixTuwDAGZUkJPk6hJT5jchbk/WCyg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/node-config-provider": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.3.0.tgz", + "integrity": "sha512-5QgHNuWdT9j9GwMPPJCKxy2KDxZ3E5l4M3/5TatSZrqYVoEiqQrDfAq8I6KWZw7RZOHtVtCzEPdYz7rHZixwcA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/property-provider": "^4.2.0", + "@smithy/shared-ini-file-loader": "^4.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/node-http-handler": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.3.0.tgz", + "integrity": "sha512-RHZ/uWCmSNZ8cneoWEVsVwMZBKy/8123hEpm57vgGXA3Irf/Ja4v9TVshHK2ML5/IqzAZn0WhINHOP9xl+Qy6Q==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/abort-controller": "^4.2.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/querystring-builder": "^4.2.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/property-provider": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/property-provider/-/property-provider-4.2.0.tgz", + "integrity": "sha512-rV6wFre0BU6n/tx2Ztn5LdvEdNZ2FasQbPQmDOPfV9QQyDmsCkOAB0osQjotRCQg+nSKFmINhyda0D3AnjSBJw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/protocol-http": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-5.3.0.tgz", + "integrity": "sha512-6POSYlmDnsLKb7r1D3SVm7RaYW6H1vcNcTWGWrF7s9+2noNYvUsm7E4tz5ZQ9HXPmKn6Hb67pBDRIjrT4w/d7Q==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/querystring-builder": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/querystring-builder/-/querystring-builder-4.2.0.tgz", + "integrity": "sha512-Q4oFD0ZmI8yJkiPPeGUITZj++4HHYCW3pYBYfIobUCkYpI6mbkzmG1MAQQ3lJYYWj3iNqfzOenUZu+jqdPQ16A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "@smithy/util-uri-escape": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/querystring-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/querystring-parser/-/querystring-parser-4.2.0.tgz", + "integrity": "sha512-BjATSNNyvVbQxOOlKse0b0pSezTWGMvA87SvoFoFlkRsKXVsN3bEtjCxvsNXJXfnAzlWFPaT9DmhWy1vn0sNEA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/service-error-classification": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/service-error-classification/-/service-error-classification-4.2.0.tgz", + "integrity": "sha512-Ylv1ttUeKatpR0wEOMnHf1hXMktPUMObDClSWl2TpCVT4DwtJhCeighLzSLbgH3jr5pBNM0LDXT5yYxUvZ9WpA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/shared-ini-file-loader": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/@smithy/shared-ini-file-loader/-/shared-ini-file-loader-4.3.0.tgz", + "integrity": "sha512-VCUPPtNs+rKWlqqntX0CbVvWyjhmX30JCtzO+s5dlzzxrvSfRh5SY0yxnkirvc1c80vdKQttahL71a9EsdolSQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/signature-v4": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.3.0.tgz", + "integrity": "sha512-MKNyhXEs99xAZaFhm88h+3/V+tCRDQ+PrDzRqL0xdDpq4gjxcMmf5rBA3YXgqZqMZ/XwemZEurCBQMfxZOWq/g==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^4.2.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/types": "^4.6.0", + "@smithy/util-hex-encoding": "^4.2.0", + "@smithy/util-middleware": "^4.2.0", + "@smithy/util-uri-escape": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/smithy-client": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/@smithy/smithy-client/-/smithy-client-4.7.0.tgz", + "integrity": "sha512-3BDx/aCCPf+kkinYf5QQhdQ9UAGihgOVqI3QO5xQfSaIWvUE4KYLtiGRWsNe1SR7ijXC0QEPqofVp5Sb0zC8xQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/core": "^3.14.0", + "@smithy/middleware-endpoint": "^4.3.0", + "@smithy/middleware-stack": "^4.2.0", + "@smithy/protocol-http": "^5.3.0", + "@smithy/types": "^4.6.0", + "@smithy/util-stream": "^4.4.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/types": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.6.0.tgz", + "integrity": "sha512-4lI9C8NzRPOv66FaY1LL1O/0v0aLVrq/mXP/keUa9mJOApEeae43LsLd2kZRUJw91gxOQfLIrV3OvqPgWz1YsA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/url-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/url-parser/-/url-parser-4.2.0.tgz", + "integrity": "sha512-AlBmD6Idav2ugmoAL6UtR6ItS7jU5h5RNqLMZC7QrLCoITA9NzIN3nx9GWi8g4z1pfWh2r9r96SX/jHiNwPJ9A==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/querystring-parser": "^4.2.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-base64": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-base64/-/util-base64-4.2.0.tgz", + "integrity": "sha512-+erInz8WDv5KPe7xCsJCp+1WCjSbah9gWcmUXc9NqmhyPx59tf7jqFz+za1tRG1Y5KM1Cy1rWCcGypylFp4mvA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-body-length-browser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-body-length-browser/-/util-body-length-browser-4.2.0.tgz", + "integrity": "sha512-Fkoh/I76szMKJnBXWPdFkQJl2r9SjPt3cMzLdOB6eJ4Pnpas8hVoWPYemX/peO0yrrvldgCUVJqOAjUrOLjbxg==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-body-length-node": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-body-length-node/-/util-body-length-node-4.2.0.tgz", + "integrity": "sha512-U8q1WsSZFjXijlD7a4wsDQOvOwV+72iHSfq1q7VD+V75xP/pdtm0WIGuaFJ3gcADDOKj2MIBn4+zisi140HEnQ==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-buffer-from": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-4.2.0.tgz", + "integrity": "sha512-kAY9hTKulTNevM2nlRtxAG2FQ3B2OR6QIrPY3zE5LqJy1oxzmgBGsHLWTcNhWXKchgA0WHW+mZkQrng/pgcCew==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/is-array-buffer": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-config-provider": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-config-provider/-/util-config-provider-4.2.0.tgz", + "integrity": "sha512-YEjpl6XJ36FTKmD+kRJJWYvrHeUvm5ykaUS5xK+6oXffQPHeEM4/nXlZPe+Wu0lsgRUcNZiliYNh/y7q9c2y6Q==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-defaults-mode-browser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-browser/-/util-defaults-mode-browser-4.2.0.tgz", + "integrity": "sha512-qzHp7ZDk1Ba4LDwQVCNp90xPGqSu7kmL7y5toBpccuhi3AH7dcVBIT/pUxYcInK4jOy6FikrcTGq5wxcka8UaQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/property-provider": "^4.2.0", + "@smithy/smithy-client": "^4.7.0", + "@smithy/types": "^4.6.0", + "bowser": "^2.11.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-defaults-mode-node": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-node/-/util-defaults-mode-node-4.2.0.tgz", + "integrity": "sha512-FxUHS3WXgx3bTWR6yQHNHHkQHZm/XKIi/CchTnKvBulN6obWpcbzJ6lDToXn+Wp0QlVKd7uYAz2/CTw1j7m+Kg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/config-resolver": "^4.3.0", + "@smithy/credential-provider-imds": "^4.2.0", + "@smithy/node-config-provider": "^4.3.0", + "@smithy/property-provider": "^4.2.0", + "@smithy/smithy-client": "^4.7.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-endpoints": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-endpoints/-/util-endpoints-3.2.0.tgz", + "integrity": "sha512-TXeCn22D56vvWr/5xPqALc9oO+LN+QpFjrSM7peG/ckqEPoI3zaKZFp+bFwfmiHhn5MGWPaLCqDOJPPIixk9Wg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/node-config-provider": "^4.3.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-hex-encoding": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-hex-encoding/-/util-hex-encoding-4.2.0.tgz", + "integrity": "sha512-CCQBwJIvXMLKxVbO88IukazJD9a4kQ9ZN7/UMGBjBcJYvatpWk+9g870El4cB8/EJxfe+k+y0GmR9CAzkF+Nbw==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-middleware": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-4.2.0.tgz", + "integrity": "sha512-u9OOfDa43MjagtJZ8AapJcmimP+K2Z7szXn8xbty4aza+7P1wjFmy2ewjSbhEiYQoW1unTlOAIV165weYAaowA==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-retry": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-retry/-/util-retry-4.2.0.tgz", + "integrity": "sha512-BWSiuGbwRnEE2SFfaAZEX0TqaxtvtSYPM/J73PFVm+A29Fg1HTPiYFb8TmX1DXp4hgcdyJcNQmprfd5foeORsg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/service-error-classification": "^4.2.0", + "@smithy/types": "^4.6.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-stream": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/@smithy/util-stream/-/util-stream-4.4.0.tgz", + "integrity": "sha512-vtO7ktbixEcrVzMRmpQDnw/Ehr9UWjBvSJ9fyAbadKkC4w5Cm/4lMO8cHz8Ysb8uflvQUNRcuux/oNHKPXkffg==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/fetch-http-handler": "^5.3.0", + "@smithy/node-http-handler": "^4.3.0", + "@smithy/types": "^4.6.0", + "@smithy/util-base64": "^4.2.0", + "@smithy/util-buffer-from": "^4.2.0", + "@smithy/util-hex-encoding": "^4.2.0", + "@smithy/util-utf8": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-uri-escape": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-uri-escape/-/util-uri-escape-4.2.0.tgz", + "integrity": "sha512-igZpCKV9+E/Mzrpq6YacdTQ0qTiLm85gD6N/IrmyDvQFA4UnU3d5g3m8tMT/6zG/vVkWSU+VxeUyGonL62DuxA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-utf8": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.2.0.tgz", + "integrity": "sha512-zBPfuzoI8xyBtR2P6WQj63Rz8i3AmfAaJLuNG8dWsfvPe8lO4aCPYLn879mEgHndZH1zQ2oXmG8O1GGzzaoZiw==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/util-buffer-from": "^4.2.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/util-waiter": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@smithy/util-waiter/-/util-waiter-4.1.1.tgz", + "integrity": "sha512-PJBmyayrlfxM7nbqjomF4YcT1sApQwZio0NHSsT0EzhJqljRmvhzqZua43TyEs80nJk2Cn2FGPg/N8phH6KeCQ==", + "license": "Apache-2.0", + "dependencies": { + "@smithy/abort-controller": "^4.1.1", + "@smithy/types": "^4.5.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@smithy/uuid": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@smithy/uuid/-/uuid-1.1.0.tgz", + "integrity": "sha512-4aUIteuyxtBUhVdiQqcDhKFitwfd9hqoSDYY2KRXiWtgoWJ9Bmise+KfEPDiVHWeJepvF8xJO9/9+WDIciMFFw==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@supabase/auth-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.87.1.tgz", + "integrity": "sha512-6RDeOf5TVoaXFtEstN188ykp3pXLZaU9qoAWfx8dc50FFAAqt+kcFJ96V0IvSmcpb4mDAWcpTJ7BegmVDn/WIw==", + "license": "MIT", + "dependencies": { + "tslib": "2.8.1" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@supabase/functions-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/functions-js/-/functions-js-2.87.1.tgz", + "integrity": "sha512-rWmYo4gRD0XAjMhYDlz7IH67bp4TIQ1UE4VqwIQtl1gGPwtLDq6wcRnu7jLKlXx0Gtrknw/eoiHYG9//XrCTzQ==", + "license": "MIT", + "dependencies": { + "tslib": "2.8.1" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@supabase/postgrest-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/postgrest-js/-/postgrest-js-2.87.1.tgz", + "integrity": "sha512-Yzu5eL3iGmZW0C/8x+vEojAOou63FI9oVw8HI8YOq63+5yM8g8aGh7Y1E2vbXFb7+gHGsPqLnaC6dPhrYt7qBA==", + "license": "MIT", + "dependencies": { + "tslib": "2.8.1" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@supabase/realtime-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/realtime-js/-/realtime-js-2.87.1.tgz", + "integrity": "sha512-XvLtEznxmYZXA7LYuy5zbSXpSYjDLJq2wQeRh3MzON2OR4U8Kq+RtPz2E2Wi8HEzvBfsc+nNu1TG8LQ9+3DRkA==", + "license": "MIT", + "dependencies": { + "@types/phoenix": "^1.6.6", + "@types/ws": "^8.18.1", + "tslib": "2.8.1", + "ws": "^8.18.2" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@supabase/storage-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/storage-js/-/storage-js-2.87.1.tgz", + "integrity": "sha512-0Uc8tNV4yzkNNmp1inpXru0RB4a7ECq05G2S6BDvSpMxTxJrDVJ4vVDwyhqB8ZZ+O9+8prHaQYoByQeuDnwpFQ==", + "license": "MIT", + "dependencies": { + "iceberg-js": "^0.8.1", + "tslib": "2.8.1" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@supabase/supabase-js": { + "version": "2.87.1", + "resolved": "https://registry.npmjs.org/@supabase/supabase-js/-/supabase-js-2.87.1.tgz", + "integrity": "sha512-tVgqZqnHZVum584KuUKSQZgcy6ZkhVd6gG8QWg2QfIXH9HmXdamauxdVsLXwaNPJxEdOyfAfwIyi5XUsiVYWtg==", + "license": "MIT", + "dependencies": { + "@supabase/auth-js": "2.87.1", + "@supabase/functions-js": "2.87.1", + "@supabase/postgrest-js": "2.87.1", + "@supabase/realtime-js": "2.87.1", + "@supabase/storage-js": "2.87.1" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@types/node": { + "version": "25.0.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.0.0.tgz", + "integrity": "sha512-rl78HwuZlaDIUSeUKkmogkhebA+8K1Hy7tddZuJ3D0xV8pZSfsYGTsliGUol1JPzu9EKnTxPC4L1fiWouStRew==", + "license": "MIT", + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/@types/phoenix": { + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/@types/phoenix/-/phoenix-1.6.7.tgz", + "integrity": "sha512-oN9ive//QSBkf19rfDv45M7eZPi0eEXylht2OLEXicu5b4KoQ1OzXIw+xDSGWxSxe1JmepRR/ZH283vsu518/Q==", + "license": "MIT" + }, + "node_modules/@types/retry": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz", + "integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==", + "license": "MIT" + }, + "node_modules/@types/uuid": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz", + "integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==", + "license": "MIT" + }, + "node_modules/@types/ws": { + "version": "8.18.1", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", + "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "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" + } + ], + "license": "MIT" + }, + "node_modules/boolean": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/boolean/-/boolean-3.2.0.tgz", + "integrity": "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==", + "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.", + "license": "MIT" + }, + "node_modules/bowser": { + "version": "2.12.1", + "resolved": "https://registry.npmjs.org/bowser/-/bowser-2.12.1.tgz", + "integrity": "sha512-z4rE2Gxh7tvshQ4hluIT7XcFrgLIQaw9X3A+kTTRdovCz5PMukm/0QC/BKSYPj3omF5Qfypn9O/c5kgpmvYUCw==", + "license": "MIT" + }, + "node_modules/camelcase": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", + "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chalk/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/chownr": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", + "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/console-table-printer": { + "version": "2.14.6", + "resolved": "https://registry.npmjs.org/console-table-printer/-/console-table-printer-2.14.6.tgz", + "integrity": "sha512-MCBl5HNVaFuuHW6FGbL/4fB7N/ormCy+tQ+sxTrF6QtSbSNETvPuOVbkJBhzDgYhvjWGrTma4eYJa37ZuoQsPw==", + "license": "MIT", + "dependencies": { + "simple-wcswidth": "^1.0.1" + } + }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-properties": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/detect-node": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz", + "integrity": "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==", + "license": "MIT" + }, + "node_modules/dotenv": { + "version": "17.2.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.2.1.tgz", + "integrity": "sha512-kQhDYKZecqnM0fCnzI5eIv5L4cAe/iRI+HqMbO/hbRdTAeXDG+M9FjipUxNfbARuEg4iHIbhnhs78BCHNbSxEQ==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "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/es6-error": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz", + "integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==", + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.25.9", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.9.tgz", + "integrity": "sha512-CRbODhYyQx3qp7ZEwzxOk4JBqmD/seJrzPa/cGjY1VtIn5E09Oi9/dB4JwctnfZ8Q8iT7rioVv5k/FNT/uf54g==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.9", + "@esbuild/android-arm": "0.25.9", + "@esbuild/android-arm64": "0.25.9", + "@esbuild/android-x64": "0.25.9", + "@esbuild/darwin-arm64": "0.25.9", + "@esbuild/darwin-x64": "0.25.9", + "@esbuild/freebsd-arm64": "0.25.9", + "@esbuild/freebsd-x64": "0.25.9", + "@esbuild/linux-arm": "0.25.9", + "@esbuild/linux-arm64": "0.25.9", + "@esbuild/linux-ia32": "0.25.9", + "@esbuild/linux-loong64": "0.25.9", + "@esbuild/linux-mips64el": "0.25.9", + "@esbuild/linux-ppc64": "0.25.9", + "@esbuild/linux-riscv64": "0.25.9", + "@esbuild/linux-s390x": "0.25.9", + "@esbuild/linux-x64": "0.25.9", + "@esbuild/netbsd-arm64": "0.25.9", + "@esbuild/netbsd-x64": "0.25.9", + "@esbuild/openbsd-arm64": "0.25.9", + "@esbuild/openbsd-x64": "0.25.9", + "@esbuild/openharmony-arm64": "0.25.9", + "@esbuild/sunos-x64": "0.25.9", + "@esbuild/win32-arm64": "0.25.9", + "@esbuild/win32-ia32": "0.25.9", + "@esbuild/win32-x64": "0.25.9" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eventemitter3": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", + "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", + "license": "MIT" + }, + "node_modules/fast-xml-parser": { + "version": "5.2.5", + "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.2.5.tgz", + "integrity": "sha512-pfX9uG9Ki0yekDHx2SiuRIyFdyAr1kMIMitPvb0YBo8SUfKvia7w7FIyd/l6av85pFYRhZscS75MwMnbvY+hcQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT", + "dependencies": { + "strnum": "^2.1.0" + }, + "bin": { + "fxparser": "src/cli/cli.js" + } + }, + "node_modules/flatbuffers": { + "version": "25.9.23", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-25.9.23.tgz", + "integrity": "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==", + "license": "Apache-2.0" + }, + "node_modules/global-agent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/global-agent/-/global-agent-3.0.0.tgz", + "integrity": "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==", + "license": "BSD-3-Clause", + "dependencies": { + "boolean": "^3.0.1", + "es6-error": "^4.1.1", + "matcher": "^3.0.0", + "roarr": "^2.15.3", + "semver": "^7.3.2", + "serialize-error": "^7.0.1" + }, + "engines": { + "node": ">=10.0" + } + }, + "node_modules/globalthis": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", + "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", + "license": "MIT", + "dependencies": { + "define-properties": "^1.2.1", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "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/guid-typescript": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/guid-typescript/-/guid-typescript-1.0.9.tgz", + "integrity": "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==", + "license": "ISC" + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/iceberg-js": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/iceberg-js/-/iceberg-js-0.8.1.tgz", + "integrity": "sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA==", + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/idb": { + "version": "8.0.3", + "resolved": "https://registry.npmjs.org/idb/-/idb-8.0.3.tgz", + "integrity": "sha512-LtwtVyVYO5BqRvcsKuB2iUMnHwPVByPCXFXOpuU96IZPPoPN6xjOGxZQ74pgSVVLQWtUOYgyeL4GE98BY5D3wg==", + "license": "ISC" + }, + "node_modules/js-tiktoken": { + "version": "1.0.21", + "resolved": "https://registry.npmjs.org/js-tiktoken/-/js-tiktoken-1.0.21.tgz", + "integrity": "sha512-biOj/6M5qdgx5TKjDnFT1ymSpM5tbd3ylwDtrQvFQSu0Z7bBYko2dF+W/aUkXUPuk6IVpRxk/3Q2sHOzGlS36g==", + "license": "MIT", + "dependencies": { + "base64-js": "^1.5.1" + } + }, + "node_modules/json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==", + "license": "ISC" + }, + "node_modules/langsmith": { + "version": "0.3.62", + "resolved": "https://registry.npmjs.org/langsmith/-/langsmith-0.3.62.tgz", + "integrity": "sha512-ApoGLs28cJCxL91l1PDDkjsA4oLrbeNlE1pyTvyopqXq9bNJrP8JPUNWZm/tpU0DzZpvZFctRzru4gNAr/bkxg==", + "license": "MIT", + "dependencies": { + "@types/uuid": "^10.0.0", + "chalk": "^4.1.2", + "console-table-printer": "^2.12.1", + "p-queue": "^6.6.2", + "p-retry": "4", + "semver": "^7.6.3", + "uuid": "^10.0.0" + }, + "peerDependencies": { + "@opentelemetry/api": "*", + "@opentelemetry/exporter-trace-otlp-proto": "*", + "@opentelemetry/sdk-trace-base": "*", + "openai": "*" + }, + "peerDependenciesMeta": { + "@opentelemetry/api": { + "optional": true + }, + "@opentelemetry/exporter-trace-otlp-proto": { + "optional": true + }, + "@opentelemetry/sdk-trace-base": { + "optional": true + }, + "openai": { + "optional": true + } + } + }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, + "node_modules/matcher": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/matcher/-/matcher-3.0.0.tgz", + "integrity": "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==", + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/minipass": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/minisearch": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/minisearch/-/minisearch-7.2.0.tgz", + "integrity": "sha512-dqT2XBYUOZOiC5t2HRnwADjhNS2cecp9u+TJRiJ1Qp/f5qjkeT5APcGPjHw+bz89Ms8Jp+cG4AlE+QZ/QnDglg==", + "license": "MIT" + }, + "node_modules/minizlib": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", + "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", + "license": "MIT", + "dependencies": { + "minipass": "^7.1.2" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/mustache": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/mustache/-/mustache-4.2.0.tgz", + "integrity": "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==", + "license": "MIT", + "bin": { + "mustache": "bin/mustache" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/onnxruntime-common": { + "version": "1.21.0", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.21.0.tgz", + "integrity": "sha512-Q632iLLrtCAVOTO65dh2+mNbQir/QNTVBG3h/QdZBpns7mZ0RYbLRBgGABPbpU9351AgYy7SJf1WaeVwMrBFPQ==", + "license": "MIT" + }, + "node_modules/onnxruntime-node": { + "version": "1.21.0", + "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.21.0.tgz", + "integrity": "sha512-NeaCX6WW2L8cRCSqy3bInlo5ojjQqu2fD3D+9W5qb5irwxhEyWKXeH2vZ8W9r6VxaMPUan+4/7NDwZMtouZxEw==", + "hasInstallScript": true, + "license": "MIT", + "os": [ + "win32", + "darwin", + "linux" + ], + "dependencies": { + "global-agent": "^3.0.0", + "onnxruntime-common": "1.21.0", + "tar": "^7.0.1" + } + }, + "node_modules/onnxruntime-web": { + "version": "1.22.0-dev.20250409-89f8206ba4", + "resolved": "https://registry.npmjs.org/onnxruntime-web/-/onnxruntime-web-1.22.0-dev.20250409-89f8206ba4.tgz", + "integrity": "sha512-0uS76OPgH0hWCPrFKlL8kYVV7ckM7t/36HfbgoFw6Nd0CZVVbQC4PkrR8mBX8LtNUFZO25IQBqV2Hx2ho3FlbQ==", + "license": "MIT", + "dependencies": { + "flatbuffers": "^25.1.24", + "guid-typescript": "^1.0.9", + "long": "^5.2.3", + "onnxruntime-common": "1.22.0-dev.20250409-89f8206ba4", + "platform": "^1.3.6", + "protobufjs": "^7.2.4" + } + }, + "node_modules/onnxruntime-web/node_modules/onnxruntime-common": { + "version": "1.22.0-dev.20250409-89f8206ba4", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.22.0-dev.20250409-89f8206ba4.tgz", + "integrity": "sha512-vDJMkfCfb0b1A836rgHj+ORuZf4B4+cc2bASQtpeoJLueuFc5DuYwjIZUBrSvx/fO5IrLjLz+oTrB3pcGlhovQ==", + "license": "MIT" + }, + "node_modules/p-finally": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", + "integrity": "sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/p-queue": { + "version": "6.6.2", + "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-6.6.2.tgz", + "integrity": "sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ==", + "license": "MIT", + "dependencies": { + "eventemitter3": "^4.0.4", + "p-timeout": "^3.2.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-retry": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz", + "integrity": "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==", + "license": "MIT", + "dependencies": { + "@types/retry": "0.12.0", + "retry": "^0.13.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-timeout": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-3.2.0.tgz", + "integrity": "sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg==", + "license": "MIT", + "dependencies": { + "p-finally": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/platform": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz", + "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==", + "license": "MIT" + }, + "node_modules/protobufjs": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.5.4.tgz", + "integrity": "sha512-CvexbZtbov6jW2eXAvLukXjXUW1TzFaivC46BpWc/3BpcCysb5Vffu+B3XHMm8lVEuy2Mm4XGex8hBSg1yapPg==", + "hasInstallScript": true, + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.4", + "@protobufjs/eventemitter": "^1.1.0", + "@protobufjs/fetch": "^1.1.0", + "@protobufjs/float": "^1.0.2", + "@protobufjs/inquire": "^1.1.0", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.0", + "@types/node": ">=13.7.0", + "long": "^5.0.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/railroad-memory": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/railroad-memory/-/railroad-memory-0.2.1.tgz", + "integrity": "sha512-sHzqsrIZ1Jkvztx/1X4lYjC/awyxAes3bVyNmRXL1ygnRmea/PalzWQU8RgtY1S8wE8WAuvy6O3Bs/l2zJOfVg==", + "license": "MIT", + "dependencies": { + "yaml": "^2.3.4" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/retry": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", + "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/roarr": { + "version": "2.15.4", + "resolved": "https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz", + "integrity": "sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==", + "license": "BSD-3-Clause", + "dependencies": { + "boolean": "^3.0.1", + "detect-node": "^2.0.4", + "globalthis": "^1.0.1", + "json-stringify-safe": "^5.0.1", + "semver-compare": "^1.0.0", + "sprintf-js": "^1.1.2" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/semver-compare": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz", + "integrity": "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==", + "license": "MIT" + }, + "node_modules/serialize-error": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-7.0.1.tgz", + "integrity": "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==", + "license": "MIT", + "dependencies": { + "type-fest": "^0.13.1" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/sharp": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz", + "integrity": "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.0.0", + "detect-libc": "^2.1.2", + "semver": "^7.7.3" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.34.5", + "@img/sharp-darwin-x64": "0.34.5", + "@img/sharp-libvips-darwin-arm64": "1.2.4", + "@img/sharp-libvips-darwin-x64": "1.2.4", + "@img/sharp-libvips-linux-arm": "1.2.4", + "@img/sharp-libvips-linux-arm64": "1.2.4", + "@img/sharp-libvips-linux-ppc64": "1.2.4", + "@img/sharp-libvips-linux-riscv64": "1.2.4", + "@img/sharp-libvips-linux-s390x": "1.2.4", + "@img/sharp-libvips-linux-x64": "1.2.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.2.4", + "@img/sharp-libvips-linuxmusl-x64": "1.2.4", + "@img/sharp-linux-arm": "0.34.5", + "@img/sharp-linux-arm64": "0.34.5", + "@img/sharp-linux-ppc64": "0.34.5", + "@img/sharp-linux-riscv64": "0.34.5", + "@img/sharp-linux-s390x": "0.34.5", + "@img/sharp-linux-x64": "0.34.5", + "@img/sharp-linuxmusl-arm64": "0.34.5", + "@img/sharp-linuxmusl-x64": "0.34.5", + "@img/sharp-wasm32": "0.34.5", + "@img/sharp-win32-arm64": "0.34.5", + "@img/sharp-win32-ia32": "0.34.5", + "@img/sharp-win32-x64": "0.34.5" + } + }, + "node_modules/simple-wcswidth": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/simple-wcswidth/-/simple-wcswidth-1.1.2.tgz", + "integrity": "sha512-j7piyCjAeTDSjzTSQ7DokZtMNwNlEAyxqSZeCS+CXH7fJ4jx3FuJ/mTW3mE+6JLs4VJBbcll0Kjn+KXI5t21Iw==", + "license": "MIT" + }, + "node_modules/sprintf-js": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz", + "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==", + "license": "BSD-3-Clause" + }, + "node_modules/strnum": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.1.1.tgz", + "integrity": "sha512-7ZvoFTiCnGxBtDqJ//Cu6fWtZtc7Y3x+QOirG15wztbdngGSkht27o2pyGWrVy0b4WAy3jbKmnoK6g5VlVNUUw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "license": "MIT" + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/tar": { + "version": "7.5.9", + "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.9.tgz", + "integrity": "sha512-BTLcK0xsDh2+PUe9F6c2TlRp4zOOBMTkoQHQIWSIzI0R7KG46uEwq4OPk2W7bZcprBMsuaeFsqwYr7pjh6CuHg==", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/fs-minipass": "^4.0.0", + "chownr": "^3.0.0", + "minipass": "^7.1.2", + "minizlib": "^3.1.0", + "yallist": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/type-fest": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.13.1.tgz", + "integrity": "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typescript": { + "version": "5.9.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.2.tgz", + "integrity": "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "license": "MIT" + }, + "node_modules/uuid": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz", + "integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/ws": { + "version": "8.18.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz", + "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==", + "license": "MIT", + "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 + } + } + }, + "node_modules/yallist": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", + "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/yaml": { + "version": "2.8.4", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.4.tgz", + "integrity": "sha512-ml/JPOj9fOQK8RNnWojA67GbZ0ApXAUlN2UQclwv2eVgTgn7O9gg9o7paZWKMp4g0H3nTLtS9LVzhkpOFIKzog==", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, + "node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-to-json-schema": { + "version": "3.24.6", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.24.6.tgz", + "integrity": "sha512-h/z3PKvcTcTetyjl1fkj79MHNEjm+HpD6NXheWjzOekY7kV+lwDYnHw+ivHkijnCSMz1yJaWBD9vu/Fcmk+vEg==", + "license": "ISC", + "peerDependencies": { + "zod": "^3.24.1" + } + } + } +} diff --git a/browser/base/content/assistant/build/package.json b/browser/base/content/assistant/build/package.json new file mode 100644 index 0000000000000..3933a39601dd1 --- /dev/null +++ b/browser/base/content/assistant/build/package.json @@ -0,0 +1,36 @@ +{ + "name": "assistant-bundle", + "private": true, + "type": "module", + "scripts": { + "build": "node esbuild.config.mjs", + "build:embedding-worker": "esbuild src/embedding-worker-entry.ts --bundle --platform=browser --format=iife --target=es2022 --outfile=../embedding-worker.bundle.js", + "sync-embedding-assets": "node scripts/sync-embedding-assets.mjs", + "test:reliability": "tsc -p tests/tsconfig.json && node --test tests/dist/build/tests/**/*.test.js", + "test:voice-guards": "esbuild src/utils/voiceUtteranceGuards.test.ts --bundle --platform=node --packages=external --format=esm --outfile=tests/tmp-voice-utterance-guards.mjs && esbuild src/utils/voiceVadDebounce.test.ts --bundle --platform=node --packages=external --format=esm --outfile=tests/tmp-voice-vad-debounce.mjs && node --test tests/tmp-voice-utterance-guards.mjs tests/tmp-voice-vad-debounce.mjs", + "test:explicit-routes": "esbuild tests/explicitRouteRules.test.ts --bundle --platform=node --format=esm --outfile=tests/tmp-explicit-route.mjs && node --test tests/tmp-explicit-route.mjs", + "test:capabilities-overview": "esbuild tests/capabilitiesOverview.test.ts --bundle --platform=node --format=esm --outfile=tests/tmp-capabilities-overview.mjs && node --test tests/tmp-capabilities-overview.mjs", + "test:assist-usage": "esbuild tests/assistUsageMeta.test.ts --bundle --platform=node --format=esm --outfile=tests/tmp-assist-usage.mjs && node --test tests/tmp-assist-usage.mjs", + "eval:agent-loop": "esbuild tests/agentLoopEval.test.ts --bundle --platform=node --format=esm --outfile=tests/tmp-agent-loop-eval.mjs && node --test tests/tmp-agent-loop-eval.mjs" + }, + "devDependencies": { + "dotenv": "^17.2.1", + "esbuild": "^0.25.9", + "typescript": "^5.5.4" + }, + "dependencies": { + "@aws-crypto/sha256-js": "^5.2.0", + "@aws-sdk/client-s3": "^3.896.0", + "@aws-sdk/credential-provider-cognito-identity": "^3.901.0", + "@aws-sdk/protocol-http": "^3.370.0", + "@aws-sdk/signature-v4": "^3.370.0", + "@huggingface/transformers": "^3.4.0", + "@langchain/core": "^0.3.72", + "@orama/orama": "^3.1.0", + "@supabase/supabase-js": "^2.45.4", + "idb": "^8.0.3", + "minisearch": "^7.2.0", + "railroad-memory": "^0.2.1", + "zod": "^3.25.76" + } +} diff --git a/browser/base/content/assistant/build/scripts/sync-embedding-assets.mjs b/browser/base/content/assistant/build/scripts/sync-embedding-assets.mjs new file mode 100644 index 0000000000000..71bba97c67fff --- /dev/null +++ b/browser/base/content/assistant/build/scripts/sync-embedding-assets.mjs @@ -0,0 +1,71 @@ +/** + * One-shot vendoring: copies ORT WASM (matching @huggingface/transformers) and + * Xenova/all-MiniLM-L6-v2 ONNX artifacts into ../embedding-assets/ for chrome:// packaging. + * Run from repo: cd browser/base/content/assistant/build && node scripts/sync-embedding-assets.mjs + */ +import { createWriteStream, mkdirSync, readFileSync, existsSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { pipeline } from "node:stream/promises"; +import { Readable } from "node:stream"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const ROOT = join(__dirname, "..", "..", "embedding-assets"); +const ORT_DIR = join(ROOT, "ort"); +const MODEL_DIR = join(ROOT, "models", "Xenova", "all-MiniLM-L6-v2"); +const ONNX_DIR = join(MODEL_DIR, "onnx"); + +const pkg = JSON.parse( + readFileSync( + join(__dirname, "..", "node_modules", "@huggingface", "transformers", "package.json"), + "utf8" + ) +); +const TF_VERSION = pkg.version; +const CDN_DIST = `https://cdn.jsdelivr.net/npm/@huggingface/transformers@${TF_VERSION}/dist/`; +const HF = "https://huggingface.co/Xenova/all-MiniLM-L6-v2/resolve/main"; + +const ORT_FILES = [ + "ort-wasm-simd-threaded.jsep.wasm", + "ort-wasm-simd-threaded.jsep.mjs", +]; + +const MODEL_FILES = [ + "config.json", + "tokenizer.json", + "tokenizer_config.json", + "special_tokens_map.json", + "vocab.txt", + { url: `${HF}/onnx/model_quantized.onnx`, dest: join(ONNX_DIR, "model_quantized.onnx") }, +]; + +async function download(url, dest) { + mkdirSync(dirname(dest), { recursive: true }); + const res = await fetch(url); + if (!res.ok) { + throw new Error(`GET ${url} -> ${res.status}`); + } + const body = Readable.fromWeb(res.body); + await pipeline(body, createWriteStream(dest)); + console.log(dest); +} + +async function main() { + mkdirSync(ORT_DIR, { recursive: true }); + for (const f of ORT_FILES) { + await download(CDN_DIST + f, join(ORT_DIR, f)); + } + for (const item of MODEL_FILES) { + if (typeof item === "string") { + await download(`${HF}/${item}`, join(MODEL_DIR, item)); + } else { + await download(item.url, item.dest); + } + } + console.log("Done. Commit embedding-assets/ and update jar.mn if you added files."); +} + +main().catch(e => { + console.error(e); + process.exit(1); +}); diff --git a/browser/base/content/assistant/build/src/assistant.ts b/browser/base/content/assistant/build/src/assistant.ts new file mode 100644 index 0000000000000..ddf58b6f1027f --- /dev/null +++ b/browser/base/content/assistant/build/src/assistant.ts @@ -0,0 +1,176 @@ +/** + * Entry point for the Oasis AI Assistant. + * + * Called by the UI when the user sends a message. Orchestrates: + * 1. Auth & subscription checks + * 2. Command registry creation (all 30+ browser commands) + * 3. Agent stream runner (supervisor / tools / chat via agentLoopDriver) + * 4. Streaming execution back to the UI + * + * Exports `runAssistantStream` and `resetAssistantSession` onto + * the browser's window object for the privileged shim to call. + */ +import { marked } from "../../../../../../toolkit/content/vendor/marked/marked.mjs"; +import DOMPurify from "../../../../../../toolkit/content/vendor/dompurify/dompurify.mjs"; +import { HumanMessage, SystemMessage } from "@langchain/core/messages"; + +import { buildCapabilitiesOverviewMarkdown } from "./assistant/capabilitiesOverview.js"; +import { createAssistantCommandsRegistry } from "./assistant/commandsRegistry.js"; +import { ASSISTANT_RECURSION_LIMIT } from "./assistant/constants.js"; +import { buildAssistantGraph } from "./assistant/graph.js"; +import { + getRailroadMemoryPromptBlock, + invalidateRailroadSessionCache, + maybeRunRailroadStructuredExtraction, + recordRailroadTurn, +} from "./services/railroadMemory.js"; +import { + createAssistantSessionController, + type PlainSessionTurn, +} from "./assistant/session.js"; +import { consumeAssistantGraphStream } from "./assistant/stream.js"; +import { + VOICE_CHAT_TEXT_REPLY_ADDENDUM, + VOICE_REPLY_ADDENDUM, +} from "./prompts/voicePrompt.js"; +import SupabaseAuth from "./services/supabase"; +import { subscriptionService } from "./services/subscription"; +import voiceInputService from "./services/voiceInput"; +import voiceAgent from "./services/voiceAgent"; +import { textToSpeech } from "./proxyClient.js"; +import type { AssistantWindowLike } from "./types/runtime"; +import { + OASIS_EVENT_HISTORY_UPDATE, + type VoiceUiDelivery, +} from "../../shared/contracts.js"; + +const supabaseAuth = SupabaseAuth.getInstance(); +const assistantWindow = window as AssistantWindowLike; +assistantWindow.supabaseAuth = supabaseAuth; +assistantWindow.subscriptionService = subscriptionService; +assistantWindow.voiceInputService = voiceInputService; +assistantWindow.textToSpeech = textToSpeech; +assistantWindow.marked = marked; +assistantWindow.DOMPurify = DOMPurify; +const aw = assistantWindow as AssistantWindowLike & { + oasisSetOAuthCallbackBaseUrl?: (url: string) => string; + oasisGetOAuthCallbackBaseUrl?: () => string; +}; +aw.oasisSetOAuthCallbackBaseUrl = (url: string) => + supabaseAuth.setOAuthCallbackBaseUrl(url); +aw.oasisGetOAuthCallbackBaseUrl = () => supabaseAuth.getOAuthCallbackBaseUrl(); + +const sessionController = createAssistantSessionController(assistantWindow); + +let oasisCapabilitiesMarkdownCache: string | null = null; +function getOasisCapabilitiesMarkdown(): string { + if (oasisCapabilitiesMarkdownCache == null) { + const { assistTools } = createAssistantCommandsRegistry(); + oasisCapabilitiesMarkdownCache = + buildCapabilitiesOverviewMarkdown(assistTools); + } + return oasisCapabilitiesMarkdownCache; +} +assistantWindow.getOasisCapabilitiesMarkdown = getOasisCapabilitiesMarkdown; + +function oasisPushLocalChatTurn( + userText: string, + assistantMarkdown: string +): void { + sessionController.pushCurrentTurn(userText, assistantMarkdown); + try { + assistantWindow.dispatchEvent(new CustomEvent(OASIS_EVENT_HISTORY_UPDATE)); + } catch { + void 0; + } +} +assistantWindow.oasisPushLocalChatTurn = oasisPushLocalChatTurn; + +export function resetAssistantSession() { + sessionController.resetAssistantSession(); +} +assistantWindow.resetAssistantSession = resetAssistantSession; + +export function getAssistantHistory() { + return sessionController.getAssistantHistory(); +} +assistantWindow.getAssistantHistory = getAssistantHistory; + +function oasisSyncSessionFromPlainTurns(turns: PlainSessionTurn[]): void { + sessionController.syncSessionFromPlainTurns(turns); +} +assistantWindow.oasisSyncSessionFromPlainTurns = oasisSyncSessionFromPlainTurns; + +function oasisSetRailroadSessionKey(key: string | null) { + if (key == null || key === "") { + assistantWindow.oasisRailroadSessionKey = undefined; + } else { + assistantWindow.oasisRailroadSessionKey = key; + } + invalidateRailroadSessionCache(); +} +assistantWindow.oasisSetRailroadSessionKey = oasisSetRailroadSessionKey; + +export async function runAssistantStream( + prompt: string, + onChunk: (text: string) => void, + inputType: "text" | "voice" = "text", + messageId?: string, + voiceDelivery: VoiceUiDelivery = "spoken" +): Promise { + const isAuthenticated = await supabaseAuth.isAuthenticated(); + + const { commands, toolCommandNames, assistTools } = + createAssistantCommandsRegistry(); + const railroadMemoryBlock = + await getRailroadMemoryPromptBlock(assistantWindow); + const graph = buildAssistantGraph( + commands, + assistantWindow, + messageId, + assistTools, + { railroadMemoryBlock } + ); + const sessionHistory = sessionController.getCurrentSessionMessages(); + + const voiceSystemAddendum = + inputType === "voice" + ? voiceDelivery === "text_chat" + ? VOICE_CHAT_TEXT_REPLY_ADDENDUM + : VOICE_REPLY_ADDENDUM + : null; + + const stream = await graph.stream( + { + messages: [ + ...sessionHistory, + ...(voiceSystemAddendum + ? [new SystemMessage(voiceSystemAddendum)] + : []), + new HumanMessage({ content: prompt }), + ], + }, + { recursionLimit: ASSISTANT_RECURSION_LIMIT } + ); + + const combined = await consumeAssistantGraphStream({ + stream, + prompt, + onChunk, + inputType, + toolCommandNames, + pushCurrentTurn: sessionController.pushCurrentTurn, + trackUsage: (nextInputType, meta) => { + if (isAuthenticated) { + subscriptionService.trackUsage(nextInputType, undefined, meta); + } + }, + }); + void recordRailroadTurn(assistantWindow, prompt, combined); + maybeRunRailroadStructuredExtraction(assistantWindow, prompt, combined); + return combined; +} +assistantWindow.runAssistantStream = runAssistantStream; + +voiceAgent.setRunAssistant(runAssistantStream); +assistantWindow.voiceAgent = voiceAgent; diff --git a/browser/base/content/assistant/build/src/assistant/agentGraphSupport.ts b/browser/base/content/assistant/build/src/assistant/agentGraphSupport.ts new file mode 100644 index 0000000000000..d9e13e9198446 --- /dev/null +++ b/browser/base/content/assistant/build/src/assistant/agentGraphSupport.ts @@ -0,0 +1,62 @@ +/** + * Shared graph helpers (supervisor / tool arg shaping, ambiguity wiring). + * Keeps graph.ts slimmer; see agentSteps.ts for per-command tool nodes. + */ +import type { PendingAmbiguityPayload } from "../../../shared/contracts.js"; +import type { PendingAmbiguityPayload as RouterPendingAmbiguityPayload } from "../utils/routerTypes.js"; +import { setPendingAmbiguity } from "../services/interactionState.js"; +import { assistantLogger } from "../utils/assistantLogger.js"; +import type { GraphArgs } from "./messageUtils.js"; +import { INTERNAL_CHAIN_NOTICE_ARG } from "./constants.js"; + +export function splitInternalArgs(args: GraphArgs): { + commandArgs: GraphArgs; + chainNotice: string | null; +} { + const commandArgs: GraphArgs = {}; + let chainNotice: string | null = null; + + for (const [key, value] of Object.entries(args || {})) { + if (key === INTERNAL_CHAIN_NOTICE_ARG && typeof value === "string") { + chainNotice = value.trim() || null; + continue; + } + if (key.startsWith("__oasis")) { + continue; + } + commandArgs[key] = value; + } + + return { commandArgs, chainNotice }; +} + +export function toAmbiguityPayload( + routePending: RouterPendingAmbiguityPayload +): PendingAmbiguityPayload { + return { + kind: routePending.kind || "container_target", + name: routePending.name, + query: routePending.query, + all: routePending.all, + choices: routePending.choices, + tabIndex: routePending.tabIndex, + verb: routePending.verb, + originalText: routePending.originalText, + description: + routePending.kind === "close_delete_target" + ? `Ambiguous close/delete target for "${routePending.name}"` + : `Ambiguous container target for "${routePending.name}"`, + }; +} + +export function setRoutePendingAmbiguity( + routePending: RouterPendingAmbiguityPayload +): void { + setPendingAmbiguity(toAmbiguityPayload(routePending)); + assistantLogger.debug("router", "Ambiguity detected", { + name: routePending.name, + query: routePending.query || "", + all: !!routePending.all, + kind: routePending.kind || "container_target", + }); +} diff --git a/browser/base/content/assistant/build/src/assistant/agentLoopDriver.ts b/browser/base/content/assistant/build/src/assistant/agentLoopDriver.ts new file mode 100644 index 0000000000000..d6c3d81f80daa --- /dev/null +++ b/browser/base/content/assistant/build/src/assistant/agentLoopDriver.ts @@ -0,0 +1,127 @@ +/** + * Explicit agent loop driver — replaces LangGraph stream for the assistant. + * + * Mirrors START → supervisor → (tool | chat)* → END with the same merge + * semantics as the former Annotation reducers (messages concat, next/args replace). + */ +import type { BaseMessage } from "@langchain/core/messages"; + +import { assistantLogger } from "../utils/assistantLogger.js"; +import type { GraphArgs } from "./messageUtils.js"; + +/** LangGraph END sentinel — same string as @langchain/langgraph END. */ +export const AGENT_END = "__end__"; + +export type AgentState = { + messages: BaseMessage[]; + lastWorker: string; + next: string; + args: GraphArgs; + commandQueue: string[]; +}; + +export type AgentNodePatch = Partial; + +export function mergeAgentState(prev: AgentState, patch: AgentNodePatch): AgentState { + return { + messages: + patch.messages && patch.messages.length > 0 + ? [...prev.messages, ...patch.messages] + : prev.messages, + lastWorker: patch.lastWorker ?? prev.lastWorker, + next: + patch.next !== undefined && patch.next !== "" + ? String(patch.next) + : prev.next, + args: patch.args !== undefined ? patch.args : prev.args, + commandQueue: + patch.commandQueue !== undefined ? patch.commandQueue : prev.commandQueue, + }; +} + +export type AgentNode = (state: AgentState) => Promise; + +export type AgentStreamRunnerParams = { + initialMessages: BaseMessage[]; + maxSteps: number; + supervisorNode: AgentNode; + chatNode: AgentNode; + toolAgents: Record; + memberNames: readonly string[]; +}; + +/** + * AsyncIterable compatible with consumeAssistantGraphStream: each step is + * `{ [nodeName]: { messages?: ... } }`; final `{ __end__: true }`. + */ +export async function* streamAgentLoop( + params: AgentStreamRunnerParams +): AsyncGenerator> { + const { + initialMessages, + maxSteps, + supervisorNode, + chatNode, + toolAgents, + memberNames, + } = params; + + const memberSet = new Set(memberNames); + + let state: AgentState = { + messages: [...initialMessages], + lastWorker: "", + next: "", + args: {}, + commandQueue: [], + }; + + let cursor = "supervisor"; + + for (let i = 0; i < maxSteps; i++) { + if (cursor === AGENT_END) { + yield { __end__: true }; + return; + } + + if (cursor === "supervisor") { + const patch = await supervisorNode(state); + state = mergeAgentState(state, patch); + cursor = state.next && state.next !== "" ? state.next : AGENT_END; + continue; + } + + if (cursor === "chat") { + const patch = await chatNode(state); + state = mergeAgentState(state, patch); + yield { chat: patch }; + yield { __end__: true }; + return; + } + + const toolFn = toolAgents[cursor]; + if (toolFn && memberSet.has(cursor)) { + const patch = await toolFn(state); + state = mergeAgentState(state, patch); + yield { [cursor]: patch }; + const nextCursor = String(patch.next ?? "supervisor"); + if (nextCursor === AGENT_END) { + yield { __end__: true }; + return; + } + cursor = nextCursor; + continue; + } + + assistantLogger.warn("agentLoop", "Unknown graph node; stopping.", { + cursor, + }); + yield { __end__: true }; + return; + } + + assistantLogger.warn("agentLoop", "Recursion limit reached; stopping.", { + maxSteps, + }); + yield { __end__: true }; +} diff --git a/browser/base/content/assistant/build/src/assistant/agentSteps.ts b/browser/base/content/assistant/build/src/assistant/agentSteps.ts new file mode 100644 index 0000000000000..52f9f28b8a5fd --- /dev/null +++ b/browser/base/content/assistant/build/src/assistant/agentSteps.ts @@ -0,0 +1,119 @@ +/** + * Per-command agent step implementations (tool nodes for agentLoopDriver). + */ +import { AIMessage } from "@langchain/core/messages"; + +import type { Command, CmdResult } from "../commands.js"; +import { AGENT_END, type AgentState } from "./agentLoopDriver.js"; +import { + clearContinuationQueue, + setContinuationQueue, +} from "../services/interactionState.js"; +import type { + AssistantWindowLike, + OasisRecordToolActionStart, + OasisRecordToolActionUpdate, +} from "../types/runtime.js"; +import { assistantLogger } from "../utils/assistantLogger.js"; +import type { ToolResultPayload } from "./messageUtils.js"; +import { splitInternalArgs } from "./agentGraphSupport.js"; + +export type CommandToolAgentDeps = { + assistantWindow: AssistantWindowLike; + messageId?: string; +}; + +export function createCommandToolAgent( + command: Command, + deps: CommandToolAgentDeps +): (state: AgentState) => Promise> { + const { assistantWindow, messageId } = deps; + return async (state: AgentState) => { + const recordStart = assistantWindow.oasisRecordToolActionStart as + | OasisRecordToolActionStart + | undefined; + const recordUpdate = assistantWindow.oasisRecordToolActionUpdate as + | OasisRecordToolActionUpdate + | undefined; + let actionId: string | undefined; + + if (typeof recordStart === "function") { + actionId = recordStart(command.commandName, messageId); + } + + const { commandArgs, chainNotice } = splitInternalArgs(state.args); + let result: CmdResult; + try { + result = await command.execute(commandArgs); + if (typeof recordUpdate === "function" && actionId) { + recordUpdate(actionId, "done"); + } + } catch (error) { + if (typeof recordUpdate === "function" && actionId) { + recordUpdate(actionId, "error"); + } + assistantLogger.error( + "graph", + `Command execution failed: ${command.commandName}`, + error + ); + result = { message: String(error) }; + } + + if (result.requiresConfirmation) { + const remainingQueue = + state.commandQueue.length > 1 ? state.commandQueue.slice(1) : []; + if (remainingQueue.length > 0) { + setContinuationQueue(remainingQueue); + } else { + clearContinuationQueue(); + } + assistantLogger.debug( + "graph", + `Command requires confirmation: ${command.commandName}` + ); + const confirmationMessage = String(result.message || "").trim(); + const toolResultPayload: ToolResultPayload = { + kind: "tool_result", + commandName: command.commandName, + message: confirmationMessage, + }; + return { + messages: [ + new AIMessage({ + content: confirmationMessage, + name: command.commandName, + additional_kwargs: { oasisToolResult: toolResultPayload }, + }), + ], + lastWorker: command.commandName, + next: AGENT_END, + args: {}, + commandQueue: state.commandQueue, + }; + } + + const resultMessage = chainNotice + ? `${chainNotice}\n${result.message}` + : result.message; + const toolResultPayload: ToolResultPayload = { + kind: "tool_result", + commandName: command.commandName, + message: resultMessage, + }; + + return { + messages: [ + new AIMessage({ + content: resultMessage, + name: command.commandName, + additional_kwargs: { oasisToolResult: toolResultPayload }, + }), + ], + lastWorker: command.commandName, + next: "supervisor", + args: {}, + commandQueue: state.commandQueue, + }; + }; +} diff --git a/browser/base/content/assistant/build/src/assistant/capabilitiesOverview.ts b/browser/base/content/assistant/build/src/assistant/capabilitiesOverview.ts new file mode 100644 index 0000000000000..537dd59b260cf --- /dev/null +++ b/browser/base/content/assistant/build/src/assistant/capabilitiesOverview.ts @@ -0,0 +1,171 @@ +import { + CAPABILITIES_BLOCK_DELIMITER, + CAPABILITIES_OVERVIEW_FIRST_LINE, + OASIS_CAPABILITIES_FEATURES_URL, + OASIS_CAPABILITIES_LINK_LABEL, + OASIS_CAPABILITIES_FEEDBACK_URL, + OASIS_CAPABILITIES_FEEDBACK_LINK_LABEL, +} from "../../../shared/capabilitiesOverviewConstants.js"; + +export type AssistToolForOverview = { + name: string; + description: string; +}; + +export { + CAPABILITIES_BLOCK_DELIMITER, + CAPABILITIES_OVERVIEW_FIRST_LINE, + OASIS_CAPABILITIES_FEATURES_URL, + OASIS_CAPABILITIES_FEEDBACK_URL, +}; + +const MAX_SUMMARY_CHARS = 180; + +function stripLlmArgumentClauses(text: string): string { + let s = text; + const patterns = [ + /\s*\.?\s*accepts optional arguments:.*$/is, + /\s*\.?\s*accepts arguments:.*$/is, + /\s*\.?\s*accepts arguments\s.*$/is, + /\s*\.?\s*accepts no arguments\.?\s*$/is, + /\s*\.?\s*arguments:.*$/is, + /\s*\.?\s*args:.*$/is, + ]; + for (const re of patterns) { + s = s.replace(re, ""); + } + return s.replace(/\s+/g, " ").replace(/\s+\./g, ".").trim(); +} + +function firstSentenceOrCap(text: string): string { + const t = text.trim(); + if (t.length <= MAX_SUMMARY_CHARS) { + return t; + } + const dot = t.indexOf(". "); + if (dot > 0 && dot <= MAX_SUMMARY_CHARS) { + return t.slice(0, dot + 1).trim(); + } + return `${t.slice(0, MAX_SUMMARY_CHARS - 1).trim()}…`; +} + +export function summarizeForUser(description: string): string { + const beforeArgs = description.split(" Args JSON:")[0]?.trim() || description.trim(); + let s = stripLlmArgumentClauses(beforeArgs); + s = s.replace(/\.\s*$/, "").trim(); + if (!s) { + return "Browser action you can ask for in plain English."; + } + if (!s.endsWith(".")) { + s = `${s}.`; + } + s = firstSentenceOrCap(s); + return s; +} + +const kahanaMd = `[${OASIS_CAPABILITIES_LINK_LABEL}](${OASIS_CAPABILITIES_FEATURES_URL})`; +const feedbackMd = `[${OASIS_CAPABILITIES_FEEDBACK_LINK_LABEL}](${OASIS_CAPABILITIES_FEEDBACK_URL})`; + +const SUPPORT_AND_FEEDBACK_HEADING = "### Support and feedback"; + +export function buildCapabilitiesOverviewMarkdown( + assistTools: AssistToolForOverview[] +): string { + if (!assistTools.length) { + return [ + `${CAPABILITIES_OVERVIEW_FIRST_LINE}`, + "", + "Oasis capabilities are not available in this build.", + "", + "You can still describe what you wanted in plain English. When something is wrong or missing, use the feedback link below or the thumbs up and thumbs down on assistant replies (training) so we can widen what Oasis supports.", + "", + SUPPORT_AND_FEEDBACK_HEADING, + "", + "Kahana lists commands in depth; the feedback form captures suggestions. Thumbs on each reply add training signal so we can expand supported behavior quickly.", + "", + `- ${kahanaMd}`, + `- ${feedbackMd}`, + ].join("\n"); + } + + const intro = [ + `${CAPABILITIES_OVERVIEW_FIRST_LINE}`, + "", + "Ask in plain English; Oasis picks the right browser action. Destructive steps may ask you to confirm first.", + "", + "Use your imagination: rephrase, combine ideas, and try requests that are not spelled out here. If something fails or is missing, use the feedback link in Support and feedback below or the thumbs up and thumbs down on that assistant reply (training). You help expand what Oasis supports, and we use that signal to improve quickly.", + ].join("\n"); + + const webSearch = [ + "### Web and search", + "", + "Open a site in a new tab or run a web search when you want something beyond the page you are on.", + "", + "- Open a link, e.g. `Open example.com in a new tab`", + "- Search the web, e.g. `Search the web for cheap flights to Lisbon`", + ].join("\n"); + + const generalQuestions = [ + "### General questions", + "", + "Ask quick factual or how-to questions that are not about the browser; Oasis answers in chat and may use the web when that helps.", + "", + "- Example: `Who is the president of Djibouti?`", + "- Example: `What is the square root of 256?`", + ].join("\n"); + + const summarize = [ + "### Summarization", + "", + "Ask for a concise readout of the page you are on (or a tab you point at).", + "", + "- Example: `Summarize this page`", + ].join("\n"); + + const navigation = [ + "### Navigation", + "", + "Work with tabs and windows: list what is open, open new windows, move or reload tabs, pin, mute, and similar moves without digging through menus.", + "", + "- List or switch tabs, e.g. `What tabs do I have open?`", + "- New windows, e.g. `Open a new window`", + ].join("\n"); + + const organization = [ + "### Organization", + "", + "Group tabs, split the view, and arrange how you work across tabs and panes.", + "", + "- Tab groups, e.g. `Create a tab group called Research`", + "- Split view shows two tabs side by side; you can choose which tabs. Try: `split view`", + ].join("\n"); + + const memory = [ + "### Memory and history", + "", + "Search across open tabs, tab groups, browsing history, and saved memory. For cross-source recall, ask in your own words. For history only, start your request with `search history` (plain find is not wired to history yet).", + "", + "- Cross-source recall, e.g. `Find anything about budgets across my tabs and history`", + "- History-only search, e.g. `search history for pages I read about taxes last month`", + ].join("\n"); + + const supportAndFeedback = [ + SUPPORT_AND_FEEDBACK_HEADING, + "", + "The first link opens Kahana for the full command list and roadmap. The second is the feedback form for broad suggestions. Thumbs on assistant replies feed training so we can grow what Oasis handles in step with real use.", + "", + `- ${kahanaMd}`, + `- ${feedbackMd}`, + ].join("\n"); + + return [ + intro, + webSearch, + generalQuestions, + summarize, + navigation, + organization, + memory, + supportAndFeedback, + ].join("\n\n"); +} diff --git a/browser/base/content/assistant/build/src/assistant/commandChain.ts b/browser/base/content/assistant/build/src/assistant/commandChain.ts new file mode 100644 index 0000000000000..515a64c8180b3 --- /dev/null +++ b/browser/base/content/assistant/build/src/assistant/commandChain.ts @@ -0,0 +1,75 @@ +/** + * Command chain parser — splits multi-command inputs. + * + * Detects and splits chained user inputs like "do X; then Y" or + * "open tabs and then list bookmarks" into separate command strings. + * Uses connector patterns: ";", "and then", "then", "and ". + * Max 3 commands per chain. + * + * Called by supervisorQueue.ts to populate the command queue. + */ +const CHAIN_VERBS = [ + "open", + "close", + "delete", + "remove", + "create", + "make", + "new", + "add", + "save", + "move", + "put", + "rename", + "list", + "show", + "search", + "find", + "summarize", + "split", + "organize", + "copy", +] as const; + +const CHAIN_VERB_PATTERN = CHAIN_VERBS.join("|"); +const CHAIN_CONNECTOR_RE = new RegExp( + `(?:\\s*;\\s*|\\s+(?:and\\s+then|then)\\s+(?=(?:please\\s+)?(?:${CHAIN_VERB_PATTERN})\\b)|\\s+and\\s+(?=(?:please\\s+)?(?:${CHAIN_VERB_PATTERN})\\b))`, + "i" +); +const CHAIN_SPLIT_RE = new RegExp( + `\\s*;\\s*|\\s+(?:and\\s+then|then)\\s+(?=(?:please\\s+)?(?:${CHAIN_VERB_PATTERN})\\b)|\\s+and\\s+(?=(?:please\\s+)?(?:${CHAIN_VERB_PATTERN})\\b)`, + "gi" +); + +export type CommandChainResult = { + commands: string[]; + truncated: boolean; +}; + +export function looksLikeCommandChain(input: string): boolean { + return CHAIN_CONNECTOR_RE.test(String(input || "").trim()); +} + +export function splitCommandChain( + input: string, + maxCommands = 3 +): CommandChainResult { + const text = String(input || "").trim(); + if (!text || maxCommands < 1) { + return { commands: [], truncated: false }; + } + + const parts = text + .split(CHAIN_SPLIT_RE) + .map(part => part.trim()) + .filter(Boolean); + + if (parts.length <= maxCommands) { + return { commands: parts, truncated: false }; + } + + return { + commands: parts.slice(0, maxCommands), + truncated: true, + }; +} diff --git a/browser/base/content/assistant/build/src/assistant/commandsRegistry.ts b/browser/base/content/assistant/build/src/assistant/commandsRegistry.ts new file mode 100644 index 0000000000000..f56283c2ec7e3 --- /dev/null +++ b/browser/base/content/assistant/build/src/assistant/commandsRegistry.ts @@ -0,0 +1,187 @@ +/** + * Command registry — instantiates all commands and builds tool definitions. + * + * Creates instances of all 30+ Command classes and generates the + * tool definitions (name + description + JSON arg schema) that are + * sent to the remote LLM for routing decisions. + * + * COMMAND_ARG_SCHEMA defines the argument shape for each command. + * These schemas are appended to each tool's description so the LLM + * knows what arguments to extract from the user's message. + */ +import { + AddSplitViewCommand, + AddTabToBookmarkFolderCommand, + AddTabToGroupCommand, + BookmarkTabCommand, + CloseDuplicateTabsCommand, + CloseOtherTabsCommand, + CloseTabCommand, + CloseTabsToLeftCommand, + CloseTabsToRightCommand, + Command, + ConfirmActionCommand, + CopyTabUrlsCommand, + CreateBookmarkFolderCommand, + CreateTabGroupCommand, + DeleteBookmarkFolderCommand, + DeleteTabGroupCommand, + DuplicateTabCommand, + ListBookmarkFoldersCommand, + ListTabGroupsCommand, + ListTabsCommand, + MoveTabToEndCommand, + MoveTabToNewWindowCommand, + MoveTabToStartCommand, + NewTabToRightCommand, + NewWindowCommand, + OpenBookmarkFolderCommand, + GetRecentSearchResultsCommand, + OpenSearchResultCommand, + OpenSendTabToDeviceCommand, + OpenUrlCommand, + OpenTabCommand, + OpenTabNoteCommand, + OrganizeWindowsCommand, + PinTabCommand, + ReloadTabCommand, + RemoveSplitViewCommand, + RemoveTabFromBookmarkFolderCommand, + RemoveTabFromGroupCommand, + RenameBookmarkFolderCommand, + RenameTabGroupCommand, + ReopenClosedTabCommand, + ResolveAmbiguityCommand, + SearchMemoryCommand, + SearchHistorySemanticCommand, + SelectAllTabsCommand, + ShowSubscriptionCommand, + ShowURLCommand, + SplitTabsCommand, + SummarizePageCommand, + ToggleMuteTabCommand, + UnloadTabCommand, + UnpinTabCommand, + WebSearchCommand, +} from "../commands.js"; +import { registerCommandExecutors } from "../services/commandExecutionRegistry.js"; + +export type AssistantCommandsRegistry = { + commands: Command[]; + toolCommandNames: Set; + assistTools: Array<{ name: string; description: string }>; +}; + +const COMMAND_ARG_SCHEMA: Readonly> = { + list_tabs: `{"scope?":"window|tab-group|bookmark-folder","name?":"string"}`, + open_url: `{"url":"string"}`, + web_search: `{"query":"string"}`, + open_tab: `{"url":"string"} (legacy alias; prefer open_url/web_search)`, + close_tab: `{"index?":"number","confirmed?":"boolean"}`, + move_tab_to_new_window: `{"index?":"number"}`, + copy_tab_urls: `{}`, + split_tabs: `{"indices":"number[]"}`, + add_split_view: `{"indices?":"number[]","withIndex?":"number","withQuery?":"string"}`, + remove_split_view: `{}`, + create_bookmark_folder: `{"name":"string","include?":"none|current|all"}`, + delete_bookmark_folder: `{"name":"string","confirmed?":"boolean"}`, + list_bookmark_folders: `{}`, + rename_bookmark_folder: `{"from":"string","to":"string"}`, + add_tab_to_bookmark_folder: `{"name":"string","query?":"string","all?":"boolean"}`, + remove_tab_from_bookmark_folder: `{"name":"string","query?":"string","all?":"boolean"}`, + open_bookmark_folder: `{"name":"string","where?":"tabgroup|window"}`, + list_tab_groups: `{}`, + create_tab_group: `{"name":"string","indices?":"number[]","openUrl?":"string","confirmed?":"boolean"}`, + delete_tab_group: `{"name":"string","confirmed?":"boolean"}`, + add_tab_to_group: `{"name":"string","query?":"string","all?":"boolean","confirmed?":"boolean"}`, + remove_tab_from_group: `{"index?":"number"}`, + rename_tab_group: `{"from":"string","to":"string"}`, + resolve_ambiguity: `{"target?":"bookmark-folder|tab-group|tab|cancel"}`, + confirm_action: `{"confirmed":"boolean"}`, + new_window: `{}`, + new_tab_to_right: `{"index?":"number"}`, + organize_windows: `{}`, + show_url: `{"url":"string"}`, + search_memory: `{"query":"string","folder?":"string","source?":"bookmark-folder"}`, + get_recent_search_results: `{"limit?":"number"}`, + open_search_result: `{"url?":"string","index?":"number","type?":"tab","bookmarkGuid?":"string"}`, + summarize_page: `{"index?":"number","query?":"string"}`, + show_subscription: `{}`, + search_history: `{"query":"string (optional; omit or \"\" for recent visits)"}`, +}; + +function toAssistToolDescription(command: Command): string { + const schema = COMMAND_ARG_SCHEMA[command.commandName]; + if (!schema) { + return command.description; + } + return `${command.description} Args JSON: ${schema}`; +} + +export function createAssistantCommandsRegistry(): AssistantCommandsRegistry { + const commands: Command[] = [ + new ListTabsCommand(), + new OpenUrlCommand(), + new WebSearchCommand(), + new OpenTabCommand(), + new CloseTabCommand(), + new ReloadTabCommand(), + new ToggleMuteTabCommand(), + new PinTabCommand(), + new UnpinTabCommand(), + new UnloadTabCommand(), + new NewTabToRightCommand(), + new DuplicateTabCommand(), + new BookmarkTabCommand(), + new MoveTabToStartCommand(), + new MoveTabToEndCommand(), + new SelectAllTabsCommand(), + new CloseDuplicateTabsCommand(), + new CloseTabsToRightCommand(), + new CloseTabsToLeftCommand(), + new CloseOtherTabsCommand(), + new ReopenClosedTabCommand(), + new OpenSendTabToDeviceCommand(), + new OpenTabNoteCommand(), + new MoveTabToNewWindowCommand(), + new CopyTabUrlsCommand(), + new SplitTabsCommand(), + new AddSplitViewCommand(), + new RemoveSplitViewCommand(), + new CreateBookmarkFolderCommand(), + new DeleteBookmarkFolderCommand(), + new ListBookmarkFoldersCommand(), + new RenameBookmarkFolderCommand(), + new AddTabToBookmarkFolderCommand(), + new RemoveTabFromBookmarkFolderCommand(), + new OpenBookmarkFolderCommand(), + new ListTabGroupsCommand(), + new CreateTabGroupCommand(), + new DeleteTabGroupCommand(), + new AddTabToGroupCommand(), + new RemoveTabFromGroupCommand(), + new RenameTabGroupCommand(), + new ResolveAmbiguityCommand(), + new ConfirmActionCommand(), + new NewWindowCommand(), + new OrganizeWindowsCommand(), + new ShowURLCommand(), + new SearchMemoryCommand(), + new GetRecentSearchResultsCommand(), + new OpenSearchResultCommand(), + new SummarizePageCommand(), + new ShowSubscriptionCommand(), + // Semantic history search (local embeddings + vector DB) + new SearchHistorySemanticCommand(), + ]; + registerCommandExecutors(commands); + + return { + commands, + toolCommandNames: new Set(commands.map(command => command.commandName)), + assistTools: commands.map(command => ({ + name: command.commandName, + description: toAssistToolDescription(command), + })), + }; +} diff --git a/browser/base/content/assistant/build/src/assistant/constants.ts b/browser/base/content/assistant/build/src/assistant/constants.ts new file mode 100644 index 0000000000000..ff78ecde2a260 --- /dev/null +++ b/browser/base/content/assistant/build/src/assistant/constants.ts @@ -0,0 +1,8 @@ +/** Graph execution limits. Used by graph.ts and supervisorQueue.ts. */ +export const ASSISTANT_RECURSION_LIMIT = 24; +export const MAX_NESTED_COMMANDS = 3; + +/** Internal arg key for chained-command truncation notice (supervisor → tool). */ +export const INTERNAL_CHAIN_NOTICE_ARG = "__oasisChainNotice"; +export const STREAM_GUARD_MESSAGE = + "I stopped this request to avoid a routing loop. Please rephrase and try again."; diff --git a/browser/base/content/assistant/build/src/assistant/extractLatestActionableText.ts b/browser/base/content/assistant/build/src/assistant/extractLatestActionableText.ts new file mode 100644 index 0000000000000..37ec5c9458cbe --- /dev/null +++ b/browser/base/content/assistant/build/src/assistant/extractLatestActionableText.ts @@ -0,0 +1,47 @@ +/** + * Extracts the latest user message from the conversation history + * and identifies the most actionable line (one containing both + * a verb like "open"/"close" and an object like "tab"/"folder"). + * Used by the supervisor node to get the text for routing. + */ +import type { BaseMessage } from "@langchain/core/messages"; + +import { msgText } from "./messageUtils.js"; + +export type LatestActionableText = { + latestTextRaw: string; + lines: string[]; + commandLine: string; + commandText: string; + confirmationText: string; +}; + +const ACTIONABLE_ENTITY_PATTERN = + /(tab\s*group|group|tabs?|bookmark|folder|window|search|memory)/i; +const ACTIONABLE_VERB_PATTERN = + /(delete|remove|create|make|new|add|save|move|put|list|open|close|rename|show|split|find|summarize)/i; + +export function extractLatestActionableText( + messages: BaseMessage[] +): LatestActionableText { + const latestUserMsg = [...messages].reverse().find(m => m._getType() === "human"); + const latestTextRaw = msgText(latestUserMsg) || ""; + const lines = latestTextRaw + .split(/\r?\n/) + .map(line => line.trim()) + .filter(Boolean); + const commandLine = + lines.find( + line => + ACTIONABLE_ENTITY_PATTERN.test(line) && + ACTIONABLE_VERB_PATTERN.test(line) + ) || latestTextRaw; + + return { + latestTextRaw, + lines, + commandLine, + commandText: commandLine.toLowerCase(), + confirmationText: (lines[lines.length - 1] || latestTextRaw).trim(), + }; +} diff --git a/browser/base/content/assistant/build/src/assistant/graph.ts b/browser/base/content/assistant/build/src/assistant/graph.ts new file mode 100644 index 0000000000000..e82f0af16056b --- /dev/null +++ b/browser/base/content/assistant/build/src/assistant/graph.ts @@ -0,0 +1,535 @@ +/** + * Assistant agent graph — supervisor, per-command tool nodes, and chat. + * + * Execution uses {@link streamAgentLoop} (explicit driver) instead of LangGraph. + * Flow: supervisor → tool or chat → supervisor → … → END + * Recursion limit: 24 steps. Max 3 chained commands per request. + * + * Called from assistant.ts via `buildAssistantGraph()`. + */ +import { AIMessage, BaseMessage, HumanMessage } from "@langchain/core/messages"; + +import { AGENT_END, streamAgentLoop, type AgentState } from "./agentLoopDriver.js"; + +import type { Command } from "../commands.js"; +import { assistRemote, type AssistTool } from "../proxyClient.js"; +import { + clearContinuationQueue, + clearPendingAmbiguity, + getContinuationQueue, + getPendingAmbiguity, + getPendingConfirmation, + takeContinuationQueue, +} from "../services/interactionState.js"; +import type { AssistantWindowLike } from "../types/runtime.js"; +import { routeDeterministically } from "../utils/deterministicRouter.js"; +import { assistantLogger } from "../utils/assistantLogger.js"; +import { looksLikeNewActionCommand } from "../utils/routingUtils.js"; +import { getAssistantApiBase, QuotaExceededError } from "../awsSignedFetch.js"; +import { CHAT_SYSTEM_PROMPT } from "../prompts/chatPrompt.js"; +import { subscriptionService } from "../services/subscription.js"; +import { buildHiddenInstruction } from "../prompts/hiddenInstructions.js"; +import { buildAssistRouterPrompt } from "../prompts/routerPrompt.js"; +import { + ASSISTANT_RECURSION_LIMIT, + INTERNAL_CHAIN_NOTICE_ARG, + MAX_NESTED_COMMANDS, +} from "./constants.js"; +import { setRoutePendingAmbiguity } from "./agentGraphSupport.js"; +import { createCommandToolAgent } from "./agentSteps.js"; +import { formatQuotaExceededMessage } from "../utils/quotaUserMessage.js"; +import { getOasisCapabilitiesReply } from "../utils/oasisCapabilitiesFaq.js"; + +const CHAT_GENERATION_CONFIG = { + responseMimeType: "application/json", + responseJsonSchema: { + type: "object", + properties: { + response: { + type: "string", + description: + "The assistant's complete reply to the user. Use Markdown formatting: **bold**, bullet lists, `code blocks`, headings. Do NOT include raw JSON or internal data dumps.", + }, + command_type: { + type: "string", + enum: [ + "info_retrieval", + "navigation", + "organization", + "content_transform", + "content_create", + "search", + "automation", + "system", + "help", + "other", + ], + description: + "The action category: info_retrieval=answer a factual question, navigation=open/visit a URL or site, organization=manage tabs/bookmarks/groups, content_transform=summarize/translate/rewrite, content_create=write/generate new content, search=find in history/memory/web, automation=multi-step browser task, system=browser settings or preferences, help=how-to question about the assistant, other=none of the above.", + }, + user_intent: { + type: "string", + enum: [ + "learning", + "research", + "work", + "dev", + "marketing", + "shopping", + "personal", + "entertainment", + "meta", + "other", + ], + description: + "The user's underlying goal: learning=understand a topic, research=gather info for a decision, work=professional/business task, dev=coding or technical task, marketing=content or growth, shopping=buy or find products, personal=personal life task, entertainment=leisure/media/fun, meta=asking about the AI itself, other=none of the above.", + }, + }, + required: ["response", "command_type", "user_intent"], + }, +}; +import { extractLatestActionableText } from "./extractLatestActionableText.js"; +import { + resolvePendingAmbiguityGate, + resolvePendingConfirmationGate, +} from "./supervisorGates.js"; +import { + buildCommandQueuePlan, + shouldClearContinuationQueue, +} from "./supervisorQueue.js"; +import { tryResolveAssistRoute } from "./supervisorAssist.js"; +import { decodePlannedAction, encodePlannedAction } from "./plannedActions.js"; +import { presentToolResult } from "./toolResultPresenter.js"; +import { + classifyToolAction, + extractChatContent, + getToolResultPayload, + msgText, + parseChatEnvelope, + toWire, + type GraphArgs, + type MessageLike, +} from "./messageUtils.js"; + +export function buildAssistantGraph( + commands: Command[], + assistantWindow: AssistantWindowLike, + messageId?: string, + assistToolDefs: AssistTool[] = [], + options?: { railroadMemoryBlock?: string } +) { + const railroadMemoryBlock = String(options?.railroadMemoryBlock || ""); + const toolAgents: Record< + string, + (state: AgentState) => Promise> + > = {}; + const memberNames: string[] = []; + + for (const command of commands) { + toolAgents[command.commandName] = createCommandToolAgent(command, { + assistantWindow, + messageId, + }); + memberNames.push(command.commandName); + } + const memberNameSet = new Set(memberNames); + + const assistTools: AssistTool[] = + assistToolDefs.length > 0 + ? assistToolDefs + : commands.map(command => ({ + name: command.commandName, + description: command.description, + })); + const assistOptions = [...memberNames, "chat"]; + const assistRouterPrompt = buildAssistRouterPrompt(memberNames); + const endpointKey = getAssistantApiBase(); + + const chatNode = async (state: AgentState) => { + const routerMessage = state.args?.routerMessage; + if (typeof routerMessage === "string" && routerMessage.trim()) { + return { + messages: [new AIMessage(routerMessage.trim())], + lastWorker: "chat", + commandQueue: [], + }; + } + + const lastMsg = state.messages[state.messages.length - 1]; + const lastMsgText = msgText(lastMsg as MessageLike); + const toolPayload = getToolResultPayload(lastMsg as MessageLike); + const hasToolOutput = Boolean(toolPayload); + const hasSummarizeRequest = lastMsgText.includes("__SUMMARIZE_REQUEST__"); + + if (toolPayload && !hasSummarizeRequest) { + return { + messages: [ + new AIMessage({ + content: presentToolResult(toolPayload), + additional_kwargs: { + oasisUsageMeta: classifyToolAction(toolPayload.commandName), + }, + }), + ], + lastWorker: "chat", + commandQueue: [], + }; + } + + const capabilitiesReply = getOasisCapabilitiesReply(lastMsgText); + if (capabilitiesReply) { + return { + messages: [new AIMessage(capabilitiesReply)], + lastWorker: "chat", + commandQueue: [], + }; + } + + const hiddenInstruction = buildHiddenInstruction({ + hasSummarizeRequest, + hasToolOutput, + }); + + const messagesWithPrompt = [ + ...state.messages, + new HumanMessage(hiddenInstruction), + ]; + + let res: unknown; + try { + res = await assistRemote( + CHAT_SYSTEM_PROMPT + railroadMemoryBlock, + toWire(messagesWithPrompt), + ["chat"], + [], + CHAT_GENERATION_CONFIG + ); + if ((res as any)?.quota) { + subscriptionService.updateFromQuota((res as any).quota); + } + } catch (error) { + assistantLogger.warn("chat", "Assist chat call failed.", error); + + if (error instanceof QuotaExceededError || (error as any).isQuotaError) { + if ((error as any).quota) { + subscriptionService.updateFromQuota((error as any).quota); + } + return { + messages: [ + new AIMessage(formatQuotaExceededMessage((error as Error).message)), + ], + lastWorker: "chat", + commandQueue: [], + }; + } + + if (hasToolOutput) { + const fallback = String(msgText(lastMsg as MessageLike) || "").trim(); + return { + messages: [new AIMessage(fallback || "Done.")], + lastWorker: "chat", + commandQueue: [], + }; + } + return { + messages: [ + new AIMessage( + "I'm having trouble reaching the assistant service right now. Please try again." + ), + ], + lastWorker: "chat", + commandQueue: [], + }; + } + + const { text: chatText, meta: usageMeta } = parseChatEnvelope(res); + const trimmedText = chatText.trim(); + if (!trimmedText) { + if (hasToolOutput) { + const fallback = String(msgText(lastMsg as MessageLike) || "").trim(); + return { + messages: [new AIMessage(fallback || "Done.")], + lastWorker: "chat", + commandQueue: [], + }; + } + return { + messages: [ + new AIMessage("I couldn't generate a response. Please try again."), + ], + lastWorker: "chat", + commandQueue: [], + }; + } + + return { + messages: [ + new AIMessage({ + content: trimmedText, + additional_kwargs: { oasisUsageMeta: usageMeta }, + }), + ], + lastWorker: "chat", + commandQueue: [], + }; + }; + + const supervisorNode = async (state: AgentState) => { + const { latestTextRaw, commandLine, commandText, confirmationText } = + extractLatestActionableText(state.messages); + + const justRanTool = memberNameSet.has(state.lastWorker); + const justRanConfirm = state.lastWorker === "confirm_action"; + const pendingConfirmation = getPendingConfirmation(); + const confirmationGate = resolvePendingConfirmationGate({ + confirmationText, + pendingConfirmation, + justRanConfirm, + }); + if (confirmationGate.kind === "route") { + return { next: confirmationGate.next, args: confirmationGate.args }; + } + if (confirmationGate.kind === "end") { + return { next: AGENT_END, args: {} }; + } + + const pendingAmbiguity = getPendingAmbiguity(); + const ambiguityGate = resolvePendingAmbiguityGate({ + pendingAmbiguity, + confirmationText, + commandText, + lastWorker: state.lastWorker, + }); + if (ambiguityGate.kind === "route") { + return { next: ambiguityGate.next, args: ambiguityGate.args }; + } + if (ambiguityGate.kind === "clear") { + clearPendingAmbiguity(); + } + + const pendingContinuationQueue = getContinuationQueue(); + const shouldResumeContinuation = + state.lastWorker === "confirm_action" && + pendingContinuationQueue.length > 0 && + !getPendingConfirmation(); + + if ( + shouldClearContinuationQueue({ + hasContinuation: pendingContinuationQueue.length > 0, + shouldResumeContinuation, + justRanTool, + commandText, + }) + ) { + clearContinuationQueue(); + } + + if (justRanTool) { + if (state.commandQueue.length <= 1 && !shouldResumeContinuation) { + return { next: "chat", args: {}, commandQueue: [] }; + } + } + + const continuationQueue = shouldResumeContinuation + ? takeContinuationQueue() + : []; + const hasQueuedCommands = + state.commandQueue.length > 0 || continuationQueue.length > 0; + const topLevelActionText = commandLine.toLowerCase(); + const topLevelActionLike = looksLikeNewActionCommand(topLevelActionText); + + if (!hasQueuedCommands && commandLine) { + const topLevelAssist = await tryResolveAssistRoute({ + endpointKey, + activeCommandText: topLevelActionText, + commandQueueLength: 1, + messages: state.messages, + assistRouterPrompt, + assistOptions, + assistTools, + memberNameSet, + maxPlanActions: MAX_NESTED_COMMANDS, + railroadMemoryBlock, + }); + + if (topLevelAssist.kind === "plan") { + const encodedQueue = topLevelAssist.actions.map(action => + encodePlannedAction(action) + ); + const first = topLevelAssist.actions[0]; + if (!first) { + return { next: "chat", args: {}, commandQueue: [] }; + } + return { + next: first.next, + args: first.args, + commandQueue: encodedQueue, + }; + } + + if (topLevelAssist.kind === "tool") { + const guardRoute = routeDeterministically(commandLine); + if ( + guardRoute.type === "tool" && + guardRoute.next === "resolve_ambiguity" && + guardRoute.pendingAmbiguity + ) { + setRoutePendingAmbiguity(guardRoute.pendingAmbiguity); + return { + next: guardRoute.next, + args: guardRoute.args, + commandQueue: [commandLine], + }; + } + return { + next: topLevelAssist.next, + args: topLevelAssist.args, + commandQueue: [commandLine], + }; + } + + if (topLevelAssist.kind === "chat" && !topLevelActionLike) { + return { + next: "chat", + args: { routerMessage: topLevelAssist.content }, + commandQueue: [], + }; + } + } + + const queuePlan = buildCommandQueuePlan({ + existingQueue: state.commandQueue, + continuationQueue, + latestTextRaw, + commandLine, + lastWorker: state.lastWorker, + justRanTool: justRanTool && state.commandQueue.length > 0, + maxCommands: MAX_NESTED_COMMANDS, + }); + if (!queuePlan) { + return { next: "chat", args: {}, commandQueue: [] }; + } + const { commandQueue, activeCommand, truncationNotice } = queuePlan; + const applyNoticeToArgs = (args: GraphArgs): GraphArgs => + truncationNotice + ? { ...args, [INTERNAL_CHAIN_NOTICE_ARG]: truncationNotice } + : args; + const applyNoticeToMessage = (message: string): string => + truncationNotice ? `${truncationNotice}\n${message}` : message; + + const plannedAction = decodePlannedAction(activeCommand); + if (plannedAction) { + return { + next: plannedAction.next, + args: applyNoticeToArgs(plannedAction.args), + commandQueue, + }; + } + + const activeCommandText = activeCommand.toLowerCase(); + const actionLikeCommand = looksLikeNewActionCommand(activeCommandText); + const assistRoute = await tryResolveAssistRoute({ + endpointKey, + activeCommandText, + commandQueueLength: commandQueue.length, + messages: state.messages, + assistRouterPrompt, + assistOptions, + assistTools, + memberNameSet, + maxPlanActions: MAX_NESTED_COMMANDS, + railroadMemoryBlock, + }); + + if (assistRoute.kind === "plan") { + const encodedQueue = assistRoute.actions.map(action => + encodePlannedAction(action) + ); + const first = assistRoute.actions[0]; + if (first) { + return { + next: first.next, + args: applyNoticeToArgs(first.args), + commandQueue: encodedQueue, + }; + } + } + + const route = routeDeterministically(activeCommand); + if (assistRoute.kind === "tool") { + if ( + route.type === "tool" && + route.next === "resolve_ambiguity" && + route.pendingAmbiguity + ) { + setRoutePendingAmbiguity(route.pendingAmbiguity); + return { + next: route.next, + args: applyNoticeToArgs(route.args), + commandQueue, + }; + } + return { + next: assistRoute.next, + args: applyNoticeToArgs(assistRoute.args), + commandQueue, + }; + } + if (assistRoute.kind === "chat") { + if (actionLikeCommand) { + assistantLogger.debug( + "router", + "Ignoring assist chat response for action-like command" + ); + } else { + return { + next: "chat", + args: { routerMessage: applyNoticeToMessage(assistRoute.content) }, + commandQueue: [], + }; + } + } + + if (route.type === "tool") { + if (route.pendingAmbiguity) { + setRoutePendingAmbiguity(route.pendingAmbiguity); + } + return { + next: route.next, + args: applyNoticeToArgs(route.args), + commandQueue, + }; + } + + if (route.type === "chat") { + return { + next: "chat", + args: { routerMessage: applyNoticeToMessage(route.message) }, + commandQueue: [], + }; + } + + return { + next: "chat", + args: truncationNotice ? { routerMessage: truncationNotice } : {}, + commandQueue: [], + }; + }; + + return { + stream( + input: { messages: BaseMessage[] }, + options?: { recursionLimit?: number } + ) { + const maxSteps = options?.recursionLimit ?? ASSISTANT_RECURSION_LIMIT; + return streamAgentLoop({ + initialMessages: input.messages, + maxSteps, + supervisorNode, + chatNode, + toolAgents, + memberNames, + }); + }, + }; +} diff --git a/browser/base/content/assistant/build/src/assistant/messageUtils.ts b/browser/base/content/assistant/build/src/assistant/messageUtils.ts new file mode 100644 index 0000000000000..7bfaed4c14cd6 --- /dev/null +++ b/browser/base/content/assistant/build/src/assistant/messageUtils.ts @@ -0,0 +1,444 @@ +/** + * Message utilities — serialization and extraction helpers. + * + * Converts LangChain BaseMessages to wire format for the remote API, + * extracts text content from various message shapes, detects tool + * result payloads embedded in additional_kwargs, and strips echoed + * tool output from assistant responses. + */ +import type { BaseMessage } from "@langchain/core/messages"; + +export type GraphArgs = Record; + +export type CommandType = + | "info_retrieval" + | "navigation" + | "organization" + | "content_transform" + | "content_create" + | "search" + | "automation" + | "system" + | "help" + | "other"; + +export type UserIntent = + | "learning" + | "research" + | "work" + | "dev" + | "marketing" + | "shopping" + | "personal" + | "entertainment" + | "meta" + | "other"; + +export type UsageMeta = { + command_type: CommandType; + user_intent: UserIntent; + input_tokens: number | null; + output_tokens: number | null; +}; + +const TOOL_COMMAND_TYPE_MAP: Partial> = { + open_url: "navigation", + navigate_tab: "navigation", + new_window: "navigation", + new_tab_to_right: "navigation", + open_bookmark_folder: "navigation", + open_search_result: "navigation", + close_tab: "organization", + create_tab_group: "organization", + delete_tab_group: "organization", + rename_tab_group: "organization", + add_tab_to_group: "organization", + remove_tab_from_group: "organization", + move_tab_to_new_window: "organization", + split_tabs: "organization", + add_split_view: "organization", + remove_split_view: "organization", + organize_windows: "organization", + create_bookmark_folder: "organization", + delete_bookmark_folder: "organization", + rename_bookmark_folder: "organization", + add_tab_to_bookmark_folder: "organization", + remove_tab_from_bookmark_folder: "organization", + list_tabs: "info_retrieval", + list_bookmark_folders: "info_retrieval", + list_tab_groups: "info_retrieval", + search_memory: "search", + get_recent_search_results: "search", + web_search: "search", + search_history: "search", +}; + +export function classifyToolAction(commandName: string): UsageMeta { + return { + command_type: TOOL_COMMAND_TYPE_MAP[commandName] ?? "other", + user_intent: "other", + input_tokens: null, + output_tokens: null, + }; +} + +export type ToolResultPayload = { + kind: "tool_result"; + commandName: string; + message: string; +}; + +export type MessageLike = { + content?: unknown; + additional_kwargs?: unknown; + _getType?: () => string; + getType?: () => string; + type?: string; +}; + +export type WireMsg = { role: "user" | "model"; content: string }; + +export type StreamMessageLike = MessageLike; +export type StreamStateValue = { + messages?: StreamMessageLike[]; + [key: string]: unknown; +}; + +export function isRecord(value: unknown): value is Record { + return !!value && typeof value === "object"; +} + +function asToolResultPayload(value: unknown): ToolResultPayload | null { + if (!isRecord(value)) { + return null; + } + const kind = value.kind; + const commandName = value.commandName; + const message = value.message; + if (kind !== "tool_result") { + return null; + } + if (typeof commandName !== "string" || !commandName.trim()) { + return null; + } + if (typeof message !== "string") { + return null; + } + return { + kind, + commandName, + message, + }; +} + +export function getToolResultPayload( + message: MessageLike | null | undefined +): ToolResultPayload | null { + if (!message) { + return null; + } + const rawKwargs = message.additional_kwargs; + if (!isRecord(rawKwargs)) { + return null; + } + return asToolResultPayload(rawKwargs.oasisToolResult); +} + +export function msgText(m: MessageLike | null | undefined): string { + if (!m) return ""; + const toolResult = getToolResultPayload(m); + if (toolResult) { + return toolResult.message; + } + const c = m.content; + if (typeof c === "string") return c; + if (Array.isArray(c)) { + return c + .map(v => + typeof v === "string" + ? v + : typeof v === "object" && v && "text" in v + ? String((v as { text?: unknown }).text || "") + : "" + ) + .join(""); + } + return String(c ?? ""); +} + +export function toWire(messages: BaseMessage[]): WireMsg[] { + return messages.map(m => { + const role = m._getType() === "human" ? "user" : "model"; + const toolResult = getToolResultPayload(m as unknown as MessageLike); + if (toolResult) { + return { + role, + content: + `Internal command result\n` + + `Command: ${toolResult.commandName}\n` + + `Result: ${toolResult.message}`, + }; + } + return { role, content: msgText(m) }; + }); +} + +export function extractChatContent(response: unknown): string { + if (typeof response === "string") { + return response; + } + if (response && typeof response === "object" && "content" in response) { + return String((response as { content?: unknown }).content ?? ""); + } + return ""; +} + +const VALID_COMMAND_TYPES = new Set([ + "info_retrieval", + "navigation", + "organization", + "content_transform", + "content_create", + "search", + "automation", + "system", + "help", + "other", +]); + +const VALID_USER_INTENTS = new Set([ + "learning", + "research", + "work", + "dev", + "marketing", + "shopping", + "personal", + "entertainment", + "meta", + "other", +]); + +export type ParsedChatEnvelope = { + text: string; + meta: UsageMeta; +}; + +/** + * Token counts from a Gemini `usage_metadata` object (snake_case REST or camelCase SDK). + */ +export function extractTokenCountsFromUsageMetadata( + usage: unknown +): { input_tokens: number | null; output_tokens: number | null } { + let inputTokens: number | null = null; + let outputTokens: number | null = null; + if (!isRecord(usage)) { + return { input_tokens: null, output_tokens: null }; + } + if (typeof usage.prompt_token_count === "number") { + inputTokens = usage.prompt_token_count; + } else if (typeof usage.promptTokenCount === "number") { + inputTokens = usage.promptTokenCount; + } + if (typeof usage.candidates_token_count === "number") { + outputTokens = usage.candidates_token_count; + } else if (typeof usage.candidatesTokenCount === "number") { + outputTokens = usage.candidatesTokenCount; + } + return { input_tokens: inputTokens, output_tokens: outputTokens }; +} + +/** Reads `usage_metadata` from an assist or chat API payload. */ +export function extractTokenCountsFromAssistPayload( + payload: unknown +): { input_tokens: number | null; output_tokens: number | null } { + if (!isRecord(payload)) { + return { input_tokens: null, output_tokens: null }; + } + return extractTokenCountsFromUsageMetadata(payload.usage_metadata); +} + +export function parseChatEnvelope(response: unknown): ParsedChatEnvelope { + const defaultMeta: UsageMeta = { + command_type: "other", + user_intent: "other", + input_tokens: null, + output_tokens: null, + }; + + const tokenCounts = extractTokenCountsFromAssistPayload(response); + const tokenMeta = { + input_tokens: tokenCounts.input_tokens, + output_tokens: tokenCounts.output_tokens, + }; + + // The content field may already be a parsed JSON object (Gemini structured output) + // or a JSON string we need to parse ourselves. + if (!isRecord(response)) { + return { + text: extractChatContent(response), + meta: { ...defaultMeta, ...tokenMeta }, + }; + } + + const contentField = (response as { content?: unknown }).content; + + if (isRecord(contentField)) { + // Already a parsed object — Gemini structured output forwarded as an object + return extractFromParsed(contentField, tokenMeta, defaultMeta); + } + + if (typeof contentField !== "string" || !contentField.trim()) { + return { + text: extractChatContent(response), + meta: { ...defaultMeta, ...tokenMeta }, + }; + } + + let jsonStr = contentField.trim(); + + // Strip markdown fences the LLM may add + const fenceMatch = jsonStr.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/); + if (fenceMatch) { + jsonStr = fenceMatch[1].trim(); + } + + // Tier 1: direct parse + const direct = tryJsonParse(jsonStr); + if (direct !== null) { + return extractFromParsed(direct, tokenMeta, defaultMeta); + } + + // Tier 2: repair unescaped control characters (most common LLM mistake — + // actual newline/tab bytes inside a JSON string value) + const repaired = jsonStr + .replace(/\r\n/g, "\\n") + .replace(/\r/g, "\\n") + .replace(/\n/g, "\\n") + .replace(/\t/g, "\\t"); + const fromRepair = tryJsonParse(repaired); + if (fromRepair !== null) { + return extractFromParsed(fromRepair, tokenMeta, defaultMeta); + } + + // Tier 3: regex extraction as last resort + const regexResult = extractViaRegex(jsonStr, tokenMeta, defaultMeta); + if (regexResult !== null) { + return regexResult; + } + + // Full fallback: display whatever came back + return { + text: jsonStr || contentField, + meta: { ...defaultMeta, ...tokenMeta }, + }; +} + +function tryJsonParse(str: string): unknown { + try { + return JSON.parse(str); + } catch { + return null; + } +} + +function extractFromParsed( + parsed: unknown, + tokenMeta: { input_tokens: number | null; output_tokens: number | null }, + defaultMeta: UsageMeta +): ParsedChatEnvelope { + if (!isRecord(parsed) || typeof parsed.response !== "string") { + return { + text: typeof parsed === "string" ? parsed : "", + meta: { ...defaultMeta, ...tokenMeta }, + }; + } + const commandType: CommandType = VALID_COMMAND_TYPES.has( + String(parsed.command_type ?? "") + ) + ? (parsed.command_type as CommandType) + : "other"; + const userIntent: UserIntent = VALID_USER_INTENTS.has( + String(parsed.user_intent ?? "") + ) + ? (parsed.user_intent as UserIntent) + : "other"; + return { + text: parsed.response, + meta: { command_type: commandType, user_intent: userIntent, ...tokenMeta }, + }; +} + +function extractViaRegex( + str: string, + tokenMeta: { input_tokens: number | null; output_tokens: number | null }, + defaultMeta: UsageMeta +): ParsedChatEnvelope | null { + // Match "response":"" where value may span multiple lines + const responseMatch = str.match( + /"response"\s*:\s*"([\s\S]*?)"\s*,\s*"command_type"/ + ); + if (!responseMatch) { + return null; + } + const responseText = responseMatch[1] + .replace(/\\n/g, "\n") + .replace(/\\t/g, "\t") + .replace(/\\"/g, '"') + .replace(/\\\\/g, "\\"); + + const cmdMatch = str.match(/"command_type"\s*:\s*"([^"]+)"/); + const intentMatch = str.match(/"user_intent"\s*:\s*"([^"]+)"/); + + const commandType: CommandType = + cmdMatch && VALID_COMMAND_TYPES.has(cmdMatch[1]) + ? (cmdMatch[1] as CommandType) + : "other"; + const userIntent: UserIntent = + intentMatch && VALID_USER_INTENTS.has(intentMatch[1]) + ? (intentMatch[1] as UserIntent) + : "other"; + + return { + text: responseText || str, + meta: { command_type: commandType, user_intent: userIntent, ...tokenMeta }, + }; +} + +export function stripLeadingEchoedPayload( + value: string, + payloads: readonly string[] +): string { + let text = String(value || "").trim(); + if (!text || payloads.length === 0) { + return text; + } + + for (const payload of payloads) { + const candidate = String(payload || "").trim(); + if (!candidate) { + continue; + } + + if (text.startsWith(candidate)) { + if (text.length === candidate.length) { + continue; + } + text = text + .slice(candidate.length) + .replace(/^[\s:.,;!-]+/, "") + .trim(); + break; + } + } + + return text; +} + +export function hasMessages(value: unknown): value is StreamStateValue { + return ( + !!value && + typeof value === "object" && + Array.isArray((value as { messages?: unknown }).messages) + ); +} diff --git a/browser/base/content/assistant/build/src/assistant/plannedActions.ts b/browser/base/content/assistant/build/src/assistant/plannedActions.ts new file mode 100644 index 0000000000000..7213bd2944c67 --- /dev/null +++ b/browser/base/content/assistant/build/src/assistant/plannedActions.ts @@ -0,0 +1,89 @@ +/** + * Planned actions — encode/decode multi-step action plans. + * + * When the LLM returns a route_action_plan (multiple commands to run + * sequentially), this module serializes each planned action into the + * command queue as prefixed JSON strings, and deserializes them when + * the supervisor dequeues the next command. + */ +import type { GraphArgs } from "./messageUtils.js"; + +export type PlannedAction = { + next: string; + args: GraphArgs; +}; + +const PLAN_PREFIX = "__oasis_plan__:"; + +function asRecord(value: unknown): Record | null { + if (!value || typeof value !== "object" || Array.isArray(value)) { + return null; + } + return value as Record; +} + +function normalizeAction( + value: unknown, + memberNameSet: ReadonlySet +): PlannedAction | null { + const record = asRecord(value); + if (!record) { + return null; + } + const nextRaw = record.next; + const next = + typeof nextRaw === "string" ? nextRaw.trim() : String(nextRaw || "").trim(); + if (!next || !memberNameSet.has(next)) { + return null; + } + const argsRecord = asRecord(record.args) || {}; + return { next, args: argsRecord }; +} + +export function parsePlannedActions( + rawArgs: Record, + memberNameSet: ReadonlySet, + maxActions: number +): PlannedAction[] { + const rawActions = Array.isArray(rawArgs.actions) ? rawArgs.actions : []; + const actions: PlannedAction[] = []; + + for (const item of rawActions) { + const normalized = normalizeAction(item, memberNameSet); + if (!normalized) { + continue; + } + actions.push(normalized); + if (actions.length >= maxActions) { + break; + } + } + + return actions; +} + +export function encodePlannedAction(action: PlannedAction): string { + return `${PLAN_PREFIX}${JSON.stringify(action)}`; +} + +export function decodePlannedAction(value: string): PlannedAction | null { + const text = String(value || "").trim(); + if (!text.startsWith(PLAN_PREFIX)) { + return null; + } + + try { + const parsed = JSON.parse(text.slice(PLAN_PREFIX.length)); + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { + return null; + } + const next = String((parsed as { next?: unknown }).next || "").trim(); + if (!next) { + return null; + } + const args = asRecord((parsed as { args?: unknown }).args) || {}; + return { next, args }; + } catch { + return null; + } +} diff --git a/browser/base/content/assistant/build/src/assistant/session.ts b/browser/base/content/assistant/build/src/assistant/session.ts new file mode 100644 index 0000000000000..29110f60bc4fd --- /dev/null +++ b/browser/base/content/assistant/build/src/assistant/session.ts @@ -0,0 +1,190 @@ +/** + * Session controller — manages conversation history. + * + * Imports the AssistantSession singleton from Firefox's privileged + * module system (chrome://). Falls back to an in-memory store if + * ChromeUtils is unavailable. Provides: + * - getCurrentSessionMessages(): gets full history as BaseMessage[] + * - pushCurrentTurn(): appends a user+assistant message pair + * - resetAssistantSession(): clears all history + */ +import { AIMessage, BaseMessage, HumanMessage } from "@langchain/core/messages"; + +import { OASIS_EVENT_HISTORY_UPDATE } from "../../../shared/contracts.js"; +import { assistantLogger } from "../utils/assistantLogger.js"; +import type { + AssistantSessionLike, + AssistantWindowLike, +} from "../types/runtime.js"; +import { msgText, type MessageLike } from "./messageUtils.js"; + +type SessionObserver = { + observe: (subject: unknown, topic: string, data: string | null) => void; +}; + +export type PlainSessionTurn = { type: "human" | "ai"; content: string }; + +export type AssistantSessionController = { + getCurrentSessionMessages: () => BaseMessage[]; + pushCurrentTurn: (user: string, assistant: string) => void; + resetAssistantSession: () => void; + getAssistantHistory: () => BaseMessage[]; + syncSessionFromPlainTurns: (turns: PlainSessionTurn[]) => void; +}; + +function createFallbackSessionStore(): AssistantSessionLike { + let messages: unknown[] = []; + const CAP = 24; + return { + get messages() { + return [...messages]; + }, + addTurn(user: unknown, assistant: unknown) { + messages.push(user, assistant); + if (messages.length > CAP) { + messages.splice(0, messages.length - CAP); + } + }, + clear() { + messages = []; + }, + setSession(nextMessages: unknown[]) { + messages = [...nextMessages]; + if (messages.length > CAP) { + messages.splice(0, messages.length - CAP); + } + }, + }; +} + +function importAssistantSession( + assistantWindow: AssistantWindowLike +): AssistantSessionLike { + if (!assistantWindow.ChromeUtils?.importESModule) { + assistantLogger.warn( + "session", + "ChromeUtils unavailable, using fallback session store." + ); + return createFallbackSessionStore(); + } + + try { + const mod = assistantWindow.ChromeUtils.importESModule( + "chrome://browser/content/assistant/AssistantSession.sys.mjs" + ); + const importedSession = mod.AssistantSession as + | AssistantSessionLike + | undefined; + if (importedSession) { + assistantLogger.info("session", "Imported AssistantSession singleton."); + return importedSession; + } + assistantLogger.warn( + "session", + "AssistantSession export missing, using fallback session store." + ); + return createFallbackSessionStore(); + } catch (error) { + assistantLogger.error( + "session", + "Failed to import AssistantSession singleton.", + error + ); + return createFallbackSessionStore(); + } +} + +function installSessionObserver(assistantWindow: AssistantWindowLike): void { + try { + const services = assistantWindow.Services; + if (!services?.obs) { + return; + } + const observer: SessionObserver = { + observe: (_subject: unknown, topic: string, _data: string | null) => { + if (topic === "oasis-session-updated") { + try { + assistantWindow.dispatchEvent( + new CustomEvent(OASIS_EVENT_HISTORY_UPDATE) + ); + } catch { + // no-op + } + } + }, + }; + services.obs.addObserver(observer, "oasis-session-updated", false); + } catch (error) { + assistantLogger.error( + "session", + "Failed to install session observer.", + error + ); + } +} + +function hydrateSessionMessages(session: AssistantSessionLike): BaseMessage[] { + return session.messages.map((m): BaseMessage => { + const message = (m || {}) as MessageLike; + if (typeof message._getType === "function") { + return message as BaseMessage; + } + if (message.type === "human") { + return new HumanMessage(msgText(message)); + } + if (message.type === "ai") { + return new AIMessage(msgText(message)); + } + return new HumanMessage(msgText(message)); + }); +} + +export function createAssistantSessionController( + assistantWindow: AssistantWindowLike +): AssistantSessionController { + const session = importAssistantSession(assistantWindow); + installSessionObserver(assistantWindow); + + function getCurrentSessionMessages(): BaseMessage[] { + return hydrateSessionMessages(session); + } + + function pushCurrentTurn(user: string, assistant: string): void { + session.addTurn( + { type: "human", content: user }, + { type: "ai", content: assistant } + ); + } + + function syncSessionFromPlainTurns(turns: PlainSessionTurn[]): void { + session.setSession( + turns.map(t => ({ + type: t.type, + content: t.content, + })) + ); + } + + function resetAssistantSession(): void { + session.clear(); + try { + assistantWindow.dispatchEvent( + new CustomEvent(OASIS_EVENT_HISTORY_UPDATE) + ); + } catch { + // no-op + } + } + + function getAssistantHistory(): BaseMessage[] { + return getCurrentSessionMessages(); + } + + return { + getCurrentSessionMessages, + pushCurrentTurn, + resetAssistantSession, + getAssistantHistory, + syncSessionFromPlainTurns, + }; +} diff --git a/browser/base/content/assistant/build/src/assistant/stream.ts b/browser/base/content/assistant/build/src/assistant/stream.ts new file mode 100644 index 0000000000000..7d812b35d5958 --- /dev/null +++ b/browser/base/content/assistant/build/src/assistant/stream.ts @@ -0,0 +1,230 @@ +/** + * Graph output stream consumer. + * + * Iterates over the async output of the agent stream (`graph.stream()`), filters out + * internal tool messages, strips echoed payloads, and sends clean + * text to the UI via `onChunk()`. Also: + * - Saves completed turns to session history + * - Tracks usage for subscription limits + * - Detects infinite loops via stream guards + * + * Called from assistant.ts after the graph is built. + */ +import type { AssistantInputType } from "../../../shared/contracts.js"; +import { + advanceStreamGuard, + createStreamGuardState, + shouldStopForStreamGuard, + STREAM_GUARD_DEFAULTS, +} from "../utils/streamGuards.js"; +import { assistantLogger } from "../utils/assistantLogger.js"; +import { + getToolResultPayload, + hasMessages, + isRecord, + stripLeadingEchoedPayload, + type MessageLike, + type UsageMeta, +} from "./messageUtils.js"; +import { STREAM_GUARD_MESSAGE } from "./constants.js"; + +type ConsumeAssistantStreamArgs = { + stream: AsyncIterable>; + prompt: string; + onChunk: (text: string) => void; + inputType: AssistantInputType; + toolCommandNames: Set; + pushCurrentTurn: (user: string, assistant: string) => void; + trackUsage: (inputType: AssistantInputType, meta?: UsageMeta) => void; +}; + +function extractMessageText(msg: MessageLike): string { + if (typeof msg?.content === "string") { + return msg.content; + } + if (Array.isArray(msg?.content)) { + return msg.content + .map(c => { + if (typeof c === "string") { + return c; + } + if (typeof c === "object" && c && "text" in c) { + const value = (c as { text?: unknown }).text; + if (value != null) { + return String(value); + } + } + if ( + typeof c === "object" && + c && + "type" in c && + (c as { type?: unknown }).type === "text" && + "text" in c + ) { + return String((c as { text?: unknown }).text ?? ""); + } + return String(c ?? ""); + }) + .join(""); + } + if (msg?.content != null) { + return String(msg.content); + } + return ""; +} + +export async function consumeAssistantGraphStream( + args: ConsumeAssistantStreamArgs +): Promise { + const { + stream, + prompt, + onChunk, + inputType, + toolCommandNames, + pushCurrentTurn, + trackUsage, + } = args; + + let combinedSessionString = ""; + let toolOutputBuffer = ""; + let isSaved = false; + let hasEmittedUserMessage = false; + const recentToolPayloads: string[] = []; + let toolMessageCount = 0; + let emittedChars = 0; + let guardTriggered = false; + let lastUsageMeta: UsageMeta | undefined; + + let streamGuardState = createStreamGuardState(); + + for await (const state of stream) { + if ("__end__" in state) { + if (combinedSessionString && !isSaved) { + pushCurrentTurn(prompt, combinedSessionString); + trackUsage(inputType, lastUsageMeta); + isSaved = true; + } + break; + } + + const step = Object.entries(state).find(([k]) => k !== "__end"); + const stepValue = step?.[1]; + const stepName = step?.[0] || "unknown"; + streamGuardState = advanceStreamGuard(streamGuardState, stepName); + + if (shouldStopForStreamGuard(streamGuardState, STREAM_GUARD_DEFAULTS)) { + guardTriggered = true; + assistantLogger.warn("stream", "Stream guard triggered.", { + stepCount: streamGuardState.stepCount, + stepName, + sameStepStreak: streamGuardState.sameStepStreak, + }); + if (!hasEmittedUserMessage) { + onChunk(`${STREAM_GUARD_MESSAGE}\n`); + combinedSessionString = STREAM_GUARD_MESSAGE; + hasEmittedUserMessage = true; + } + break; + } + + if (!hasMessages(stepValue) || !stepValue.messages) { + continue; + } + + const messages = stepValue.messages; + for (const rawMessage of messages) { + const msg = rawMessage as MessageLike; + const text = extractMessageText(msg); + if (!text) { + continue; + } + + const kwargs = (msg as { additional_kwargs?: unknown }).additional_kwargs; + if (isRecord(kwargs) && isRecord(kwargs.oasisUsageMeta)) { + const newMeta = kwargs.oasisUsageMeta as UsageMeta; + if (!lastUsageMeta) { + lastUsageMeta = newMeta; + } else { + lastUsageMeta = { + command_type: lastUsageMeta.command_type !== "other" && newMeta.command_type === "other" + ? lastUsageMeta.command_type : newMeta.command_type, + user_intent: lastUsageMeta.user_intent !== "other" && newMeta.user_intent === "other" + ? lastUsageMeta.user_intent : newMeta.user_intent, + input_tokens: newMeta.input_tokens ?? lastUsageMeta.input_tokens, + output_tokens: newMeta.output_tokens ?? lastUsageMeta.output_tokens, + }; + } + } + + const msgName = + typeof (msg as { name?: unknown }).name === "string" + ? ((msg as { name?: string }).name ?? "") + : ""; + const toolResult = getToolResultPayload(msg); + const isToolNodeMessage = + toolCommandNames.has(stepName) || + toolCommandNames.has(msgName) || + !!toolResult; + + if (isToolNodeMessage) { + toolMessageCount += 1; + const payloadText = toolResult?.message || text; + toolOutputBuffer += `${payloadText}\n`; + const payload = String(payloadText || "").trim(); + if (payload) { + recentToolPayloads.unshift(payload); + if (recentToolPayloads.length > 8) { + recentToolPayloads.pop(); + } + } + continue; + } + + const sanitizedText = stripLeadingEchoedPayload( + String(text || "").trim(), + recentToolPayloads + ); + if (!sanitizedText) { + continue; + } + + const newContent = `${sanitizedText}\n`; + onChunk(newContent); + combinedSessionString += newContent; + emittedChars += newContent.length; + hasEmittedUserMessage = true; + } + } + + if (!hasEmittedUserMessage && toolOutputBuffer) { + const sanitizedFallback = stripLeadingEchoedPayload( + String(toolOutputBuffer || "").trim(), + recentToolPayloads + ); + if (sanitizedFallback) { + const friendlyMessage = sanitizedFallback.endsWith("\n") + ? sanitizedFallback + : `${sanitizedFallback}\n`; + onChunk(friendlyMessage); + combinedSessionString = friendlyMessage; + hasEmittedUserMessage = true; + emittedChars += friendlyMessage.length; + } + } + + if (combinedSessionString && !isSaved) { + pushCurrentTurn(prompt, combinedSessionString); + trackUsage(inputType, lastUsageMeta); + } + + assistantLogger.debug("stream", "Run summary", { + steps: streamGuardState.stepCount, + sameStepStreak: streamGuardState.sameStepStreak, + guardTriggered, + emittedChars, + toolMessageCount, + }); + + return combinedSessionString || "(no output)"; +} diff --git a/browser/base/content/assistant/build/src/assistant/supervisorAssist.ts b/browser/base/content/assistant/build/src/assistant/supervisorAssist.ts new file mode 100644 index 0000000000000..9d5a8c88a37c9 --- /dev/null +++ b/browser/base/content/assistant/build/src/assistant/supervisorAssist.ts @@ -0,0 +1,422 @@ +/** + * LLM-based routing — asks the remote Assist API which command to run. + * + * Called by the supervisor node when it needs to route a user request. + * 1. Classifies the command family (list/search/mutation/other) + * 2. Constrains the available tools to the relevant family + * 3. Sends the router prompt + tools + conversation history to the LLM + * 4. Parses the LLM response into a tool route, chat decision, or action plan + * + * Falls through to deterministic routing (decisionEngine.ts) if the + * Assist API is unavailable or returns an error. + */ +import type { BaseMessage } from "@langchain/core/messages"; + +import { + assistRemote, + getAssistLoopOptionsFromBuildEnv, + type AssistResponse, + type AssistTool, +} from "../proxyClient.js"; +import { + getAssistCapability, + markAssistSupported, + markAssistUnsupported, + shouldAttemptAssist, +} from "../services/assistEndpointState.js"; +import { assistantLogger } from "../utils/assistantLogger.js"; +import { looksLikeNewActionCommand } from "../utils/routingUtils.js"; +import { classifyCommandFamily } from "../utils/intentParser.js"; +import type { IntentFamily } from "../utils/routerTypes.js"; +import { + extractTokenCountsFromAssistPayload, + isRecord, + toWire, +} from "./messageUtils.js"; +import { parsePlannedActions, type PlannedAction } from "./plannedActions.js"; +import { looksLikeCommandChain } from "./commandChain.js"; +import { QuotaExceededError } from "../awsSignedFetch.js"; +import { subscriptionService } from "../services/subscription.js"; +import { formatQuotaExceededMessage } from "../utils/quotaUserMessage.js"; + +const PLAN_TOOL_NAME = "route_action_plan"; +const LIST_FAMILY_TOOLS = new Set([ + "list_tabs", + "list_bookmark_folders", + "list_tab_groups", +]); +const SEARCH_FAMILY_TOOLS = new Set([ + "search_memory", + "search_history", + "get_recent_search_results", + "open_search_result", +]); +const SEARCH_WEB_TOOL = "web_search"; +const MUTATION_FAMILY_TOOLS = new Set([ + "add_tab_to_bookmark_folder", + "add_tab_to_group", + "remove_tab_from_bookmark_folder", + "remove_tab_from_group", + "create_bookmark_folder", + "delete_bookmark_folder", + "rename_bookmark_folder", + "open_bookmark_folder", + "create_tab_group", + "delete_tab_group", + "rename_tab_group", + "close_tab", + "move_tab_to_new_window", + "split_tabs", + "add_split_view", + "remove_split_view", + "confirm_action", + "resolve_ambiguity", + "new_window", + "organize_windows", +]); +// const SEARCH_WEB_HINT_RE = +// /\b(?:google|web|internet|online|bing|duckduckgo|search\s+the\s+web)\b/i; +// const SEARCH_LOCAL_HINT_RE = +// /\b(?:bookmark|folder|hub|tab|tabs|group|groups|history|memory|saved|visited|recent\s+results?)\b/i; + +const SEARCH_WEB_HINT_RE = + /\b(?:google|web|internet|online|bing|duckduckgo|search\s+the\s+web)\b/i; +const SEARCH_LOCAL_HINT_RE = + /\b(?:bookmark|folder|hub|tab|tabs|group|groups|history|memory|saved|visited|recent\s+results?)\b/i; +const SEARCH_HISTORY_HINT_RE = + /\b(?:visited|browsed|looked\s+at|read|viewed|pages?\s+i\s+(?:visited|read|browsed|looked\s+at|viewed)|articles?\s+i\s+(?:read|browsed|viewed)|sites?\s+i\s+(?:visited|browsed)|what\s+(?:was|did\s+i)|pull\s+that|get\s+that)\b/i; +const SEARCH_BOOKMARKS_HINT_RE = + /\b(?:bookmark|bookmarks|folder|saved|bookmarked|in\s+(?:my\s+)?(?:bookmark\s+)?folder|what'?s\s+in)\b/i; + +function constrainAssistRoutingForFamily(params: { + activeCommandText: string; + assistOptions: string[]; + assistTools: AssistTool[]; +}): { + family: IntentFamily; + constrained: boolean; + options: string[]; + tools: AssistTool[]; + allowPlanTool: boolean; +} { + const { activeCommandText, assistOptions, assistTools } = params; + const family = classifyCommandFamily(activeCommandText); + const chainLike = looksLikeCommandChain(activeCommandText); + const allowPlanTool = chainLike; + const toResult = (options: string[]) => { + const deduped: string[] = []; + const seen = new Set(); + for (const option of options) { + const name = String(option || "").trim(); + if (!name || seen.has(name)) { + continue; + } + seen.add(name); + deduped.push(name); + } + if (!seen.has("chat")) { + deduped.push("chat"); + seen.add("chat"); + } + const allowedSet = new Set(deduped.filter(option => option !== "chat")); + const tools = assistTools.filter(tool => allowedSet.has(tool.name)); + return { + family, + constrained: true, + options: deduped, + tools, + allowPlanTool, + }; + }; + + if (chainLike || family === "other") { + return { + family, + constrained: false, + options: [...assistOptions], + tools: [...assistTools], + allowPlanTool, + }; + } + + if (family === "list") { + return toResult( + assistOptions.filter( + option => option === "chat" || LIST_FAMILY_TOOLS.has(option) + ) + ); + } + + // if (family === "search") { + // const hasWebHint = SEARCH_WEB_HINT_RE.test(activeCommandText); + // const hasLocalHint = SEARCH_LOCAL_HINT_RE.test(activeCommandText); + // const allowedTools = new Set(SEARCH_FAMILY_TOOLS); + // if (hasWebHint || !hasLocalHint) { + // allowedTools.add(SEARCH_WEB_TOOL); + // } + // return toResult( + // assistOptions.filter( + // option => option === "chat" || allowedTools.has(option) + // ) + // ); + // } + + if (family === "search") { + const hasWebHint = SEARCH_WEB_HINT_RE.test(activeCommandText); + const hasLocalHint = SEARCH_LOCAL_HINT_RE.test(activeCommandText); + const hasHistoryHint = SEARCH_HISTORY_HINT_RE.test(activeCommandText); + const hasBookmarksHint = SEARCH_BOOKMARKS_HINT_RE.test(activeCommandText); + + const allowedTools = new Set(); + + // Strong signals for specific search types + if (hasHistoryHint && !hasBookmarksHint) { + // Clear history query - only allow search_history + allowedTools.add("search_history"); + allowedTools.add("get_recent_search_results"); + allowedTools.add("open_search_result"); + } else if (hasBookmarksHint && !hasHistoryHint) { + // Clear bookmarks query - only allow search_memory + allowedTools.add("search_memory"); + allowedTools.add("get_recent_search_results"); + allowedTools.add("open_search_result"); + } else { + // Ambiguous or no strong hints - allow both + SEARCH_FAMILY_TOOLS.forEach(tool => allowedTools.add(tool)); + } + + // Add web search if web hint present or no local hint + if (hasWebHint || !hasLocalHint) { + allowedTools.add(SEARCH_WEB_TOOL); + } + + return toResult( + assistOptions.filter( + option => option === "chat" || allowedTools.has(option) + ) + ); + } + + if (family === "mutation") { + return toResult( + assistOptions.filter( + option => option === "chat" || MUTATION_FAMILY_TOOLS.has(option) + ) + ); + } + + return { + family: "other", + constrained: false, + options: [...assistOptions], + tools: [...assistTools], + allowPlanTool, + }; +} + +export type AssistRouteResult = + | { kind: "none" } + | { kind: "tool"; next: string; args: Record } + | { kind: "plan"; actions: PlannedAction[] } + | { kind: "chat"; content: string }; + +/** + * Keeps subscription / daily token bar in sync with assist routing: + * Edge (authenticated) sends `usage_stats` after server-side RPC — update cache only. + * Lambda (or anonymous) sends `usage_metadata` — insert `llm_usage` row with real tokens. + */ +function syncSubscriptionFromAssistRouterResponse(assist: AssistResponse): void { + const raw = assist as Record; + if (isRecord(raw.usage_stats)) { + subscriptionService.updateFromAssistUsageStats( + raw.usage_stats as Record + ); + return; + } + const tokens = extractTokenCountsFromAssistPayload(assist); + const hasTokens = + (tokens.input_tokens != null && tokens.input_tokens > 0) || + (tokens.output_tokens != null && tokens.output_tokens > 0); + if (!hasTokens) { + return; + } + subscriptionService.recordAssistRoutingTokens({ + command_type: "system", + user_intent: "other", + input_tokens: tokens.input_tokens, + output_tokens: tokens.output_tokens, + }); +} + +export async function tryResolveAssistRoute(params: { + endpointKey: string; + activeCommandText: string; + commandQueueLength: number; + messages: BaseMessage[]; + assistRouterPrompt: string; + assistOptions: string[]; + assistTools: AssistTool[]; + memberNameSet: ReadonlySet; + maxPlanActions: number; + /** Appended to router system prompt (e.g. Railroad getPrunedPrompt). */ + railroadMemoryBlock?: string; +}): Promise { + const { + endpointKey, + activeCommandText, + commandQueueLength, + messages, + assistRouterPrompt, + assistOptions, + assistTools, + memberNameSet, + maxPlanActions, + railroadMemoryBlock = "", + } = params; + + const shouldTryAssistRouting = + commandQueueLength <= 1 && looksLikeNewActionCommand(activeCommandText); + if (!shouldTryAssistRouting) { + return { kind: "none" }; + } + + const constrained = constrainAssistRoutingForFamily({ + activeCommandText, + assistOptions, + assistTools, + }); + const effectiveOptions = constrained.options; + const effectiveTools = constrained.tools; + const effectiveOptionSet = new Set(effectiveOptions); + const allowPlanTool = constrained.allowPlanTool; + + const capability = getAssistCapability(endpointKey); + if (!shouldAttemptAssist(endpointKey)) { + if (capability === "unsupported") { + assistantLogger.debug( + "router", + "Assist endpoint currently cooling down." + ); + } + return { kind: "none" }; + } + + try { + const assistMessages = toWire(messages.slice(-10)); + const optionsForAssist = allowPlanTool + ? [...effectiveOptions, PLAN_TOOL_NAME] + : effectiveOptions; + const toolsForAssist = allowPlanTool + ? [ + ...effectiveTools, + { + name: PLAN_TOOL_NAME, + description: + `Plan up to ${maxPlanActions} commands for chained requests. ` + + `Args JSON: {"actions":[{"next":"","args":{...}}]}`, + }, + ] + : effectiveTools; + const assistLoop = getAssistLoopOptionsFromBuildEnv(); + const routerSystem = + assistRouterPrompt + + (typeof railroadMemoryBlock === "string" ? railroadMemoryBlock : ""); + const assist = await assistRemote( + routerSystem, + assistMessages, + optionsForAssist, + toolsForAssist, + undefined, + assistLoop + ); + const innerRounds = + typeof assist?.inner_rounds === "number" ? assist.inner_rounds : undefined; + if (innerRounds != null && innerRounds > 1) { + assistantLogger.debug("router", "Assist inner rounds", { innerRounds }); + } + if ((assist as any)?.quota) { + subscriptionService.updateFromQuota((assist as any).quota); + } + syncSubscriptionFromAssistRouterResponse(assist); + markAssistSupported(endpointKey); + + const assistNext = + typeof assist?.next === "string" ? assist.next.trim() : ""; + const assistArgs = isRecord(assist?.args) ? assist.args : {}; + + if (allowPlanTool && assistNext === PLAN_TOOL_NAME) { + const actions = parsePlannedActions( + assistArgs, + memberNameSet, + maxPlanActions + ); + if (actions.length > 0) { + assistantLogger.debug("router", "Assist returned action plan", { + count: actions.length, + }); + return { kind: "plan", actions }; + } + return { kind: "none" }; + } + + if ( + assistNext && + assistNext !== "chat" && + !effectiveOptionSet.has(assistNext) + ) { + assistantLogger.debug( + "router", + "Assist route rejected by family policy", + { + assistNext, + family: constrained.family, + constrained: constrained.constrained, + } + ); + return { kind: "none" }; + } + + if (assistNext && assistNext !== "chat" && memberNameSet.has(assistNext)) { + assistantLogger.debug("router", `Assist route selected: ${assistNext}`); + return { kind: "tool", next: assistNext, args: assistArgs }; + } + + if (assistNext === "chat") { + const content = + typeof assist?.content === "string" ? assist.content.trim() : ""; + if (content) { + return { kind: "chat", content }; + } + } + + return { kind: "none" }; + } catch (error) { + if (error instanceof QuotaExceededError || (error as any).isQuotaError) { + if ((error as any).quota) { + subscriptionService.updateFromQuota((error as any).quota); + } + return { + kind: "chat", + content: formatQuotaExceededMessage((error as Error).message), + }; + } + + const message = String(error || ""); + const assistUnsupported = + /\b404\b|not found|post with\s*\{op:\s*"?assist"?\}/i.test(message); + if (assistUnsupported) { + markAssistUnsupported(endpointKey); + assistantLogger.warn( + "router", + "Assist endpoint unavailable, using fallback." + ); + } else { + assistantLogger.warn( + "router", + "Assist route failed, using fallback.", + error + ); + } + return { kind: "none" }; + } +} diff --git a/browser/base/content/assistant/build/src/assistant/supervisorGates.ts b/browser/base/content/assistant/build/src/assistant/supervisorGates.ts new file mode 100644 index 0000000000000..34277f3f8e913 --- /dev/null +++ b/browser/base/content/assistant/build/src/assistant/supervisorGates.ts @@ -0,0 +1,106 @@ +/** + * Confirmation & ambiguity gates — checked BEFORE any routing. + * + * When the supervisor receives a new user message, these gates run first: + * - Confirmation gate: if a destructive action is pending and the user + * says "yes"/"no", routes directly to confirm_action (skips LLM). + * - Ambiguity gate: if the user was asked "tab group or bookmark folder?", + * routes to resolve_ambiguity based on their reply. + * + * If neither gate fires, normal routing proceeds. + */ +import type { + PendingAmbiguity, + PendingConfirmation, +} from "../services/interactionState.js"; +import { + looksLikeNewActionCommand, + parseAmbiguityResolution, +} from "../utils/routingUtils.js"; + +const CONFIRM_RE = /^(?:yes|confirm|do\s+it|go\s+ahead|approve|ok|okay)$/i; +const CANCEL_RE = /^(?:no|cancel|nevermind|don'?t|stop)$/i; + +type RouteGateDecision = { + kind: "route"; + next: "confirm_action" | "resolve_ambiguity" | "chat"; + args: Record; +}; + +type EndGateDecision = { + kind: "end"; +}; + +type ClearGateDecision = { + kind: "clear"; +}; + +type NoneGateDecision = { + kind: "none"; +}; + +export type ConfirmationGateDecision = + | RouteGateDecision + | EndGateDecision + | NoneGateDecision; + +export type AmbiguityGateDecision = + | RouteGateDecision + | ClearGateDecision + | NoneGateDecision; + +export function resolvePendingConfirmationGate(params: { + confirmationText: string; + pendingConfirmation: PendingConfirmation | null; + justRanConfirm: boolean; +}): ConfirmationGateDecision { + const { confirmationText, pendingConfirmation, justRanConfirm } = params; + const confirmMatch = CONFIRM_RE.test(confirmationText); + const cancelMatch = CANCEL_RE.test(confirmationText); + + if ((confirmMatch || cancelMatch) && pendingConfirmation && !justRanConfirm) { + return { + kind: "route", + next: "confirm_action", + args: { confirmed: confirmMatch }, + }; + } + + if (pendingConfirmation) { + return { kind: "end" }; + } + + return { kind: "none" }; +} + +export function resolvePendingAmbiguityGate(params: { + pendingAmbiguity: PendingAmbiguity | null; + confirmationText: string; + commandText: string; + lastWorker: string; +}): AmbiguityGateDecision { + const { pendingAmbiguity, confirmationText, commandText, lastWorker } = params; + if (!pendingAmbiguity) { + return { kind: "none" }; + } + + if (lastWorker === "resolve_ambiguity") { + return { kind: "route", next: "chat", args: {} }; + } + + const resolution = parseAmbiguityResolution(confirmationText); + if (resolution) { + return { + kind: "route", + next: "resolve_ambiguity", + args: { target: resolution }, + }; + } + + const wordCount = confirmationText.split(/\s+/).filter(Boolean).length; + if (!looksLikeNewActionCommand(commandText) && wordCount <= 3) { + return { kind: "route", next: "resolve_ambiguity", args: {} }; + } + + return { kind: "clear" }; +} diff --git a/browser/base/content/assistant/build/src/assistant/supervisorQueue.ts b/browser/base/content/assistant/build/src/assistant/supervisorQueue.ts new file mode 100644 index 0000000000000..8123e0251dad3 --- /dev/null +++ b/browser/base/content/assistant/build/src/assistant/supervisorQueue.ts @@ -0,0 +1,101 @@ +/** + * Command queue management for chained requests. + * + * Handles "do X and then Y" by maintaining a queue of commands. + * Decides which command to execute next, resumes continuation + * queues after confirmations, and enforces the max of 3 commands + * per chain. Called by the supervisor node on each iteration. + */ +import { splitCommandChain } from "./commandChain.js"; +import { looksLikeNewActionCommand } from "../utils/routingUtils.js"; + +export type QueueSource = "existing" | "continuation" | "parsed"; + +export type CommandQueuePlan = { + commandQueue: string[]; + activeCommand: string; + source: QueueSource; + truncated: boolean; + truncationNotice: string | null; +}; + +export function buildCommandQueuePlan(params: { + existingQueue: string[]; + continuationQueue: string[]; + latestTextRaw: string; + commandLine: string; + lastWorker: string; + justRanTool: boolean; + maxCommands: number; +}): CommandQueuePlan | null { + const { + existingQueue, + continuationQueue, + latestTextRaw, + commandLine, + lastWorker, + justRanTool, + maxCommands, + } = params; + + let commandQueue: string[]; + let source: QueueSource; + let truncated = false; + + if (existingQueue.length > 0) { + commandQueue = [...existingQueue]; + source = "existing"; + } else if (lastWorker === "confirm_action" && continuationQueue.length > 0) { + commandQueue = [...continuationQueue]; + source = "continuation"; + } else { + const split = splitCommandChain(latestTextRaw || commandLine, maxCommands); + commandQueue = [...split.commands]; + truncated = split.truncated; + source = "parsed"; + } + + if (commandQueue.length === 0 && commandLine) { + commandQueue = [commandLine]; + } + + if (justRanTool && commandQueue.length > 1) { + commandQueue = commandQueue.slice(1); + } + + const activeCommand = commandQueue[0] || commandLine; + if (!activeCommand) { + return null; + } + + const truncationNotice = + source === "parsed" && truncated + ? `I can run up to ${maxCommands} commands per request, so I will run the first ${maxCommands}.` + : null; + + return { + commandQueue, + activeCommand, + source, + truncated, + truncationNotice, + }; +} + +export function shouldClearContinuationQueue(params: { + hasContinuation: boolean; + shouldResumeContinuation: boolean; + justRanTool: boolean; + commandText: string; +}): boolean { + const { + hasContinuation, + shouldResumeContinuation, + justRanTool, + commandText, + } = params; + if (!hasContinuation || shouldResumeContinuation || justRanTool) { + return false; + } + return looksLikeNewActionCommand(commandText); +} diff --git a/browser/base/content/assistant/build/src/assistant/toolResultPresenter.ts b/browser/base/content/assistant/build/src/assistant/toolResultPresenter.ts new file mode 100644 index 0000000000000..cfb69a1675a6a --- /dev/null +++ b/browser/base/content/assistant/build/src/assistant/toolResultPresenter.ts @@ -0,0 +1,202 @@ +/** + * Tool result presenter — formats raw command output for display. + * + * Converts JSON tool output into user-friendly text: + * - list_bookmark_folders: bullet list of folder names + * - list_tab_groups: names with tab counts and collapsed state + * - list_tabs: formatted titles and URLs + * - search_memory/get_recent_search_results: structured results + * + * Called by the chat node before sending output to the user. + */ +import type { ToolResultPayload } from "./messageUtils.js"; + +type SearchResultRow = { + index?: number; + source?: string; + title?: string; + url?: string; + context?: string; + snippet?: string; +}; + +function safeParseJson(value: string): unknown { + try { + return JSON.parse(value); + } catch { + return null; + } +} + +function toStringList(value: unknown): string[] { + if (!Array.isArray(value)) { + return []; + } + return value + .map(item => (typeof item === "string" ? item.trim() : "")) + .filter(Boolean); +} + +function toObjectList>(value: unknown): T[] { + if (!Array.isArray(value)) { + return []; + } + return value.filter( + item => !!item && typeof item === "object" && !Array.isArray(item) + ) as T[]; +} + +function formatLines(title: string, lines: string[]): string { + if (lines.length === 0) { + return title; + } + return `${title}\n\n${lines.map(line => `- ${line}`).join("\n")}`; +} + +function formatListBookmarkFolders(message: string): string { + const parsed = safeParseJson(message); + const rows = toStringList(parsed); + if (rows.length === 0) { + return message; + } + return formatLines("Here are your bookmark folders:", rows); +} + +function formatListTabGroups(message: string): string { + const parsed = safeParseJson(message); + const rows = toObjectList<{ + name?: unknown; + tabCount?: unknown; + collapsed?: unknown; + }>(parsed); + if (rows.length === 0) { + return message; + } + + const lines = rows.map(row => { + const name = typeof row.name === "string" ? row.name : "(unnamed)"; + const tabCount = + typeof row.tabCount === "number" && Number.isFinite(row.tabCount) + ? row.tabCount + : 0; + const collapsed = row.collapsed === true ? "collapsed" : "expanded"; + return `${name} (${tabCount} tabs, ${collapsed})`; + }); + return formatLines("Here are your tab groups:", lines); +} + +function extractJsonArrayTail(message: string): unknown { + const colon = message.indexOf(":"); + if (colon < 0) { + return null; + } + const tail = message.slice(colon + 1).trim(); + if (!tail.startsWith("[")) { + return null; + } + return safeParseJson(tail); +} + +function formatListTabs(message: string): string { + const parsedTop = safeParseJson(message); + const strings = toStringList(parsedTop); + if (strings.length > 0) { + return formatLines("Here are your open tabs:", strings); + } + + const tail = extractJsonArrayTail(message); + const rows = toObjectList<{ title?: unknown; url?: unknown }>(tail); + if (rows.length === 0) { + return message; + } + + const containerMatch = message.match(/^Tabs in ([^:]+):/i); + const container = containerMatch?.[1]?.trim() || "the requested target"; + const lines = rows.map(row => { + const title = typeof row.title === "string" ? row.title : "(untitled)"; + const url = typeof row.url === "string" ? row.url : ""; + return url ? `${title} (${url})` : title; + }); + return formatLines(`Here are the tabs in ${container}:`, lines); +} + +function formatSearchResults(message: string): string { + const parsed = safeParseJson(message) as + | { + summary?: unknown; + results?: unknown; + } + | null; + if (!parsed || typeof parsed !== "object") { + return message; + } + const summary = + typeof parsed.summary === "string" ? parsed.summary.trim() : "Search results:"; + const rows = toObjectList(parsed.results).slice(0, 10); + if (rows.length === 0) { + return summary || message; + } + + const lines = rows.map(row => { + const index = + typeof row.index === "number" && Number.isFinite(row.index) + ? row.index + : undefined; + const title = typeof row.title === "string" ? row.title : "(untitled)"; + const url = typeof row.url === "string" ? row.url : ""; + const prefix = index != null ? `${index}. ` : ""; + return url ? `${prefix}${title} (${url})` : `${prefix}${title}`; + }); + return formatLines(summary, lines); +} + +type HistorySearchRow = { + index?: number; + title?: string; + url?: string; + relevance?: string; + visited?: string; +}; + +function formatHistorySearchResults(message: string): string { + const parsed = safeParseJson(message); + const rows = toObjectList(parsed); + if (rows.length === 0) { + return message; + } + + const lines = rows.map(row => { + const idx = typeof row.index === "number" ? `${row.index}. ` : ""; + const title = typeof row.title === "string" ? row.title : "(untitled)"; + const url = typeof row.url === "string" ? row.url : ""; + const relevance = typeof row.relevance === "string" ? ` (${row.relevance} match)` : ""; + const visited = typeof row.visited === "string" ? ` — visited ${row.visited}` : ""; + return url + ? `${idx}[**${title}**](${url})${relevance}${visited}` + : `${idx}**${title}**${relevance}${visited}`; + }); + return `Here's what I found in your browsing history:\n\n${lines.join("\n\n")}`; +} + +export function presentToolResult(payload: ToolResultPayload): string { + const message = String(payload.message || "").trim(); + if (!message) { + return "Done."; + } + + switch (payload.commandName) { + case "list_bookmark_folders": + return formatListBookmarkFolders(message); + case "list_tab_groups": + return formatListTabGroups(message); + case "list_tabs": + return formatListTabs(message); + case "search_memory": + case "get_recent_search_results": + return formatSearchResults(message); + case "search_history": + return formatHistorySearchResults(message); + default: + return message; + } +} diff --git a/browser/base/content/assistant/build/src/awsSignedFetch.ts b/browser/base/content/assistant/build/src/awsSignedFetch.ts new file mode 100644 index 0000000000000..08c4ef529b988 --- /dev/null +++ b/browser/base/content/assistant/build/src/awsSignedFetch.ts @@ -0,0 +1,94 @@ +/** HTTP client for assist (Supabase) and voice Lambda (IAM SigV4 + JWT in x-oasis-authorization). */ +import SupabaseAuth from "./services/supabase.js"; +import { assistantLogger } from "./utils/assistantLogger.js"; +import { postVoiceLambdaWithIam } from "./voiceLambdaIamFetch.js"; + +export class QuotaExceededError extends Error { + quota: any; + isQuotaError = true; + constructor(message: string, quota: any) { + super(message); + this.name = "QuotaExceededError"; + this.quota = quota; + } +} + +const normalizeEndpoint = (value: string | undefined): string => + String(value || "") + .trim() + .replace(/\/+$/, ""); + +const assistantUrl = normalizeEndpoint(process.env.OASIS_ASSIST_URL); +const transcribeUrl = normalizeEndpoint(process.env.OASIS_TRANSCRIBE_URL); +const supabaseAuth = SupabaseAuth.getInstance(); + +type SignedOperation = "assist" | "transcribe" | "tts"; +const endpointByOperation: Record = { + assist: assistantUrl, + transcribe: transcribeUrl, + tts: transcribeUrl, +}; +const endpointEnvByOperation: Record = { + assist: "OASIS_ASSIST_URL", + transcribe: "OASIS_TRANSCRIBE_URL", + tts: "OASIS_TRANSCRIBE_URL", +}; + +export function getAssistantApiBase(): string { + return assistantUrl; +} + +export async function postSigned>( + op: SignedOperation, + payload: Record +): Promise { + const endpoint = endpointByOperation[op]; + if (!endpoint) { + throw new Error( + `Endpoint not configured for operation "${op}". Missing ${endpointEnvByOperation[op]}.` + ); + } + + const body = JSON.stringify({ op, ...payload }); + + const session = await supabaseAuth.getSession(); + const token = session?.access_token; + const requiresJwt = op !== "assist"; + if (requiresJwt && !token) { + throw new Error("Authentication required: No JWT found"); + } + + const headers: Record = { + "content-type": "application/json", + }; + + if (token) { + headers.Authorization = `Bearer ${token}`; + } + + const res = + op === "transcribe" || op === "tts" + ? await postVoiceLambdaWithIam(endpoint, body, token) + : await fetch(endpoint, { method: "POST", headers, body }); + + if (!res.ok) { + const errorBody = await res.text(); + if (res.status === 429 && op === "assist") { + try { + const parsed = JSON.parse(errorBody); + if (parsed.error === "quota_exceeded") { + throw new QuotaExceededError(parsed.message || "Usage limit reached.", parsed.quota); + } + } catch (e: any) { + if (e.isQuotaError) throw e; + } + } + assistantLogger.error("transport", "Assistant backend error", { + op, + status: res.status, + errorBody, + }); + throw new Error(`Assistant backend ${res.status} ${errorBody}`); + } + return res.json() as Promise; +} diff --git a/browser/base/content/assistant/build/src/bookmarkFolders.ts b/browser/base/content/assistant/build/src/bookmarkFolders.ts new file mode 100644 index 0000000000000..45c317f1bf6b3 --- /dev/null +++ b/browser/base/content/assistant/build/src/bookmarkFolders.ts @@ -0,0 +1,607 @@ +/** + * Bookmark folder manager — CRUD operations for managed bookmark folders. + * + * Creates/deletes/renames bookmark folders under a root "Oasis Hubs" folder + * in Firefox's bookmarks system (PlacesUtils). Handles tab-to-bookmark + * operations, content extraction, and syncs changes to localMemory. + * Listens for Places events to keep the routing state cache in sync. + */ +import { + localMemory, + type BookmarkFolderMemoryEntry, +} from "./services/localMemory.js"; +import { + fetchBookmarkByGuid, + fetchChildrenBookmarks, + getChromeContext, + getSystemPrincipal, + getTabs, + normalizeName, + tabTitle, + tabUrl, + toUrlString, +} from "./services/firefoxFacade.js"; +import type { BrowserTabLike, PlacesBookmarkEntry, PlacesUtilsLike } from "./types/runtime.js"; +import { assistantLogger } from "./utils/assistantLogger.js"; +import { OASIS_EVENT_BOOKMARK_FOLDERS_CHANGED } from "../../shared/contracts.js"; + +type FolderItem = { url: string; title?: string; host: string; id: string }; +type BookmarkNode = PlacesBookmarkEntry & { uri?: string }; +type PlacesEventLike = { + guid?: string; + parentGuid?: string; + oldParentGuid?: string; +}; + +const ROOT_FOLDER_NAME = "Oasis Hubs"; + +function hostOf(url: string): string { + try { + return new URL(url).host.toLowerCase(); + } catch { + return ""; + } +} + +function bookmarkUri(bookmark: PlacesBookmarkEntry): string { + return toUrlString(bookmark.url) || String(bookmark.uri || "").trim(); +} + +function isFolderNode(places: PlacesUtilsLike | null, bookmark: PlacesBookmarkEntry): boolean { + return bookmark.type === places?.bookmarks?.TYPE_FOLDER; +} + +function isBookmarkNode(places: PlacesUtilsLike | null, bookmark: PlacesBookmarkEntry): boolean { + return bookmark.type === places?.bookmarks?.TYPE_BOOKMARK; +} + +async function findRootFolderId(places: PlacesUtilsLike | null): Promise { + if (!places?.bookmarks?.search || !places.bookmarks.unfiledGuid) return null; + const results = await places.bookmarks.search({ title: ROOT_FOLDER_NAME }); + const existing = results.find( + bookmark => + isFolderNode(places, bookmark) && + bookmark.parentGuid === places.bookmarks?.unfiledGuid + ); + return existing?.guid || null; +} + +async function ensureRootFolderId(places: PlacesUtilsLike | null): Promise { + if (!places?.bookmarks) throw new Error("PlacesUtils.bookmarks not available"); + const existing = await findRootFolderId(places); + if (existing) return existing; + if (!places.bookmarks.insert) throw new Error("Bookmarks insert API not available"); + + const root = await places.bookmarks.insert({ + title: ROOT_FOLDER_NAME, + type: places.bookmarks.TYPE_FOLDER, + parentGuid: places.bookmarks.unfiledGuid, + }); + return root.guid; +} + +async function getBookmarkChildren( + places: PlacesUtilsLike | null, + guid: string +): Promise { + if (!places?.bookmarks?.fetch || !guid) return []; + const parent = await fetchBookmarkByGuid(places, guid); + if (!parent) return []; + + const children = await fetchChildrenBookmarks(places, guid); + return children.map(child => ({ + ...child, + uri: bookmarkUri(child), + })); +} + +async function createBookmark( + places: PlacesUtilsLike | null, + details: { + parentGuid: string; + title: string; + url?: string; + type?: number; + } +): Promise { + if (!places?.bookmarks?.insert) throw new Error("Bookmarks insert API not available"); + const created = await places.bookmarks.insert({ + parentGuid: details.parentGuid, + title: details.title, + url: details.url, + type: + details.type || + (details.url + ? places.bookmarks.TYPE_BOOKMARK + : places.bookmarks.TYPE_FOLDER), + }); + return { ...created, uri: bookmarkUri(created) }; +} + +async function removeBookmark(places: PlacesUtilsLike | null, guid: string): Promise { + if (!places?.bookmarks?.remove) return; + await places.bookmarks.remove(guid); +} + +async function updateBookmark( + places: PlacesUtilsLike | null, + guid: string, + changes: { title?: string } +): Promise { + if (!places?.bookmarks?.update) throw new Error("Bookmarks update API not available"); + const updated = await places.bookmarks.update({ guid, ...changes }); + return { ...updated, uri: bookmarkUri(updated) }; +} + +export type CreateFolderOpts = { include?: "none" | "current" | "all" }; +export type DeleteFolderOpts = { closeTabs?: boolean }; + +class BookmarkFolderManager { + private rootFolderId: string | null = null; + private placesObserverRegistered = false; + private managedFolderGuids = new Set(); + private syncTimer: number | null = null; + private syncInFlight = false; + + constructor() { + this.ensurePlacesObserver(); + this.scheduleManagedFolderSync("startup"); + } + + private emitFoldersChanged(folderNames: string[] = []): void { + try { + window.dispatchEvent( + new CustomEvent(OASIS_EVENT_BOOKMARK_FOLDERS_CHANGED, { + detail: { folderNames }, + }) + ); + } catch (error) { + assistantLogger.warn("bookmark-folders", "failed to emit folder change event", error); + } + } + + private ensurePlacesObserver(): void { + if (this.placesObserverRegistered) return; + const { PlacesUtils } = getChromeContext(); + if (!PlacesUtils?.observers?.addListener) return; + + PlacesUtils.observers.addListener( + [ + "bookmark-added", + "bookmark-removed", + "bookmark-moved", + "bookmark-title-changed", + "bookmark-url-changed", + ], + this.handlePlacesEvents + ); + this.placesObserverRegistered = true; + } + + private handlePlacesEvents = async (events: unknown[]): Promise => { + try { + const rootId = await this.ensureExistingRootFolder(); + if (!rootId) return; + + let isRelevant = false; + for (const rawEvent of events || []) { + const event = (rawEvent || {}) as PlacesEventLike; + const guid = String(event.guid || ""); + const parentGuid = String(event.parentGuid || ""); + const oldParentGuid = String(event.oldParentGuid || ""); + if ( + guid === rootId || + parentGuid === rootId || + oldParentGuid === rootId || + this.managedFolderGuids.has(guid) || + this.managedFolderGuids.has(parentGuid) || + this.managedFolderGuids.has(oldParentGuid) + ) { + isRelevant = true; + break; + } + } + + if (!isRelevant) return; + this.scheduleManagedFolderSync("places-event"); + } catch (error) { + assistantLogger.warn("bookmark-folders", "places event processing failed", error); + } + }; + + private scheduleManagedFolderSync(reason: string): void { + this.ensurePlacesObserver(); + if (this.syncTimer != null) return; + this.syncTimer = window.setTimeout(() => { + this.syncTimer = null; + void this.syncManagedFolderMemoryFromBookmarks(reason); + }, 250); + } + + private async ensureRootFolder(): Promise { + this.ensurePlacesObserver(); + if (this.rootFolderId) return this.rootFolderId; + const { PlacesUtils } = getChromeContext(); + this.rootFolderId = await ensureRootFolderId(PlacesUtils); + return this.rootFolderId; + } + + private async ensureExistingRootFolder(): Promise { + this.ensurePlacesObserver(); + const { PlacesUtils } = getChromeContext(); + if (!PlacesUtils?.bookmarks?.fetch) { + this.rootFolderId = null; + return null; + } + + if (this.rootFolderId) { + const existing = await fetchBookmarkByGuid(PlacesUtils, this.rootFolderId); + if (existing) return this.rootFolderId; + this.rootFolderId = null; + } + + const rootId = await findRootFolderId(PlacesUtils); + if (rootId) this.rootFolderId = rootId; + return rootId; + } + + private async getFolderNodes(rootId: string): Promise { + const { PlacesUtils } = getChromeContext(); + const children = await getBookmarkChildren(PlacesUtils, rootId); + return children.filter(child => isFolderNode(PlacesUtils, child)); + } + + private async findFolderNode(rootId: string, name: string): Promise { + const target = normalizeName(name); + if (!target) return null; + const folders = await this.getFolderNodes(rootId); + return ( + folders.find(folder => normalizeName(folder.title || "") === target) || null + ); + } + + private async collectFolders( + rootId: string + ): Promise> { + const { PlacesUtils } = getChromeContext(); + const folders = await this.getFolderNodes(rootId); + const result: Array<{ name: string; items: FolderItem[] }> = []; + + for (const folder of folders) { + const bookmarks = await getBookmarkChildren(PlacesUtils, folder.guid); + const items: FolderItem[] = bookmarks + .filter(bookmark => !!bookmark.uri) + .map(bookmark => ({ + id: bookmark.guid, + url: String(bookmark.uri), + title: bookmark.title, + host: hostOf(String(bookmark.uri)), + })); + result.push({ name: folder.title || "Untitled", items }); + } + + return result; + } + + private async syncManagedFolderMemoryFromBookmarks(reason: string): Promise { + if (this.syncInFlight) return; + this.syncInFlight = true; + try { + const { PlacesUtils } = getChromeContext(); + const rootId = await this.ensureExistingRootFolder(); + if (!rootId) { + this.managedFolderGuids.clear(); + const removed = await localMemory.removeAllBookmarkFolderDocuments(); + if (removed > 0) { + assistantLogger.debug( + "bookmark-folders", + `managed folder root missing; removed ${removed} memory docs` + ); + } + this.emitFoldersChanged([]); + return; + } + + const folders = await this.getFolderNodes(rootId); + this.managedFolderGuids = new Set(folders.map(folder => folder.guid)); + + const folderNames: string[] = []; + const entries: BookmarkFolderMemoryEntry[] = []; + + for (const folder of folders) { + const folderName = folder.title || "Untitled"; + folderNames.push(folderName); + const bookmarks = await getBookmarkChildren(PlacesUtils, folder.guid); + for (const bookmark of bookmarks) { + if (!bookmark.uri || !isBookmarkNode(PlacesUtils, bookmark)) continue; + entries.push({ + bookmarkGuid: bookmark.guid, + parentGuid: folder.guid, + folderName, + title: bookmark.title || bookmark.uri, + url: bookmark.uri, + }); + } + } + + const syncResult = await localMemory.syncBookmarkFolderDocuments(entries); + this.emitFoldersChanged(folderNames); + assistantLogger.debug( + "bookmark-folders", + `sync complete reason=${reason} folders=${folderNames.length} added=${syncResult.added} updated=${syncResult.updated} removed=${syncResult.removed}` + ); + } catch (error) { + assistantLogger.warn("bookmark-folders", "managed folder sync failed", error); + } finally { + this.syncInFlight = false; + } + } + + async list(): Promise> { + try { + const { PlacesUtils } = getChromeContext(); + const rootId = await this.ensureRootFolder(); + const folders = await this.getFolderNodes(rootId); + const result: Array<{ name: string; count: number }> = []; + + for (const folder of folders) { + const items = await getBookmarkChildren(PlacesUtils, folder.guid); + result.push({ name: folder.title || "Untitled", count: items.length }); + } + return result; + } catch (error) { + assistantLogger.error("bookmark-folders", "Failed to list bookmark folders", error); + return []; + } + } + + async getAll(): Promise> { + try { + const rootId = await this.ensureRootFolder(); + return await this.collectFolders(rootId); + } catch (error) { + assistantLogger.error("bookmark-folders", "Failed to get all bookmark folders", error); + return []; + } + } + + async getAllReadOnly(): Promise<{ + ok: boolean; + folders: Array<{ name: string; items: FolderItem[] }>; + }> { + try { + const rootId = await this.ensureExistingRootFolder(); + if (!rootId) return { ok: true, folders: [] }; + const folders = await this.collectFolders(rootId); + return { ok: true, folders }; + } catch (error) { + assistantLogger.warn("bookmark-folders", "read-only folder lookup failed", error); + return { ok: false, folders: [] }; + } + } + + async create(name: string, opts?: CreateFolderOpts): Promise<{ name: string; count: number }> { + const context = getChromeContext(); + const places = context.PlacesUtils; + const normalizedName = (name || "").trim() || this.suggestName(); + const rootId = await this.ensureRootFolder(); + let folder = await this.findFolderNode(rootId, normalizedName); + + if (!folder) { + folder = await createBookmark(places, { + parentGuid: rootId, + title: normalizedName, + }); + } + + const include = opts?.include || "none"; + const tabs = getTabs(context.gBrowser); + let count = 0; + + if (include === "current" && tabs.length > 0) { + const current = context.gBrowser?.selectedTab || tabs[0]; + if (current) { + await this.addTabs(folder.title || normalizedName, [current]); + count = 1; + } + } else if (include === "all" && tabs.length > 0) { + await this.addTabs(folder.title || normalizedName, tabs); + count = tabs.length; + } + + this.scheduleManagedFolderSync("create-folder"); + return { name: folder.title || normalizedName, count }; + } + + async delete( + name: string, + opts?: DeleteFolderOpts + ): Promise<{ name: string; removed: number }> { + const context = getChromeContext(); + const rootId = await this.ensureRootFolder(); + const folder = await this.findFolderNode(rootId, name); + if (!folder) return { name, removed: 0 }; + + const items = await getBookmarkChildren(context.PlacesUtils, folder.guid); + const bookmarks = items.filter(bookmark => !!bookmark.uri); + + if (opts?.closeTabs) { + const hostSet = new Set(bookmarks.map(bookmark => hostOf(String(bookmark.uri)))); + for (const tab of getTabs(context.gBrowser)) { + if (hostSet.has(hostOf(tabUrl(tab)))) { + context.gBrowser?.removeTab?.(tab); + } + } + } + + await removeBookmark(context.PlacesUtils, folder.guid); + await localMemory.removeBookmarkFolderDocuments(folder.title || name); + this.scheduleManagedFolderSync("delete-folder"); + return { name: folder.title || name, removed: bookmarks.length }; + } + + async rename( + oldName: string, + newName: string + ): Promise<{ ok: boolean; msg?: string }> { + const normalizedOld = (oldName || "").trim(); + const normalizedNew = (newName || "").trim(); + if (!normalizedOld || !normalizedNew) return { ok: false }; + + const context = getChromeContext(); + const rootId = await this.ensureRootFolder(); + const folder = await this.findFolderNode(rootId, normalizedOld); + if (!folder) return { ok: false }; + + const existing = await this.findFolderNode(rootId, normalizedNew); + if (existing) return { ok: false, msg: "Target exists" }; + + await updateBookmark(context.PlacesUtils, folder.guid, { title: normalizedNew }); + await localMemory.renameBookmarkFolderDocuments(folder.title || normalizedOld, normalizedNew); + this.scheduleManagedFolderSync("rename-folder"); + return { ok: true }; + } + + async addTabs(name: string, tabs: BrowserTabLike[]): Promise<{ ok: boolean }> { + const context = getChromeContext(); + const rootId = await this.ensureRootFolder(); + let folder = await this.findFolderNode(rootId, name); + + if (!folder) { + folder = await createBookmark(context.PlacesUtils, { + parentGuid: rootId, + title: name, + }); + } + + for (const tab of tabs) { + await this.addTabToFolder(folder.guid, tab, folder.title || name); + } + + this.scheduleManagedFolderSync("add-tabs"); + return { ok: true }; + } + + async removeUrl(name: string, url: string): Promise<{ ok: boolean }> { + const normalizedName = (name || "").trim(); + const rootId = await this.ensureRootFolder(); + const folder = await this.findFolderNode(rootId, normalizedName); + if (!folder) return { ok: false }; + + const bookmarks = await getBookmarkChildren(getChromeContext().PlacesUtils, folder.guid); + const toRemove = bookmarks.filter(bookmark => bookmark.uri === url); + for (const bookmark of toRemove) { + await removeBookmark(getChromeContext().PlacesUtils, bookmark.guid); + } + + if (toRemove.length > 0) { + await localMemory.removeBookmarkFolderDocumentByUrl(folder.title || normalizedName, url); + this.scheduleManagedFolderSync("remove-url"); + } + + return { ok: toRemove.length > 0 }; + } + + async openFolder( + name: string, + where: "tabs" | "window" | "tabgroup" = "tabs" + ): Promise<{ ok: boolean }> { + const normalizedName = (name || "").trim(); + const context = getChromeContext(); + const rootId = await this.ensureRootFolder(); + const folder = await this.findFolderNode(rootId, normalizedName); + if (!folder) return { ok: false }; + + const bookmarks = await getBookmarkChildren(context.PlacesUtils, folder.guid); + const urls = bookmarks + .filter(bookmark => !!bookmark.uri) + .map(bookmark => String(bookmark.uri)); + if (urls.length === 0) return { ok: true }; + + let targetBrowser = context.gBrowser; + if (where === "window") { + const newWindow = context.topWin?.OpenBrowserWindow?.(); + if (!newWindow) return { ok: false }; + await new Promise(resolve => setTimeout(resolve, 250)); + targetBrowser = newWindow.gBrowser || null; + } + + if (!targetBrowser?.addTrustedTab) return { ok: false }; + const principal = getSystemPrincipal(context.Services); + const openedTabs: BrowserTabLike[] = []; + + for (const url of urls) { + try { + const tab = targetBrowser.addTrustedTab(url, { + triggeringPrincipal: principal, + relatedToCurrent: false, + }); + if (tab) openedTabs.push(tab); + } catch (error) { + assistantLogger.error("bookmark-folders", `Failed to open tab for URL: ${url}`, error); + } + } + + if (where === "tabgroup" && openedTabs.length > 0) { + try { + targetBrowser.addTabGroup?.(openedTabs, { label: normalizedName }); + } catch (error) { + assistantLogger.warn("bookmark-folders", "Failed to group opened tabs", error); + } + } + + return { ok: true }; + } + + private async addTabToFolder( + folderGuid: string, + tab: BrowserTabLike, + folderName?: string + ): Promise { + const url = tabUrl(tab); + if (!url) return; + + const title = tabTitle(tab); + const context = getChromeContext(); + const existing = await getBookmarkChildren(context.PlacesUtils, folderGuid); + const alreadyExists = existing.some(bookmark => bookmark.uri === url); + if (alreadyExists) return; + + const createdBookmark = await createBookmark(context.PlacesUtils, { + parentGuid: folderGuid, + title, + url, + }); + + let content = ""; + try { + const bodyText = tab.linkedBrowser?.contentDocument?.body?.innerText || ""; + content = String(bodyText).substring(0, 5000); + } catch (error) { + assistantLogger.warn("bookmark-folders", "Failed to extract tab content", error); + } + + const text = `Title: ${title}\nURL: ${url}\nContent: ${content}`; + await localMemory.addDocument( + text, + { + title, + type: "bookmark_folder_item", + hub: folderGuid, + hubName: folderName, + folderName, + url, + bookmarkGuid: createdBookmark.guid, + parentGuid: folderGuid, + description: content.substring(0, 200), + }, + url + ); + } + + private suggestName(): string { + return "Folder 1"; + } +} + +export const bookmarkFolders = new BookmarkFolderManager(); diff --git a/browser/base/content/assistant/build/src/commands.ts b/browser/base/content/assistant/build/src/commands.ts new file mode 100644 index 0000000000000..fbb336ff2d289 --- /dev/null +++ b/browser/base/content/assistant/build/src/commands.ts @@ -0,0 +1,2420 @@ +/** + * All browser command implementations. + * + * Each command is a class implementing the Command interface with: + * - commandName: identifier used for routing (e.g. "close_tab") + * - description: human-readable text sent to the LLM for tool selection + * - execute(args): performs the browser action and returns a result + * + * Commands cover: tab management, navigation, bookmark folders, tab groups, + * search (full-text + semantic), window management, page summarization, + * and interaction flows (confirmation, ambiguity resolution). + */ +import { bookmarkFolders, CreateFolderOpts } from "./bookmarkFolders"; +import { localMemory } from "./services/localMemory"; +import { subscriptionService } from "./services/subscription"; +import { fetchRecentHistory } from "./services/historyCollector"; +import { semanticHistorySearch } from "./services/semanticHistorySearch"; +import { + buildFolderUrlMap, + filterStaleBookmarkFolderResults, + hasBookmarkFolderCandidates, +} from "./utils/searchMemoryUtils"; +import { getMemoryDocSource } from "./utils/localMemoryUtils"; +import { assistantLogger } from "./utils/assistantLogger"; +import { + applyRoutingStateMutation, + markRoutingStateDirty, +} from "./utils/deterministicRouter"; +import { + findGroupByName, + findTabByIndex, + findTabsByQuery, + getChromeContext, + getTabGroups, + getTabs, + normalizeName, + tabTitle, + tabUrl, + toUrlString, + withUriFixup, +} from "./services/firefoxFacade"; +import { + clearPendingAmbiguity, + clearContinuationQueue, + clearPendingConfirmation, + clearRecentSearchResults, + getRecentSearchResults, + getPendingAmbiguity, + getPendingConfirmation, + setRecentSearchResults, + setPendingConfirmation, + type AmbiguityTarget, + type InteractionCommandArgs, + type RecentSearchResult, +} from "./services/interactionState"; +import { + getCommandExecutor, + listRegisteredCommandNames, +} from "./services/commandExecutionRegistry"; +import type { + GBrowserLike, + BrowserTabLike, + BrowserWindowLike, +} from "./types/runtime"; + +type CommandArgs = InteractionCommandArgs; +type SearchResultItem = { + title: string; + url: string; + snippet: string; + bookmarkGuid?: string; +}; + +export type CmdResult = { + message: string; + requiresConfirmation?: boolean; + confirmationData?: Record; +}; + +export interface Command { + commandName: string; + description: string; + execute(args: CommandArgs): Promise; +} + +/** Get the privileged top-level browser window/objects */ +function getChrome() { + const { topWin, gBrowser, Services, PlacesUtils } = getChromeContext(); + return { topWin, gBrowser, Services, PlacesUtils }; +} + +function stringArg(args: CommandArgs, key: string): string | undefined { + const value = args[key]; + return typeof value === "string" ? value : undefined; +} + +function numberArg(args: CommandArgs, key: string): number | undefined { + const value = args[key]; + return typeof value === "number" && Number.isFinite(value) + ? value + : undefined; +} + +function booleanArg(args: CommandArgs, key: string): boolean | undefined { + const value = args[key]; + return typeof value === "boolean" ? value : undefined; +} + +function numberArrayArg(args: CommandArgs, key: string): number[] { + const value = args[key]; + if (!Array.isArray(value)) return []; + return value + .map(item => + typeof item === "number" && Number.isFinite(item) ? item : null + ) + .filter((item): item is number => item != null); +} + +function ambiguityTargetArg( + args: CommandArgs +): AmbiguityTarget | "cancel" | undefined { + const value = stringArg(args, "target"); + if (!value) { + return undefined; + } + const normalized = value.trim().toLowerCase(); + if ( + normalized === "bookmark-folder" || + normalized === "tab-group" || + normalized === "tab" || + normalized === "cancel" + ) { + return normalized; + } + return undefined; +} + +function tabByIndexOrCurrent( + gBrowser: GBrowserLike | null, + index: number | undefined +): BrowserTabLike | null { + if (index == null) return gBrowser?.selectedTab || null; + return findTabByIndex(gBrowser, index); +} + +function tabByIndex( + gBrowser: { tabs: ArrayLike }, + index: number +): BrowserTabLike | null { + const i = Math.max(1, Math.floor(index)); + const tabs = Array.from(gBrowser.tabs); + if (i > tabs.length) return null; + return tabs[i - 1] || null; +} + +type GBrowserTabOps = GBrowserLike & { + reloadTab?: (tab: BrowserTabLike) => void; + addAdjacentNewTab?: (tab: BrowserTabLike) => void; + pinTab?: (tab: BrowserTabLike, opts?: unknown) => void; + unpinTab?: (tab: BrowserTabLike) => void; + duplicateTab?: (tab: BrowserTabLike, ...rest: unknown[]) => unknown; + explicitUnloadTabs?: (tabs: BrowserTabLike[]) => Promise; + removeTabs?: (tabs: BrowserTabLike[], opts?: Record) => void; + getDuplicateTabsToClose?: (tab: BrowserTabLike) => BrowserTabLike[]; + _getTabsToTheEndFrom?: (tab: BrowserTabLike) => BrowserTabLike[]; + _getTabsToTheStartFrom?: (tab: BrowserTabLike) => BrowserTabLike[]; + removeAllTabsBut?: ( + tab: BrowserTabLike, + opts?: Record + ) => void; + selectAllTabs?: () => void; + moveTabToStart?: (tab: BrowserTabLike) => void; + moveTabToEnd?: (tab: BrowserTabLike) => void; + tabNoteMenu?: { openPanel?: (tab: BrowserTabLike, opts?: unknown) => void }; +}; + +function asTabOps(gBrowser: GBrowserLike | null): GBrowserTabOps | null { + return gBrowser as GBrowserTabOps | null; +} + +type BrowserChromeExtras = BrowserWindowLike & { + PlacesCommandHook?: { bookmarkTabs?: (tabs: BrowserTabLike[]) => void }; + SessionStore?: { undoCloseTab?: (win: Window, index?: number) => unknown }; + gSync?: { showSendToDeviceViewFromFxaMenu?: (anchor: Element) => void }; +}; + +function normalizeQuery(value: string | undefined): string { + return (value || "").trim().toLowerCase(); +} + +function toWebSearchUrl(query: string): string { + return `https://www.google.com/search?q=${encodeURIComponent(query)}`; +} + +function analyzeGroupMoveImpact(tabsToMove: BrowserTabLike[]): { + affectedGroups: string[]; + emptiedGroups: string[]; +} { + const affectedGroups = new Set(); + const emptiedGroups = new Set(); + + for (const tab of tabsToMove) { + const group = tab.group; + if (!group) continue; + + const groupName = group.label || "(unnamed)"; + affectedGroups.add(groupName); + + const groupTabs = group.tabs || []; + const movingTabs = groupTabs.filter(groupTab => + tabsToMove.includes(groupTab) + ); + if (groupTabs.length > 0 && movingTabs.length === groupTabs.length) { + emptiedGroups.add(groupName); + } + } + + return { + affectedGroups: Array.from(affectedGroups), + emptiedGroups: Array.from(emptiedGroups), + }; +} + +const LIST_WINDOW_SCOPE_ALIASES = new Set([ + "window", + "current window", + "this window", + "open tabs", + "all open tabs", + "tabs", + "all tabs", + "my tabs", + "current tabs", + "active tabs", +]); + +function normalizeListTargetName(value: string): string { + let next = String(value || "") + .replace(/["']/g, " ") + .trim(); + next = next.replace(/^\s*(?:my|the)\s+/i, ""); + next = next.replace( + /\s+(?:tab\s*group|bookmark\s*folder|folder|group|hub)\s*$/i, + "" + ); + return next.trim(); +} + +/* =========================== + * Tab Commands + * =========================== */ + +export class ListTabsCommand implements Command { + commandName = "list_tabs"; + description = + "List tabs. Accepts optional arguments: { scope?: 'window'|'tab-group'|'bookmark-folder', name?: string }. If name is provided without scope, resolves tab-group vs bookmark-folder by runtime state."; + async execute(args: CommandArgs): Promise { + const { gBrowser } = getChrome(); + if (!gBrowser) return { message: "Browser UI (gBrowser) not available." }; + + const scope = normalizeName(stringArg(args, "scope") || ""); + const name = normalizeListTargetName(stringArg(args, "name") || ""); + + const listWindowTabs = (): CmdResult => { + const titles = getTabs(gBrowser).map(tab => tabTitle(tab)); + return { message: JSON.stringify(titles.slice(0, 50)) }; + }; + + const listGroupTabs = (groupName: string): CmdResult => { + if (!groupName) { + return { message: "Which tab group should I list tabs from?" }; + } + const group = findGroupByName(gBrowser, groupName); + if (!group) { + return { message: `No tab group named "${groupName}".` }; + } + + const tabs = (group.tabs || []).slice(0, 50).map(tab => ({ + title: tabTitle(tab), + url: tabUrl(tab), + })); + if (tabs.length === 0) { + return { message: `Tab group "${groupName}" has no tabs.` }; + } + return { + message: `Tabs in tab group "${group.label || groupName}": ${JSON.stringify(tabs)}`, + }; + }; + + const listFolderTabs = async (folderName: string): Promise => { + if (!folderName) { + return { message: "Which bookmark folder should I list tabs from?" }; + } + const foldersReadOnly = await bookmarkFolders.getAllReadOnly(); + if (!foldersReadOnly.ok) { + return { message: "Failed to read bookmark folders right now." }; + } + const target = normalizeName(folderName); + const folder = foldersReadOnly.folders.find( + item => normalizeName(item.name) === target + ); + if (!folder) { + return { message: `No bookmark folder named "${folderName}".` }; + } + + const items = folder.items.slice(0, 50).map(item => ({ + title: item.title || item.url, + url: item.url, + })); + if (items.length === 0) { + return { message: `Bookmark folder "${folder.name}" is empty.` }; + } + return { + message: `Tabs in bookmark folder "${folder.name}": ${JSON.stringify(items)}`, + }; + }; + + if ( + scope === "window" || + scope === "current-window" || + scope === "this-window" + ) { + return listWindowTabs(); + } + + if (scope === "tab-group" || scope === "tab_group" || scope === "group") { + return listGroupTabs(name); + } + + if ( + scope === "bookmark-folder" || + scope === "bookmark_folder" || + scope === "folder" || + scope === "hub" + ) { + return await listFolderTabs(name); + } + + if (name) { + if (LIST_WINDOW_SCOPE_ALIASES.has(normalizeName(name))) { + return listWindowTabs(); + } + + const group = findGroupByName(gBrowser, name); + const foldersReadOnly = await bookmarkFolders.getAllReadOnly(); + + if (!foldersReadOnly.ok) { + if (group) { + return listGroupTabs(name); + } + return { + message: + `I could not find a tab group named "${name}", and bookmark folders are temporarily unavailable. ` + + `Try "list tabs", "list tabs in tab group ${name}", or retry in a moment.`, + }; + } + + const folder = foldersReadOnly.folders.find( + item => normalizeName(item.name) === normalizeName(name) + ); + if (group && folder) { + return { + message: + `I found both a tab group and a bookmark folder named "${name}". ` + + `Say "list tabs in tab group ${name}" or "list tabs in bookmark folder ${name}".`, + }; + } + + if (group) { + return listGroupTabs(name); + } + + if (folder) { + return await listFolderTabs(name); + } + + return { + message: + `I could not find a tab group or bookmark folder named "${name}". ` + + `Try "list tabs" for open tabs, or "list tabs in tab group ${name}" / "list tabs in bookmark folder ${name}".`, + }; + } + + return listWindowTabs(); + } +} + +export class NewWindowCommand implements Command { + commandName = "new_window"; + description = "Open a new browser window."; + async execute(_args: CommandArgs): Promise { + const { topWin } = getChrome(); + if (!topWin?.OpenBrowserWindow) + return { message: "Browser UI not available." }; + + topWin.OpenBrowserWindow(); + return { message: "Successfully opened a new window." }; + } +} + +export class OrganizeWindowsCommand implements Command { + commandName = "organize_windows"; + description = "Arrange two or more windows side-by-side."; + async execute(_args: CommandArgs): Promise { + const { Services } = getChrome(); + const windowManager = Services?.wm; + const windows = windowManager?.getEnumerator?.("navigator:browser"); + if (!windows) return { message: "Services module not available." }; + const browserWindows: BrowserWindowLike[] = []; + + while (windows.hasMoreElements()) { + const win = windows.getNext(); + const docEl = win.document?.documentElement; + // Filter for visible, non-minimized windows if possible, or just all browser windows + if ( + !win.closed && + docEl?.getAttribute("windowtype") === "navigator:browser" + ) { + browserWindows.push(win); + } + } + + if (browserWindows.length < 2) { + return { message: "You need at least two windows to organize." }; + } + + // Use the screen of the first window as the target screen + const screen = browserWindows[0].screen; + const availWidth = screen.availWidth; + const availHeight = screen.availHeight; + const availLeft = screen.availLeft || 0; + const availTop = screen.availTop || 0; + const numWindows = browserWindows.length; + const windowWidth = Math.floor(availWidth / numWindows); + + for (let i = 0; i < numWindows; i++) { + const win = browserWindows[i]; + // Ensure the window is restored (not minimized/maximized) before resizing + if (win.windowState !== 1) { + // 1 is STATE_NORMAL + win.restore(); + } + + const xPos = availLeft + windowWidth * i; + win.resizeTo(windowWidth, availHeight); + win.moveTo(xPos, availTop); + } + + return { message: `Organized ${numWindows} windows side-by-side.` }; + } +} + +export class ShowURLCommand implements Command { + commandName = "show_url"; + description = "Open a URL in a new tab."; + async execute(args: CommandArgs): Promise { + const { topWin } = getChrome(); + if (!topWin?.openTrustedLinkIn) + return { message: "Browser UI not available." }; + + const url = stringArg(args, "url"); + if (!url) return { message: "Missing 'url' argument." }; + + topWin.openTrustedLinkIn(url, "tab"); + return { message: `Successfully opened URL: ${url}` }; + } +} + +export class OpenUrlCommand implements Command { + commandName = "open_url"; + description = "Open a URL in a new browser tab. Arguments: { url: string }."; + async execute(args: CommandArgs): Promise { + const { topWin, Services } = getChrome(); + const rawUrl = stringArg(args, "url"); + if (!rawUrl) { + return { message: "Missing 'url' argument." }; + } + if (!topWin?.openTrustedLinkIn) { + return { message: "Cannot open URL (openTrustedLinkIn not found)." }; + } + + const normalizedInput = rawUrl.trim(); + if (!normalizedInput) { + return { message: "Missing 'url' argument." }; + } + + let url = normalizedInput; + try { + url = withUriFixup(normalizedInput, Services); + } catch (error) { + assistantLogger.warn("commands", "Failed to fixup URI", error); + } + topWin.openTrustedLinkIn(url, "tab"); + return { message: `Opened URL in a new tab: ${url}` }; + } +} + +export class WebSearchCommand implements Command { + commandName = "web_search"; + description = + "Search the web in a new tab. Arguments: { query: string }."; + async execute(args: CommandArgs): Promise { + const { topWin } = getChrome(); + const query = stringArg(args, "query"); + if (!query) { + return { message: "Missing 'query' argument." }; + } + if (!topWin?.openTrustedLinkIn) { + return { message: "Cannot open web search (openTrustedLinkIn not found)." }; + } + const searchUrl = toWebSearchUrl(query); + topWin.openTrustedLinkIn(searchUrl, "tab"); + return { message: `Opened web search for "${query}" in a new tab.` }; + } +} + +export class OpenTabCommand implements Command { + commandName = "open_tab"; + description = + "Legacy alias that opens a URL or web query in a new tab. Prefer open_url({url}) or web_search({query})."; + async execute(args: CommandArgs): Promise { + const url = stringArg(args, "url"); + const query = stringArg(args, "query"); + if (query?.trim()) { + return await new WebSearchCommand().execute({ query }); + } + if (!url) { + return { message: "Missing 'url' argument." }; + } + if (url.includes(" ")) { + return await new WebSearchCommand().execute({ query: url }); + } + return await new OpenUrlCommand().execute({ url }); + } +} + +export class CloseTabCommand implements Command { + commandName = "close_tab"; + description = + "Close the active tab (or a tab by index). Accepts arguments: { index?: number, confirmed?: boolean } (1-based)."; + async execute(args: CommandArgs): Promise { + const { gBrowser } = getChrome(); + if (!gBrowser) return { message: "Browser UI (gBrowser) not available." }; + const idx = numberArg(args, "index"); + const tab = tabByIndexOrCurrent(gBrowser, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + const title = tabTitle(tab); + + if (booleanArg(args, "confirmed") !== true) { + setPendingConfirmation({ + command: "close_tab", + args: { ...args, confirmed: true }, + description: `Close tab "${title}"?`, + }); + return { + message: `Requesting confirmation to close tab "${title}"...`, + requiresConfirmation: true, + confirmationData: { title }, + }; + } + + clearPendingConfirmation(); + gBrowser.removeTab?.(tab); + return { message: `Closed tab: ${title}` }; + } +} + +export class ReloadTabCommand implements Command { + commandName = "reload_tab"; + description = + "Reload the current tab or a tab by index. Accepts arguments: { index?: number } (1-based)."; + async execute(args: CommandArgs): Promise { + const gb = asTabOps(getChrome().gBrowser); + if (!gb?.reloadTab) + return { message: "Browser UI (gBrowser.reloadTab) not available." }; + const idx = numberArg(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + gb.reloadTab(tab); + return { message: `Reloaded tab: ${tabTitle(tab)}` }; + } +} + +export class ToggleMuteTabCommand implements Command { + commandName = "toggle_mute_tab"; + description = + "Toggle mute for the current tab or a tab by index. Accepts arguments: { index?: number } (1-based)."; + async execute(args: CommandArgs): Promise { + const { gBrowser } = getChrome(); + if (!gBrowser) return { message: "Browser UI (gBrowser) not available." }; + const idx = numberArg(args, "index"); + const tab = tabByIndexOrCurrent(gBrowser, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + const toggle = (tab as BrowserTabLike & { toggleMuteAudio?: () => void }) + .toggleMuteAudio; + if (typeof toggle !== "function") + return { message: "Mute is not available for this tab." }; + toggle.call(tab); + return { message: `Toggled mute for: ${tabTitle(tab)}` }; + } +} + +export class PinTabCommand implements Command { + commandName = "pin_tab"; + description = + "Pin the current tab or a tab by index. Accepts arguments: { index?: number } (1-based)."; + async execute(args: CommandArgs): Promise { + const gb = asTabOps(getChrome().gBrowser); + if (!gb?.pinTab) + return { message: "Browser UI (gBrowser.pinTab) not available." }; + const idx = numberArg(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + if (tab.pinned) + return { message: `Tab is already pinned: ${tabTitle(tab)}` }; + gb.pinTab(tab, {}); + return { message: `Pinned tab: ${tabTitle(tab)}` }; + } +} + +export class UnpinTabCommand implements Command { + commandName = "unpin_tab"; + description = + "Unpin the current tab or a tab by index. Accepts arguments: { index?: number } (1-based)."; + async execute(args: CommandArgs): Promise { + const gb = asTabOps(getChrome().gBrowser); + if (!gb?.unpinTab) + return { message: "Browser UI (gBrowser.unpinTab) not available." }; + const idx = numberArg(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + if (!tab.pinned) return { message: `Tab is not pinned: ${tabTitle(tab)}` }; + gb.unpinTab(tab); + return { message: `Unpinned tab: ${tabTitle(tab)}` }; + } +} + +export class UnloadTabCommand implements Command { + commandName = "unload_tab"; + description = + "Unload (discard) the current tab or a tab by index to free memory. Accepts arguments: { index?: number } (1-based)."; + async execute(args: CommandArgs): Promise { + const gb = asTabOps(getChrome().gBrowser); + if (!gb?.explicitUnloadTabs) { + return { message: "Tab unload is not available in this build." }; + } + const idx = numberArg(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + await gb.explicitUnloadTabs([tab]); + return { message: `Unloaded tab: ${tabTitle(tab)}` }; + } +} + +export class NewTabToRightCommand implements Command { + commandName = "new_tab_to_right"; + description = + "Open a new tab immediately to the right of the current tab or a tab by index. Accepts arguments: { index?: number } (1-based)."; + async execute(args: CommandArgs): Promise { + const gb = asTabOps(getChrome().gBrowser); + if (!gb?.addAdjacentNewTab) { + return { + message: "Browser UI (gBrowser.addAdjacentNewTab) not available.", + }; + } + const idx = numberArg(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + gb.addAdjacentNewTab(tab); + return { message: `Opened a new tab to the right of: ${tabTitle(tab)}` }; + } +} + +export class DuplicateTabCommand implements Command { + commandName = "duplicate_tab"; + description = + "Duplicate the current tab or a tab by index. Accepts arguments: { index?: number } (1-based)."; + async execute(args: CommandArgs): Promise { + const gb = asTabOps(getChrome().gBrowser); + if (!gb?.duplicateTab) { + return { message: "Browser UI (gBrowser.duplicateTab) not available." }; + } + const idx = numberArg(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + gb.duplicateTab(tab); + return { message: `Duplicated tab: ${tabTitle(tab)}` }; + } +} + +export class BookmarkTabCommand implements Command { + commandName = "bookmark_tab"; + description = + "Bookmark the current tab or a tab by index (default bookmarks location). Accepts arguments: { index?: number } (1-based)."; + async execute(args: CommandArgs): Promise { + const { topWin, gBrowser } = getChrome(); + const hook = (topWin as BrowserChromeExtras | null)?.PlacesCommandHook + ?.bookmarkTabs; + if (!hook || !gBrowser) return { message: "Bookmarking is not available." }; + const idx = numberArg(args, "index"); + const tab = tabByIndexOrCurrent(gBrowser, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + hook([tab]); + return { message: `Bookmarked tab: ${tabTitle(tab)}` }; + } +} + +export class MoveTabToStartCommand implements Command { + commandName = "move_tab_to_start"; + description = + "Move the current tab or a tab by index to the start of the tab strip. Accepts arguments: { index?: number } (1-based)."; + async execute(args: CommandArgs): Promise { + const gb = asTabOps(getChrome().gBrowser); + if (!gb?.moveTabToStart) + return { message: "Browser UI (gBrowser.moveTabToStart) not available." }; + const idx = numberArg(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + gb.moveTabToStart(tab); + return { message: `Moved tab to start: ${tabTitle(tab)}` }; + } +} + +export class MoveTabToEndCommand implements Command { + commandName = "move_tab_to_end"; + description = + "Move the current tab or a tab by index to the end of the tab strip. Accepts arguments: { index?: number } (1-based)."; + async execute(args: CommandArgs): Promise { + const gb = asTabOps(getChrome().gBrowser); + if (!gb?.moveTabToEnd) + return { message: "Browser UI (gBrowser.moveTabToEnd) not available." }; + const idx = numberArg(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + gb.moveTabToEnd(tab); + return { message: `Moved tab to end: ${tabTitle(tab)}` }; + } +} + +export class SelectAllTabsCommand implements Command { + commandName = "select_all_tabs"; + description = + "Select all tabs in the current window for multi-tab actions. Accepts no arguments."; + async execute(_args: CommandArgs): Promise { + const gb = asTabOps(getChrome().gBrowser); + if (!gb?.selectAllTabs) + return { message: "Browser UI (gBrowser.selectAllTabs) not available." }; + gb.selectAllTabs(); + return { message: "Selected all tabs in this window." }; + } +} + +export class CloseDuplicateTabsCommand implements Command { + commandName = "close_duplicate_tabs"; + description = + "Close duplicate tabs (same URL) relative to the current tab or a tab by index. Accepts arguments: { index?: number, confirmed?: boolean } (1-based)."; + async execute(args: CommandArgs): Promise { + const gb = asTabOps(getChrome().gBrowser); + if (!gb?.getDuplicateTabsToClose || !gb.removeTabs) { + return { message: "Closing duplicate tabs is not available." }; + } + const idx = numberArg(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + const dupes = gb.getDuplicateTabsToClose(tab); + if (!dupes.length) { + return { message: "No duplicate tabs to close for this tab." }; + } + + if (booleanArg(args, "confirmed") !== true) { + setPendingConfirmation({ + command: "close_duplicate_tabs", + args: { ...args, confirmed: true }, + description: `Close ${dupes.length} duplicate tab(s)?`, + }); + return { + message: `Requesting confirmation to close ${dupes.length} duplicate tab(s)...`, + requiresConfirmation: true, + confirmationData: { count: dupes.length }, + }; + } + + clearPendingConfirmation(); + gb.removeTabs(dupes, { isUserTriggered: true }); + return { message: `Closed ${dupes.length} duplicate tab(s).` }; + } +} + +export class CloseTabsToRightCommand implements Command { + commandName = "close_tabs_to_right"; + description = + "Close all tabs to the right of the current tab or a tab by index. Accepts arguments: { index?: number, confirmed?: boolean } (1-based)."; + async execute(args: CommandArgs): Promise { + const gb = asTabOps(getChrome().gBrowser); + if (!gb?._getTabsToTheEndFrom || !gb.removeTabs) { + return { message: "Closing tabs to the right is not available." }; + } + const idx = numberArg(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + const toClose = gb._getTabsToTheEndFrom(tab); + if (!toClose.length) { + return { message: "No tabs to the right to close." }; + } + + if (booleanArg(args, "confirmed") !== true) { + setPendingConfirmation({ + command: "close_tabs_to_right", + args: { ...args, confirmed: true }, + description: `Close ${toClose.length} tab(s) to the right?`, + }); + return { + message: `Requesting confirmation to close ${toClose.length} tab(s) to the right...`, + requiresConfirmation: true, + confirmationData: { count: toClose.length }, + }; + } + + clearPendingConfirmation(); + gb.removeTabs(toClose, { isUserTriggered: true }); + return { message: `Closed ${toClose.length} tab(s) to the right.` }; + } +} + +export class CloseTabsToLeftCommand implements Command { + commandName = "close_tabs_to_left"; + description = + "Close all tabs to the left of the current tab or a tab by index. Accepts arguments: { index?: number, confirmed?: boolean } (1-based)."; + async execute(args: CommandArgs): Promise { + const gb = asTabOps(getChrome().gBrowser); + if (!gb?._getTabsToTheStartFrom || !gb.removeTabs) { + return { message: "Closing tabs to the left is not available." }; + } + const idx = numberArg(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + const toClose = gb._getTabsToTheStartFrom(tab); + if (!toClose.length) { + return { message: "No tabs to the left to close." }; + } + + if (booleanArg(args, "confirmed") !== true) { + setPendingConfirmation({ + command: "close_tabs_to_left", + args: { ...args, confirmed: true }, + description: `Close ${toClose.length} tab(s) to the left?`, + }); + return { + message: `Requesting confirmation to close ${toClose.length} tab(s) to the left...`, + requiresConfirmation: true, + confirmationData: { count: toClose.length }, + }; + } + + clearPendingConfirmation(); + gb.removeTabs(toClose, { isUserTriggered: true }); + return { message: `Closed ${toClose.length} tab(s) to the left.` }; + } +} + +export class CloseOtherTabsCommand implements Command { + commandName = "close_other_tabs"; + description = + "Close all tabs except the current tab or a tab by index. Accepts arguments: { index?: number, confirmed?: boolean } (1-based)."; + async execute(args: CommandArgs): Promise { + const gb = asTabOps(getChrome().gBrowser); + if (!gb?.removeAllTabsBut) + return { message: "Closing other tabs is not available." }; + const idx = numberArg(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + const others = getTabs(gb).filter(t => t !== tab && !t.pinned); + if (!others.length) { + return { message: "No other unpinned tabs to close." }; + } + + if (booleanArg(args, "confirmed") !== true) { + setPendingConfirmation({ + command: "close_other_tabs", + args: { ...args, confirmed: true }, + description: `Close ${others.length} other tab(s) (keeping "${tabTitle(tab)}")?`, + }); + return { + message: `Requesting confirmation to close ${others.length} other tab(s)...`, + requiresConfirmation: true, + confirmationData: { count: others.length }, + }; + } + + clearPendingConfirmation(); + gb.removeAllTabsBut(tab, { skipWarnAboutClosingTabs: true }); + return { message: `Closed other tabs (kept: ${tabTitle(tab)}).` }; + } +} + +export class ReopenClosedTabCommand implements Command { + commandName = "reopen_closed_tab"; + description = + "Reopen the most recently closed tab from this window's closed-tab list. Accepts arguments: { index?: number } (0 = most recent)."; + async execute(args: CommandArgs): Promise { + const { topWin } = getChrome(); + const ss = (topWin as BrowserChromeExtras | null)?.SessionStore; + if (!ss?.undoCloseTab) + return { + message: "Session restore (reopen closed tab) is not available.", + }; + const index = numberArg(args, "index"); + const reopened = ss.undoCloseTab(topWin as Window, index ?? 0); + if (!reopened) return { message: "No closed tab to reopen." }; + return { message: "Reopened the last closed tab." }; + } +} + +export class OpenSendTabToDeviceCommand implements Command { + commandName = "open_send_tab_to_device"; + description = + 'Open Firefox Sync "Send Tab to Device" so the user can pick a synced device. Accepts no arguments.'; + async execute(_args: CommandArgs): Promise { + const { topWin } = getChrome(); + const sync = (topWin as BrowserChromeExtras | null)?.gSync; + const anchor = topWin?.document?.getElementById?.( + "fxa-toolbar-menu-button" + ); + if (!sync?.showSendToDeviceViewFromFxaMenu || !anchor) { + return { + message: + "Could not open Send Tab to Device. Sign in to Sync and ensure the account toolbar button is visible.", + }; + } + sync.showSendToDeviceViewFromFxaMenu(anchor); + return { message: "Opened Send Tab to Device." }; + } +} + +export class OpenTabNoteCommand implements Command { + commandName = "open_tab_note"; + description = + "Open the tab note editor for the current tab or a tab by index. Accepts arguments: { index?: number } (1-based)."; + async execute(args: CommandArgs): Promise { + const gb = asTabOps(getChrome().gBrowser); + const menu = gb?.tabNoteMenu; + if (!menu?.openPanel) + return { message: "Tab notes are not available in this build." }; + const idx = numberArg(args, "index"); + const tab = tabByIndexOrCurrent(gb, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + menu.openPanel(tab, {}); + return { message: `Opened tab note for: ${tabTitle(tab)}` }; + } +} + +export class MoveTabToNewWindowCommand implements Command { + commandName = "move_tab_to_new_window"; + description = + "Move the active tab (or a tab by index) to a new window. Accepts arguments: { index?: number } (1-based)."; + async execute(args: CommandArgs): Promise { + const { topWin, gBrowser } = getChrome(); + if (!gBrowser || !topWin?.OpenBrowserWindow) { + return { message: "Browser UI not available." }; + } + + const idx = numberArg(args, "index"); + const tab = tabByIndexOrCurrent(gBrowser, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + + const title = tabTitle(tab); + const newWin = topWin.OpenBrowserWindow(); + await new Promise(r => setTimeout(r, 250)); // give it a tick + newWin.gBrowser?.adoptTab?.(tab, 0); + return { message: `Moved tab to new window: ${title}` }; + } +} + +export class CopyTabUrlsCommand implements Command { + commandName = "copy_tab_urls"; + description = + "Copy all tab URLs in the current window to the clipboard (one per line). Accepts no arguments."; + async execute(_args: CommandArgs): Promise { + const { gBrowser } = getChrome(); + if (!gBrowser) return { message: "Browser UI (gBrowser) not available." }; + const urls = getTabs(gBrowser) + .map(tab => tabUrl(tab)) + .filter(Boolean); + const text = urls.join("\n"); + try { + await navigator.clipboard.writeText(text); + return { message: `Copied ${urls.length} URLs to clipboard.` }; + } catch { + return { message: `Copied fallback. URLs:\n${text}` }; + } + } +} + +/* =========================== + * Bookmark Folder Commands (formerly Hubs) + * =========================== */ + +export class CreateBookmarkFolderCommand implements Command { + commandName = "create_bookmark_folder"; + description = + "Create a managed bookmark folder. Accepts arguments: { name: string, include?: 'none'|'current'|'all' }."; + async execute(args: CommandArgs): Promise { + const name = stringArg(args, "name") || ""; + const includeRaw = stringArg(args, "include"); + const include: CreateFolderOpts["include"] = + includeRaw === "current" || includeRaw === "all" || includeRaw === "none" + ? includeRaw + : "none"; + const res = await bookmarkFolders.create(name, { include }); + applyRoutingStateMutation({ + kind: "upsert", + entity: "folder", + name: res.name, + }); + return { + message: `Created bookmark folder "${res.name}" with ${res.count} items.`, + }; + } +} + +export class DeleteBookmarkFolderCommand implements Command { + commandName = "delete_bookmark_folder"; + description = + "Delete a managed bookmark folder by name. Accepts arguments: { name: string, closeTabs?: boolean, confirmed?: boolean }."; + async execute(args: CommandArgs): Promise { + const name = stringArg(args, "name"); + if (!name) return { message: "Which folder should I delete?" }; + + if (booleanArg(args, "confirmed") !== true) { + const closeTabs = booleanArg(args, "closeTabs") === true; + const closeMsg = closeTabs ? " and close all associated tabs" : ""; + setPendingConfirmation({ + command: "delete_bookmark_folder", + args: { ...args, confirmed: true }, + description: `Delete bookmark folder "${name}"${closeMsg}?`, + }); + return { + message: `Requesting confirmation to delete bookmark folder "${name}"${closeMsg}...`, + requiresConfirmation: true, + confirmationData: { name, closeTabs }, + }; + } + + clearPendingConfirmation(); + const closeTabs = booleanArg(args, "closeTabs") === true; + const res = await bookmarkFolders.delete(name, { closeTabs }); + if (res.removed === 0) return { message: `No folder named "${name}".` }; + applyRoutingStateMutation({ + kind: "delete", + entity: "folder", + name: res.name, + }); + return { + message: `Deleted bookmark folder "${res.name}" (${res.removed} items removed).`, + }; + } +} + +export class ListBookmarkFoldersCommand implements Command { + commandName = "list_bookmark_folders"; + description = "List all managed bookmark folders. Accepts no arguments."; + async execute(_args: CommandArgs): Promise { + const items = await bookmarkFolders.list(); + if (!items.length) return { message: "No bookmark folders yet." }; + return { + message: JSON.stringify(items.map(h => `${h.name} (${h.count})`)), + }; + } +} + +export class RenameBookmarkFolderCommand implements Command { + commandName = "rename_bookmark_folder"; + description = + "Rename a managed bookmark folder. Accepts arguments: { from: string, to: string }."; + async execute(args: CommandArgs): Promise { + const from = stringArg(args, "from"); + const to = stringArg(args, "to"); + if (!from || !to) + return { message: "Please provide old and new folder names." }; + const r = await bookmarkFolders.rename(from, to); + if (r.ok) { + applyRoutingStateMutation({ + kind: "rename", + entity: "folder", + from, + to, + }); + } + return { + message: r.ok + ? `Renamed "${from}" to "${to}".` + : `Rename failed: ${r.msg || "unknown error"}`, + }; + } +} + +export class AddTabToBookmarkFolderCommand implements Command { + commandName = "add_tab_to_bookmark_folder"; + description = + "Add tabs to a managed bookmark folder. Accepts arguments: { name: string, query?: string, all?: boolean } (query matches title/URL). all=true adds all tabs. If no query/all, adds current tab."; + async execute(args: CommandArgs): Promise { + const name = stringArg(args, "name"); + if (!name) return { message: "Which folder should I add tabs to?" }; + + const { gBrowser } = getChrome(); + if (!gBrowser) return { message: "Browser UI not available." }; + + const query = normalizeQuery(stringArg(args, "query")); + const all = booleanArg(args, "all") === true; + let tabsToAdd: BrowserTabLike[] = []; + + if (all) { + tabsToAdd = getTabs(gBrowser); + } else if (query) { + tabsToAdd = findTabsByQuery(gBrowser, query); + + if (tabsToAdd.length === 0) { + return { + message: `No tabs found matching "${stringArg(args, "query") || ""}".`, + }; + } + } else { + // Default to current tab + const current = gBrowser.selectedTab; + if (current) { + tabsToAdd = [current]; + } + } + + if (tabsToAdd.length === 0) return { message: "No tabs available to add." }; + + const r = await bookmarkFolders.addTabs(name, tabsToAdd); + + if (!r.ok) return { message: `Failed to add tabs to "${name}".` }; + applyRoutingStateMutation({ + kind: "upsert", + entity: "folder", + name, + }); + + const count = tabsToAdd.length; + return { message: `Added ${count} tab(s) to bookmark folder "${name}".` }; + } +} + +export class RemoveTabFromBookmarkFolderCommand implements Command { + commandName = "remove_tab_from_bookmark_folder"; + description = + "Remove a tab from a managed bookmark folder. Accepts arguments: { name: string, url?: string } (defaults to current tab URL)."; + async execute(args: CommandArgs): Promise { + const name = stringArg(args, "name"); + if (!name) return { message: "Which folder?" }; + + let url = stringArg(args, "url"); + if (!url) { + const { gBrowser } = getChrome(); + if (gBrowser) { + url = tabUrl(gBrowser.selectedTab || null); + } + } + + if (!url) return { message: "Could not determine URL to remove." }; + + const r = await bookmarkFolders.removeUrl(name, url); + return { + message: r.ok + ? `Removed URL from folder "${name}".` + : `Failed to remove URL from folder "${name}" (maybe not found).`, + }; + } +} + +export class OpenBookmarkFolderCommand implements Command { + commandName = "open_bookmark_folder"; + description = + "Open all bookmarks from a managed folder. Accepts arguments: { name: string, where?: 'tabs'|'window'|'tabgroup' }. 'tabgroup' creates a new visual group."; + async execute(args: CommandArgs): Promise { + const name = stringArg(args, "name"); + if (!name) return { message: "Which folder should I open?" }; + const whereRaw = stringArg(args, "where"); + const where: "tabs" | "window" | "tabgroup" = + whereRaw === "window" || whereRaw === "tabgroup" ? whereRaw : "tabs"; + const r = await bookmarkFolders.openFolder(name, where); + return { + message: r.ok + ? `Opened folder "${name}" in ${where}.` + : `Failed to open folder "${name}".`, + }; + } +} + +export class AddSplitViewCommand implements Command { + commandName = "add_split_view"; + description = + "Add split view with tabs side-by-side. Accepts arguments: { indices?: [number, number], withIndex?: number, withQuery?: string }. Use 'indices' to specify two tabs by number. Use 'withIndex' or 'withQuery' to split current tab with another. If no arguments, opens split view with a new tab."; + async execute(args: CommandArgs): Promise { + const { topWin, gBrowser, Services } = getChrome(); + if (!gBrowser || !topWin) return { message: "Browser UI not available." }; + + const splitViewEnabled = Services?.prefs?.getBoolPref?.( + "browser.tabs.splitView.enabled", + false + ); + if (!splitViewEnabled) { + return { message: "Split view is not enabled in this browser." }; + } + + let tab1: BrowserTabLike | null = null; + let tab2: BrowserTabLike | null = null; + + const indices = numberArrayArg(args, "indices"); + if (indices.length >= 2) { + const i1 = Math.max(1, Math.floor(indices[0])); + const i2 = Math.max(1, Math.floor(indices[1])); + const first = tabByIndex(gBrowser, i1); + const second = tabByIndex(gBrowser, i2); + if (!first) return { message: `No tab ${i1}.` }; + if (!second) return { message: `No tab ${i2}.` }; + if (i1 === i2) return { message: "Cannot split a tab with itself." }; + tab1 = first; + tab2 = second; + } else { + tab1 = gBrowser.selectedTab || null; + const withIndex = numberArg(args, "withIndex"); + const withQuery = normalizeQuery(stringArg(args, "withQuery")); + + if (withIndex != null) { + const i = Math.max(1, Math.floor(withIndex)); + tab2 = tabByIndex(gBrowser, i); + if (!tab2) return { message: `No tab ${i}.` }; + } else if (withQuery) { + tab2 = findTabsByQuery(gBrowser, withQuery)[0] || null; + if (!tab2) { + return { + message: `No tab found matching "${stringArg(args, "withQuery") || ""}".`, + }; + } + } else { + tab2 = gBrowser.addTrustedTab?.("about:newtab") || null; + } + } + + if (!tab1 || !tab2) + return { message: "Unable to resolve tabs for split view." }; + if (tab1 === tab2) { + return { message: "Cannot split a tab with itself." }; + } + + if (tab1.pinned || tab2.pinned) { + return { message: "Cannot add pinned tabs to split view." }; + } + + if (tab1.splitview) { + return { message: `Tab "${tab1.label}" is already in a split view.` }; + } + if (tab2.splitview) { + return { message: `Tab "${tab2.label}" is already in a split view.` }; + } + + try { + gBrowser.addTabSplitView?.([tab1, tab2], { + insertBefore: tab1, + }); + + const title1 = tabTitle(tab1); + const title2 = tabTitle(tab2); + return { + message: `Added split view: "${title1}" and "${title2}".`, + }; + } catch (e) { + return { message: `Failed to create split view: ${e}` }; + } + } +} + +export class RemoveSplitViewCommand implements Command { + commandName = "remove_split_view"; + description = "Remove split view from the current tab (unsplit tabs)."; + async execute(_args: CommandArgs): Promise { + const { gBrowser } = getChrome(); + if (!gBrowser) return { message: "Browser UI not available." }; + + const currentTab = gBrowser.selectedTab; + if (!currentTab) return { message: "No active tab found." }; + const splitview = currentTab.splitview; + + if (!splitview?.unsplitTabs) { + return { message: "This tab is not in a split view." }; + } + + try { + splitview.unsplitTabs(); + return { message: "Split view removed. Tabs are now separate." }; + } catch (e) { + return { message: `Failed to remove split view: ${e}` }; + } + } +} + +export class SplitTabsCommand implements Command { + commandName = "split_tabs"; + description = + "Split specified tabs into side-by-side windows. Accepts arguments: { indices: number[] }."; + async execute(args: CommandArgs): Promise { + const { topWin, gBrowser } = getChrome(); + if (!gBrowser || !topWin?.OpenBrowserWindow) + return { message: "Browser UI not available." }; + + const indices = numberArrayArg(args, "indices"); + if (indices.length < 2) { + return { + message: + "Please provide at least 2 tab indices to split (e.g., { indices: [1, 2] }).", + }; + } + + // Validate all indices first + const tabs: BrowserTabLike[] = []; + for (const idx of indices) { + const i = Math.max(1, Math.floor(idx)); + const tab = tabByIndex(gBrowser, i); + if (!tab) return { message: `No tab ${i}.` }; + tabs.push(tab); + } + + // Get screen dimensions + const screen = topWin.screen; + const availWidth = screen.availWidth; + const availHeight = screen.availHeight; + const availLeft = screen.availLeft || 0; + const availTop = screen.availTop || 0; + + const numTabs = tabs.length; + const windows: Array<{ + win: BrowserWindowLike; + tab: BrowserTabLike; + title: string; + }> = []; + + // Create windows for each tab + for (let i = 0; i < numTabs; i++) { + const tab = tabs[i]; + const title = tabTitle(tab); + + // Create new window + const newWin = topWin.OpenBrowserWindow(); + windows.push({ win: newWin, tab, title }); + + // Small delay to ensure window is created + await new Promise(r => setTimeout(r, 100)); + } + + // Give windows time to fully initialize + await new Promise(r => setTimeout(r, 300)); + + // Position and resize windows, then move tabs + for (let i = 0; i < numTabs; i++) { + const { win, tab } = windows[i]; + + // Horizontal layout (side-by-side, left to right) + const windowWidth = Math.floor(availWidth / numTabs); + const windowHeight = availHeight; + const xPos = availLeft + windowWidth * i; + const yPos = availTop; + + win.resizeTo(windowWidth, windowHeight); + win.moveTo(xPos, yPos); + + // Close the sidebar if it's open (since session storage isn't implemented yet) + try { + const sidebar = win.document?.getElementById("sidebar-box") as { + hidden?: boolean; + } | null; + if (sidebar && !sidebar.hidden) { + win.SidebarController?.hide?.(); + } + } catch (e) { + assistantLogger.warn("commands", "Failed to close sidebar", e); + } + + // Move the tab to the new window + win.gBrowser?.adoptTab?.(tab, 0); + } + + const tabTitles = windows.map(w => w.title).join(", "); + return { message: `Split ${numTabs} tabs side-by-side: ${tabTitles}` }; + } +} + +export class SummarizePageCommand implements Command { + commandName = "summarize_page"; + description = + "Summarize the content of a webpage. Accepts arguments: { index?: number, query?: string }. Use 'index' for tab number (1-based), 'query' to find tab by title/URL. If no arguments, summarizes current tab."; + async execute(args: CommandArgs): Promise { + const { gBrowser } = getChrome(); + if (!gBrowser) return { message: "Browser UI not available." }; + + const idx = numberArg(args, "index"); + let tab = tabByIndexOrCurrent(gBrowser, idx); + + // Allow specifying tab by index + if (idx != null && !tab) return { message: `No tab ${idx}.` }; + + // Allow specifying tab by query (title/URL match) + const query = normalizeQuery(stringArg(args, "query")); + if (query && !idx) { + tab = findTabsByQuery(gBrowser, query)[0] || null; + if (!tab) { + return { + message: `No tab found matching "${stringArg(args, "query") || ""}".`, + }; + } + } + + const browser = tab?.linkedBrowser; + if (!browser) return { message: "No active tab found." }; + + const url = browser.currentURI?.spec || ""; + const title = tabTitle(tab); + + // Skip certain pages that can't be summarized + if ( + url.startsWith("about:") || + url.startsWith("chrome://") || + url.startsWith("moz-extension://") + ) { + return { message: "Cannot summarize browser internal pages." }; + } + + try { + // Use PageExtractor actor for Fission-compatible content extraction + const currentWindowContext = browser.browsingContext?.currentWindowContext; + + if (!currentWindowContext) { + return { + message: "Cannot access page content. The page may still be loading.", + }; + } + + const pageExtractor = currentWindowContext.getActor("PageExtractor"); + + if (!pageExtractor) { + return { message: "Page content extractor not available." }; + } + + // Try Reader Mode first (cleaner content), fall back to full text + let content = ""; + try { + content = (await pageExtractor.getReaderModeContent?.()) || ""; + } catch (e) { + assistantLogger.warn( + "commands", + "Reader mode extraction failed, trying full text", + e + ); + } + + // If reader mode failed or returned empty, try full text extraction + if (!content || content.length < 50) { + try { + const result = await pageExtractor.getText?.(); + content = typeof result === "string" ? result : result?.text || ""; + } catch (e) { + assistantLogger.warn("commands", "Full text extraction failed", e); + } + } + + // Clean up whitespace + content = content + .replace(/\s+/g, " ") + .replace(/\n\s*\n/g, "\n") + .trim(); + + if (!content || content.length < 50) { + return { + message: "Not enough content found on this page to summarize.", + }; + } + + // Truncate to reasonable length for LLM (roughly 10k chars ≈ 2.5k tokens) + const maxLength = 12000; + if (content.length > maxLength) { + content = content.substring(0, maxLength) + "..."; + } + + // Return the content for the chat node to summarize + return { + message: `__SUMMARIZE_REQUEST__\nTitle: ${title}\nURL: ${url}\n\nContent:\n${content}`, + }; + } catch (e) { + return { message: `Failed to extract page content: ${e}` }; + } + } +} + +export class SearchMemoryCommand implements Command { + commandName = "search_memory"; + description = + `Search across multiple local sources: browsing history, bookmarks (including managed bookmark folders), open tabs, tab groups, and stored memory. ` + + `Arguments: { query: string, folder?: string, source?: 'bookmark-folder' }. ` + + `'folder' filters to a specific managed bookmark folder; 'source' can scope to bookmark-folder results. ` + + `Returns JSON with: { summary: string, resultsBySource: { [source]: [{ title, url, snippet }] }, results: [{ index, source, title, url, context, snippet }] }. ` + + `Sources are: "history", "bookmark", "bookmark-folder", "tab", "tab-group", "memory".`; + async execute(args: CommandArgs): Promise { + const query = stringArg(args, "query"); + const folder = stringArg(args, "folder"); + const source = stringArg(args, "source"); + const sourceScope = + source === "bookmark-folder" ? "bookmark-folder" : undefined; + if (!query) return { message: "Missing 'query' argument." }; + + let results = await localMemory.search( + query, + 10, + folder ? { folder } : undefined + ); + + if (hasBookmarkFolderCandidates(results)) { + const snapshot = await bookmarkFolders.getAllReadOnly(); + if (snapshot.ok) { + const folderToUrls = buildFolderUrlMap(snapshot.folders); + const filtered = filterStaleBookmarkFolderResults( + results, + folderToUrls + ); + results = filtered.results; + if (filtered.dropped > 0) { + assistantLogger.debug( + "search-memory", + "Dropped stale bookmark-folder results", + { dropped: filtered.dropped } + ); + } + } else { + assistantLogger.warn( + "search-memory", + "Read-only folder snapshot failed; returning lexical results" + ); + } + } + + const folderScoped = Boolean(folder); + const requiresBookmarkFolderOnly = + folderScoped || sourceScope === "bookmark-folder"; + if (requiresBookmarkFolderOnly) { + const before = results.length; + results = results.filter( + r => getMemoryDocSource(r) === "bookmark-folder" + ); + if (before !== results.length) { + assistantLogger.debug( + "search-memory", + "Restricted results to bookmark-folder scope", + { + before, + after: results.length, + folderScoped, + sourceScope: sourceScope || "none", + } + ); + } + } + + const scopeSuffix = folder + ? ` in bookmark folder "${folder}"` + : sourceScope === "bookmark-folder" + ? " in bookmark folders" + : ""; + + if (results.length === 0) { + clearRecentSearchResults(); + if (!folderScoped && !sourceScope && query.trim() !== "*") { + setPendingConfirmation({ + command: "web_search", + args: { query }, + description: `No local matches found for "${query}". Search the web in a new tab?`, + }); + return { + message: + `No local matches found for "${query}". ` + + `Would you like me to open a web search in a new tab?`, + requiresConfirmation: true, + confirmationData: { query, url: toWebSearchUrl(query) }, + }; + } + const guidance = folder + ? ` Try "list tabs in bookmark folder ${folder}" to inspect what is saved there.` + : ""; + return { + message: `No matches found for "${query}"${scopeSuffix}.${guidance}`, + }; + } + + const sourceMap: Record = { + history: "history", + bookmark: "bookmark", + tab: "tab", + "tab-group": "tab-group", + hub_item: "bookmark-folder", + bookmark_folder_item: "bookmark-folder", + memory: "memory", + }; + + const structured: RecentSearchResult[] = results.map((r, i) => { + const rawType = r.metadata?.type || "memory"; + const source = sourceMap[rawType] || rawType; + const resolvedUrl = r.url || r.metadata?.url || r.metadata?.hubName || ""; + return { + index: i + 1, + source, + title: r.metadata?.title || "(no title)", + url: resolvedUrl, + bookmarkGuid: r.metadata?.bookmarkGuid || undefined, + context: + r.metadata?.context || + (source === "history" ? "Browsing History" : + source === "bookmark" ? "Bookmarks" : + source === "bookmark-folder" ? `Bookmark Folder: ${r.metadata?.hubName || "unknown"}` : + source === "tab" ? "Open Tab" : + source === "tab-group" ? "Tab Group" : + "Memory"), + snippet: r.text.length > 120 ? r.text.substring(0, 120) + "..." : r.text, + }; + }); + setRecentSearchResults(structured); + + const resultsBySource: Record = {}; + for (const r of structured) { + const bucket = (resultsBySource[r.source] ??= []); + bucket.push({ + title: r.title, + url: r.url, + snippet: r.snippet ?? "", + bookmarkGuid: r.bookmarkGuid, + }); + } + + const sourceCounts = Object.entries(resultsBySource) + .map(([src, items]) => `${items.length} from ${src}`) + .join(", "); + const summary = `Found ${structured.length} result(s) for "${query}"${scopeSuffix}: ${sourceCounts}.`; + + return { + message: JSON.stringify({ + summary, + resultsBySource, + results: structured, + }), + }; + } +} + +export class GetRecentSearchResultsCommand implements Command { + commandName = "get_recent_search_results"; + description = + "Get cached results from the most recent search_memory command. Arguments: { limit?: number }."; + async execute(args: CommandArgs): Promise { + const limit = numberArg(args, "limit"); + const cappedLimit = + limit != null ? Math.max(1, Math.min(Math.floor(limit), 25)) : 5; + const recent = getRecentSearchResults(); + if (recent.length === 0) { + return { + message: JSON.stringify({ + summary: "No recent search results available.", + results: [], + }), + }; + } + + const results = recent.slice(0, cappedLimit).map((result, idx) => ({ + index: idx + 1, + source: result.source, + title: result.title, + url: result.url, + bookmarkGuid: result.bookmarkGuid, + context: result.context, + snippet: result.snippet, + })); + return { + message: JSON.stringify({ + summary: `Found ${results.length} cached recent search result(s).`, + results, + }), + }; + } +} + +export class OpenSearchResultCommand implements Command { + commandName = "open_search_result"; + description = + "Open a search result. Accepts arguments: { url?: string, index?: number, type?: string, bookmarkGuid?: string }. If index is provided (or omitted), resolves from recent search results. If type is 'tab', switches to it if found."; + async execute(args: CommandArgs): Promise { + let url = stringArg(args, "url"); + const index = numberArg(args, "index"); + let type = stringArg(args, "type"); + let bookmarkGuid = stringArg(args, "bookmarkGuid"); + + if (!url) { + const recent = getRecentSearchResults(); + if (recent.length === 0) { + return { + message: + "No recent search result is available to open. Run a search first or pass a URL.", + }; + } + const targetIndex = index != null ? Math.max(1, Math.floor(index)) : 1; + const selected = recent[targetIndex - 1]; + if (!selected?.url) { + return { + message: + `Result index ${targetIndex} is out of range. ` + + `I currently have ${recent.length} recent result(s).`, + }; + } + url = selected.url; + bookmarkGuid = bookmarkGuid || selected.bookmarkGuid; + if (!type && selected.source === "tab") { + type = "tab"; + } + } + + const { topWin, gBrowser, PlacesUtils } = getChrome(); + if (!topWin?.openTrustedLinkIn || !gBrowser) + return { message: "Browser UI not available." }; + + // If we have a bookmark GUID, prefer a fresh URL from Places at open-time. + if (bookmarkGuid && PlacesUtils?.bookmarks?.fetch) { + try { + const fetched = await PlacesUtils.bookmarks.fetch(bookmarkGuid); + const bookmark = Array.isArray(fetched) ? fetched[0] : fetched; + const freshUrl = toUrlString(bookmark?.url); + if (freshUrl) { + url = freshUrl; + } + } catch (e) { + assistantLogger.warn( + "open-search-result", + `Failed bookmark GUID lookup guid=${bookmarkGuid}`, + e + ); + } + } + + if (!url) return { message: "Missing 'url' argument." }; + + // If it's an open tab, try to find and switch to it + if (type === "tab") { + const foundTab = getTabs(gBrowser).find(tab => tabUrl(tab) === url); + + if (foundTab) { + gBrowser.selectedTab = foundTab; + return { message: `Switched to tab: ${url}` }; + } + } + + // Otherwise (or if tab not found), open in new tab + topWin.openTrustedLinkIn(url, "tab"); + return { message: `Opened in new tab: ${url}` }; + } +} + +export class ShowSubscriptionCommand implements Command { + commandName = "show_subscription"; + description = "Show the current subscription plan and usage options."; + async execute(_args: CommandArgs): Promise { + const { topWin } = getChrome(); + if (!topWin?.openTrustedLinkIn) + return { message: "Browser UI not available." }; + + const stats = await subscriptionService.checkAvailability(); + const url = subscriptionService.getSubscriptionUrl(); + + topWin.openTrustedLinkIn(url, "tab"); + + return { + message: `Opened subscription page.\nUsage this month: ${stats.totalUnits} units / ${stats.limit} limit.`, + }; + } +} + +/* =========================== + * Tab Group Commands (Native Firefox Tab Groups) + * =========================== */ + +export class ListTabGroupsCommand implements Command { + commandName = "list_tab_groups"; + description = + "List all tab groups in the current window. Accepts no arguments."; + async execute(_args: CommandArgs): Promise { + const { gBrowser } = getChrome(); + if (!gBrowser) return { message: "Browser UI (gBrowser) not available." }; + + const groups = getTabGroups(gBrowser); + if (groups.length === 0) { + return { message: "No tab groups in this window." }; + } + + const groupInfo = groups.map(group => ({ + name: group.label || "(unnamed)", + tabCount: (group.tabs || []).length, + collapsed: group.collapsed || false, + })); + + return { message: JSON.stringify(groupInfo) }; + } +} + +export class CreateTabGroupCommand implements Command { + commandName = "create_tab_group"; + description = + "Create a new tab group from specified tabs. Accepts arguments: { name: string, indices?: number[], openUrl?: string, confirmed?: boolean }. Use 'openUrl' to open a URL in the new group. If no indices provided, creates with current tab (or new tab if current is already grouped)."; + async execute(args: CommandArgs): Promise { + const { gBrowser, Services } = getChrome(); + if (!gBrowser) return { message: "Browser UI (gBrowser) not available." }; + + const name = stringArg(args, "name") || "New Group"; + const indices = numberArrayArg(args, "indices"); + + let tabsToGroup: BrowserTabLike[] = []; + let createdNewTab = false; + const openUrl = stringArg(args, "openUrl"); + + if (indices.length > 0) { + for (const idx of indices) { + const i = Math.max(1, Math.floor(idx)); + const tab = tabByIndex(gBrowser, i); + if (!tab) return { message: `No tab ${i}.` }; + tabsToGroup.push(tab); + } + } else if (openUrl) { + // If a URL is specified, create a new tab with that URL for the group + let url = openUrl; + // Fixup URL if needed + if (!url.includes("://")) { + try { + url = withUriFixup(url, Services); + } catch (e) { + // Fallback: add https:// + if (!url.startsWith("http")) { + url = "https://" + url; + } + } + } + const newTab = gBrowser.addTrustedTab?.(url); + if (!newTab) + return { message: "Failed to open a tab for the new group." }; + tabsToGroup = [newTab]; + createdNewTab = true; + } else { + const currentTab = gBrowser.selectedTab || null; + // If current tab is already in a group, create a new tab instead of moving it + if (currentTab?.group) { + const newTab = gBrowser.addTrustedTab?.("about:newtab"); + if (!newTab) + return { message: "Failed to create a tab for the new group." }; + tabsToGroup = [newTab]; + createdNewTab = true; + } else { + if (!currentTab) return { message: "No active tab available." }; + tabsToGroup = [currentTab]; + } + } + + const groupableTabs = tabsToGroup.filter(tab => !tab.pinned); + if (groupableTabs.length === 0) { + return { message: "No groupable tabs (pinned tabs cannot be grouped)." }; + } + + // Check if any tabs are already in groups + const tabsInGroups = groupableTabs.filter(tab => !!tab.group); + if (tabsInGroups.length > 0 && booleanArg(args, "confirmed") !== true) { + const impact = analyzeGroupMoveImpact(tabsInGroups); + const groupNames = impact.affectedGroups.join(", "); + + let warningMsg = `${tabsInGroups.length} tab(s) will be moved from existing group(s): ${groupNames}.`; + if (impact.emptiedGroups.length > 0) { + warningMsg += ` This will delete the following empty group(s): ${impact.emptiedGroups.join(", ")}.`; + } + warningMsg += ` Create "${name}" anyway?`; + + setPendingConfirmation({ + command: "create_tab_group", + args: { ...args, confirmed: true }, + description: warningMsg, + }); + return { + message: warningMsg, + requiresConfirmation: true, + confirmationData: { + name, + affectedGroups: impact.affectedGroups, + willBeEmpty: impact.emptiedGroups, + }, + }; + } + + clearPendingConfirmation(); + + try { + gBrowser.addTabGroup?.(groupableTabs, { label: name }); + applyRoutingStateMutation({ + kind: "upsert", + entity: "group", + name, + }); + let msg: string; + if (openUrl) { + msg = `Created tab group "${name}" and opened ${openUrl} in it.`; + } else if (createdNewTab) { + msg = `Created tab group "${name}" with a new tab.`; + } else { + msg = `Created tab group "${name}" with ${groupableTabs.length} tab(s).`; + } + return { message: msg }; + } catch (e) { + return { message: `Failed to create tab group: ${e}` }; + } + } +} + +export class DeleteTabGroupCommand implements Command { + commandName = "delete_tab_group"; + description = + "Delete a tab group by name. Accepts arguments: { name: string, closeTabs?: boolean, confirmed?: boolean }."; + async execute(args: CommandArgs): Promise { + const { gBrowser } = getChrome(); + if (!gBrowser) return { message: "Browser UI (gBrowser) not available." }; + + const name = stringArg(args, "name"); + if (!name) return { message: "Which tab group should I delete?" }; + + const group = findGroupByName(gBrowser, name); + + if (!group) { + return { message: `No tab group named "${name}".` }; + } + + const tabCount = (group.tabs || []).length; + const closeTabs = booleanArg(args, "closeTabs") === true; + + if (booleanArg(args, "confirmed") !== true) { + const closeMsg = closeTabs + ? " and close all its tabs" + : " (tabs will be ungrouped)"; + setPendingConfirmation({ + command: "delete_tab_group", + args: { ...args, confirmed: true }, + description: `Delete tab group "${name}"${closeMsg}?`, + }); + return { + message: `Requesting confirmation to delete tab group "${name}" (${tabCount} tabs)${closeMsg}...`, + requiresConfirmation: true, + confirmationData: { name, tabCount, closeTabs }, + }; + } + + clearPendingConfirmation(); + + try { + const tabs = group.tabs || []; + if (closeTabs) { + for (const tab of tabs) { + gBrowser.removeTab?.(tab); + } + } else { + for (const tab of tabs) { + gBrowser.ungroupTab?.(tab); + } + } + applyRoutingStateMutation({ + kind: "delete", + entity: "group", + name: group.label || name, + }); + return { + message: `Deleted tab group "${name}"${closeTabs ? " and closed its tabs" : ""}.`, + }; + } catch (e) { + return { message: `Failed to delete tab group: ${e}` }; + } + } +} + +export class AddTabToGroupCommand implements Command { + commandName = "add_tab_to_group"; + description = + "Add tab(s) to an existing tab group. Accepts arguments: { name: string, query?: string, index?: number, all?: boolean, confirmed?: boolean }. Use 'query' to find tab by title/URL. Use 'all: true' to add all ungrouped tabs. If no query/index/all, adds current tab."; + async execute(args: CommandArgs): Promise { + const { gBrowser } = getChrome(); + if (!gBrowser) return { message: "Browser UI (gBrowser) not available." }; + + const name = stringArg(args, "name"); + if (!name) return { message: "Which tab group should I add the tab to?" }; + + const group = findGroupByName(gBrowser, name); + + if (!group) { + return { + message: `No tab group named "${name}". Use create_tab_group to create one first.`, + }; + } + + let tabsToAdd: BrowserTabLike[] = []; + const query = normalizeQuery(stringArg(args, "query")); + const idx = numberArg(args, "index"); + const all = booleanArg(args, "all"); + + if (all === true) { + tabsToAdd = getTabs(gBrowser).filter(tab => !tab.group); + } else if (query) { + tabsToAdd = findTabsByQuery(gBrowser, query); + + if (tabsToAdd.length === 0) { + return { + message: `No tabs found matching "${stringArg(args, "query") || ""}".`, + }; + } + } else if (idx != null) { + const tab = tabByIndex(gBrowser, idx); + if (!tab) return { message: `No tab ${idx}.` }; + tabsToAdd = [tab]; + } else { + const selected = gBrowser.selectedTab; + if (selected) { + tabsToAdd = [selected]; + } + } + + const groupableTabs = tabsToAdd.filter(tab => !tab.pinned); + if (groupableTabs.length === 0) { + return { + message: + "No groupable tabs found (pinned tabs cannot be grouped, or all tabs are already in groups).", + }; + } + + // Check if any tabs are already in OTHER groups (not the target group) + const tabsInOtherGroups = groupableTabs.filter( + tab => tab.group && tab.group !== group + ); + if ( + tabsInOtherGroups.length > 0 && + booleanArg(args, "confirmed") !== true + ) { + const impact = analyzeGroupMoveImpact(tabsInOtherGroups); + const groupNames = impact.affectedGroups.join(", "); + + let warningMsg = `${tabsInOtherGroups.length} tab(s) will be moved from existing group(s): ${groupNames}.`; + if (impact.emptiedGroups.length > 0) { + warningMsg += ` This will delete the following empty group(s): ${impact.emptiedGroups.join(", ")}.`; + } + warningMsg += ` Add to "${name}" anyway?`; + + setPendingConfirmation({ + command: "add_tab_to_group", + args: { ...args, confirmed: true }, + description: warningMsg, + }); + return { + message: warningMsg, + requiresConfirmation: true, + confirmationData: { + name, + affectedGroups: impact.affectedGroups, + willBeEmpty: impact.emptiedGroups, + }, + }; + } + + clearPendingConfirmation(); + + try { + group.addTabs?.(groupableTabs); + applyRoutingStateMutation({ + kind: "upsert", + entity: "group", + name: group.label || name, + }); + const titles = groupableTabs.map(tab => tabTitle(tab)).join(", "); + return { + message: `Added ${groupableTabs.length} tab(s) to group "${name}": ${titles}`, + }; + } catch (e) { + return { message: `Failed to add tab to group: ${e}` }; + } + } +} + +export class RemoveTabFromGroupCommand implements Command { + commandName = "remove_tab_from_group"; + description = + "Remove a tab from its tab group (ungroup it). Accepts arguments: { index?: number }. If no index, uses current tab."; + async execute(args: CommandArgs): Promise { + const { gBrowser } = getChrome(); + if (!gBrowser) return { message: "Browser UI (gBrowser) not available." }; + + const idx = numberArg(args, "index"); + const tab = tabByIndexOrCurrent(gBrowser, idx); + if (!tab) + return { message: idx != null ? `No tab ${idx}.` : "No active tab." }; + + const title = tabTitle(tab); + + if (!tab.group) { + return { message: `Tab "${title}" is not in any group.` }; + } + + try { + if (gBrowser.ungroupTab) { + gBrowser.ungroupTab(tab); + markRoutingStateDirty("remove-tab-from-group"); + return { message: `Removed tab "${title}" from its group.` }; + } else { + return { + message: "Tab ungrouping is not available in this Firefox version.", + }; + } + } catch (e) { + return { message: `Failed to remove tab from group: ${e}` }; + } + } +} + +export class RenameTabGroupCommand implements Command { + commandName = "rename_tab_group"; + description = + "Rename a tab group. Accepts arguments: { from: string, to: string }."; + async execute(args: CommandArgs): Promise { + const { gBrowser } = getChrome(); + if (!gBrowser) return { message: "Browser UI (gBrowser) not available." }; + + const from = stringArg(args, "from"); + const to = stringArg(args, "to"); + if (!from || !to) + return { message: "Please provide old and new group names." }; + + const groups = getTabGroups(gBrowser); + const group = findGroupByName(gBrowser, from); + + if (!group) { + return { message: `No tab group named "${from}".` }; + } + + const existingWithNewName = groups.find( + existingGroup => + normalizeName(existingGroup.label || "") === normalizeName(to) + ); + if (existingWithNewName) { + return { message: `A tab group named "${to}" already exists.` }; + } + + try { + group.label = to; + applyRoutingStateMutation({ + kind: "rename", + entity: "group", + from, + to, + }); + return { message: `Renamed tab group "${from}" to "${to}".` }; + } catch (e) { + return { message: `Failed to rename tab group: ${e}` }; + } + } +} + +export class ResolveAmbiguityCommand implements Command { + commandName = "resolve_ambiguity"; + description = + "Resolve an ambiguous request. Accepts arguments: { target?: 'bookmark-folder'|'tab-group'|'tab'|'cancel' }."; + + async execute(args: CommandArgs): Promise { + const pending = getPendingAmbiguity(); + if (!pending) { + return { message: "No pending ambiguous request to resolve." }; + } + + const target = ambiguityTargetArg(args); + if (target === "cancel") { + clearPendingAmbiguity(); + return { message: "Okay, cancelled that request." }; + } + + if (pending.kind === "close_delete_target") { + const allowed = new Set( + pending.choices || ["tab", "tab-group", "bookmark-folder"] + ); + if (!target || !allowed.has(target as AmbiguityTarget)) { + const optionLabels = Array.from(allowed).map(opt => { + if (opt === "tab-group") return "tab group"; + if (opt === "bookmark-folder") return "bookmark folder"; + return "tab"; + }); + const choicesText = + optionLabels.length > 1 + ? `${optionLabels.slice(0, -1).join(", ")} or ${optionLabels[optionLabels.length - 1]}` + : optionLabels[0] || "tab, tab group, or bookmark folder"; + return { + message: + `I found multiple matches for "${pending.name}". ` + + `Do you mean ${choicesText}?`, + }; + } + + clearPendingAmbiguity(); + assistantLogger.debug("ambiguity", "Resolved close/delete target", { + target, + name: pending.name, + }); + + if (target === "tab") { + const cmd = new CloseTabCommand(); + return await cmd.execute( + pending.tabIndex ? { index: pending.tabIndex } : {} + ); + } + if (target === "tab-group") { + const cmd = new DeleteTabGroupCommand(); + return await cmd.execute({ name: pending.name }); + } + const cmd = new DeleteBookmarkFolderCommand(); + return await cmd.execute({ name: pending.name }); + } + + if (target !== "bookmark-folder" && target !== "tab-group") { + return { + message: + `Do you mean a bookmark folder or a tab group for "${pending.name}"? ` + + `Reply with "bookmark folder" or "tab group".`, + }; + } + + clearPendingAmbiguity(); + assistantLogger.debug("ambiguity", "Resolved container target", { + target, + name: pending.name, + }); + + if (target === "tab-group") { + const cmd = new AddTabToGroupCommand(); + return await cmd.execute({ + name: pending.name, + query: pending.query, + all: pending.all, + }); + } + + const cmd = new AddTabToBookmarkFolderCommand(); + return await cmd.execute({ + name: pending.name, + query: pending.query, + all: pending.all, + }); + } +} + +export class ConfirmActionCommand implements Command { + commandName = "confirm_action"; + description = + "Confirm or cancel a pending action. Accepts arguments: { confirmed: boolean }."; + async execute(args: CommandArgs): Promise { + const pending = getPendingConfirmation(); + assistantLogger.debug("confirm-action", "Received confirmation input", { + hasPending: !!pending, + }); + if (!pending) { + assistantLogger.debug("confirm-action", "No pending confirmation found"); + clearContinuationQueue(); + return { message: "No pending action to confirm." }; + } + + const confirmed = args?.confirmed; + if (confirmed !== true && confirmed !== false) { + return { + message: `Pending action: ${pending.description}. Reply "yes" to confirm or "no" to cancel.`, + }; + } + + if (!confirmed) { + clearPendingConfirmation(); + clearContinuationQueue(); + return { message: "Action cancelled." }; + } + + const cmd = getCommandExecutor(pending.command); + if (!cmd) { + clearPendingConfirmation(); + clearContinuationQueue(); + const known = listRegisteredCommandNames().sort(); + return { + message: + `Unknown command: ${pending.command}. ` + + `Known commands: ${known.join(", ")}`, + }; + } + + if (cmd.commandName === this.commandName) { + clearPendingConfirmation(); + clearContinuationQueue(); + return { message: "Cannot confirm confirm_action recursively." }; + } + + return await cmd.execute(pending.args); + } +} + +function formatRelativeVisitTime(visitDate: number): string { + const diff = Date.now() - visitDate; + const minutes = Math.floor(diff / 60000); + if (minutes < 1) return "just now"; + if (minutes < 60) return `${minutes}m ago`; + const hours = Math.floor(minutes / 60); + if (hours < 24) return `${hours}h ago`; + const days = Math.floor(hours / 24); + if (days === 1) return "yesterday"; + if (days < 7) return `${days}d ago`; + if (days < 30) return `${Math.floor(days / 7)}w ago`; + return new Date(visitDate).toLocaleDateString(); +} + +export class SearchHistorySemanticCommand implements Command { + commandName = "search_history"; + description = + "Search the user's recent browsing history (AI semantic search). Use for pages visited, articles read, topics in history. Arguments: { query: string }. If the user asks to list or show their history without a topic, pass query as \"\" to return recent visits."; + + async execute(args: CommandArgs): Promise { + const qVal = (args as Record)?.query; + const query = typeof qVal === "string" ? qVal.trim() : ""; + + if (!query) { + try { + const entries = await fetchRecentHistory(15, false); + if (entries.length === 0) { + return { + message: + "No browsing history found yet, or history could not be read. Open a few websites, then try again.", + }; + } + const formatted = entries.map((r, i) => ({ + index: i + 1, + title: r.title, + url: r.url, + visited: new Date(r.visitDate).toLocaleDateString(), + })); + return { message: JSON.stringify(formatted) }; + } catch (e: any) { + console.error("[SearchHistorySemantic] Recent list failed:", e); + return { + message: + "Could not read browsing history. If this persists, check the Browser Console for [HistoryCollector] errors.", + }; + } + } + + try { + const results = await semanticHistorySearch.search(query, 10); + + const MIN_RELEVANCE = 0.3; + const MAX_RESULTS = 5; + const filtered = results + .filter(r => r.score >= MIN_RELEVANCE) + .slice(0, MAX_RESULTS); + + if (filtered.length === 0) { + let recent: Awaited> = []; + try { + recent = await fetchRecentHistory(50, false); + } catch { + recent = []; + } + if (recent.length === 0) { + return { + message: + "No browsing history is available in this profile (0 visits from Places). " + + "That usually means Firefox's history database did not load — try ./mach run --temp-profile, or delete obj-*/tmp/profile-default and rebuild, then visit a few https sites and retry. " + + `Searched for: "${query}".`, + }; + } + return { + message: + `No history entries matched "${query}" among recent visits (Places has ${recent.length} recent URLs indexed for lookup). ` + + "Try a shorter keyword (e.g. domain name), visit the page again, or check Library → History.", + }; + } + + const formatted = filtered.map((r, i) => ({ + index: i + 1, + title: r.title, + url: r.url, + relevance: Math.round(r.score * 100) + "%", + visited: formatRelativeVisitTime(r.visitDate), + })); + + return { message: JSON.stringify(formatted) }; + } catch (e: any) { + console.error("[SearchHistorySemantic] Search failed:", e); + return { + message: `History search failed: ${e.message || "Unknown error"}. The embedding model may still be loading — please try again in a moment.`, + }; + } + } +} diff --git a/browser/base/content/assistant/build/src/config/env.ts b/browser/base/content/assistant/build/src/config/env.ts new file mode 100644 index 0000000000000..61a3a2dd4a83c --- /dev/null +++ b/browser/base/content/assistant/build/src/config/env.ts @@ -0,0 +1,15 @@ +/** Environment configuration — Supabase URL, anon key, app version. Injected at build time via process.env. */ +export const ENV = { + SUPABASE_URL: process.env.SUPABASE_URL || "", + SUPABASE_ANON_KEY: process.env.SUPABASE_ANON_KEY || "", + APP_VERSION: "1.0.0", + LOG_LEVEL: "info", + validate(): void { + if (!this.SUPABASE_URL) { + throw new Error("SUPABASE_URL is required"); + } + if (!this.SUPABASE_ANON_KEY) { + throw new Error("SUPABASE_ANON_KEY is required"); + } + }, +}; diff --git a/browser/base/content/assistant/build/src/embedding-worker-entry.ts b/browser/base/content/assistant/build/src/embedding-worker-entry.ts new file mode 100644 index 0000000000000..48840478b07f1 --- /dev/null +++ b/browser/base/content/assistant/build/src/embedding-worker-entry.ts @@ -0,0 +1,108 @@ +/** + * Embedding Worker — Runs in Content Process + * + * Loaded inside a element. + * Communicates with the frame script via CustomEvents on document. + * + * Events dispatched (page → frame script): + * "embed-ready" — page script loaded + * "embed-model-loaded" — ONNX model is ready + * "embed-result" — embedding completed { id, embedding } + * "embed-error" — embedding failed { id, error } + * + * Events listened for (frame script → page): + * "embed-request" — { id, text } request to embed + */ + +import { pipeline, env, type FeatureExtractionPipeline } from "@huggingface/transformers"; + +const EMBEDDING_CHROME_BASE = + "chrome://browser/content/assistant/embedding-assets"; + +env.allowRemoteModels = false; +env.allowLocalModels = true; +env.useBrowserCache = false; +env.localModelPath = `${EMBEDDING_CHROME_BASE}/models`; + +const onnxWasm = env.backends.onnx.wasm!; +onnxWasm.numThreads = 1; +onnxWasm.proxy = false; +onnxWasm.wasmPaths = `${EMBEDDING_CHROME_BASE}/ort/`; + +const MODEL_NAME = "Xenova/all-MiniLM-L6-v2"; + +const rootDoc: Document = (() => { + const d = globalThis.document; + if (!d) { + throw new Error("[EmbeddingWorker] document is not available"); + } + return d; +})(); + +let extractor: FeatureExtractionPipeline | null = null; +let loadingPromise: Promise | null = null; + +async function ensureModel(): Promise { + if (extractor) return extractor; + if (loadingPromise) return loadingPromise; + + console.log("[EmbeddingWorker] Loading model..."); + console.time("[EmbeddingWorker] Model load"); + + loadingPromise = pipeline("feature-extraction", MODEL_NAME, { + dtype: "q8", + }) as unknown as Promise; + + try { + extractor = await loadingPromise; + console.timeEnd("[EmbeddingWorker] Model load"); + console.log("[EmbeddingWorker] Model loaded successfully"); + rootDoc.dispatchEvent(new CustomEvent("embed-model-loaded")); + return extractor; + } catch (err) { + loadingPromise = null; + console.error("[EmbeddingWorker] Model load failed:", err); + throw err; + } +} + +async function embed(text: string): Promise { + const model = await ensureModel(); + const truncated = text.length > 512 ? text.substring(0, 512) : text; + const output = await model(truncated, { pooling: "mean", normalize: true }); + return Array.from(output.data as Float32Array); +} + +// Listen for embedding requests from frame script (via CustomEvent) +rootDoc.addEventListener("embed-request", async (event: Event) => { + const detail = (event as CustomEvent<{ id: string; text: string }>).detail; + const { id, text } = detail; + console.log("[EmbeddingWorker] Received embed request, id:", id); + + try { + const embedding = await embed(text); + rootDoc.dispatchEvent(new CustomEvent("embed-result", { + detail: { id, embedding }, + })); + } catch (err: unknown) { + const message = err instanceof Error ? err.message : String(err); + rootDoc.dispatchEvent(new CustomEvent("embed-error", { + detail: { id, error: message }, + })); + } +}); + +// Signal ready — dispatched multiple times to handle timing +function signalReady() { + console.log("[EmbeddingWorker] Dispatching embed-ready event"); + rootDoc.dispatchEvent(new CustomEvent("embed-ready")); +} + +// Signal immediately +signalReady(); +// Signal again after a short delay in case the frame script isn't listening yet +setTimeout(signalReady, 100); +setTimeout(signalReady, 500); +setTimeout(signalReady, 2000); + +console.log("[EmbeddingWorker] Ready, waiting for requests..."); diff --git a/browser/base/content/assistant/build/src/prompts/chatPrompt.ts b/browser/base/content/assistant/build/src/prompts/chatPrompt.ts new file mode 100644 index 0000000000000..ae587d66314e1 --- /dev/null +++ b/browser/base/content/assistant/build/src/prompts/chatPrompt.ts @@ -0,0 +1,88 @@ +/** + * Chat system prompt — defines the assistant's conversational persona. + * + * Used by the chat node when generating natural language responses. + * Defines "Oasis AI" as a general-purpose assistant, with instructions + * for Markdown formatting, search result presentation, and tone. + */ +export const CHAT_SYSTEM_PROMPT = `You are Oasis AI, a helpful and knowledgeable assistant integrated into the Oasis browser. You can help with ANYTHING - not just browser tasks. + +**Product naming:** The browser is Oasis (or Oasis Browser). Do not call it Firefox or imply the user is in Firefox unless you are quoting an external site or add-on name. + +**Your Capabilities:** +- Answer ANY question on any topic (science, history, coding, math, writing, etc.) +- Help with creative tasks (writing, brainstorming, explaining concepts) +- Provide advice and recommendations +- Assist with coding and technical problems +- Have casual conversations +- Format browser-command results into clean user-facing answers + +**Important:** You have access to the complete conversation history, including: +- All previous user requests +- Internal command traces and command results + +Treat command traces as internal context only. Never repeat raw tool payloads verbatim. + +**Response Guidelines:** +1. **Use Markdown inside the response field:** Format your answer using Markdown. + - Use **bold** for key terms or emphasis. + - Use bullet points or numbered lists for organized information. + - Use \`code blocks\` for code, URLs, or technical terms. + - Use headings for longer explanations. +2. **Be Helpful:** Answer questions thoroughly and accurately. If you don't know something, say so. +3. **Interpret Data:** If command context contains raw data, summarize it into human-readable prose inside the response field. Do not echo raw serialized payloads, IDs, or data dumps directly. +4. **Natural Tone:** Be friendly and conversational. Don't mention internal workings or "tool outputs". +5. **Context Aware:** Use the conversation history to provide relevant, contextual responses. +6. **No Trace Echo:** Never start a response by repeating command payload text, IDs, or serialized objects. + +**Formatting search_memory Results:** +When the command context contains search results (from search_memory), the data is structured JSON with: +- **summary**: A short description like "Found 5 results for 'Amazon'". +- **resultsBySource**: Results grouped by source (e.g., "history", "bookmark-folder", "tab"). +- **results**: Flat array of all matches with source, title, url, context, snippet. + +Present them grouped by source with clear headings. For example: + +**Browsing History** +- [Page Title](url) - snippet of matching content + +**Bookmark Folder: Research** +- [Saved Article](url) - snippet + +**Open Tabs** +- [Tab Title](url) - snippet + +If results are empty, say so naturally ("I couldn't find anything matching X in your history or bookmarks."). +If results come from a specific folder, mention the folder name. +When there are many results, highlight the top 3-5 most relevant and mention how many total were found. +Always make URLs clickable using Markdown link syntax. + +**Example - Internal Command Result:** +If the history shows: + - User: "list tabs" + - Internal command result: "[\"Google\", \"CNN\"]" + +You should respond with the response field set to: +"Here are your open tabs: +- **Google** +- **CNN**" + +**Example - General Question:** +User: "What is machine learning?" +You should respond with a clear, helpful explanation inside the response field. + +Remember: You are a fully capable AI assistant. Help the user with whatever they need! + +**IMPORTANT — Output Format:** +Your ENTIRE reply must be a single valid JSON object — no text before or after it, no markdown fences around it. +The Markdown formatting described above goes inside the "response" string value, not at the top level. + +{"response":"","command_type":"","user_intent":""} + +command_type — what the user is asking you to DO: + info_retrieval, navigation, organization, content_transform, content_create, search, automation, system, help, other + +user_intent — the user's underlying goal: + learning, research, work, dev, marketing, shopping, personal, entertainment, meta, other + +Use "other" only when genuinely uncertain. Output ONLY the JSON object.`; diff --git a/browser/base/content/assistant/build/src/prompts/hiddenInstructions.ts b/browser/base/content/assistant/build/src/prompts/hiddenInstructions.ts new file mode 100644 index 0000000000000..4e8edb30948c7 --- /dev/null +++ b/browser/base/content/assistant/build/src/prompts/hiddenInstructions.ts @@ -0,0 +1,38 @@ +/** + * Hidden instructions — context-dependent instructions for the LLM. + * + * Appended as a hidden HumanMessage right before the chat LLM call. + * The user never sees these. Three modes: + * - Summarize: instructions for page summarization + * - Tool output: instructions to present tool results naturally + * - Default: generic "respond helpfully" instruction + */ +export type HiddenInstructionContext = { + hasSummarizeRequest: boolean; + hasToolOutput: boolean; +}; + +const SUMMARIZE_INSTRUCTION = `The content above is from a webpage that the user wants summarized. Please provide a clear, concise summary that: +1. Captures the main topic and key points +2. Uses bullet points for easy reading +3. Keeps it to 3-5 paragraphs max +4. Highlights any important facts, dates, or conclusions +Do NOT mention that you received page content or reference this instruction. Just provide the summary naturally.`; + +const TOOL_OUTPUT_INSTRUCTION = + "The command context above is internal trace data. Write a natural language response to the user's request using it, but never echo raw payload text, JSON, IDs, or serialized objects. Do NOT reference this instruction."; + +const DEFAULT_INSTRUCTION = + "Please respond to the user's message naturally and helpfully. Do NOT reference this instruction."; + +export function buildHiddenInstruction( + ctx: HiddenInstructionContext +): string { + if (ctx.hasSummarizeRequest) { + return SUMMARIZE_INSTRUCTION; + } + if (ctx.hasToolOutput) { + return TOOL_OUTPUT_INSTRUCTION; + } + return DEFAULT_INSTRUCTION; +} diff --git a/browser/base/content/assistant/build/src/prompts/routerPrompt.ts b/browser/base/content/assistant/build/src/prompts/routerPrompt.ts new file mode 100644 index 0000000000000..38684aa4f4c0a --- /dev/null +++ b/browser/base/content/assistant/build/src/prompts/routerPrompt.ts @@ -0,0 +1,61 @@ +/** + * Router system prompt — guides the LLM's command selection. + * + * Sent to the remote Assist API when the supervisor needs to decide + * which command to run. Tells the LLM to pick one command from the + * available list and return it with JSON args. Includes heuristics + * like preferring search_history for browsing history queries, + * open_url for explicit URLs, and web_search for text queries. + */ +// export function buildAssistRouterPrompt( +// commandNames: readonly string[] +// ): string { +// return [ +// "You route the latest user request to one browser command.", +// `Valid commands: ${commandNames.join(", ")}.`, +// "For chained requests, you may call route_action_plan with actions[] (max 3) instead of a single command.", +// "Return chat only when the latest user message is not a browser action.", +// "When selecting a command, return only the command and JSON args.", +// "Never invent command names outside the valid list.", +// "For list/show requests, prefer list_* tools and avoid search_memory unless user explicitly asks to search.", +// "For local find/search requests over tabs/bookmarks/folders, prefer search_memory with folder/source args.", +// "For browsing history queries (pages visited, articles read, sites browsed, 'what was that page about X', 'pull that article', 'what did I read/visit/browse'), ALWAYS use search_history — do NOT respond with chat. Extract the topic as the query argument.", +// "For add/remove/delete/move requests, prefer mutation tools and keep destructive actions explicit.", +// "Prefer open_url for explicit URLs/domains and web_search for plain-language queries.", +// "For follow-ups like 'open it' after search results, prefer open_search_result with index (default 1).", +// "If the user asks to inspect previous search results, use get_recent_search_results.", +// "For ambiguous destructive/container targets, prefer safe commands like resolve_ambiguity instead of guessing.", +// ].join(" "); +// } + +export function buildAssistRouterPrompt( + commandNames: readonly string[] +): string { + return [ + "You route the latest user request to one browser command.", + `Valid commands: ${commandNames.join(", ")}.`, + "For chained requests, you may call route_action_plan with actions[] (max 3) instead of a single command.", + "Return chat only when the latest user message is not a browser action.", + "When selecting a command, return only the command and JSON args.", + "Never invent command names outside the valid list.", + + // CRITICAL: Clear distinction between search_history and search_memory + "SEARCH ROUTING RULES:", + "- search_history: ONLY for BROWSING HISTORY (pages the user visited in the past). Use for: 'what did I read', 'pages I visited', 'articles I browsed', 'what was that site about X', 'pull that article', 'find that page I visited', 'did I visit X'. Extract the topic as the query argument.", + "- search_memory: ONLY for BOOKMARKS, TABS, and BOOKMARK FOLDERS (things the user explicitly saved). Use for: 'search my bookmarks', 'what's in my folder', 'find in bookmarks', 'search bookmark folder X', 'do I have X bookmarked'. Supports folder and source args.", + "- search_memory does NOT search browsing history — use search_history instead.", + "- If the query mentions 'visited', 'browsed', 'read', 'looked at' (past tense) → search_history.", + "- If the query mentions 'bookmarks', 'folder', 'saved', 'tabs' → search_memory.", + + "SPLIT VIEW:", + "- When the user wants split view, side-by-side tabs, two tabs at once, or a split screen of two pages in one window, prefer add_split_view (not chat). Use indices: [i,j] for two tab numbers, withIndex or withQuery to pair the current tab with another, or {} to split the current tab with a new tab.", + "- For removing split view or unsplitting, prefer remove_split_view.", + + "For list/show requests, prefer list_* tools and avoid search_memory unless user explicitly asks to search.", + "For add/remove/delete/move requests, prefer mutation tools and keep destructive actions explicit.", + "Prefer open_url for explicit URLs/domains and web_search for plain-language queries.", + "For follow-ups like 'open it' after search results, prefer open_search_result with index (default 1).", + "If the user asks to inspect previous search results, use get_recent_search_results.", + "For ambiguous destructive/container targets, prefer safe commands like resolve_ambiguity instead of guessing.", + ].join(" "); +} diff --git a/browser/base/content/assistant/build/src/prompts/voicePrompt.ts b/browser/base/content/assistant/build/src/prompts/voicePrompt.ts new file mode 100644 index 0000000000000..94bc5b5276b93 --- /dev/null +++ b/browser/base/content/assistant/build/src/prompts/voicePrompt.ts @@ -0,0 +1,28 @@ +export const VOICE_SCOPE_AND_RECOVERY = `Scope and recovery (voice input — applies to every reply): +- You are primarily an Oasis browsing assistant. Treat what you heard as a command or question about tabs, windows, search, navigation, or page content unless the user clearly asks for general conversation with no browser angle. +- Do not refer to the product as Firefox; the browser is Oasis. +- If a request does not map safely to a browser action or tool, give ONE short clarification (for example: "Say the site name to open, or say 'search X on Google'"). Do not pivot into long empathy, therapy-style, or storytelling replies. +- If the transcript looks fragmentary, nonsensical, or unrelated to browsing, do not invent a personal situation or backstory. Ask them to repeat, or suggest one concrete browser-focused phrase they can try. +`; + +export const VOICE_REPLY_ADDENDUM = `${VOICE_SCOPE_AND_RECOVERY} +You are the user's personal voice assistant in Oasis. Be warm and clear, but stay task-oriented. + +Voice and spoken delivery (this will be read by text-to-speech): +- Sound conversational: vary rhythm, use short and medium sentences, and connect ideas the way people talk ("So the main idea is…", "Here's why that matters…"). +- When explaining something, teach in layers: start with a simple takeaway, then add nuance if useful. Do not sound like you are reading a numbered list aloud unless the user asked for steps. +- Avoid robotic patterns: do not say "Item one, item two", do not over-use "Additionally" or "Furthermore", and do not read markdown symbols or formatting cues. +- Do not read bullet characters or headings as words; rephrase as flowing speech. +- For code, URLs, or file paths: give a short spoken summary unless the user explicitly asked for exact text; spell critical tokens slowly only when needed. +- Keep answers focused for listening; offer to go deeper if the topic is large. + +`; + +export const VOICE_CHAT_TEXT_REPLY_ADDENDUM = `${VOICE_SCOPE_AND_RECOVERY} +You are replying in the chat sidebar as text (nothing will be read aloud). The user spoke their message via the voice orb. + +- Use markdown when it helps (short lists, links, **bold** for emphasis). +- Be concise but complete; they may glance at the chat while continuing the conversation. +- Use your tools when they help fulfill the request. + +`; diff --git a/browser/base/content/assistant/build/src/proxyClient.ts b/browser/base/content/assistant/build/src/proxyClient.ts new file mode 100644 index 0000000000000..bfbee5f20718c --- /dev/null +++ b/browser/base/content/assistant/build/src/proxyClient.ts @@ -0,0 +1,208 @@ +/** + * Remote API client for the backend Lambda. + * + * Provides three endpoints via AWS-signed HTTP requests: + * - assistRemote(): sends user message + tools to the LLM for routing + * - transcribeAudio(): converts voice recordings to text + * - textToSpeech(): converts text responses to audio + * + * All requests require Supabase authentication. + */ +import { postSigned } from "./awsSignedFetch.js"; +import SupabaseAuth from "./services/supabase.js"; + +export type WireMsg = { role: "user" | "model"; content: string }; +export type AssistTool = { + name: string; + description?: string; +}; + +/** + * Lambda should enforce daily tokens using an effective cap: + * daily_limit_base + sum_feedback_bonus_tokens_for_user(user_id) (UTC day, Supabase RPC). + * Return that sum in daily_limit / daily_remaining, or the client bar and server may disagree. + */ +export type QuotaResult = { + allowed?: boolean; + reason?: string; + daily_used?: number; + /** Base daily token cap before feedback bonuses unless backend already folds them in. */ + daily_limit?: number; + daily_remaining?: number; + monthly_used?: number; + monthly_limit?: number; + monthly_remaining?: number; +}; + +export type AssistResponse = { + next?: string; + args?: Record; + content?: string; + reason?: string; + /** Number of model calls used for this assist request (native-assist multi-turn routing). */ + inner_rounds?: number; + /** Gemini usage for this assist (Lambda aggregate or Edge last round); snake_case counts. */ + usage_metadata?: Record; + /** Present on authenticated Supabase Edge responses after `record_llm_usage`. */ + usage_stats?: Record; + quota?: QuotaResult; + [key: string]: unknown; +}; + +/** Optional native-assist routing loop controls (Claude-style inner tool loop). */ +export type AssistRemoteOptions = { + max_inner_rounds?: number; + refine_after_route?: boolean; +}; + +/** + * Reads optional build-time env for multi-turn native assist routing. + * Set in `build/.env.local`: OASIS_ASSIST_MAX_INNER_ROUNDS=1..8, + * OASIS_ASSIST_REFINE_AFTER_ROUTE=1 (requires at least 2 inner rounds; defaults to 3 if max unset). + */ +export function getAssistLoopOptionsFromBuildEnv(): + | AssistRemoteOptions + | undefined { + const rawMax = String( + typeof process.env.OASIS_ASSIST_MAX_INNER_ROUNDS === "string" + ? process.env.OASIS_ASSIST_MAX_INNER_ROUNDS + : "" + ).trim(); + const rawRefine = String( + typeof process.env.OASIS_ASSIST_REFINE_AFTER_ROUTE === "string" + ? process.env.OASIS_ASSIST_REFINE_AFTER_ROUTE + : "" + ).trim(); + const refine = + rawRefine === "1" || /^true$/i.test(rawRefine); + + let max: number | undefined; + if (rawMax !== "") { + const n = parseInt(rawMax, 10); + if (Number.isFinite(n) && n >= 1) { + max = Math.min(8, n); + } + } + if (refine && (max == null || max < 2)) { + max = 3; + } + if (max == null && !refine) { + return undefined; + } + const out: AssistRemoteOptions = {}; + if (max != null) { + out.max_inner_rounds = max; + } + if (refine) { + out.refine_after_route = true; + } + return Object.keys(out).length ? out : undefined; +} +type TtsResponse = { audio: string; mimeType?: string }; +export type TranscribeAudioCaptureMeta = { + preprocessed: boolean; + mimeType: string; + durationMs?: number; + rms?: number; + sampleRateHz?: number; + channels?: number; +}; +export type TranscribeAudioOptions = { + language?: string; + captureMeta?: TranscribeAudioCaptureMeta; + source?: string; + utteranceSeq?: number; +}; + +const supabaseAuth = SupabaseAuth.getInstance(); +let ttsWarmPromise: Promise | null = null; +let ttsWarmed = false; + +async function ensureAuthenticated(): Promise { + const isAuthenticated = await supabaseAuth.isAuthenticated(); + if (!isAuthenticated) { + throw new Error("Authentication required: Please sign in to use voice features"); + } +} + +export async function assistRemote( + system: string, + messages: WireMsg[], + options: string[], + tools: AssistTool[] = [], + generationConfig?: Record, + assistLoop?: AssistRemoteOptions +): Promise { + return postSigned("assist", { + system, + messages, + options, + tools, + ...(generationConfig ? { generation_config: generationConfig } : {}), + ...(assistLoop?.max_inner_rounds != null + ? { max_inner_rounds: assistLoop.max_inner_rounds } + : {}), + ...(assistLoop?.refine_after_route ? { refine_after_route: true } : {}), + }); +} + +export async function transcribeAudio( + audioBlob: Blob, + options: TranscribeAudioOptions = {} +): Promise<{ transcript: string }> { + await ensureAuthenticated(); + + // Convert blob to base64 + const arrayBuffer = await audioBlob.arrayBuffer(); + const base64Audio = btoa( + new Uint8Array(arrayBuffer).reduce((data, byte) => data + String.fromCharCode(byte), '') + ); + + // Call lambda with op: "transcribe" + const result = await postSigned<{ transcript: string }>("transcribe", { + audio: base64Audio, + mimeType: audioBlob.type, + ...(options.language ? { language: options.language } : {}), + ...(options.captureMeta ? { captureMeta: options.captureMeta } : {}), + ...(options.source != null ? { source: options.source } : {}), + ...(options.utteranceSeq != null ? { utteranceSeq: options.utteranceSeq } : {}), + }); + + // Backend returns { transcript: "..." } + return result; +} + +export async function textToSpeech(text: string): Promise { + await ensureAuthenticated(); + + const result = await postSigned("tts", { text }); + + // The lambda should return base64 encoded audio + const audioData = atob(result.audio); + const arrayBuffer = new Uint8Array(audioData.length); + for (let i = 0; i < audioData.length; i++) { + arrayBuffer[i] = audioData.charCodeAt(i); + } + + return new Blob([arrayBuffer], { type: result.mimeType || 'audio/mpeg' }); +} + +export async function warmTextToSpeech(): Promise { + await ensureAuthenticated(); + if (ttsWarmed) { + return; + } + if (!ttsWarmPromise) { + ttsWarmPromise = textToSpeech('Okay.') + .then(() => { + ttsWarmed = true; + }) + .catch(() => { + // ignore warmup failures; real playback can still retry normally + }) + .finally(() => { + ttsWarmPromise = null; + }); + } + await ttsWarmPromise; +} diff --git a/browser/base/content/assistant/build/src/services/assistEndpointState.ts b/browser/base/content/assistant/build/src/services/assistEndpointState.ts new file mode 100644 index 0000000000000..9b00b03df33e6 --- /dev/null +++ b/browser/base/content/assistant/build/src/services/assistEndpointState.ts @@ -0,0 +1,73 @@ +/** + * Assist API health tracking. + * + * Tracks whether the remote Assist endpoint is working. If a call + * returns 404, the endpoint is marked "unsupported" with a 60-second + * cooldown before retrying. Prevents wasted API calls to a failing + * endpoint. Used by supervisorAssist.ts. + */ +export type AssistEndpointCapability = "unknown" | "supported" | "unsupported"; + +type AssistEndpointEntry = { + capability: AssistEndpointCapability; + unsupportedAt: number; +}; + +const ASSIST_UNSUPPORTED_RETRY_MS = 60_000; +const endpointStates = new Map(); + +function normalizeEndpointKey(endpointKey: string): string { + return String(endpointKey || "").trim().toLowerCase(); +} + +function readEntry(endpointKey: string): AssistEndpointEntry { + const key = normalizeEndpointKey(endpointKey); + return ( + endpointStates.get(key) || { + capability: "unknown", + unsupportedAt: 0, + } + ); +} + +function writeEntry(endpointKey: string, entry: AssistEndpointEntry): void { + endpointStates.set(normalizeEndpointKey(endpointKey), entry); +} + +export function shouldAttemptAssist( + endpointKey: string, + now = Date.now() +): boolean { + const entry = readEntry(endpointKey); + if (entry.capability !== "unsupported") { + return true; + } + return now - entry.unsupportedAt >= ASSIST_UNSUPPORTED_RETRY_MS; +} + +export function markAssistSupported(endpointKey: string): void { + writeEntry(endpointKey, { + capability: "supported", + unsupportedAt: 0, + }); +} + +export function markAssistUnsupported( + endpointKey: string, + now = Date.now() +): void { + writeEntry(endpointKey, { + capability: "unsupported", + unsupportedAt: now, + }); +} + +export function getAssistCapability( + endpointKey: string +): AssistEndpointCapability { + return readEntry(endpointKey).capability; +} + +export function __resetAssistEndpointStateForTests(): void { + endpointStates.clear(); +} diff --git a/browser/base/content/assistant/build/src/services/commandExecutionRegistry.ts b/browser/base/content/assistant/build/src/services/commandExecutionRegistry.ts new file mode 100644 index 0000000000000..04312064b4fac --- /dev/null +++ b/browser/base/content/assistant/build/src/services/commandExecutionRegistry.ts @@ -0,0 +1,23 @@ +/** Command lookup registry — maps command names to Command instances. Used by confirm_action to re-execute a pending command by name. */ +import type { Command } from "../commands.js"; + +const commandExecutors = new Map(); + +export function registerCommandExecutors(commands: Command[]): void { + commandExecutors.clear(); + for (const command of commands) { + commandExecutors.set(command.commandName, command); + } +} + +export function getCommandExecutor(commandName: string): Command | null { + const key = String(commandName || "").trim(); + if (!key) { + return null; + } + return commandExecutors.get(key) || null; +} + +export function listRegisteredCommandNames(): string[] { + return Array.from(commandExecutors.keys()); +} diff --git a/browser/base/content/assistant/build/src/services/embeddingService.ts b/browser/base/content/assistant/build/src/services/embeddingService.ts new file mode 100644 index 0000000000000..a670dd8385338 --- /dev/null +++ b/browser/base/content/assistant/build/src/services/embeddingService.ts @@ -0,0 +1,169 @@ +/** + * Embedding Service — Content process worker page + * + * Creates a hidden that loads + * chrome://browser/content/assistant/embedding-worker.html, which runs + * embedding-worker.bundle.js with local ORT WASM + MiniLM weights under + * chrome://browser/content/assistant/embedding-assets/ (no remote hub/CDN). + * The frame script relays CustomEvents between that document and chrome. + */ + +const VECTOR_DIMENSIONS = 384; +const EMBEDDING_WORKER_PAGE_URL = + "chrome://browser/content/assistant/embedding-worker.html"; +const FRAME_SCRIPT_URL = "chrome://browser/content/assistant/embedding-frame-script.js"; + +interface PendingRequest { + resolve: (embedding: number[]) => void; + reject: (error: Error) => void; +} + +class EmbeddingService { + private browser: any = null; + private ready = false; + private modelLoaded = false; + private readyPromise: Promise | null = null; + private pendingRequests = new Map(); + private requestCounter = 0; + + private async ensureBrowser(): Promise { + if (this.ready) return; + if (this.readyPromise) { + await this.readyPromise; + return; + } + + this.readyPromise = new Promise((resolve, reject) => { + console.log("[EmbeddingService] Creating remote content browser..."); + + try { + const Services = (window as any).Services + || (window as any).top?.Services + || (globalThis as any).Services; + + const browserWin = Services?.wm?.getMostRecentWindow("navigator:browser"); + + if (!browserWin) { + reject(new Error("Could not find main browser window")); + return; + } + + this.browser = browserWin.document.createXULElement("browser"); + this.browser.setAttribute("type", "content"); + this.browser.setAttribute("remote", "true"); + this.browser.setAttribute("src", EMBEDDING_WORKER_PAGE_URL); + this.browser.style.cssText = "display:none; width:0; height:0; position:fixed; visibility:hidden;"; + + browserWin.document.documentElement.appendChild(this.browser); + console.log("[EmbeddingService] Browser element appended, waiting for init..."); + + // Wait for the browser to initialize, then load frame script + setTimeout(() => { + try { + if (!this.browser.messageManager) { + console.error("[EmbeddingService] messageManager not available after timeout"); + reject(new Error("messageManager not available")); + return; + } + + console.log("[EmbeddingService] Loading frame script..."); + this.browser.messageManager.loadFrameScript(FRAME_SCRIPT_URL, false); + + this.browser.messageManager.addMessageListener("EmbedWorkerReady", () => { + if (this.ready) return; + console.log("[EmbeddingService] ✅ Worker ready in content process!"); + this.ready = true; + resolve(); + }); + + this.browser.messageManager.addMessageListener("EmbedModelLoaded", () => { + console.log("[EmbeddingService] Model loaded in content process"); + this.modelLoaded = true; + }); + + this.browser.messageManager.addMessageListener("EmbedResponse", (msg: any) => { + const { id, embedding, error } = msg.data; + const pending = this.pendingRequests.get(id); + if (pending) { + this.pendingRequests.delete(id); + if (error) { + pending.reject(new Error(error)); + } else { + pending.resolve(embedding); + } + } + }); + + console.log("[EmbeddingService] Message listeners set up"); + + } catch (err) { + console.error("[EmbeddingService] Setup failed:", err); + reject(err as Error); + } + }, 1000); // Allow browser element to fully initialize + + setTimeout(() => { + if (!this.ready) { + console.error("[EmbeddingService] Timeout: never received EmbedWorkerReady"); + reject(new Error("Embedding browser failed to initialize within 60s")); + } + }, 60000); + + } catch (err) { + console.error("[EmbeddingService] Failed to create browser:", err); + reject(err as Error); + } + }); + + await this.readyPromise; + } + + async embed(text: string): Promise { + await this.ensureBrowser(); + const id = `embed-${++this.requestCounter}`; + + return new Promise((resolve, reject) => { + this.pendingRequests.set(id, { resolve, reject }); + this.browser.messageManager.sendAsyncMessage("EmbedRequest", { id, text }); + + const timeout = this.modelLoaded ? 30000 : 120000; + setTimeout(() => { + if (this.pendingRequests.has(id)) { + this.pendingRequests.delete(id); + reject(new Error(`Embedding timed out after ${timeout / 1000}s`)); + } + }, timeout); + }); + } + + async embedBatch(texts: string[]): Promise { + const results: number[][] = []; + for (const text of texts) { + results.push(await this.embed(text)); + } + return results; + } + + /** + * Start loading the model in the background. + * Does not block — just kicks off the download. + * If it fails, no harm done — ensureBrowser() will retry on first search. + */ + preload(): void { + if (this.ready || this.readyPromise) return; // Already loading or loaded + + console.log("[EmbeddingService] 🚀 Background pre-warming started..."); + this.ensureBrowser().catch(err => { + console.warn("[EmbeddingService] Pre-warming failed (will retry on search):", err); + // Reset so ensureBrowser() tries again on actual search + this.readyPromise = null; + }); + } + + isLoaded(): boolean { + return this.modelLoaded; + } +} + +export const embeddingService = new EmbeddingService(); +export { VECTOR_DIMENSIONS }; diff --git a/browser/base/content/assistant/build/src/services/firefoxFacade.ts b/browser/base/content/assistant/build/src/services/firefoxFacade.ts new file mode 100644 index 0000000000000..709b527ea684b --- /dev/null +++ b/browser/base/content/assistant/build/src/services/firefoxFacade.ts @@ -0,0 +1,180 @@ +/** + * Firefox API facade — abstraction over privileged browser APIs. + * + * Resolves the chrome window, gBrowser, PlacesUtils, and Services. + * Provides helpers for tab/group/bookmark operations: + * - getTabs(), getTabGroups(), findTabsByQuery(), findGroupByName() + * - tabUrl(), tabTitle(), findTabByIndex() + * - withUriFixup(), fetchChildrenBookmarks(), fetchBookmarkByGuid() + * + * Decouples command implementations from direct Firefox API access. + */ +import { + getBrowserWindow, + type AssistantWindowLike, + type BrowserTabGroupLike, + type BrowserTabLike, + type BrowserUriLike, + type BrowserWindowLike, + type GBrowserLike, + type PlacesBookmarkEntry, + type PlacesUtilsLike, + type ServicesLike, +} from "../types/runtime.js"; + +export type ChromeContext = { + topWin: BrowserWindowLike | null; + gBrowser: GBrowserLike | null; + PlacesUtils: PlacesUtilsLike | null; + Services: ServicesLike | null; +}; + +function getAssistantWindow(): AssistantWindowLike { + return window as AssistantWindowLike; +} + +export function getChromeContext(): ChromeContext { + const topWin = getBrowserWindow(); + const assistantWindow = getAssistantWindow(); + const Services = + topWin?.Services || + assistantWindow.Services || + (assistantWindow.top as AssistantWindowLike | undefined)?.Services || + null; + const PlacesUtils = + topWin?.PlacesUtils || + assistantWindow.PlacesUtils || + (assistantWindow.top as AssistantWindowLike | undefined)?.PlacesUtils || + null; + const gBrowser = topWin?.gBrowser || null; + return { topWin, gBrowser, PlacesUtils, Services }; +} + +export function toUrlString(value: unknown): string { + if (!value) return ""; + if (typeof value === "string") return value.trim(); + if (typeof value === "object") { + const uri = value as BrowserUriLike; + const fromSpec = String(uri.spec || "").trim(); + if (fromSpec) return fromSpec; + const fromHref = String(uri.href || "").trim(); + if (fromHref) return fromHref; + const fromToString = String(uri.toString?.() || "").trim(); + if (fromToString && fromToString !== "[object Object]") return fromToString; + } + return ""; +} + +export function normalizeName(value: string): string { + return (value || "").trim().toLowerCase(); +} + +export function getTabs(gBrowser: GBrowserLike | null | undefined): BrowserTabLike[] { + if (!gBrowser?.tabs) return []; + return Array.from(gBrowser.tabs); +} + +export function getTabGroups( + gBrowser: GBrowserLike | null | undefined +): BrowserTabGroupLike[] { + if (!gBrowser) return []; + const groups = gBrowser.getAllTabGroups + ? gBrowser.getAllTabGroups() + : gBrowser.tabGroups || []; + return Array.from(groups); +} + +export function tabUrl(tab: BrowserTabLike | null | undefined): string { + return toUrlString(tab?.linkedBrowser?.currentURI); +} + +export function tabTitle(tab: BrowserTabLike | null | undefined): string { + return ( + tab?.label || + tab?.linkedBrowser?.contentTitle || + tabUrl(tab) || + "(untitled)" + ); +} + +export function findTabByIndex( + gBrowser: GBrowserLike | null | undefined, + index: number | undefined +): BrowserTabLike | null { + const tabs = getTabs(gBrowser); + if (!tabs.length) return null; + if (index == null) return gBrowser?.selectedTab || tabs[0] || null; + const i = Math.max(1, Math.floor(index)); + if (i > tabs.length) return null; + return tabs[i - 1] || null; +} + +export function findTabsByQuery( + gBrowser: GBrowserLike | null | undefined, + query: string +): BrowserTabLike[] { + const target = normalizeName(query); + if (!target) return []; + return getTabs(gBrowser).filter(tab => { + const title = normalizeName(tabTitle(tab)); + const url = normalizeName(tabUrl(tab)); + return title.includes(target) || url.includes(target); + }); +} + +export function findGroupByName( + gBrowser: GBrowserLike | null | undefined, + name: string +): BrowserTabGroupLike | null { + const target = normalizeName(name); + if (!target) return null; + return ( + getTabGroups(gBrowser).find(group => normalizeName(group.label || "") === target) || + null + ); +} + +export function withUriFixup(rawInput: string, services: ServicesLike | null): string { + let input = String(rawInput || "").trim(); + if (!input) return ""; + const info = services?.uriFixup?.getFixupURIInfo?.(input, 2 | 4); + const fixed = toUrlString(info?.preferredURI); + return fixed || input; +} + +export function getSystemPrincipal(services: ServicesLike | null): unknown { + return services?.scriptSecurityManager?.getSystemPrincipal?.(); +} + +export async function fetchChildrenBookmarks( + places: PlacesUtilsLike | null | undefined, + parentGuid: string +): Promise { + if (!places?.bookmarks?.fetch || !parentGuid) return []; + + const collected: PlacesBookmarkEntry[] = []; + const fetched = await places.bookmarks.fetch({ parentGuid }, (bookmark: PlacesBookmarkEntry) => { + collected.push(bookmark); + }); + + if (collected.length > 0) { + return collected; + } + if (Array.isArray(fetched)) { + return fetched; + } + return fetched ? [fetched] : []; +} + +export async function fetchBookmarkByGuid( + places: PlacesUtilsLike | null | undefined, + guid: string +): Promise { + if (!places?.bookmarks?.fetch || !guid) return null; + const fetched = await places.bookmarks.fetch(guid); + if (!fetched) return null; + if (Array.isArray(fetched)) { + return fetched[0] || null; + } + return fetched; +} diff --git a/browser/base/content/assistant/build/src/services/historyCollector.ts b/browser/base/content/assistant/build/src/services/historyCollector.ts new file mode 100644 index 0000000000000..66ca6abdd2bfc --- /dev/null +++ b/browser/base/content/assistant/build/src/services/historyCollector.ts @@ -0,0 +1,224 @@ +/** + * History Collector — Firefox Places API Reader + * + * Reads recent browser history entries from Firefox's internal + * Places database using the privileged PlacesUtils API. This is the + * same API used by hubs.ts for bookmark access. + * + * Returns cleaned, deduplicated { title, url, visitDate, snippet } items, + * filtering out internal Firefox pages (about:, chrome://, etc.) + * and search engine result pages. + */ + +export interface HistoryEntry { + title: string; + url: string; + visitDate: number; // epoch ms + snippet: string; // first ~500 chars of page body text +} + +/** + * Get PlacesUtils from the privileged browser window. + * Follows the same pattern as hubs.ts / commands.ts. + */ +function getPlacesUtils(): any { + const topWin = (window as any).top; + const Services = topWin?.Services || (window as any).Services; + + if (Services?.wm) { + const browserWin = Services.wm.getMostRecentWindow("navigator:browser"); + return browserWin?.PlacesUtils; + } + return topWin?.PlacesUtils; +} + +/** + * Internal URL prefixes that should be excluded from search results. + */ +const EXCLUDED_PREFIXES = [ + "about:", + "chrome://", + "moz-extension://", + "resource://", + "data:", + "blob:", + "javascript:", + "view-source:", +]; + +/** + * Search engine result page (SERP) URL patterns to exclude. + * The actual destination pages are more valuable than the search pages. + */ +const SEARCH_ENGINE_PATTERNS = [ + /^https?:\/\/(www\.)?google\.\w+\/search\?/, + /^https?:\/\/(www\.)?bing\.com\/search\?/, + /^https?:\/\/(www\.)?duckduckgo\.com\/\?q=/, + /^https?:\/\/(www\.)?yahoo\.com\/search/, + /^https?:\/\/(www\.)?baidu\.com\/s\?/, + /^https?:\/\/(www\.)?search\.yahoo\.com\//, +]; + +/** + * Check if a URL is a search engine results page. + */ +function isSearchEnginePage(url: string): boolean { + return SEARCH_ENGINE_PATTERNS.some(pattern => pattern.test(url)); +} + +/** + * Check if a URL is a user-visible web page worth indexing. + */ +function isUserVisibleUrl(url: string): boolean { + if (!url) return false; + if (EXCLUDED_PREFIXES.some(prefix => url.startsWith(prefix))) return false; + if (isSearchEnginePage(url)) return false; + return true; +} + +// ─── Snippet Extraction ──────────────────────────────────────── + +const SNIPPET_MAX_LENGTH = 500; +const SNIPPET_FETCH_TIMEOUT = 5000; // 5s max per page + +/** + * Fetch a URL and extract the first ~500 chars of readable body text. + * Returns empty string on any failure (timeout, 404, CORS, etc.) + * — the caller falls back to title+url for embedding. + */ +async function fetchPageSnippet(url: string): Promise { + try { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), SNIPPET_FETCH_TIMEOUT); + + const response = await fetch(url, { + signal: controller.signal, + headers: { Accept: "text/html" }, + }); + clearTimeout(timeout); + + if (!response.ok) return ""; + + const contentType = response.headers.get("content-type") || ""; + if ( + !contentType.includes("text/html") && + !contentType.includes("text/plain") + ) { + return ""; // Skip PDFs, images, etc. + } + + const html = await response.text(); + + // Strip scripts, styles, and HTML tags — keep only readable text + const textContent = html + .replace(/]*>[\s\S]*?<\/script>/gi, "") + .replace(/]*>[\s\S]*?<\/style>/gi, "") + .replace(/]*>[\s\S]*?<\/nav>/gi, "") + .replace(/]*>[\s\S]*?<\/header>/gi, "") + .replace(/]*>[\s\S]*?<\/footer>/gi, "") + .replace(/<[^>]+>/g, " ") + .replace(/&[a-zA-Z]+;/g, " ") // HTML entities + .replace(/\s+/g, " ") + .trim() + .substring(0, SNIPPET_MAX_LENGTH); + + return textContent; + } catch { + return ""; // Silently fail — title+url fallback is fine + } +} + +// ─── Main History Fetch ──────────────────────────────────────── + +/** + * Fetch recent browsing history from Firefox Places API. + * + * @param maxResults - Maximum number of history entries to return (default 200) + * @param includeSnippets - Whether to fetch page content snippets (default false) + * @returns Array of history entries sorted by visit date (most recent first) + */ +export async function fetchRecentHistory( + maxResults = 200, + includeSnippets = false +): Promise { + const PlacesUtils = getPlacesUtils(); + + if (!PlacesUtils) { + console.warn("[HistoryCollector] PlacesUtils not available"); + return []; + } + + try { + console.time("[HistoryCollector] Fetch history"); + + const options = PlacesUtils.history.getNewQueryOptions(); + options.sortingMode = options.SORT_BY_DATE_DESCENDING; + options.maxResults = maxResults * 2; // fetch extra to account for filtering/dedup + options.includeHidden = false; + + const query = PlacesUtils.history.getNewQuery(); + const result = PlacesUtils.history.executeQuery(query, options); + const root = result.root; + root.containerOpen = true; + + const entries: HistoryEntry[] = []; + const seenUrls = new Set(); + + for (let i = 0; i < root.childCount && entries.length < maxResults; i++) { + const node = root.getChild(i); + const url = node.uri; + + // Skip internal/non-user-visible pages + if (!isUserVisibleUrl(url)) continue; + + // Deduplicate by URL (keep most recent visit) + if (seenUrls.has(url)) continue; + seenUrls.add(url); + + entries.push({ + title: node.title || url, // fallback to URL if no title + url, + // Places stores time in microseconds; convert to ms + visitDate: Math.floor(node.time / 1000), + snippet: "", // populated below if includeSnippets=true + }); + } + + root.containerOpen = false; + + console.timeEnd("[HistoryCollector] Fetch history"); + console.log( + `[HistoryCollector] Fetched ${entries.length} unique history entries` + ); + + // Fetch snippets if requested (parallel, batched to avoid overwhelming) + if (includeSnippets && entries.length > 0) { + console.log( + `[HistoryCollector] Fetching snippets for ${entries.length} entries...` + ); + console.time("[HistoryCollector] Fetch snippets"); + + const BATCH_SIZE = 5; + for (let i = 0; i < entries.length; i += BATCH_SIZE) { + const batch = entries.slice(i, i + BATCH_SIZE); + const snippets = await Promise.all( + batch.map(e => fetchPageSnippet(e.url)) + ); + batch.forEach((entry, j) => { + entry.snippet = snippets[j]; + }); + } + + const withSnippets = entries.filter(e => e.snippet.length > 0).length; + console.timeEnd("[HistoryCollector] Fetch snippets"); + console.log( + `[HistoryCollector] Got snippets for ${withSnippets}/${entries.length} entries` + ); + } + + return entries; + } catch (e) { + console.error("[HistoryCollector] Failed to fetch history:", e); + return []; + } +} diff --git a/browser/base/content/assistant/build/src/services/historyVectorStore.ts b/browser/base/content/assistant/build/src/services/historyVectorStore.ts new file mode 100644 index 0000000000000..d3355acf951a6 --- /dev/null +++ b/browser/base/content/assistant/build/src/services/historyVectorStore.ts @@ -0,0 +1,289 @@ +/** + * History Vector Store — Orama In-Memory Vector Database with IndexedDB Persistence + * + * Creates and manages an Orama database with a schema designed for + * browser history entries. Supports: + * - Inserting history items with pre-computed embeddings + * - Vector similarity search + * - Full reset for re-indexing + * - Save/restore to IndexedDB for persistence across browser restarts + */ + +import { create, insert, search, count, save, load } from "@orama/orama"; +import { VECTOR_DIMENSIONS } from "./embeddingService"; + +// IndexedDB constants +const IDB_NAME = "oasis-semantic-search"; +const IDB_STORE = "vector-index"; +const IDB_KEY_SNAPSHOT = "orama-snapshot"; +const IDB_KEY_URLS = "indexed-urls"; + +export interface HistoryItem { + title: string; + url: string; + snippet: string; + visitDate: number; + embedding: number[]; +} + +export interface SearchResult { + title: string; + url: string; + snippet: string; + visitDate: number; + score: number; +} + +class HistoryVectorStore { + private db: any = null; + + async init(): Promise { + if (this.db) return; + + this.db = create({ + schema: { + title: "string", + url: "string", + snippet: "string", + visitDate: "number", + embedding: `vector[${VECTOR_DIMENSIONS}]` as any, + }, + }); + + console.log("[HistoryVectorStore] Orama DB created"); + } + + async addItem(item: HistoryItem): Promise { + await this.init(); + await insert(this.db, { + title: item.title, + url: item.url, + snippet: item.snippet, + visitDate: item.visitDate, + embedding: item.embedding, + }); + } + + async search( + queryEmbedding: number[], + limit = 10, + minSimilarity = 0.15 + ): Promise { + await this.init(); + + const results = await search(this.db, { + mode: "vector", + vector: { + value: queryEmbedding, + property: "embedding", + }, + similarity: minSimilarity, + limit, + includeVectors: false, + }); + + return results.hits.map((hit: any) => ({ + title: hit.document.title, + url: hit.document.url, + snippet: hit.document.snippet, + visitDate: hit.document.visitDate, + score: hit.score, + })); + } + + async hybridSearch( + queryText: string, + queryEmbedding: number[], + limit = 10 + ): Promise { + await this.init(); + + try { + const results = await search(this.db, { + mode: "hybrid", + term: queryText, + vector: { + value: queryEmbedding, + property: "embedding", + }, + similarity: 0.1, + limit, + includeVectors: false, + hybridWeights: { + text: 0.4, + vector: 0.6, + }, + }); + + return results.hits.map((hit: any) => ({ + title: hit.document.title, + url: hit.document.url, + snippet: hit.document.snippet, + visitDate: hit.document.visitDate, + score: hit.score, + })); + } catch (err) { + console.warn("[HistoryVectorStore] Hybrid search failed, falling back to vector:", err); + return this.search(queryEmbedding, limit, 0.1); + } + } + + async keywordSearch( + queryText: string, + limit = 10 + ): Promise { + await this.init(); + + try { + const results = await search(this.db, { + mode: "fulltext", + term: queryText, + limit, + includeVectors: false, + }); + + return results.hits.map((hit: any) => ({ + title: hit.document.title, + url: hit.document.url, + snippet: hit.document.snippet, + visitDate: hit.document.visitDate, + score: hit.score, + })); + } catch (err) { + console.warn("[HistoryVectorStore] Keyword search failed:", err); + return []; + } + } + + async getCount(): Promise { + await this.init(); + return count(this.db); + } + + async clear(): Promise { + this.db = null; + await this.init(); + } + + // ─── IndexedDB Persistence ───────────────────────────────── + + /** + * Save the current Orama DB state + indexed URLs to IndexedDB. + */ + async saveToStorage(indexedUrls: Set): Promise { + if (!this.db) return; + + try { + const snapshot = save(this.db); + const snapshotJson = JSON.stringify(snapshot); + const urlsJson = JSON.stringify([...indexedUrls]); + + await this.idbPut(IDB_KEY_SNAPSHOT, snapshotJson); + await this.idbPut(IDB_KEY_URLS, urlsJson); + + console.log( + `[HistoryVectorStore] Saved to IndexedDB (${(snapshotJson.length / 1024).toFixed(1)} KB snapshot, ${indexedUrls.size} URLs)` + ); + } catch (err) { + console.warn("[HistoryVectorStore] Failed to save to IndexedDB:", err); + } + } + + /** + * Restore the Orama DB + indexed URLs from IndexedDB. + * Returns the set of indexed URLs if restore was successful, null if not. + */ + async restoreFromStorage(): Promise | null> { + try { + const snapshotJson = await this.idbGet(IDB_KEY_SNAPSHOT); + const urlsJson = await this.idbGet(IDB_KEY_URLS); + + if (!snapshotJson) { + console.log("[HistoryVectorStore] No saved data in IndexedDB"); + return null; + } + + await this.init(); // Create empty DB with schema + const snapshot = JSON.parse(snapshotJson); + load(this.db, snapshot); + + const itemCount = await count(this.db); + console.log( + `[HistoryVectorStore] Restored ${itemCount} entries from IndexedDB` + ); + + // Restore indexed URLs + const urls = urlsJson ? new Set(JSON.parse(urlsJson)) : new Set(); + return urls; + } catch (err) { + console.warn("[HistoryVectorStore] Failed to restore from IndexedDB:", err); + // Reset DB in case of partial load + this.db = null; + return null; + } + } + + /** + * Clear the persisted data from IndexedDB. + */ + async clearStorage(): Promise { + try { + await this.idbDelete(IDB_KEY_SNAPSHOT); + await this.idbDelete(IDB_KEY_URLS); + console.log("[HistoryVectorStore] Cleared IndexedDB storage"); + } catch (err) { + console.warn("[HistoryVectorStore] Failed to clear IndexedDB:", err); + } + } + + // ─── IndexedDB Helpers ───────────────────────────────────── + + private openIDB(): Promise { + return new Promise((resolve, reject) => { + if (typeof indexedDB === "undefined" || !indexedDB) { + reject(new Error("IndexedDB not available")); + return; + } + const request = indexedDB.open(IDB_NAME, 1); + request.onupgradeneeded = () => { + if (!request.result.objectStoreNames.contains(IDB_STORE)) { + request.result.createObjectStore(IDB_STORE); + } + }; + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); + } + + private async idbPut(key: string, value: string): Promise { + const db = await this.openIDB(); + return new Promise((resolve, reject) => { + const tx = db.transaction(IDB_STORE, "readwrite"); + tx.objectStore(IDB_STORE).put(value, key); + tx.oncomplete = () => { db.close(); resolve(); }; + tx.onerror = () => { db.close(); reject(tx.error); }; + }); + } + + private async idbGet(key: string): Promise { + const db = await this.openIDB(); + return new Promise((resolve, reject) => { + const tx = db.transaction(IDB_STORE, "readonly"); + const getReq = tx.objectStore(IDB_STORE).get(key); + getReq.onsuccess = () => { db.close(); resolve(getReq.result || null); }; + getReq.onerror = () => { db.close(); reject(getReq.error); }; + }); + } + + private async idbDelete(key: string): Promise { + const db = await this.openIDB(); + return new Promise((resolve, reject) => { + const tx = db.transaction(IDB_STORE, "readwrite"); + tx.objectStore(IDB_STORE).delete(key); + tx.oncomplete = () => { db.close(); resolve(); }; + tx.onerror = () => { db.close(); reject(tx.error); }; + }); + } +} + +export const historyVectorStore = new HistoryVectorStore(); diff --git a/browser/base/content/assistant/build/src/services/interactionState.ts b/browser/base/content/assistant/build/src/services/interactionState.ts new file mode 100644 index 0000000000000..5d8340bd71a25 --- /dev/null +++ b/browser/base/content/assistant/build/src/services/interactionState.ts @@ -0,0 +1,219 @@ +/** + * Interaction state store — transient state for multi-turn flows. + * + * Singleton managing: + * - pendingConfirmation: destructive action awaiting "yes"/"no" + * - pendingAmbiguity: target matching both a tab group and folder + * - continuationQueue: remaining chained commands after confirmation + * - recentSearchResults: cached results for "open result #N" follow-ups + * + * Emits CustomEvents to notify the UI of state changes. + */ +import type { AssistantWindowLike } from "../types/runtime.js"; +import type { + AmbiguityTarget, + InteractionCommandArgs, + PendingAmbiguityPayload, + PendingConfirmationPayload, +} from "../../../shared/contracts.js"; +import { OASIS_EVENT_CONFIRMATION_UPDATE } from "../../../shared/contracts.js"; +import { assistantLogger } from "../utils/assistantLogger.js"; + +export type { InteractionCommandArgs, AmbiguityTarget }; + +export type PendingConfirmation = PendingConfirmationPayload; + +export type PendingAmbiguity = PendingAmbiguityPayload; + +export type RecentSearchResult = { + index: number; + source: string; + title: string; + url: string; + bookmarkGuid?: string; + context?: string; + snippet?: string; +}; + +class InteractionStateStore { + private pendingConfirmation: PendingConfirmation | null = null; + private pendingAmbiguity: PendingAmbiguity | null = null; + private continuationQueue: string[] = []; + private recentSearchResults: RecentSearchResult[] = []; + private readonly assistantWindow: AssistantWindowLike; + + constructor(assistantWindow: AssistantWindowLike = window as AssistantWindowLike) { + this.assistantWindow = assistantWindow; + this.assistantWindow.oasisGetPendingConfirmation = () => + this.getPendingConfirmation(); + this.assistantWindow.oasisClearPendingConfirmation = () => + this.clearPendingConfirmation(); + this.assistantWindow.oasisGetPendingAmbiguity = () => + this.getPendingAmbiguity(); + } + + getPendingConfirmation(): PendingConfirmation | null { + return this.pendingConfirmation; + } + + setPendingConfirmation(pending: PendingConfirmation | null): void { + this.pendingConfirmation = pending; + if (pending) { + this.clearPendingAmbiguity(); + } + this.emitConfirmationUpdate(pending); + } + + clearPendingConfirmation(): void { + this.pendingConfirmation = null; + this.emitConfirmationUpdate(null); + } + + getPendingAmbiguity(): PendingAmbiguity | null { + return this.pendingAmbiguity; + } + + setPendingAmbiguity(pending: PendingAmbiguity | null): void { + this.pendingAmbiguity = pending; + if (pending) { + assistantLogger.debug("interaction", "Pending ambiguity set", { + kind: pending.kind, + name: pending.name, + query: pending.query || "", + all: !!pending.all, + }); + return; + } + assistantLogger.debug("interaction", "Pending ambiguity cleared"); + } + + clearPendingAmbiguity(): void { + this.pendingAmbiguity = null; + } + + getContinuationQueue(): string[] { + return [...this.continuationQueue]; + } + + setContinuationQueue(queue: string[]): void { + this.continuationQueue = queue + .map(item => String(item || "").trim()) + .filter(Boolean); + assistantLogger.debug("interaction", "Continuation queue updated", { + length: this.continuationQueue.length, + }); + } + + takeContinuationQueue(): string[] { + const next = [...this.continuationQueue]; + this.continuationQueue = []; + if (next.length > 0) { + assistantLogger.debug("interaction", "Continuation queue consumed", { + length: next.length, + }); + } + return next; + } + + clearContinuationQueue(): void { + if (this.continuationQueue.length > 0) { + assistantLogger.debug("interaction", "Continuation queue cleared", { + length: this.continuationQueue.length, + }); + } + this.continuationQueue = []; + } + + getRecentSearchResults(): RecentSearchResult[] { + return this.recentSearchResults.map(result => ({ ...result })); + } + + setRecentSearchResults(results: RecentSearchResult[]): void { + this.recentSearchResults = results + .filter(result => !!result.url) + .slice(0, 25) + .map(result => ({ ...result })); + assistantLogger.debug("interaction", "Recent search results updated", { + count: this.recentSearchResults.length, + }); + } + + clearRecentSearchResults(): void { + if (this.recentSearchResults.length > 0) { + assistantLogger.debug("interaction", "Recent search results cleared"); + } + this.recentSearchResults = []; + } + + private emitConfirmationUpdate(pending: PendingConfirmation | null): void { + try { + const relay = this.assistantWindow.oasisSetPendingConfirmationRelay; + if (typeof relay === "function") { + relay(pending); + } + window.dispatchEvent( + new CustomEvent(OASIS_EVENT_CONFIRMATION_UPDATE, { detail: pending }) + ); + } catch (error) { + assistantLogger.error( + "interaction", + "Failed to update pending confirmation state", + error + ); + } + } +} + +export const interactionState = new InteractionStateStore(); + +export function getPendingConfirmation(): PendingConfirmation | null { + return interactionState.getPendingConfirmation(); +} + +export function setPendingConfirmation(pending: PendingConfirmation | null): void { + interactionState.setPendingConfirmation(pending); +} + +export function clearPendingConfirmation(): void { + interactionState.clearPendingConfirmation(); +} + +export function getPendingAmbiguity(): PendingAmbiguity | null { + return interactionState.getPendingAmbiguity(); +} + +export function setPendingAmbiguity(pending: PendingAmbiguity | null): void { + interactionState.setPendingAmbiguity(pending); +} + +export function clearPendingAmbiguity(): void { + interactionState.clearPendingAmbiguity(); +} + +export function getContinuationQueue(): string[] { + return interactionState.getContinuationQueue(); +} + +export function setContinuationQueue(queue: string[]): void { + interactionState.setContinuationQueue(queue); +} + +export function takeContinuationQueue(): string[] { + return interactionState.takeContinuationQueue(); +} + +export function clearContinuationQueue(): void { + interactionState.clearContinuationQueue(); +} + +export function getRecentSearchResults(): RecentSearchResult[] { + return interactionState.getRecentSearchResults(); +} + +export function setRecentSearchResults(results: RecentSearchResult[]): void { + interactionState.setRecentSearchResults(results); +} + +export function clearRecentSearchResults(): void { + interactionState.clearRecentSearchResults(); +} diff --git a/browser/base/content/assistant/build/src/services/localMemory.ts b/browser/base/content/assistant/build/src/services/localMemory.ts new file mode 100644 index 0000000000000..3867ba648a2be --- /dev/null +++ b/browser/base/content/assistant/build/src/services/localMemory.ts @@ -0,0 +1,841 @@ +/** + * Local memory — full-text search engine (MiniSearch + IndexedDB). + * + * Indexes open tabs, tab groups, bookmarks, browsing history, and + * managed bookmark folders into a searchable local database. Supports + * fuzzy matching, prefix search, and title boosting. Deduplicates + * entries via computed dedupe keys. + * + * Auto-indexes on startup: tab groups, bookmarks, then history (5s delay). + * Used by the search_memory and related commands. + */ +import { openDB, DBSchema, IDBPDatabase } from "idb"; +import MiniSearch, { type SearchResult } from "minisearch"; +import { + computeMemoryDedupeKey, + getMemoryDocFolderName, + getMemoryDocSource, + getMemoryDocUrl, + type MemoryMetadata, + normalizeMemoryName, +} from "../utils/localMemoryUtils.js"; +import { + getBrowserWindow, + type BrowserUriLike, + type BrowserTabLike, + type BrowserTabGroupLike, + type PlacesUtilsLike, +} from "../types/runtime.js"; +import { assistantLogger } from "../utils/assistantLogger.js"; + +function getChrome() { + const topWin = getBrowserWindow(); + const gBrowser = topWin?.gBrowser; + const PlacesUtils = topWin?.PlacesUtils; + return { topWin, gBrowser, PlacesUtils }; +} + +function toUrlString(value: string | BrowserUriLike | undefined): string { + if (!value) return ""; + if (typeof value === "string") return value.trim(); + const fromSpec = String(value.spec || "").trim(); + if (fromSpec) return fromSpec; + const fromHref = String(value.href || "").trim(); + if (fromHref) return fromHref; + return String(value.toString?.() || "").trim(); +} + +const logDebug = (message: unknown, ...meta: unknown[]): void => { + assistantLogger.debug( + "local-memory", + String(message ?? ""), + meta.length === 0 ? undefined : meta.length === 1 ? meta[0] : meta + ); +}; + +const logWarn = (message: unknown, ...meta: unknown[]): void => { + assistantLogger.warn( + "local-memory", + String(message ?? ""), + meta.length === 0 ? undefined : meta.length === 1 ? meta[0] : meta + ); +}; + +const logError = (message: unknown, ...meta: unknown[]): void => { + assistantLogger.error( + "local-memory", + String(message ?? ""), + meta.length === 0 ? undefined : meta.length === 1 ? meta[0] : meta + ); +}; + +// Full-text search using MiniSearch. + +interface MemoryDoc { + id?: number; + text: string; + tokens: string[]; + metadata: MemoryMetadata; + timestamp: number; + url?: string; + dedupeKey?: string; +} + +type SearchIndexedDoc = { + id: number; + text: string; + metadata: MemoryMetadata; + url?: string; + timestamp: number; + dedupeKey?: string; + title?: string; + description?: string; +}; + +export type BookmarkFolderMemoryEntry = { + bookmarkGuid: string; + parentGuid: string; + folderName: string; + title: string; + url: string; + description?: string; +}; + +const OASIS_MANAGED_BOOKMARK_ROOT = "Oasis Hubs"; + +interface MemoryDB extends DBSchema { + documents: { + key: number; + value: MemoryDoc; + indexes: { + "by-timestamp": number; + "by-url": string; + "by-dedupe-key": string; + }; + }; + usage: { + key: string; + value: { userId: string; count: number; timestamp: number }; + }; +} + +class LocalMemoryService { + private dbPromise: Promise>; + private miniSearch: MiniSearch; + private isIndexDirty: boolean = true; + + constructor() { + try { + this.dbPromise = openDB("oasis-memory", 3, { + upgrade(db, oldVersion, _newVersion, transaction) { + if (oldVersion < 1) { + const store = db.createObjectStore("documents", { + keyPath: "id", + autoIncrement: true, + }); + store.createIndex("by-timestamp", "timestamp"); + store.createIndex("by-url", "url", { unique: false }); + } + if (oldVersion < 2) { + db.createObjectStore("usage", { keyPath: "userId" }); + } + if (oldVersion < 3) { + const docsStore = transaction.objectStore("documents"); + if (!docsStore.indexNames.contains("by-dedupe-key")) { + docsStore.createIndex("by-dedupe-key", "dedupeKey", { + unique: true, + }); + } + } + }, + }); + } catch (error) { + logError("[LocalMemory] IndexedDB unavailable in this context", error); + this.dbPromise = Promise.reject(error); + } + + this.miniSearch = new MiniSearch({ + fields: ["text", "title", "description"], + storeFields: ["text", "metadata", "url", "timestamp", "dedupeKey"], + extractField: (doc, fieldName) => { + if (fieldName === "title") return doc.metadata?.title; + if (fieldName === "description") return doc.metadata?.description; + return doc[fieldName as keyof SearchIndexedDoc]; + }, + tokenize: text => this.tokenize(text), + searchOptions: { + boost: { title: 2 }, + fuzzy: 0.2, + prefix: true, + tokenize: text => this.tokenize(text), + }, + }); + + this.backfillDedupeKeys() + .then(() => this.ensureIndex()) + .then(() => { + setTimeout(() => this.indexAll(), 5000); + }) + .catch(error => { + logError("[LocalMemory] initialization failed", error); + }); + } + + // Simple tokenizer: lowercase, replace punctuation with spaces, split by whitespace + private tokenize(text: string): string[] { + return text + .toLowerCase() + .replace(/[^\w\s]/g, " ") // Replace punctuation with space to preserve words + .split(/\s+/) + .filter(t => t.length > 2); // Ignore tiny words + } + + private async backfillDedupeKeys(): Promise { + const db = await this.dbPromise; + const tx = db.transaction("documents", "readwrite"); + const store = tx.store; + const winners = new Map(); + let cursor = await store.openCursor(); + let updated = 0; + let removed = 0; + + while (cursor) { + const id = Number(cursor.primaryKey); + const doc = cursor.value as MemoryDoc; + const dedupeKey = computeMemoryDedupeKey(doc); + const timestamp = Number(doc.timestamp || 0); + const winner = winners.get(dedupeKey); + + if (winner) { + if (timestamp > winner.timestamp) { + await store.delete(winner.id); + winners.set(dedupeKey, { id, timestamp }); + if (doc.dedupeKey !== dedupeKey) { + await cursor.update({ ...doc, dedupeKey }); + updated++; + } + } else { + await cursor.delete(); + } + removed++; + cursor = await cursor.continue(); + continue; + } + + winners.set(dedupeKey, { id, timestamp }); + if (doc.dedupeKey !== dedupeKey) { + await cursor.update({ ...doc, dedupeKey }); + updated++; + } + cursor = await cursor.continue(); + } + + await tx.done; + if (updated > 0 || removed > 0) { + this.isIndexDirty = true; + logDebug( + `[LocalMemory] dedupe backfill updated=${updated} removed_duplicates=${removed}` + ); + } + } + + private async upsertDocumentByDedupeKey( + doc: MemoryDoc + ): Promise<"inserted" | "updated"> { + const db = await this.dbPromise; + const tx = db.transaction("documents", "readwrite"); + const docsStore = tx.store; + const index = docsStore.index("by-dedupe-key"); + const existing = doc.dedupeKey ? await index.get(doc.dedupeKey) : null; + + if (existing?.id != null) { + await docsStore.put({ ...doc, id: existing.id }); + await tx.done; + return "updated"; + } + + await docsStore.add(doc); + await tx.done; + return "inserted"; + } + + private async mutateDocuments( + mutator: (doc: MemoryDoc) => MemoryDoc | null + ): Promise { + const db = await this.dbPromise; + const tx = db.transaction("documents", "readwrite"); + let cursor = await tx.store.openCursor(); + let changed = 0; + + while (cursor) { + const doc = cursor.value as MemoryDoc; + const nextDoc = mutator(doc); + if (nextDoc === null) { + await cursor.delete(); + changed++; + } else if (nextDoc !== doc) { + await cursor.update(nextDoc); + changed++; + } + cursor = await cursor.continue(); + } + + await tx.done; + if (changed > 0) { + this.isIndexDirty = true; + } + return changed; + } + + private async ensureIndex() { + if (!this.isIndexDirty) return; + + const db = await this.dbPromise; + const docs = await db.getAll("documents"); + + this.miniSearch.removeAll(); + if (docs.length > 0) { + this.miniSearch.addAll( + docs.map(d => ({ + id: d.id!, + text: d.text, + metadata: d.metadata, + url: d.url, + timestamp: d.timestamp, + dedupeKey: d.dedupeKey, + })) + ); + } + + this.isIndexDirty = false; + logDebug(`[LocalMemory] Index rebuilt with ${docs.length} documents`); + } + + async addDocument(text: string, metadata: MemoryMetadata = {}, url?: string) { + const tokens = this.tokenize(text); + + const doc: MemoryDoc = { + text, + tokens, + metadata, + timestamp: Date.now(), + url, + dedupeKey: computeMemoryDedupeKey({ text, metadata, url }), + }; + + const upsertResult = await this.upsertDocumentByDedupeKey(doc); + this.isIndexDirty = true; + if (upsertResult === "updated") { + logDebug( + `[LocalMemory] dedupe hit source=${getMemoryDocSource(doc)} key=${doc.dedupeKey}` + ); + } + } + + async removeDocumentByUrl(url: string) { + const db = await this.dbPromise; + const tx = db.transaction("documents", "readwrite"); + const index = tx.store.index("by-url"); + let cursor = await index.openCursor(url); + + while (cursor) { + await cursor.delete(); + cursor = await cursor.continue(); + } + await tx.done; + this.isIndexDirty = true; + logDebug(`Removed documents for URL: ${url}`); + } + + async removeBookmarkFolderDocuments(folderName: string): Promise { + const targetFolder = normalizeMemoryName(folderName); + if (!targetFolder) return 0; + const removed = await this.mutateDocuments(doc => { + if (getMemoryDocSource(doc) !== "bookmark-folder") return doc; + if (getMemoryDocFolderName(doc) !== targetFolder) return doc; + return null; + }); + if (removed > 0) { + logDebug( + `[LocalMemory] Removed ${removed} documents for folder: ${folderName}` + ); + } + return removed; + } + + async removeAllBookmarkFolderDocuments(): Promise { + const removed = await this.mutateDocuments(doc => { + if (getMemoryDocSource(doc) !== "bookmark-folder") return doc; + return null; + }); + if (removed > 0) { + logDebug( + `[LocalMemory] Removed all bookmark-folder documents: ${removed}` + ); + } + return removed; + } + + async removeBookmarkFolderDocumentByUrl( + folderName: string, + url: string + ): Promise { + const targetFolder = normalizeMemoryName(folderName); + if (!targetFolder || !url) return 0; + const removed = await this.mutateDocuments(doc => { + if (getMemoryDocSource(doc) !== "bookmark-folder") return doc; + if (getMemoryDocFolderName(doc) !== targetFolder) return doc; + const docUrl = getMemoryDocUrl(doc); + if (docUrl !== url) return doc; + return null; + }); + if (removed > 0) { + logDebug( + `[LocalMemory] Removed ${removed} folder documents for URL: ${url}` + ); + } + return removed; + } + + async renameBookmarkFolderDocuments( + oldName: string, + newName: string + ): Promise { + const from = normalizeMemoryName(oldName); + const to = (newName || "").trim(); + const toNorm = normalizeMemoryName(newName); + if (!from || !toNorm) return 0; + + const updated = await this.mutateDocuments(doc => { + if (getMemoryDocSource(doc) !== "bookmark-folder") return doc; + if (getMemoryDocFolderName(doc) !== from) return doc; + const metadata = { ...(doc.metadata || {}) }; + metadata.folderName = to; + metadata.hubName = to; + if ( + typeof metadata.context === "string" && + metadata.context.toLowerCase().startsWith("bookmark folder:") + ) { + metadata.context = `Bookmark Folder: ${to}`; + } + return { + ...doc, + metadata, + dedupeKey: computeMemoryDedupeKey({ ...doc, metadata }), + }; + }); + if (updated > 0) { + logDebug( + `[LocalMemory] Renamed ${updated} folder documents: ${oldName} -> ${newName}` + ); + } + return updated; + } + + async syncBookmarkFolderDocuments( + entries: BookmarkFolderMemoryEntry[] + ): Promise<{ added: number; updated: number; removed: number }> { + const byGuid = new Map(); + for (const entry of entries) { + const guid = String(entry.bookmarkGuid || "").trim(); + const url = String(entry.url || "").trim(); + const folderName = String(entry.folderName || "").trim(); + if (!guid || !url || !folderName) continue; + byGuid.set(guid, { ...entry, bookmarkGuid: guid, url, folderName }); + } + + const seen = new Set(); + let updated = 0; + let removed = 0; + + await this.mutateDocuments(doc => { + if (getMemoryDocSource(doc) !== "bookmark-folder") return doc; + + const bookmarkGuid = String(doc.metadata?.bookmarkGuid || "").trim(); + if (!bookmarkGuid) { + removed++; + return null; + } + + const nextEntry = byGuid.get(bookmarkGuid); + if (!nextEntry) { + removed++; + return null; + } + seen.add(bookmarkGuid); + + const previousMetadata = doc.metadata || {}; + const nextMetadata = { + ...previousMetadata, + type: "bookmark_folder_item", + title: nextEntry.title, + url: nextEntry.url, + hub: nextEntry.parentGuid, + hubName: nextEntry.folderName, + folderName: nextEntry.folderName, + bookmarkGuid: nextEntry.bookmarkGuid, + parentGuid: nextEntry.parentGuid, + context: `Bookmark Folder: ${nextEntry.folderName}`, + description: + nextEntry.description ?? previousMetadata.description ?? "", + }; + const nextText = `Title: ${nextEntry.title}\nURL: ${nextEntry.url}\nContent: ${nextMetadata.description || ""}`; + const nextDoc: MemoryDoc = { + ...doc, + text: nextText, + metadata: nextMetadata, + url: nextEntry.url, + dedupeKey: computeMemoryDedupeKey({ + text: nextText, + metadata: nextMetadata, + url: nextEntry.url, + }), + }; + + const unchanged = + doc.text === nextDoc.text && + doc.url === nextDoc.url && + doc.metadata?.title === nextMetadata.title && + doc.metadata?.folderName === nextMetadata.folderName && + doc.metadata?.bookmarkGuid === nextMetadata.bookmarkGuid && + doc.metadata?.parentGuid === nextMetadata.parentGuid; + if (unchanged) return doc; + updated++; + return nextDoc; + }); + + let added = 0; + for (const entry of byGuid.values()) { + if (seen.has(entry.bookmarkGuid)) continue; + const text = `Title: ${entry.title}\nURL: ${entry.url}\nContent: ${entry.description || ""}`; + await this.addDocument( + text, + { + type: "bookmark_folder_item", + title: entry.title, + url: entry.url, + hub: entry.parentGuid, + hubName: entry.folderName, + folderName: entry.folderName, + bookmarkGuid: entry.bookmarkGuid, + parentGuid: entry.parentGuid, + context: `Bookmark Folder: ${entry.folderName}`, + description: entry.description || "", + }, + entry.url + ); + added++; + } + + if (added > 0 || updated > 0 || removed > 0) { + logDebug( + `[LocalMemory] bookmark-folder sync added=${added} updated=${updated} removed=${removed}` + ); + } + return { added, updated, removed }; + } + + private async removeStaleBookmarkSourceDocuments( + validDedupeKeys: Set + ): Promise { + const removed = await this.mutateDocuments(doc => { + if (getMemoryDocSource(doc) !== "bookmark") return doc; + const key = String(doc.dedupeKey || computeMemoryDedupeKey(doc)); + if (validDedupeKeys.has(key)) return doc; + return null; + }); + if (removed > 0) { + logDebug( + `[LocalMemory] Removed stale bookmark-source documents: ${removed}` + ); + } + return removed; + } + + private async removeStaleLiveSourceDocuments( + validDedupeKeys: Set + ): Promise { + const removed = await this.mutateDocuments(doc => { + const source = getMemoryDocSource(doc); + if (source !== "tab" && source !== "tab-group") return doc; + const key = String(doc.dedupeKey || computeMemoryDedupeKey(doc)); + if (validDedupeKeys.has(key)) return doc; + return null; + }); + if (removed > 0) { + logDebug( + `[LocalMemory] Removed stale live tab/tab-group documents: ${removed}` + ); + } + return removed; + } + + async search( + query: string, + limit = 5, + filter?: { hub?: string; folder?: string } + ): Promise< + { text: string; score: number; metadata: MemoryMetadata; url?: string }[] + > { + await this.ensureIndex(); + + const folderFilter = filter?.folder || filter?.hub; + const results = this.miniSearch.search(query, { + filter: result => { + if (folderFilter) { + const name = normalizeMemoryName( + String( + result.metadata?.folderName || result.metadata?.hubName || "" + ) + ); + return name === normalizeMemoryName(folderFilter); + } + return true; + }, + }); + + // Deduplicate results by URL + const seenKeys = new Set(); + const uniqueResults: Array> = []; + + for (const r of results) { + const stored = r as SearchResult & Partial; + const metadata = (stored.metadata || {}) as MemoryMetadata; + const key = String( + stored.dedupeKey || + computeMemoryDedupeKey({ + text: stored.text || "", + url: stored.url, + metadata, + }) + ); + if (seenKeys.has(key)) continue; + seenKeys.add(key); + uniqueResults.push(stored); + if (uniqueResults.length >= limit) break; + } + + return uniqueResults.map(r => ({ + text: r.text || "", + score: r.score, + metadata: (r.metadata || {}) as MemoryMetadata, + url: r.url, + })); + } + async getUsage(userId: string): Promise { + const db = await this.dbPromise; + const record = await db.get("usage", userId); + return record?.count || 0; + } + + async saveUsage(userId: string, count: number) { + const db = await this.dbPromise; + await db.put("usage", { userId, count, timestamp: Date.now() }); + logDebug(`[LocalMemory] Saved usage for ${userId}: ${count}`); + } + + // --- Indexing from Browser --- + + async indexHistory(maxItems = 1000) { + const win = window as Window & { PlacesUtils?: PlacesUtilsLike }; + const PlacesUtils = getChrome().PlacesUtils ?? win.PlacesUtils; + if (!PlacesUtils?.history) return; + + const options = PlacesUtils.history.getNewQueryOptions(); + options.sortingMode = options.SORT_BY_DATE_DESCENDING; + options.maxResults = maxItems; + options.includeHidden = false; + + const query = PlacesUtils.history.getNewQuery(); + const result = PlacesUtils.history.executeQuery(query, options); + const root = result.root; + try { + root.containerOpen = true; + + for (let i = 0; i < root.childCount; i++) { + const node = root.getChild(i); + const uri = node.uri ? String(node.uri) : ""; + if (!uri) continue; + const title = node.title != null ? String(node.title) : ""; + const rawTime = + typeof node.time === "number" ? node.time : Number(node.time) || 0; + const visitTimeMs = Math.floor(rawTime / 1000); + await this.addDocument( + `${title} ${uri}`, + { + type: "history", + title, + url: uri, + timestamp: visitTimeMs, + context: "Browsing History", + }, + uri + ); + } + logDebug(`[LocalMemory] Indexed ${root.childCount} history items.`); + } catch (e) { + logError("[LocalMemory] Failed to index history:", e); + } finally { + root.containerOpen = false; + } + } + + async indexBookmarks() { + const { PlacesUtils } = getChrome(); + const win = window as Window & { + PlacesUtils?: PlacesUtilsLike; + top?: Window & { PlacesUtils?: PlacesUtilsLike }; + }; + const PM = win.PlacesUtils || win.top?.PlacesUtils; + if (!PlacesUtils?.bookmarks && !PM?.bookmarks) return; + const PU = PlacesUtils || PM; + if (!PU?.bookmarks) return; + const bookmarksApi = PU.bookmarks; + + try { + const validBookmarkKeys = new Set(); + const unfiledGuid = bookmarksApi.unfiledGuid; + let hadTraversalFailure = false; + + const processFolder = async (folderGuid: string, folderName: string) => { + try { + const fetched = await bookmarksApi.fetch({ parentGuid: folderGuid }); + const children = Array.isArray(fetched) + ? fetched + : fetched + ? [fetched] + : []; + if (children.length === 0) return; + + for (const child of children) { + if (child.type === bookmarksApi.TYPE_FOLDER) { + const childName = String(child.title || "Untitled"); + const isManagedRoot = + folderGuid === unfiledGuid && + normalizeMemoryName(childName) === + normalizeMemoryName(OASIS_MANAGED_BOOKMARK_ROOT); + if (isManagedRoot) { + continue; + } + await processFolder(child.guid, childName); + } else if (child.type === bookmarksApi.TYPE_BOOKMARK && child.url) { + const url = toUrlString(child.url); + if (!url) continue; + + const metadata: MemoryMetadata = { + type: "bookmark", + title: child.title, + url, + timestamp: child.dateAdded, + context: `Bookmark Folder: ${folderName}`, + folderName, + hubName: folderName, + }; + const text = (child.title || "") + " " + url; + validBookmarkKeys.add( + computeMemoryDedupeKey({ + text, + metadata, + url, + }) + ); + await this.addDocument(text, metadata, url); + } + } + } catch (e) { + hadTraversalFailure = true; + logWarn(`Failed to fetch bookmarks for ${folderGuid}:`, e); + } + }; + + await processFolder(bookmarksApi.menuGuid, "Bookmarks Menu"); + await processFolder(bookmarksApi.toolbarGuid, "Bookmarks Toolbar"); + await processFolder(bookmarksApi.unfiledGuid, "Other Bookmarks"); + if (!hadTraversalFailure) { + await this.removeStaleBookmarkSourceDocuments(validBookmarkKeys); + } else { + logWarn( + "[LocalMemory] Skipped stale bookmark cleanup due to traversal failures." + ); + } + logDebug("[LocalMemory] Bookmarks indexed."); + } catch (e) { + logError("[LocalMemory] Failed to index bookmarks:", e); + } + } + + async indexTabGroups() { + const { gBrowser } = getChrome(); + if (!gBrowser) return; + + try { + const validLiveKeys = new Set(); + const groups = Array.from( + gBrowser.tabGroups || [] + ) as BrowserTabGroupLike[]; + // Index groups + for (const group of groups) { + const groupName = group.label || "(unnamed group)"; + const groupMetadata: MemoryMetadata = { + type: "tab-group", + title: groupName, + id: group.id, + }; + const groupUrl = `about:tab-group?id=${group.id}`; + const groupText = `Tab Group: ${groupName}`; + validLiveKeys.add( + computeMemoryDedupeKey({ + text: groupText, + metadata: groupMetadata, + url: groupUrl, + }) + ); + await this.addDocument(groupText, groupMetadata, groupUrl); + } + + // Index open tabs with group context + const tabs = Array.from(gBrowser.tabs || []) as BrowserTabLike[]; + for (const tab of tabs) { + const url = tab.linkedBrowser?.currentURI?.spec; + const title = tab.label || "(untitled)"; + + let context = "Open Tab"; + if (tab.group) { + const gName = tab.group.label || "Unnamed Group"; + context = `Tab Group: ${gName}`; + } + + if (url && !url.startsWith("about:")) { + const tabMetadata: MemoryMetadata = { + type: "tab", + title, + url, + timestamp: Date.now(), + context: context, + }; + const tabText = title + " " + url; + validLiveKeys.add( + computeMemoryDedupeKey({ + text: tabText, + metadata: tabMetadata, + url, + }) + ); + await this.addDocument(tabText, tabMetadata, url); + } + } + await this.removeStaleLiveSourceDocuments(validLiveKeys); + logDebug(`[LocalMemory] Indexed tabs and groups.`); + } catch (e) { + logError("[LocalMemory] Failed to index tab groups:", e); + } + } + + async indexAll() { + await this.indexTabGroups(); + await this.indexBookmarks(); + await this.indexHistory(); + } +} + +export const localMemory = new LocalMemoryService(); diff --git a/browser/base/content/assistant/build/src/services/railroadMemory.ts b/browser/base/content/assistant/build/src/services/railroadMemory.ts new file mode 100644 index 0000000000000..dec3cb713a942 --- /dev/null +++ b/browser/base/content/assistant/build/src/services/railroadMemory.ts @@ -0,0 +1,243 @@ +/** + * Railroad Memory — long-horizon structured context (IndexedDB). + * + * Session key is set from the UI via window.oasisSetRailroadSessionKey + * (typically `userId:conversationId`). Injected into assist router/chat prompts; + * completed turns are appended as raw sessions for later compaction. + * + * Optional structured extraction: every N turns (see OASIS_RAILROAD_EXTRACTION_INTERVAL, + * default 4; set 0 to disable) we call assist with Railroad.getExtractionPrompt() and + * processExtraction on the JSON result — one extra model call, better long-term memory. + */ +import { createSession, Railroad } from "railroad-memory/browser"; + +import { assistRemote } from "../proxyClient.js"; +import { assistantLogger } from "../utils/assistantLogger.js"; +import type { AssistantWindowLike } from "../types/runtime.js"; +import { parseChatEnvelope } from "../assistant/messageUtils.js"; + +const sessionCache = new Map>(); +const extractionTurnCounts = new Map(); + +const RAILROAD_EXTRACTION_GEN_CONFIG: Record = { + responseMimeType: "application/json", + responseJsonSchema: { + type: "object", + properties: { + response: { + type: "string", + description: "Brief acknowledgment; may be empty.", + }, + newMemories: { + type: "array", + items: { type: "string" }, + description: "Standalone facts to remember for future turns.", + }, + newDecisions: { + type: "array", + items: { type: "string" }, + }, + currentContext: { type: "string" }, + userUpdates: { type: "object" }, + }, + required: ["response"], + }, +}; + +function railroadExtractionInterval(): number { + const raw = String( + typeof process.env.OASIS_RAILROAD_EXTRACTION_INTERVAL === "string" + ? process.env.OASIS_RAILROAD_EXTRACTION_INTERVAL + : "" + ).trim(); + if (raw === "0") { + return 0; + } + if (raw === "") { + return 4; + } + const n = parseInt(raw, 10); + if (!Number.isFinite(n) || n < 1) { + return 4; + } + return Math.min(64, n); +} + +function parseExtractionObject(text: string): Record | null { + const t = text.trim(); + if (!t) { + return null; + } + try { + const o = JSON.parse(t) as unknown; + if (o && typeof o === "object" && !Array.isArray(o)) { + return o as Record; + } + } catch { + /* ignore */ + } + return null; +} + +function sessionKeyFromWindow(win: AssistantWindowLike): string | null { + const raw = win.oasisRailroadSessionKey; + if (typeof raw !== "string") { + return null; + } + const k = raw.trim(); + return k.length > 0 ? k : null; +} + +export function invalidateRailroadSessionCache(): void { + sessionCache.clear(); + extractionTurnCounts.clear(); +} + +async function getOrCreateSession(key: string): Promise { + let p = sessionCache.get(key); + if (!p) { + p = createSession(key, { storage: "indexedDB" }); + sessionCache.set(key, p); + } + return p; +} + +export async function getRailroadForWindow( + win: AssistantWindowLike +): Promise { + const key = sessionKeyFromWindow(win); + if (!key) { + return null; + } + try { + return await getOrCreateSession(key); + } catch (e) { + assistantLogger.warn("railroad", "Session init failed", e); + return null; + } +} + +/** Markdown block appended to router / chat system prompts. */ +export async function getRailroadMemoryPromptBlock( + win: AssistantWindowLike +): Promise { + const rr = await getRailroadForWindow(win); + if (!rr) { + return ""; + } + try { + const block = await rr.getPrunedPrompt(); + const t = String(block || "").trim(); + if (!t) { + return ""; + } + return `\n\n## Long-term memory (Railroad)\n${t}\n`; + } catch (e) { + assistantLogger.warn("railroad", "getPrunedPrompt failed", e); + return ""; + } +} + +export async function recordRailroadTurn( + win: AssistantWindowLike, + userText: string, + assistantMarkdown: string +): Promise { + const rr = await getRailroadForWindow(win); + if (!rr) { + return; + } + const u = String(userText || "").trim(); + const a = String(assistantMarkdown || "").trim(); + if (!u && !a) { + return; + } + try { + await rr.addRawSession(`User:\n${u}\n\nAssistant:\n${a}`); + await rr.incrementMessageCount(); + } catch (e) { + assistantLogger.warn("railroad", "addRawSession failed", e); + } +} + +/** + * Fire-and-forget: on every N-th completed turn, run assist + Railroad.processExtraction. + * N from `OASIS_RAILROAD_EXTRACTION_INTERVAL` (default 4); 0 disables. + */ +export function maybeRunRailroadStructuredExtraction( + win: AssistantWindowLike, + userText: string, + assistantMarkdown: string +): void { + void runRailroadStructuredExtractionMaybe(win, userText, assistantMarkdown); +} + +async function runRailroadStructuredExtractionMaybe( + win: AssistantWindowLike, + userText: string, + assistantMarkdown: string +): Promise { + const interval = railroadExtractionInterval(); + if (interval === 0) { + return; + } + const key = sessionKeyFromWindow(win); + if (!key) { + return; + } + const rr = await getRailroadForWindow(win); + if (!rr) { + return; + } + const prev = extractionTurnCounts.get(key) ?? 0; + const next = prev + 1; + extractionTurnCounts.set(key, next); + if (next % interval !== 0) { + return; + } + + const u = String(userText || "").trim(); + const a = String(assistantMarkdown || "").trim(); + if (!u && !a) { + return; + } + + const block = `USER:\n${u}\n\nASSISTANT:\n${a}`.slice(0, 120_000); + try { + const system = Railroad.getExtractionPrompt(); + const res = await assistRemote( + system, + [{ role: "user", content: block }], + ["chat"], + [], + RAILROAD_EXTRACTION_GEN_CONFIG + ); + const { text } = parseChatEnvelope(res); + const parsed = parseExtractionObject(text); + if (!parsed || typeof parsed.response !== "string") { + assistantLogger.debug("railroad", "extraction: no valid JSON payload"); + return; + } + await rr.processExtraction({ + response: parsed.response, + newMemories: Array.isArray(parsed.newMemories) + ? (parsed.newMemories as string[]).filter(x => typeof x === "string") + : undefined, + newDecisions: Array.isArray(parsed.newDecisions) + ? (parsed.newDecisions as string[]).filter(x => typeof x === "string") + : undefined, + currentContext: + typeof parsed.currentContext === "string" + ? parsed.currentContext + : undefined, + userUpdates: + parsed.userUpdates && typeof parsed.userUpdates === "object" && + !Array.isArray(parsed.userUpdates) + ? (parsed.userUpdates as Record) + : undefined, + }); + assistantLogger.debug("railroad", "extraction: processExtraction applied"); + } catch (e) { + assistantLogger.warn("railroad", "structured extraction failed", e); + } +} diff --git a/browser/base/content/assistant/build/src/services/semanticHistorySearch.ts b/browser/base/content/assistant/build/src/services/semanticHistorySearch.ts new file mode 100644 index 0000000000000..50bebc67aba22 --- /dev/null +++ b/browser/base/content/assistant/build/src/services/semanticHistorySearch.ts @@ -0,0 +1,335 @@ +/** + * Semantic History Search — Orchestrator + * + * Ties together the History Collector, Embedding Service, and + * Orama Vector Store into a single search API. + * + * Key behaviors: + * - Lazy indexing: history is only fetched & embedded on first search + * - IndexedDB persistence: index survives browser restarts + * - Incremental indexing: subsequent searches only embed NEW history entries + * - Singleton indexing: concurrent calls share one indexing pass + * - Embeddings generated in a separate content process (WASM isolation) + */ + +import { embeddingService } from "./embeddingService"; +import { historyVectorStore, type SearchResult } from "./historyVectorStore"; +import { fetchRecentHistory } from "./historyCollector"; + +const MAX_HISTORY_ENTRIES = 500; + +function buildEmbeddingText(title: string, url: string, snippet?: string): string { + if (snippet) { + return `${title} ${snippet}`; + } + try { + const parsed = new URL(url); + const domain = parsed.hostname.replace(/^www\./, ""); + const pathWords = parsed.pathname + .split(/[\/\-_.]/) + .filter(w => w.length > 2 && !/^[0-9a-f]{8,}$/i.test(w)) + .join(" "); + const searchParams = parsed.searchParams.get("q") + || parsed.searchParams.get("query") + || ""; + return `${title} ${domain} ${pathWords} ${searchParams}`.replace(/\s+/g, " ").trim(); + } catch { + return `${title} ${url}`; + } +} + +function mergeSearchResults( + primary: SearchResult[], + secondary: SearchResult[], + limit: number +): SearchResult[] { + const seen = new Set(primary.map(r => r.url)); + const merged = [...primary]; + for (const result of secondary) { + if (!seen.has(result.url)) { + merged.push(result); + seen.add(result.url); + } + } + return merged.slice(0, limit); +} + +class SemanticHistorySearch { + private indexed = false; + private indexingPromise: Promise | null = null; + private indexedUrls = new Set(); // Track what's already indexed + private lastIndexTime = 0; // Timestamp of last indexing + + /** + * Ensure history is indexed. On first call, tries to restore from + * IndexedDB. If no saved data, does a full index. On subsequent + * calls, incrementally indexes only NEW entries. + */ + async ensureIndexed(): Promise { + if (this.indexingPromise) { + await this.indexingPromise; + return; + } + + // First time: try restore, then full index if needed + if (!this.indexed) { + this.indexingPromise = this.tryRestoreOrFullIndex(); + try { + await this.indexingPromise; + } finally { + this.indexingPromise = null; + } + return; + } + + // Subsequent calls: incremental update (only new entries) + this.indexingPromise = this.doIncrementalIndex(); + try { + await this.indexingPromise; + } finally { + this.indexingPromise = null; + } + } + + /** + * Try to restore from IndexedDB first. If no saved data, do full index. + * After indexing, save to IndexedDB for next session. + */ + private async tryRestoreOrFullIndex(): Promise { + // Step 1: Try restoring from IndexedDB + console.log("[SemanticSearch] Checking IndexedDB for saved index..."); + console.time("[SemanticSearch] Restore from IndexedDB"); + + const restoredUrls = await historyVectorStore.restoreFromStorage(); + + if (restoredUrls && restoredUrls.size > 0) { + console.timeEnd("[SemanticSearch] Restore from IndexedDB"); + this.indexedUrls = restoredUrls; + this.indexed = true; + console.log(`[SemanticSearch] ✅ Restored ${restoredUrls.size} entries from IndexedDB — skipping full index`); + + // Do incremental to pick up any new pages since last save + await this.doIncrementalIndex(); + return; + } + + console.timeEnd("[SemanticSearch] Restore from IndexedDB"); + console.log("[SemanticSearch] No saved index found — starting full index"); + + // Step 2: No saved data — do full index + await this.doFullIndex(); + + // Step 3: Save to IndexedDB for next session + await this.persistToStorage(); + } + + /** + * Full index — happens on first search when no saved data exists. + */ + private async doFullIndex(): Promise { + console.log("[SemanticSearch] Starting full history indexing..."); + console.time("[SemanticSearch] Total indexing time"); + + try { + const entries = await fetchRecentHistory(MAX_HISTORY_ENTRIES, true); + + if (entries.length === 0) { + console.warn("[SemanticSearch] No history entries found to index"); + this.indexed = true; + return; + } + + console.log( + `[SemanticSearch] Generating embeddings for ${entries.length} entries...` + ); + + let successCount = 0; + for (let i = 0; i < entries.length; i++) { + const entry = entries[i]; + + try { + const textToEmbed = buildEmbeddingText(entry.title, entry.url, entry.snippet); + const embedding = await embeddingService.embed(textToEmbed); + + await historyVectorStore.addItem({ + title: entry.title, + url: entry.url, + snippet: entry.snippet || entry.title, + visitDate: entry.visitDate, + embedding, + }); + + this.indexedUrls.add(entry.url); + successCount++; + + if ((i + 1) % 50 === 0) { + console.log( + `[SemanticSearch] Indexed ${i + 1}/${entries.length} entries...` + ); + } + } catch (err) { + console.warn( + `[SemanticSearch] Failed to embed entry "${entry.title}":`, + err + ); + } + } + + const dbCount = await historyVectorStore.getCount(); + console.timeEnd("[SemanticSearch] Total indexing time"); + console.log( + `[SemanticSearch] Indexing complete. ${successCount}/${entries.length} entries indexed (${dbCount} in DB)` + ); + + this.indexed = true; + this.lastIndexTime = Date.now(); + } catch (err) { + console.error("[SemanticSearch] Indexing failed:", err); + throw err; + } + } + + /** + * Incremental index — only embed entries not already in the index. + * Runs quickly since it only processes new pages visited since last index. + * Saves to IndexedDB if new entries were added. + */ + private async doIncrementalIndex(): Promise { + try { + // First, quick check for new URLs (no snippet fetching — fast!) + const entries = await fetchRecentHistory(MAX_HISTORY_ENTRIES, false); + + // Filter to only entries NOT already indexed + const newUrls = entries.filter(e => !this.indexedUrls.has(e.url)); + + if (newUrls.length === 0) { + return; // Nothing new to index — fast path + } + + // Now fetch again with snippets only for the new entries + // (re-fetch is needed because we need snippet content for embedding) + const newEntries = await Promise.all( + newUrls.map(async (entry) => { + try { + const response = await fetch(entry.url, { + signal: AbortSignal.timeout(5000), + headers: { "Accept": "text/html" }, + }); + if (!response.ok) return entry; + const ct = response.headers.get("content-type") || ""; + if (!ct.includes("text/html")) return entry; + const html = await response.text(); + entry.snippet = html + .replace(/]*>[\s\S]*?<\/script>/gi, "") + .replace(/]*>[\s\S]*?<\/style>/gi, "") + .replace(/]*>[\s\S]*?<\/nav>/gi, "") + .replace(/]*>[\s\S]*?<\/header>/gi, "") + .replace(/]*>[\s\S]*?<\/footer>/gi, "") + .replace(/<[^>]+>/g, " ") + .replace(/&[a-zA-Z]+;/g, " ") + .replace(/\s+/g, " ") + .trim() + .substring(0, 1000); + } catch { + // Snippet fetch failed — use empty snippet (title+url fallback) + } + return entry; + }) + ); + + console.log( + `[SemanticSearch] Incremental update: ${newEntries.length} new entries to index` + ); + + let successCount = 0; + for (const entry of newEntries) { + try { + const textToEmbed = buildEmbeddingText(entry.title, entry.url, entry.snippet); + const embedding = await embeddingService.embed(textToEmbed); + + await historyVectorStore.addItem({ + title: entry.title, + url: entry.url, + snippet: entry.snippet || entry.title, + visitDate: entry.visitDate, + embedding, + }); + + this.indexedUrls.add(entry.url); + successCount++; + } catch (err) { + console.warn( + `[SemanticSearch] Failed to embed entry "${entry.title}":`, + err + ); + } + } + + const dbCount = await historyVectorStore.getCount(); + console.log( + `[SemanticSearch] Incremental update done. ${successCount} new entries added (${dbCount} total in DB)` + ); + this.lastIndexTime = Date.now(); + + // Persist updated index to IndexedDB + if (successCount > 0) { + await this.persistToStorage(); + } + } catch (err) { + console.error("[SemanticSearch] Incremental indexing failed:", err); + // Don't throw — incremental failure shouldn't break search + } + } + /** + * Save current state to IndexedDB for persistence across restarts. + */ + private async persistToStorage(): Promise { + try { + await historyVectorStore.saveToStorage(this.indexedUrls); + } catch (err) { + console.warn("[SemanticSearch] Failed to persist to storage:", err); + } + } + + async search(query: string, limit = 10): Promise { + await this.ensureIndexed(); + + console.time("[SemanticSearch] Search"); + const queryEmbedding = await embeddingService.embed(query); + let results = await historyVectorStore.hybridSearch(query, queryEmbedding, limit); + + if (results.length === 0) { + console.log("[SemanticSearch] Hybrid returned 0 — trying keyword fallback"); + const keywordResults = await historyVectorStore.keywordSearch(query, limit); + results = mergeSearchResults(results, keywordResults, limit); + } + + if (results.length === 0) { + console.log("[SemanticSearch] Still 0 — trying pure vector with low threshold"); + const vectorResults = await historyVectorStore.search(queryEmbedding, limit, 0.05); + results = mergeSearchResults(results, vectorResults, limit); + } + + console.timeEnd("[SemanticSearch] Search"); + console.log( + `[SemanticSearch] Found ${results.length} results for "${query}"` + ); + + return results; + } + + async reindex(): Promise { + this.indexed = false; + this.indexedUrls.clear(); + await historyVectorStore.clear(); + await historyVectorStore.clearStorage(); + await this.ensureIndexed(); + } + + isReady(): boolean { + return this.indexed; + } +} + +export const semanticHistorySearch = new SemanticHistorySearch(); +(window as any).semanticHistorySearch = semanticHistorySearch; diff --git a/browser/base/content/assistant/build/src/services/subscription.ts b/browser/base/content/assistant/build/src/services/subscription.ts new file mode 100644 index 0000000000000..52856acd3c669 --- /dev/null +++ b/browser/base/content/assistant/build/src/services/subscription.ts @@ -0,0 +1,709 @@ +/** + * Subscription service — usage tracking and plan limits. + * + * Tracks usage units per command (text=1, voice=10), checks monthly + * limits based on the user's plan (free=50, basic=1500, pro=3000), + * persists to both Supabase and local IndexedDB (fail-safe). + * Called before each assistant run to check availability. + * + * **Assist tokens (router + inner rounds):** Supabase Edge `oasis-assist` returns + * `usage_stats` after `record_llm_usage` — call `updateFromAssistUsageStats` so the + * daily bar matches the server without a second `llm_usage` row. Lambda (and + * anonymous Edge) return `usage_metadata` only; the router calls + * `recordAssistRoutingTokens` (token row only, no monthly `usage_count` bump) so + * `llm_usage` reflects Gemini totals including multi-turn aggregation on the server. + * + * Feedback bonus tokens: when `feedback_token_grants` exists, `refreshUsageData` sums today’s + * UTC grants; otherwise the sum is 0. Successful training also increments a per-UTC-day total in + * `sessionStorage` so the bar updates without that table. Lambda `quota` may still raise the + * displayed cap via `getDailyTokenUsageForDisplay` when the triple is self-consistent. + */ +import { supabaseAuth } from "./supabase"; +import { localMemory } from "./localMemory"; +import { assistantLogger } from "../utils/assistantLogger.js"; +import type { UsageMeta } from "../assistant/messageUtils.js"; +import type { QuotaResult } from "../proxyClient.js"; + +// Plan Limits (Units per month) +// Plan A ($20): 1500 units +// Plan B ($40): 3000 units +// Default/Free: 50 units (trial) +const PLAN_LIMITS: Record = { + free: 50, + basic: 1500, // $20/mo + pro: 3000, // $40/mo +}; + +const PLAN_DAILY_TOKEN_LIMITS: Record = { + free: 100_000, + basic: 1_000_000, + pro: 2_000_000, +}; + +const DEFAULT_LIMIT = 50; +const DEFAULT_DAILY_TOKEN_LIMIT = 100_000; + +// Unit Costs +const COST_TEXT = 1; +const COST_VOICE = 10; + +const logDebug = (message: unknown, ...meta: unknown[]): void => { + assistantLogger.debug( + "subscription", + String(message ?? ""), + meta.length === 0 ? undefined : meta.length === 1 ? meta[0] : meta + ); +}; + +const logWarn = (message: unknown, ...meta: unknown[]): void => { + assistantLogger.warn( + "subscription", + String(message ?? ""), + meta.length === 0 ? undefined : meta.length === 1 ? meta[0] : meta + ); +}; + +const logError = (message: unknown, ...meta: unknown[]): void => { + assistantLogger.error( + "subscription", + String(message ?? ""), + meta.length === 0 ? undefined : meta.length === 1 ? meta[0] : meta + ); +}; + +const OPTIMISTIC_FEEDBACK_BONUS_KEY = "oasis.daily_training_bonus.verified."; + +function utcCalendarDateString(): string { + const d = new Date(); + d.setUTCHours(0, 0, 0, 0); + return d.toISOString().slice(0, 10); +} + +function readOptimisticFeedbackBonusTokensToday(): number { + try { + const raw = sessionStorage.getItem( + OPTIMISTIC_FEEDBACK_BONUS_KEY + utcCalendarDateString() + ); + const n = parseInt(String(raw || "0"), 10); + return Number.isFinite(n) && n >= 0 ? n : 0; + } catch { + return 0; + } +} + +function writeOptimisticFeedbackBonusTokensToday(total: number): void { + try { + sessionStorage.setItem( + OPTIMISTIC_FEEDBACK_BONUS_KEY + utcCalendarDateString(), + String(Math.max(0, Math.floor(total))) + ); + } catch { + void 0; + } +} + +export interface UsageStats { + totalUnits: number; + limit: number; + remaining: number; + isLimitReached: boolean; +} + +export type DailyTokenUsageDisplay = { + used: number; + limit: number; + baseLimit: number; + bonusTokens: number; + remaining: number; + percentUsed: number; + percentOfBase: number; +}; + +export class SubscriptionService { + private static instance: SubscriptionService; + + // Cache current plan details to avoid hitting DB on every keystroke + private cachedLimit: number | null = null; + private cachedUsage: number = 0; + private lastFetchTime: number = 0; + private readonly CACHE_TTL = 60 * 1000; // 1 minute cache + + private cachedDailyLimit: number | null = null; + private cachedDailyUsedFromApi: number | null = null; + private cachedDailyRemainingFromApi: number | null = null; + private cachedDailyTokensFromDb: number = 0; + private cachedDailyTokensFromDbOk: boolean = false; + private cachedDailyTokenLimitSupabase: number | null = null; + private cachedFeedbackBonusTokensToday: number = 0; + + private constructor() {} + + public static getInstance(): SubscriptionService { + if (!SubscriptionService.instance) { + SubscriptionService.instance = new SubscriptionService(); + } + return SubscriptionService.instance; + } + + /** + * Call after a qualifying training save succeeds so the daily bar reflects bonus tokens + * even when `feedback_token_grants` is unavailable. Persists for the current UTC calendar day. + */ + public appendOptimisticTrainingBonus(amount: number): void { + if (!Number.isFinite(amount) || amount <= 0) { + return; + } + const add = Math.floor(amount); + const prevCached = this.cachedFeedbackBonusTokensToday; + writeOptimisticFeedbackBonusTokensToday( + readOptimisticFeedbackBonusTokensToday() + add + ); + const fromStorage = readOptimisticFeedbackBonusTokensToday(); + this.cachedFeedbackBonusTokensToday = Math.max( + prevCached + add, + fromStorage + ); + } + + public getUsageBarSnapshot(): DailyTokenUsageDisplay { + return this.getDailyTokenUsageForDisplay(); + } + + public updateFromQuota(quota: QuotaResult | undefined | null): void { + if (!quota) return; + if (quota.monthly_limit !== undefined) { + this.cachedLimit = quota.monthly_limit; + } + if (quota.monthly_used !== undefined) { + this.cachedUsage = quota.monthly_used; + } + if (quota.daily_limit !== undefined) { + this.cachedDailyLimit = quota.daily_limit; + } + if (quota.daily_used !== undefined) { + this.cachedDailyUsedFromApi = quota.daily_used; + } + if (quota.daily_remaining !== undefined) { + this.cachedDailyRemainingFromApi = quota.daily_remaining; + } + this.lastFetchTime = Date.now(); + logDebug( + `updateFromQuota: monthly limit=${this.cachedLimit} used=${this.cachedUsage}; daily limit=${this.cachedDailyLimit} used=${this.cachedDailyUsedFromApi}` + ); + } + + /** + * Apply `usage_stats` from Supabase Edge assist (post-`record_llm_usage`). + * Avoid calling `trackUsage` for the same request when this object is present. + */ + public updateFromAssistUsageStats( + stats: Record | null | undefined + ): void { + if (!stats || typeof stats !== "object") { + return; + } + const patch: QuotaResult = {}; + if ( + typeof stats.total_tokens === "number" && + Number.isFinite(stats.total_tokens) + ) { + patch.daily_used = stats.total_tokens; + } + if (typeof stats.limit === "number" && Number.isFinite(stats.limit)) { + patch.daily_limit = stats.limit; + } + if ( + typeof stats.remaining === "number" && + Number.isFinite(stats.remaining) + ) { + patch.daily_remaining = stats.remaining; + } + if (Object.keys(patch).length > 0) { + this.updateFromQuota(patch); + } + } + + public getDailyTokenUsageForDisplay(): DailyTokenUsageDisplay { + const fromSupabaseLimit = + this.cachedDailyTokenLimitSupabase !== null && + this.cachedDailyTokenLimitSupabase > 0 + ? this.cachedDailyTokenLimitSupabase + : null; + const baseLimit = Math.max( + 1, + fromSupabaseLimit ?? DEFAULT_DAILY_TOKEN_LIMIT + ); + const bonusTokens = Math.max(0, this.cachedFeedbackBonusTokensToday); + const limit = baseLimit + bonusTokens; + const fromApi = this.cachedDailyUsedFromApi ?? 0; + const fromDb = this.cachedDailyTokensFromDb; + const used = Math.max( + 0, + this.cachedDailyTokensFromDbOk ? fromDb : Math.max(fromApi, fromDb) + ); + const remaining = Math.max(0, limit - used); + const percentOfBase = + baseLimit > 0 + ? Math.min(9999, Math.round((used / baseLimit) * 1000) / 10) + : 0; + const percentUsed = + limit > 0 ? Math.min(9999, Math.round((used / limit) * 1000) / 10) : 0; + const local: DailyTokenUsageDisplay = { + used, + limit, + baseLimit, + bonusTokens, + remaining, + percentUsed, + percentOfBase, + }; + + const qLimit = this.cachedDailyLimit; + const qUsed = this.cachedDailyUsedFromApi; + const qRem = this.cachedDailyRemainingFromApi; + if ( + qLimit != null && + qLimit > 0 && + qUsed != null && + qRem != null && + Number.isFinite(qUsed) && + Number.isFinite(qRem) && + Math.abs(qUsed + qRem - qLimit) <= 2 && + qLimit >= local.limit + ) { + const qBonus = Math.max(0, qLimit - local.baseLimit); + const qPercentOfBase = + local.baseLimit > 0 + ? Math.min(9999, Math.round((qUsed / local.baseLimit) * 1000) / 10) + : 0; + const qPercentUsed = + qLimit > 0 + ? Math.min(9999, Math.round((qUsed / qLimit) * 1000) / 10) + : 0; + return { + used: qUsed, + limit: qLimit, + baseLimit: local.baseLimit, + bonusTokens: qBonus, + remaining: qRem, + percentUsed: qPercentUsed, + percentOfBase: qPercentOfBase, + }; + } + + return local; + } + + public async getUsageBarData(): Promise { + await this.forceRefresh(); + return this.getUsageBarSnapshot(); + } + + /** + * Track usage for a command + * @param type 'text' or 'voice' + * @param model Optional model name for record keeping + */ + /** + * Log Gemini tokens for assist **routing** only (`usage_count` / monthly units stay 0). + * Final assistant turns still use `trackUsage` from the graph stream. + */ + public recordAssistRoutingTokens(meta: UsageMeta): void { + void this.recordAssistRoutingTokensAsync(meta); + } + + private async recordAssistRoutingTokensAsync(meta: UsageMeta): Promise { + const user = await supabaseAuth.getCurrentUser(); + if (!user) { + logWarn("recordAssistRoutingTokens: No user found."); + return; + } + const input = Number(meta.input_tokens ?? 0); + const output = Number(meta.output_tokens ?? 0); + if ( + !Number.isFinite(input) || + !Number.isFinite(output) || + (input <= 0 && output <= 0) + ) { + return; + } + const supabase = (supabaseAuth as any).supabase; + const { error } = await supabase.from("llm_usage").insert({ + user_id: user.id, + tokens_used: 0, + usage_count: 0, + model_used: "assist-router", + success: true, + command_type: meta.command_type ?? null, + user_intent: meta.user_intent ?? null, + input_tokens: input, + output_tokens: output, + }); + if (error) { + logError("recordAssistRoutingTokens: DB insert failed", error); + } else { + logDebug("recordAssistRoutingTokens: logged routing tokens", { + input, + output, + }); + } + } + + public async trackUsage( + type: "text" | "voice", + model: string = "gemini-1.5-flash", + meta?: UsageMeta + ): Promise { + const user = await supabaseAuth.getCurrentUser(); + if (!user) { + logWarn("trackUsage: No user found."); + return; + } + + // Calculate units + const units = type === "voice" ? COST_VOICE : COST_TEXT; + logDebug( + `trackUsage: Tracking ${units} units for ${type} (User: ${user.id})` + ); + + // Optimistically update cache + this.cachedUsage += units; + logDebug(`trackUsage: cachedUsage is now ${this.cachedUsage}`); + + // Fail-safe: Save to local memory immediately so we don't lose it if DB fails + localMemory + .saveUsage(user.id, this.cachedUsage) + .catch(e => logError("Failed to save local usage:", e)); + + // Async fire-and-forget insert to not block UI + const supabase = (supabaseAuth as any).supabase; + + supabase + .from("llm_usage") + .insert({ + user_id: user.id, + tokens_used: units, + usage_count: units, + model_used: `${type}:${model}`, + success: true, + command_type: meta?.command_type ?? null, + user_intent: meta?.user_intent ?? null, + input_tokens: meta?.input_tokens ?? 0, + output_tokens: meta?.output_tokens ?? 0, + }) + .then(({ error }: any) => { + if (error) logError("Failed to track usage (DB Insert):", error); + else logDebug("trackUsage: DB insert successful"); + }); + } + + /** + * Check if the user can proceed with a command + */ + public async checkAvailability(): Promise { + const user = await supabaseAuth.getCurrentUser(); + + // If not logged in, they can't use it anyway (handled by auth check), + // but safe fallback: + if (!user) { + return { totalUnits: 0, limit: 0, remaining: 0, isLimitReached: true }; + } + + // Refresh cache if stale or never fetched + if ( + this.lastFetchTime === 0 || + Date.now() - this.lastFetchTime > this.CACHE_TTL + ) { + await this.refreshUsageData(user.id); + } + + const limit = this.cachedLimit ?? DEFAULT_LIMIT; + // Ensure non-negative + const remaining = Math.max(0, limit - this.cachedUsage); + + return { + totalUnits: this.cachedUsage, + limit, + remaining, + isLimitReached: this.cachedUsage >= limit, + }; + } + + public getSubscriptionUrl(): string { + return "https://kahana.co/oasis-pricing"; + } + + public async forceRefresh(): Promise { + const user = await supabaseAuth.getCurrentUser(); + if (user) { + this.lastFetchTime = 0; + await this.refreshUsageData(user.id); + } + } + + private async refreshUsageData(userId: string): Promise { + const supabase = (supabaseAuth as any).supabase; + logDebug("refreshUsageData: syncing usage..."); + + // 1. Get User Plan Limit + let limit = DEFAULT_LIMIT; + + const { data: planData, error: planError } = await supabase + .from("user_plans") + .select( + ` + plan_id, + stripe_subscription_id, + is_active, + plans ( name, llm_call_limit ) + ` + ) + .eq("user_id", userId) + .eq("is_active", true) + .maybeSingle(); + + logDebug(`refreshUsageData: Primary query result:`, { + planData, + planError, + hasPlansJoin: planData && planData.plans ? true : false, + userId, + }); + + let planNameKey = "free"; + let planIdForDaily: string | null = null; + if (planData) { + if (planData.plan_id != null) { + planIdForDaily = String(planData.plan_id); + } + const joined = planData.plans as { name?: string } | null | undefined; + if (joined && typeof joined.name === "string" && joined.name) { + planNameKey = joined.name.toLowerCase(); + } + } + + if (planData && planData.plans) { + const dbLimit = planData.plans.llm_call_limit; + const planName = (planData.plans.name || "").toLowerCase(); + if (dbLimit) { + limit = dbLimit; + logDebug(`refreshUsageData: Using plan limit from DB: ${limit}`); + } else if (PLAN_LIMITS[planName]) { + limit = PLAN_LIMITS[planName]; + logDebug( + `refreshUsageData: Using plan limit from name mapping: ${limit}` + ); + } + } else if (planData && planData.is_active) { + const stripeSubId = planData.stripe_subscription_id; + const hasStripeSubscription = + stripeSubId && + typeof stripeSubId === "string" && + stripeSubId.trim() !== ""; + + logDebug( + `refreshUsageData: Plans join failed but planData exists, checking stripe_subscription_id:`, + { + stripeSubId, + hasStripeSubscription, + is_active: planData.is_active, + } + ); + + if (hasStripeSubscription) { + limit = PLAN_LIMITS["basic"]; + planNameKey = "basic"; + logDebug( + `refreshUsageData: Using Basic plan limit (1500) based on stripe_subscription_id from primary query: ${stripeSubId}` + ); + } else { + logWarn( + "refreshUsageData: Plan data exists but no valid stripe_subscription_id, trying fallback query" + ); + } + } + + if (limit === DEFAULT_LIMIT) { + logWarn( + "refreshUsageData: Limit still at default, trying fallback query without join" + ); + const { data: fallbackData, error: fallbackError } = await supabase + .from("user_plans") + .select("plan_id, stripe_subscription_id, is_active") + .eq("user_id", userId) + .eq("is_active", true) + .maybeSingle(); + + logDebug(`refreshUsageData: Fallback query result:`, { + fallbackData, + fallbackError, + userId, + }); + + if (fallbackError) { + logError("refreshUsageData: Fallback query error:", fallbackError); + } + + if (fallbackData && fallbackData.is_active) { + if (planIdForDaily === null && fallbackData.plan_id != null) { + planIdForDaily = String(fallbackData.plan_id); + } + const stripeSubId = fallbackData.stripe_subscription_id; + const hasStripeSubscription = + stripeSubId && + typeof stripeSubId === "string" && + stripeSubId.trim() !== ""; + + logDebug(`refreshUsageData: Checking stripe_subscription_id:`, { + stripeSubId, + hasStripeSubscription, + type: typeof stripeSubId, + }); + + if (hasStripeSubscription) { + limit = PLAN_LIMITS["basic"]; + planNameKey = "basic"; + logDebug( + `refreshUsageData: Using Basic plan limit (1500) based on stripe_subscription_id: ${stripeSubId}` + ); + } else { + logWarn( + "refreshUsageData: Active plan found but no valid stripe_subscription_id, using free plan limit" + ); + } + } else { + logWarn( + "refreshUsageData: No active plan found for user, using free plan limit", + { + fallbackData, + userId, + } + ); + } + } + + logDebug(`refreshUsageData: Final limit set to: ${limit}`); + this.cachedLimit = limit; + + // 2. Get Current Month Usage from DB + let dbTotal = 0; + const startOfMonth = new Date(); + startOfMonth.setDate(1); + startOfMonth.setHours(0, 0, 0, 0); + + const { data: usageData, error: usageError } = await supabase + .from("llm_usage") + .select("usage_count") + .eq("user_id", userId) + .gte("created_at", startOfMonth.toISOString()); + + if (usageData) { + dbTotal = usageData.reduce( + (acc: number, row: any) => acc + (row.usage_count || 0), + 0 + ); + } + + // 3. Get Local Usage (Fail-safe) + const localTotal = await localMemory.getUsage(userId); + + // 4. Reconcile: DB is source of truth if fetch succeeds + if (!usageError && usageData) { + this.cachedUsage = dbTotal; + // Sync local down to DB truth (resets at month rollover) + localMemory + .saveUsage(userId, dbTotal) + .catch(e => logWarn("refreshUsageData: sync local:", e)); + } else { + if (usageError) { + logWarn( + "refreshUsageData: DB fetch failed (RLS?), using local only.", + usageError.message + ); + } + this.cachedUsage = Math.max(dbTotal, localTotal); + } + + logDebug( + `refreshUsageData: DB=${dbTotal}, Local=${localTotal} -> Final=${this.cachedUsage}` + ); + + let dailyTokLimit: number | null = null; + if (planIdForDaily) { + const { data: planRow, error: planRowErr } = await supabase + .from("plans") + .select("daily_token_limit") + .eq("id", planIdForDaily) + .maybeSingle(); + if (!planRowErr && planRow && planRow.daily_token_limit != null) { + const n = Number(planRow.daily_token_limit); + if (Number.isFinite(n) && n > 0) { + dailyTokLimit = n; + } + } + } + this.cachedDailyTokenLimitSupabase = + dailyTokLimit ?? + PLAN_DAILY_TOKEN_LIMITS[planNameKey] ?? + DEFAULT_DAILY_TOKEN_LIMIT; + + const startOfUtcDay = new Date(); + startOfUtcDay.setUTCHours(0, 0, 0, 0); + const utcGrantDate = startOfUtcDay.toISOString().slice(0, 10); + + let grantSum = 0; + const { data: grantRows, error: grantErr } = await supabase + .from("feedback_token_grants") + .select("tokens") + .eq("user_id", userId) + .eq("grant_date_utc", utcGrantDate); + + if (!grantErr && grantRows) { + grantSum = grantRows.reduce( + (acc: number, row: { tokens?: number }) => + acc + (Number(row.tokens) || 0), + 0 + ); + } else if (grantErr) { + logDebug( + "refreshUsageData: feedback_token_grants unavailable or error", + grantErr.message + ); + } + + const optimistic = readOptimisticFeedbackBonusTokensToday(); + this.cachedFeedbackBonusTokensToday = Math.max( + grantSum, + optimistic, + this.cachedFeedbackBonusTokensToday + ); + + this.cachedDailyTokensFromDbOk = false; + const { data: dayRows, error: dayErr } = await supabase + .from("llm_usage") + .select("input_tokens, output_tokens") + .eq("user_id", userId) + .gte("created_at", startOfUtcDay.toISOString()); + + if (!dayErr && dayRows) { + this.cachedDailyTokensFromDbOk = true; + this.cachedDailyTokensFromDb = dayRows.reduce( + (acc: number, row: { input_tokens?: number; output_tokens?: number }) => + acc + + (Number(row.input_tokens) || 0) + + (Number(row.output_tokens) || 0), + 0 + ); + } else { + if (dayErr) { + logWarn( + "refreshUsageData: daily token aggregate failed", + dayErr.message + ); + } + } + + this.lastFetchTime = Date.now(); + } +} + +export const subscriptionService = SubscriptionService.getInstance(); diff --git a/browser/base/content/assistant/build/src/services/supabase.ts b/browser/base/content/assistant/build/src/services/supabase.ts new file mode 100644 index 0000000000000..c36c6b2474bce --- /dev/null +++ b/browser/base/content/assistant/build/src/services/supabase.ts @@ -0,0 +1,957 @@ +// Supabase Authentication Service for Browser Assistant +import { + createClient, + SupabaseClient, + User, + Session, + AuthError, +} from "@supabase/supabase-js"; +import { ENV } from "../config/env.js"; +import { UserProfile, UserSession, AuthState } from "../types/auth.js"; + +export default class SupabaseAuth { + private static instance: SupabaseAuth; + private supabase: SupabaseClient; + private currentSession: UserSession | null = null; + private authStateCallbacks: Array<(state: AuthState) => void> = []; + private lastTrackedSessionUserId: string | null = null; + private sessionTrackInFlight: { + userId: string; + promise: Promise; + } | null = null; + private oauthCallbackBaseUrl: string | null = null; + private activeOAuthLaunch: { + provider: "google" | "azure" | "apple"; + target: "assistant" | "onboarding"; + flowId: string; + launcherUrl: string; + startedAt: number; + } | null = null; + + private constructor() { + // Initialize Supabase client + this.supabase = createClient(ENV.SUPABASE_URL, ENV.SUPABASE_ANON_KEY); + + // Set up auth state change listener + this.supabase.auth.onAuthStateChange((event, session) => { + console.log("Auth state changed:", event); + this.handleAuthStateChange(event, session); + }); + } + + public static getInstance(): SupabaseAuth { + if (!SupabaseAuth.instance) { + SupabaseAuth.instance = new SupabaseAuth(); + } + return SupabaseAuth.instance; + } + + public setOAuthCallbackBaseUrl(url?: string | null): string { + const normalized = this.normalizeOAuthCallbackBaseUrl(url); + this.oauthCallbackBaseUrl = normalized; + if (typeof window !== "undefined") { + (window as any).__oasisOAuthCallbackBaseUrl = normalized; + } + return this.getOAuthCallbackBaseUrl(); + } + + public getOAuthCallbackBaseUrl(): string { + if (this.oauthCallbackBaseUrl) { + return this.oauthCallbackBaseUrl; + } + if (typeof window !== "undefined") { + const runtimeOverride = (window as any).__oasisOAuthCallbackBaseUrl; + const normalizedRuntime = + this.normalizeOAuthCallbackBaseUrl(runtimeOverride); + if (normalizedRuntime) { + this.oauthCallbackBaseUrl = normalizedRuntime; + return normalizedRuntime; + } + try { + const override = window.localStorage?.getItem( + "oasis_oauth_callback_base_url" + ); + const normalizedStorage = this.normalizeOAuthCallbackBaseUrl(override); + if (normalizedStorage) { + this.oauthCallbackBaseUrl = normalizedStorage; + return normalizedStorage; + } + } catch (e) {} + } + return "https://kahana.co"; + } + + private normalizeOAuthCallbackBaseUrl(url?: string | null): string | null { + if (!url || !/^https?:\/\//i.test(url)) { + return null; + } + return url.replace(/\/+$/, ""); + } + + private createOAuthFlowId(): string { + return `oauth_${Date.now().toString(36)}_${Math.random() + .toString(36) + .slice(2, 8)}`; + } + + private getActiveOAuthLaunch( + provider: "google" | "azure" | "apple", + target: "assistant" | "onboarding" + ) { + if (!this.activeOAuthLaunch) { + return null; + } + + if (Date.now() - this.activeOAuthLaunch.startedAt > 600000) { + this.activeOAuthLaunch = null; + return null; + } + + if ( + this.activeOAuthLaunch.provider === provider && + this.activeOAuthLaunch.target === target + ) { + return this.activeOAuthLaunch; + } + + return null; + } + + private beginOAuthLaunch( + provider: "google" | "azure" | "apple", + target: "assistant" | "onboarding" + ) { + const existingLaunch = this.getActiveOAuthLaunch(provider, target); + if (existingLaunch) { + console.warn( + `[Oasis OAuth][${existingLaunch.flowId}] Reusing active OAuth launcher URL` + ); + return existingLaunch; + } + + const flowId = this.createOAuthFlowId(); + this.setFirefoxOAuthMarker(target, provider, flowId); + const launcherUrl = this.getOAuthLauncherUrl(provider, target, flowId); + const launch = { + provider, + target, + flowId, + launcherUrl, + startedAt: Date.now(), + }; + this.activeOAuthLaunch = launch; + return launch; + } + + private clearActiveOAuthLaunch(flowId?: string) { + if (!this.activeOAuthLaunch) { + return; + } + if (!flowId || this.activeOAuthLaunch.flowId === flowId) { + this.activeOAuthLaunch = null; + } + } + + private getOAuthRedirectUrl( + target: "assistant" | "onboarding" = "assistant", + flowId?: string + ) { + const params = new URLSearchParams({ + flow: "assistant", + handoff_target: target, + }); + if (flowId) { + params.set("flow_id", flowId); + } + return `${this.getOAuthCallbackBaseUrl()}/oauth-callback?${params.toString()}`; + } + + private getOAuthLauncherUrl( + provider: "google" | "azure" | "apple", + target: "assistant" | "onboarding" = "assistant", + flowId?: string + ) { + const params = new URLSearchParams({ + flow: "assistant", + handoff_target: target, + provider, + }); + if (flowId) { + params.set("flow_id", flowId); + } + return `${this.getOAuthCallbackBaseUrl()}/oasis-auth?${params.toString()}`; + } + + private setFirefoxOAuthMarker( + target: "assistant" | "onboarding", + provider: "google" | "azure" | "apple", + flowId: string + ) { + if (typeof window === "undefined") { + return; + } + + const Services = + (window as any).Services || + ((globalThis as any).ChromeUtils + ? (globalThis as any).ChromeUtils.import( + "resource://gre/modules/Services.jsm" + ).Services + : null); + const Ci = (window as any).Ci || (globalThis as any).Ci; + + if (!Services?.cookies || !Ci?.nsICookie) { + return; + } + + const payload = encodeURIComponent( + JSON.stringify({ + target, + provider, + flowId, + timestamp: Date.now(), + callbackBaseUrl: this.getOAuthCallbackBaseUrl(), + }) + ); + const expiry = Date.now() + 3 * 60 * 1000; + + const writeCookie = (baseUrl: string) => { + try { + const parsed = new URL(baseUrl); + const schemeMap = + parsed.protocol === "https:" + ? Ci.nsICookie.SCHEME_HTTPS + : Ci.nsICookie.SCHEME_HTTP; + Services.cookies.add( + parsed.hostname, + "/", + "oasis_firefox_oauth_target", + payload, + parsed.protocol === "https:", + false, + false, + expiry, + {}, + Ci.nsICookie.SAMESITE_LAX, + schemeMap + ); + } catch (e) { + console.warn("Failed to set Firefox OAuth marker cookie:", e); + } + }; + + const callbackBaseUrl = this.getOAuthCallbackBaseUrl(); + writeCookie(callbackBaseUrl); + if (!callbackBaseUrl.includes("kahana.co")) { + writeCookie("https://kahana.co"); + } + } + + // Google OAuth Authentication + public async signInWithGoogle( + target: "assistant" | "onboarding" = "assistant" + ): Promise<{ + user: User | null; + error: AuthError | null; + }> { + try { + const launch = this.beginOAuthLaunch("google", target); + const { flowId, launcherUrl } = launch; + console.log( + `[Oasis OAuth][${flowId}] Preparing Google OAuth launcher URL` + ); + + // Check if user is already authenticated + const currentUser = await this.getCurrentUser(); + if (currentUser) { + console.log( + `[Oasis OAuth][${flowId}] User already authenticated:`, + currentUser.id + ); + return { user: currentUser, error: null }; + } + + console.log( + `[Oasis OAuth][${flowId}] Generated launcher URL:`, + launcherUrl + ); + return { + user: null, + error: new Error(`GOOGLE_OAUTH_URL:${launcherUrl}`) as AuthError, + }; + } catch (error) { + console.error("Google sign in error:", error); + return { user: null, error: error as AuthError }; + } + } + + public async signInWithAzure( + target: "assistant" | "onboarding" = "assistant" + ): Promise<{ + user: User | null; + error: AuthError | null; + }> { + try { + const launch = this.beginOAuthLaunch("azure", target); + const { flowId, launcherUrl } = launch; + console.log( + `[Oasis OAuth][${flowId}] Preparing Azure OAuth launcher URL` + ); + + const currentUser = await this.getCurrentUser(); + if (currentUser) { + console.log( + `[Oasis OAuth][${flowId}] User already authenticated:`, + currentUser.id + ); + return { user: currentUser, error: null }; + } + + console.log( + `[Oasis OAuth][${flowId}] Generated launcher URL:`, + launcherUrl + ); + return { + user: null, + error: new Error(`AZURE_OAUTH_URL:${launcherUrl}`) as AuthError, + }; + } catch (error) { + console.error("Azure sign in error:", error); + return { user: null, error: error as AuthError }; + } + } + + public async signInWithApple( + target: "assistant" | "onboarding" = "assistant" + ): Promise<{ + user: User | null; + error: AuthError | null; + }> { + try { + const launch = this.beginOAuthLaunch("apple", target); + const { flowId, launcherUrl } = launch; + console.log( + `[Oasis OAuth][${flowId}] Preparing Apple OAuth launcher URL` + ); + + const currentUser = await this.getCurrentUser(); + if (currentUser) { + console.log( + `[Oasis OAuth][${flowId}] User already authenticated:`, + currentUser.id + ); + return { user: currentUser, error: null }; + } + + console.log( + `[Oasis OAuth][${flowId}] Generated launcher URL:`, + launcherUrl + ); + return { + user: null, + error: new Error(`APPLE_OAUTH_URL:${launcherUrl}`) as AuthError, + }; + } catch (error) { + console.error("Apple sign in error:", error); + return { user: null, error: error as AuthError }; + } + } + + // Email/Password Authentication + public async signInWithEmail( + email: string, + password: string + ): Promise<{ user: User | null; error: AuthError | null }> { + try { + console.log("Attempting email sign in for:", email); + + const { data, error } = await this.supabase.auth.signInWithPassword({ + email, + password, + }); + + if (error) { + console.error("Email sign in error:", error.message); + return { user: null, error }; + } + + if (data.user) { + await this.updateLastLogin(data.user.id); + await this.createSession(data.user.id); + console.log("Email sign in successful for user:", data.user.id); + } + + return { user: data.user, error: null }; + } catch (error) { + console.error("Sign in error:", error); + return { user: null, error: error as AuthError }; + } + } + + public async signUp( + email: string, + password: string, + name?: string + ): Promise<{ user: User | null; error: AuthError | null }> { + try { + console.log("Attempting sign up for:", email); + + const { data, error } = await this.supabase.auth.signUp({ + email, + password, + options: { + data: { + name: name || email.split("@")[0], + }, + }, + }); + + if (error) { + console.error("Sign up error:", error.message); + return { user: null, error }; + } + + if (data.user) { + // Create user profile in our custom users table + await this.createUserProfile(data.user, name); + console.log("Sign up successful for user:", data.user.id); + } + + return { user: data.user, error: null }; + } catch (error) { + console.error("Sign up error:", error); + return { user: null, error: error as AuthError }; + } + } + + public async resetPasswordForEmail( + email: string + ): Promise<{ error: AuthError | null }> { + try { + console.log("Attempting password reset for:", email); + const { error } = await this.supabase.auth.resetPasswordForEmail(email, { + redirectTo: "https://kahana.co/update-password", + }); + + if (error) { + console.error("Password reset error:", error.message); + return { error }; + } + + console.log("Password reset email sent"); + return { error: null }; + } catch (error) { + console.error("Password reset error:", error); + return { error: error as AuthError }; + } + } + + public async signOut(): Promise<{ error: AuthError | null }> { + try { + console.log("Attempting sign out"); + + // End current session if exists + if (this.currentSession) { + await this.endSession(this.currentSession.session_id); + } + + const { error } = await this.supabase.auth.signOut(); + + if (error) { + console.error("Sign out error:", error.message); + return { error }; + } + + this.currentSession = null; + console.log("Sign out successful"); + return { error: null }; + } catch (error) { + console.error("Sign out error:", error); + return { error: error as AuthError }; + } + } + + // Session Management + public async getCurrentUser(): Promise { + const { + data: { user }, + } = await this.supabase.auth.getUser(); + return user; + } + + public async getSession(): Promise { + const { + data: { session }, + } = await this.supabase.auth.getSession(); + return session; + } + + public async isAuthenticated(): Promise { + const user = await this.getCurrentUser(); + return user !== null; + } + + private normalizeOAuthCallbackPayload(authData: any): { + code?: string; + access_token?: string; + refresh_token?: string; + } { + const out: { + code?: string; + access_token?: string; + refresh_token?: string; + } = {}; + if (!authData || typeof authData !== "object") { + return out; + } + if (typeof authData.code === "string" && authData.code) { + out.code = authData.code; + } + if (authData.access_token && authData.refresh_token) { + out.access_token = authData.access_token; + out.refresh_token = authData.refresh_token; + return out; + } + + const tryParseHash = (raw: string) => { + const h = raw.replace(/^#/, ""); + const params = new URLSearchParams(h); + const at = params.get("access_token"); + const rt = params.get("refresh_token"); + if (at && rt) { + out.access_token = at; + out.refresh_token = rt; + return true; + } + return false; + }; + + const urlLike = + typeof authData.redirect_url === "string" + ? authData.redirect_url + : typeof authData.redirectUrl === "string" + ? authData.redirectUrl + : typeof authData.url === "string" + ? authData.url + : typeof authData.callback_url === "string" + ? authData.callback_url + : null; + if (urlLike?.includes("#")) { + const frag = urlLike.split("#")[1]; + if (frag) { + tryParseHash(frag); + } + } + if ( + !out.access_token && + typeof authData.fragment === "string" && + authData.fragment + ) { + tryParseHash(authData.fragment); + } + if (authData.access_token) { + out.access_token = authData.access_token; + } + if (authData.refresh_token) { + out.refresh_token = authData.refresh_token; + } + return out; + } + + /** + * Handle OAuth callback data (similar to Electron's handleOAuthRedirectCallback) + * Processes auth data from manual input and exchanges it for a session + */ + public async handleOAuthCallbackData( + authData: any + ): Promise<{ success: boolean; error?: string }> { + const flowId = authData?.flow_id || authData?.flowId || "unknown"; + try { + console.log(`[Oasis OAuth][${flowId}] Handling callback data:`, authData); + + const normalized = this.normalizeOAuthCallbackPayload(authData); + if ( + !normalized.code && + !(normalized.access_token && normalized.refresh_token) + ) { + const safeKeys = Object.keys(authData || {}).filter( + k => !/^(access_token|refresh_token|provider_token)$/i.test(k) + ); + console.warn( + `[Oasis OAuth][${flowId}] Incomplete handoff (no code or tokens). Keys: ${safeKeys.join(", ")}` + ); + this.clearActiveOAuthLaunch(flowId); + return { + success: false, + error: + "Complete sign-in in the browser window that opened, then return here.", + }; + } + + // Handle auth code exchange (preferred method) + if (normalized.code) { + console.log( + `[Oasis OAuth][${flowId}] Exchanging auth code for session...` + ); + const { data, error } = await this.supabase.auth.exchangeCodeForSession( + normalized.code + ); + if (error) { + console.error( + `[Oasis OAuth][${flowId}] Failed to exchange code for session:`, + error.message + ); + this.clearActiveOAuthLaunch(flowId); + return { success: false, error: error.message }; + } else { + console.log( + `[Oasis OAuth][${flowId}] Exchanged code for session for user:`, + data.user?.id + ); + + // Ensure user profile exists + if (data.user) { + await this.rpcEnsureUserProfile(data.user); + const existingProfile = await this.getUserProfile(); + if (!existingProfile) { + await this.createUserProfile( + data.user, + data.user.user_metadata?.name + ); + console.log( + `[Oasis OAuth][${flowId}] Created user profile from OAuth callback` + ); + } + + // Update last login and create session + await this.updateLastLogin(data.user.id); + await this.createSession(data.user.id); + } + + this.clearActiveOAuthLaunch(flowId); + return { success: true }; + } + } + + // Handle direct token setting (fallback) + if (normalized.access_token && normalized.refresh_token) { + console.log(`[Oasis OAuth][${flowId}] Setting session from tokens...`); + const { data, error } = await this.supabase.auth.setSession({ + access_token: normalized.access_token, + refresh_token: normalized.refresh_token, + }); + if (error) { + console.error( + `[Oasis OAuth][${flowId}] Failed to set session from tokens:`, + error.message + ); + this.clearActiveOAuthLaunch(flowId); + return { success: false, error: error.message }; + } else { + console.log( + `[Oasis OAuth][${flowId}] Set session from tokens for user:`, + data.user?.id + ); + + // Ensure user profile exists + if (data.user) { + await this.rpcEnsureUserProfile(data.user); + const existingProfile = await this.getUserProfile(); + if (!existingProfile) { + await this.createUserProfile( + data.user, + data.user.user_metadata?.name + ); + console.log( + `[Oasis OAuth][${flowId}] Created user profile from tokens` + ); + } + + // Update last login and create session + await this.updateLastLogin(data.user.id); + await this.createSession(data.user.id); + } + + this.clearActiveOAuthLaunch(flowId); + return { success: true }; + } + } + + console.warn( + `[Oasis OAuth][${flowId}] No valid OAuth data after normalization` + ); + this.clearActiveOAuthLaunch(flowId); + return { + success: false, + error: + "Complete sign-in in the browser window that opened, then return here.", + }; + } catch (error) { + console.error( + `[Oasis OAuth][${flowId}] Error handling callback data:`, + error + ); + this.clearActiveOAuthLaunch(flowId); + return { + success: false, + error: error instanceof Error ? error.message : "Unknown error", + }; + } + } + + // User Profile Management + public async getUserProfile(): Promise { + try { + const user = await this.getCurrentUser(); + if (!user) return null; + + const { data, error } = await this.supabase + .from("users") + .select("*") + .eq("user_id", user.id) + .single(); + + if (error) { + console.error("Error fetching user profile:", error.message); + return null; + } + + return data as UserProfile; + } catch (error) { + console.error("Error fetching user profile:", error); + return null; + } + } + + // Auth State Management + public onAuthStateChange(callback: (state: AuthState) => void): void { + this.authStateCallbacks.push(callback); + } + + private async handleAuthStateChange( + event: string, + session: Session | null + ): Promise { + const user = session?.user || null; + const authState: AuthState = { + user, + session, + isAuthenticated: user !== null, + }; + + // Notify all callbacks + this.authStateCallbacks.forEach(callback => { + try { + callback(authState); + } catch (error) { + console.error("Error in auth state callback:", error); + } + }); + + // Handle session creation/destruction + if (event === "SIGNED_IN" && user) { + await this.rpcEnsureUserProfile(user); + await this.trackSessionForUser(user.id); + } else if (event === "SIGNED_OUT" && this.currentSession) { + this.lastTrackedSessionUserId = null; + await this.endSession(this.currentSession.session_id); + this.currentSession = null; + } else if (event === "SIGNED_OUT") { + this.lastTrackedSessionUserId = null; + } + } + + private async rpcEnsureUserProfile(user: User): Promise { + try { + const meta = user.user_metadata as Record | undefined; + const fullName = + typeof meta?.full_name === "string" ? meta.full_name : undefined; + const metaName = typeof meta?.name === "string" ? meta.name : undefined; + const { error } = await this.supabase.rpc("ensure_user_profile", { + p_email: user.email ?? "", + p_name: fullName ?? metaName ?? null, + }); + if (error) { + console.warn("ensure_user_profile RPC:", error.message); + } + } catch (error) { + console.warn("ensure_user_profile RPC failed:", error); + } + } + + // Database Operations + private async createUserProfile(user: User, name?: string): Promise { + try { + const { error } = await this.supabase.from("users").insert({ + user_id: user.id, + email: user.email!, + name: name || user.user_metadata?.name || user.email!.split("@")[0], + password_hash: "", // Supabase handles this + status: "active", + }); + + if (error) { + console.error("Error creating user profile:", error.message); + } else { + console.log("User profile created successfully"); + } + } catch (error) { + console.error("Error creating user profile:", error); + } + } + + private async updateLastLogin(userId: string): Promise { + try { + const { error } = await this.supabase + .from("users") + .update({ last_login: new Date().toISOString() }) + .eq("user_id", userId); + + if (error) { + console.error("Error updating last login:", error.message); + } + } catch (error) { + console.error("Error updating last login:", error); + } + } + + private async trackSessionForUser(userId: string): Promise { + if ( + this.currentSession?.user_id === userId && + !(this.currentSession as any)?.ended_at + ) { + this.lastTrackedSessionUserId = userId; + return; + } + + if (this.lastTrackedSessionUserId === userId) { + return; + } + + if (this.sessionTrackInFlight?.userId === userId) { + await this.sessionTrackInFlight.promise; + return; + } + + const pendingTrack = { + userId, + promise: Promise.resolve(), + }; + + pendingTrack.promise = this.createSession(userId).finally(() => { + if (this.sessionTrackInFlight === pendingTrack) { + this.sessionTrackInFlight = null; + } + }); + + this.sessionTrackInFlight = pendingTrack; + await pendingTrack.promise; + this.lastTrackedSessionUserId = userId; + } + + private async createSession(userId: string): Promise { + try { + const deviceInfo = { + platform: "browser", + version: ENV.APP_VERSION, + userAgent: window.navigator.userAgent, + }; + + const { data, error } = await this.supabase + .from("sessions") + .insert({ + user_id: userId, + device_info: deviceInfo, + }) + .select() + .single(); + + if (error) { + // Ignore RLS errors as they might happen if the user is not fully synced yet + if (error.message.includes("row-level security policy")) { + console.warn( + "Session tracking skipped due to RLS policy (non-critical):", + error.message + ); + } else { + console.error("Error creating session:", error.message); + } + } else if (data) { + this.currentSession = data as UserSession; + console.log("Session created:", data.session_id); + } + } catch (error) { + console.error("Error creating session:", error); + } + } + + private async endSession(sessionId: string): Promise { + try { + const { error } = await this.supabase + .from("sessions") + .update({ ended_at: new Date().toISOString() }) + .eq("session_id", sessionId); + + if (error) { + console.error("Error ending session:", error.message); + } else { + console.log("Session ended:", sessionId); + } + } catch (error) { + console.error("Error ending session:", error); + } + } + + // Utility Methods + public handleAuthError(error: AuthError): string { + // Handle special OAuth URL case + if ( + error.message && + (error.message.startsWith("GOOGLE_OAUTH_URL:") || + error.message.startsWith("AZURE_OAUTH_URL:") || + error.message.startsWith("APPLE_OAUTH_URL:")) + ) { + return error.message; // Return the full message with URL + } + + switch (error.message) { + case "Invalid login credentials": + return "Invalid email or password. Please try again."; + case "Email not confirmed": + return "Please check your email and click the confirmation link."; + case "User already registered": + return "An account with this email already exists."; + case "Password should be at least 6 characters": + return "Password must be at least 6 characters long."; + case "Unable to validate email address: invalid format": + return "Please enter a valid email address."; + case "OAuth provider not found": + return "Google sign-in is not configured. Please contact support."; + case "OAuth account not linked": + return "This Google account is not linked to an existing account."; + case "Google sign-in is blocked by browser security. Please use email/password authentication instead.": + return "Google sign-in is blocked by browser security. Please use email/password authentication instead."; + case "Popup blocked. Please allow popups for this site and try again.": + return "Popup blocked. Please allow popups for this site and try again."; + case "Google sign-in was cancelled or failed. Please try again.": + return "Google sign-in was cancelled or failed. Please try again."; + case "Google sign-in timed out. Please try again.": + return "Google sign-in timed out. Please try again."; + case "Failed to generate OAuth URL": + return "Failed to generate OAuth URL. Please try again."; + case "Failed to open OAuth URL. Please allow popups and try again.": + return "Failed to open OAuth URL. Please allow popups and try again."; + default: + return ( + error.message || "An unexpected error occurred. Please try again." + ); + } + } +} + +// Export singleton instance +export const supabaseAuth = SupabaseAuth.getInstance(); +if (typeof window !== "undefined") { + (window as unknown as { supabaseAuth: typeof supabaseAuth }).supabaseAuth = + supabaseAuth; +} diff --git a/browser/base/content/assistant/build/src/services/voiceAgent.ts b/browser/base/content/assistant/build/src/services/voiceAgent.ts new file mode 100644 index 0000000000000..f87208c0d0a8d --- /dev/null +++ b/browser/base/content/assistant/build/src/services/voiceAgent.ts @@ -0,0 +1,1616 @@ +import type { VoiceUiDelivery } from "../../../shared/contracts.js"; +import { transcribeAudio, textToSpeech } from "../proxyClient.js"; +import type { AssistantWindowLike } from "../types/runtime.js"; +import { assistantLogger } from "../utils/assistantLogger.js"; +import { advanceVadSpeechDebounce } from "../utils/voiceVadDebounce.js"; +import { shouldDiscardAutoTranscript } from "../utils/voiceUtteranceGuards.js"; + +const TTS_STOP_EVENT = "oasis-tts-stop"; +const MAX_TTS_CHARS = 2000; +const TARGET_TRANSCRIBE_SAMPLE_RATE = 16000; +const PRE_ROLL_MS = 1200; +const MAX_CAPTURE_HISTORY_MS = 12000; +const MANUAL_FLUSH_LOOKBACK_MS = 2800; +const VAD_THRESHOLD_MULTIPLIER = 2.0; +const VAD_MIN_THRESHOLD = 0.01; +const VAD_MAX_THRESHOLD = 0.045; +const VAD_SILENCE_MS = 1250; +const VAD_SPEECH_ON_FRAMES = 2; +const VAD_MIN_UTTERANCE_MS = 240; +const RECORDER_SLICE_MS = 160; +const PRECISE_START_RMS_THRESHOLD = 0.014; +const PRECISE_START_FRAMES = 4; +const ECHO_GUARD_MS_AFTER_TTS = 700; +const ECHO_GUARD_MS_AFTER_TTS_INTERRUPT = 450; +const ECHO_GUARD_MS_AFTER_TEXT_REPLY = 180; +const AUTO_MIN_UTTERANCE_BYTES_PRECISE = 800; +const MANUAL_STOP_MIN_UTTERANCE_MS = 120; +const MANUAL_STOP_MIN_UTTERANCE_BYTES = 120; +const MIN_UTTERANCE_BYTES = 400; +const VAD_SPEECH_DEBOUNCE_FRAMES = 3; + +export type VoiceAgentState = + | "idle" + | "listening" + | "transcribing" + | "thinking" + | "speaking"; + +export type VoiceAgentListener = (event: VoiceAgentEvent) => void; + +export type VoiceAgentListeningSource = "user" | "continuous" | "handsfree"; + +export type VoiceAgentEvent = + | { + type: "state"; + state: VoiceAgentState; + listeningSource?: VoiceAgentListeningSource; + } + | { type: "userTranscript"; text: string } + | { type: "error"; message: string } + | { type: "turn_done" } + | { type: "vad"; userSpeaking: boolean } + | { type: "audio_level"; mic: number; tts: number } + | { type: "listening_phase"; phase: "echo_guard" | "capturing" } + | { type: "assistant_reply_text"; text: string }; + +type RunAssistantFn = ( + prompt: string, + onChunk: (chunk: string) => void, + inputType: "text" | "voice", + messageId?: string, + voiceDelivery?: VoiceUiDelivery +) => Promise; + +type RecorderChunk = { + blob: Blob; + timestampMs: number; +}; + +type PcmChunk = { + samples: Float32Array; + startMs: number; + endMs: number; + sampleRate: number; +}; + +type PreparedUtterance = { + blob: Blob; + captureMeta: { + preprocessed: boolean; + mimeType: string; + durationMs?: number; + rms?: number; + sampleRateHz?: number; + channels?: number; + }; +}; + +type UtterancePcm = { + samples: Float32Array; + sampleRate: number; +}; + +function eventBlob(event: Event): Blob | null { + const data = (event as { data?: unknown }).data; + return data instanceof Blob ? data : null; +} + +function nowMs(): number { + return globalThis.performance?.now() ?? Date.now(); +} + +function clamp(value: number, min: number, max: number): number { + return Math.min(max, Math.max(min, value)); +} + +function voicePreview(text: string, max = 220): string { + const t = text.replace(/\s+/g, " ").trim(); + if (!t) return "(empty)"; + return t.length <= max ? t : `${t.slice(0, max)}…`; +} + +export type VoiceCaptureMode = "continuous" | "precise"; + +export const VOICE_CAPTURE_MODE_STORAGE_KEY = "oasis.voice.captureMode"; +export const VOICE_SPOKEN_REPLIES_STORAGE_KEY = "oasis.voice.orbSpokenReplies"; + +function readStoredCaptureMode(): VoiceCaptureMode { + try { + const ls = globalThis.localStorage; + if (!ls) return "continuous"; + const v = ls.getItem(VOICE_CAPTURE_MODE_STORAGE_KEY); + if (v === "precise") return "precise"; + } catch { + // ignore + } + return "continuous"; +} + +function readStoredVoiceSpokenReplies(): boolean { + try { + const ls = globalThis.localStorage; + if (!ls) return true; + const v = ls.getItem(VOICE_SPOKEN_REPLIES_STORAGE_KEY); + if (v === "0" || v === "false") return false; + } catch { + // ignore + } + return true; +} + +function randomAssistantMessageId(): string { + try { + return crypto.randomUUID(); + } catch { + return `va-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`; + } +} + +function transcribeFailureUserMessage(error: unknown): string { + const s = String(error); + if (s.includes("403") || s.includes("Forbidden")) { + return "Voice could not reach the transcription service (access denied). See browser/base/content/assistant/VOICE_INPUT_SETUP.md or ask your admin to check AWS IAM and the Lambda URL."; + } + if (/Authentication required/i.test(s)) { + return "Please sign in to use voice. Voice transcription needs an authenticated Oasis session."; + } + return "Could not transcribe audio. Check your connection and try again."; +} + +function normalizeTextForSpeech(text: string): string { + const normalized = text + .replace(/<[^>]*>/g, "") + .replace(/^[\t ]*[-*+]\s+/gm, "") + .replace(/^[\t ]*\d+\.\s+/gm, "") + .replace(/[#*_`~\[\]()>|]/g, "") + .replace(/[–—]+/g, ", ") + .replace(/\s*:\s*/g, ": ") + .replace(/\s*;\s*/g, "; ") + .replace(/\n{2,}/g, ". ") + .replace(/\n/g, " ") + .replace(/([.,!?;:])([^\s])/g, "$1 $2") + .replace(/\s{2,}/g, " ") + .trim() + .slice(0, MAX_TTS_CHARS) + .trim(); + + if (!normalized) { + return ""; + } + if (!/[.!?]$/.test(normalized)) { + return `${normalized}.`; + } + return normalized; +} + +function summarizeUrlForSpeech(value: string): string { + try { + const parsed = new URL(value); + const host = parsed.hostname.replace(/^www\./i, ""); + if (!host) { + return "that page"; + } + return host; + } catch { + return "that page"; + } +} + +function makeSpeechFriendlyReply(text: string): string { + const raw = String(text || "").trim(); + if (!raw) { + return ""; + } + + const missingUrl = + "Okay. Tell me the website you'd like me to open."; + const missingQuery = + "Okay. What should I search for?"; + + if (/^Missing 'url' argument\.?$/i.test(raw)) { + return missingUrl; + } + if (/^Missing 'query' argument\.?$/i.test(raw)) { + return missingQuery; + } + if (/^Opened URL in a new tab:/i.test(raw)) { + return "Done. I've opened that in a new tab."; + } + if (/^Opened web search for/i.test(raw)) { + return "I've opened a web search."; + } + if (/^Opened a new tab to the right of:/i.test(raw)) { + return "I've opened a new tab."; + } + if ( + /^Cannot open URL/i.test(raw) || + /^Cannot open web search/i.test(raw) || + /^Browser UI not available\.?$/i.test(raw) + ) { + return "I can't open a new tab right now."; + } + + const openedUrlMatch = raw.match( + /^(?:Opened URL in a new tab|Successfully opened URL|Opened in new tab):\s+(.+)$/i + ); + if (openedUrlMatch) { + return `Done. I've opened ${summarizeUrlForSpeech(openedUrlMatch[1])} in a new tab.`; + } + + const searchMatch = raw.match( + /^Opened web search for "?(.+?)"? in a new tab\.?$/i + ); + if (searchMatch) { + return `Sure. I opened a web search for ${searchMatch[1]}.`; + } + + const tabActionRewrites: Array<[RegExp, string]> = [ + [/^Closed tab:/i, "Closed that tab."], + [/^Reloaded tab:/i, "Reloaded that tab."], + [/^Pinned tab:/i, "Pinned that tab."], + [/^Unpinned tab:/i, "Unpinned that tab."], + [/^Moved tab to start:/i, "Moved that tab to the start."], + [/^Moved tab to end:/i, "Moved that tab to the end."], + [/^Duplicated tab:/i, "Duplicated that tab."], + [/^Bookmarked tab:/i, "Bookmarked that tab."], + [/^Selected all tabs in this window\.?$/i, "Selected all tabs in this window."], + [/^Closed \d+ duplicate tab\(s\)\.?$/i, "Closed the duplicate tabs."], + [/^Closed \d+ tab\(s\) to the right\.?$/i, "Closed the tabs to the right."], + [/^Closed \d+ tab\(s\) to the left\.?$/i, "Closed the tabs to the left."], + [/^Closed \d+ other tab\(s\)\.?$/i, "Closed the other tabs."], + ]; + for (const [pattern, replacement] of tabActionRewrites) { + if (pattern.test(raw)) { + return replacement; + } + } + + const shortened = raw.replace(/https?:\/\/\S+/gi, url => summarizeUrlForSpeech(url)); + const sentenceMatch = shortened.match(/^([^.!?]+[.!?])(?:\s+.*)?$/s); + if (sentenceMatch && sentenceMatch[1].length < shortened.length) { + return sentenceMatch[1].trim(); + } + return shortened; +} + +export class VoiceAgentService { + private state: VoiceAgentState = "idle"; + private listeners = new Set(); + private mediaRecorder: MediaRecorder | null = null; + private recorderMimeType = ""; + private recorderStartedAt = 0; + private chunkTimeline: RecorderChunk[] = []; + private micStream: MediaStream | null = null; + private ttsAudio: HTMLAudioElement | null = null; + private ttsObjectUrl: string | null = null; + private aborted = false; + private runAssistant: RunAssistantFn | null = null; + private preferredListeningSource: VoiceAgentListeningSource = "handsfree"; + private listeningSourceActive: VoiceAgentListeningSource | null = null; + + private audioContext: AudioContext | null = null; + private micSource: MediaStreamAudioSourceNode | null = null; + private analyser: AnalyserNode | null = null; + private vadData: Uint8Array | null = null; + private pcmProcessor: ScriptProcessorNode | null = null; + private pcmSink: GainNode | null = null; + private pcmTimeline: PcmChunk[] = []; + private audioLoopId = 0; + private audioLoopRunning = false; + private ttsAnalyser: AnalyserNode | null = null; + private ttsAnalyserData: Uint8Array | null = null; + private mediaElementSource: MediaElementAudioSourceNode | null = null; + private speechActive = false; + private speechOnFrames = 0; + private silenceMs = 0; + private utteranceStartTime = 0; + private utteranceBufferStartMs = 0; + private recentSpeechDetectedAt = 0; + private peakSpeechRms = 0; + private currentVadThreshold = VAD_MIN_THRESHOLD; + private ambientNoiseFloor = 0; + private ambientSampleCount = 0; + private lastVadFrameMs = 0; + private finishUtterancePromise: Promise | null = null; + private ttsRequestId = 0; + private activeSpeakCleanup: (() => void) | null = null; + private captureMode: VoiceCaptureMode = readStoredCaptureMode(); + private speechPrimeFrames = 0; + private vadSpeechStreakFrames = 0; + private voiceSpokenRepliesEnabled = readStoredVoiceSpokenReplies(); + + constructor() { + window.addEventListener( + TTS_STOP_EVENT, + this.handleExternalTtsStop as EventListener + ); + } + + setRunAssistant(fn: RunAssistantFn) { + this.runAssistant = fn; + } + + getListeningSource(): VoiceAgentListeningSource | null { + return this.listeningSourceActive; + } + + getUserSpeaking(): boolean { + return this.speechActive; + } + + getCaptureMode(): VoiceCaptureMode { + return this.captureMode; + } + + setCaptureMode(mode: VoiceCaptureMode): void { + this.captureMode = mode; + try { + globalThis.localStorage?.setItem(VOICE_CAPTURE_MODE_STORAGE_KEY, mode); + } catch { + // ignore + } + assistantLogger.warn("voice", "capture mode set", { mode }); + } + + getVoiceSpokenRepliesEnabled(): boolean { + return this.voiceSpokenRepliesEnabled; + } + + setVoiceSpokenRepliesEnabled(enabled: boolean): void { + this.voiceSpokenRepliesEnabled = enabled; + try { + globalThis.localStorage?.setItem( + VOICE_SPOKEN_REPLIES_STORAGE_KEY, + enabled ? "1" : "0" + ); + } catch { + // ignore + } + assistantLogger.warn("voice", "orb spoken replies", { enabled }); + } + + on(listener: VoiceAgentListener) { + this.listeners.add(listener); + return () => { + this.listeners.delete(listener); + }; + } + + getState(): VoiceAgentState { + return this.state; + } + + private handleExternalTtsStop = ( + event: CustomEvent<{ source?: string }> + ): void => { + if (event.detail?.source === "voice-agent") { + return; + } + this.stopSpeaking(); + }; + + private emit(event: VoiceAgentEvent) { + for (const listener of this.listeners) { + try { + listener(event); + } catch {} + } + } + + private setState( + nextState: VoiceAgentState, + listeningSource?: VoiceAgentListeningSource + ) { + this.state = nextState; + if (nextState === "listening" && listeningSource) { + this.listeningSourceActive = listeningSource; + this.emit({ type: "state", state: nextState, listeningSource }); + return; + } + if (nextState !== "listening") { + this.listeningSourceActive = null; + } + this.emit({ type: "state", state: nextState }); + } + + private emitVad(userSpeaking: boolean) { + this.emit({ type: "vad", userSpeaking }); + } + + private emitListeningPhase(phase: "echo_guard" | "capturing"): void { + this.emit({ type: "listening_phase", phase }); + } + + private setMicTracksEnabled(enabled: boolean): void { + const tracks = this.micStream?.getAudioTracks() ?? []; + tracks.forEach(track => { + track.enabled = enabled; + }); + } + + private getAudioConstraints(): MediaTrackConstraints { + const supported = + navigator.mediaDevices?.getSupportedConstraints?.() || {}; + const constraints: MediaTrackConstraints & Record = { + echoCancellation: true, + noiseSuppression: true, + autoGainControl: true, + }; + + if (supported.channelCount) { + constraints.channelCount = { ideal: 1 }; + } + if (supported.sampleRate) { + constraints.sampleRate = { ideal: TARGET_TRANSCRIBE_SAMPLE_RATE }; + } + if (supported.sampleSize) { + constraints.sampleSize = { ideal: 16 }; + } + if ( + "suppressLocalAudioPlayback" in supported && + supported.suppressLocalAudioPlayback + ) { + constraints.suppressLocalAudioPlayback = true; + } + + return constraints; + } + + async startConversation( + listeningSource: VoiceAgentListeningSource = "handsfree" + ): Promise { + if (this.state !== "idle") { + return; + } + + this.aborted = false; + this.preferredListeningSource = listeningSource; + + if (!navigator.mediaDevices?.getUserMedia) { + this.emit({ + type: "error", + message: "Microphone is not available in this page.", + }); + return; + } + + try { + this.micStream = await navigator.mediaDevices.getUserMedia({ + audio: this.getAudioConstraints(), + }); + } catch { + if (this.aborted) { + return; + } + this.emit({ type: "error", message: "Microphone access denied." }); + return; + } + + if (this.aborted) { + this.releaseMic(); + return; + } + + this.setupAnalyser(); + if (!this.analyser || !this.audioContext) { + this.releaseAudioContext(); + this.releaseMic(); + this.emit({ + type: "error", + message: "Could not start audio analysis.", + }); + return; + } + + if (this.audioContext.state === "suspended") { + try { + await this.audioContext.resume(); + } catch (error) { + assistantLogger.error("voice-agent", "AudioContext.resume failed", error); + this.releaseAudioContext(); + this.releaseMic(); + this.emit({ + type: "error", + message: "Tap the microphone button to enable listening.", + }); + return; + } + } + + this.setMicTracksEnabled(true); + this.resetListeningCalibration(); + this.setState("listening", listeningSource); + + const captureStarted = await this.startContinuousCapture(); + if (!captureStarted) { + this.releaseAudioContext(); + this.releaseMic(); + this.setState("idle"); + this.emit({ + type: "error", + message: "Could not start microphone capture.", + }); + return; + } + + try { + const track = this.micStream.getAudioTracks()[0]; + assistantLogger.info("voice-agent", "Microphone capture started", { + mimeType: this.recorderMimeType, + settings: track?.getSettings?.() || null, + }); + } catch { + // ignore + } + + this.ensureAudioLoop(); + this.emitListeningPhase("capturing"); + this.speechPrimeFrames = 0; + } + + private setupAnalyser(): void { + if (!this.micStream) { + return; + } + try { + this.audioContext = new AudioContext(); + const source = this.audioContext.createMediaStreamSource(this.micStream); + this.micSource = source; + this.analyser = this.audioContext.createAnalyser(); + this.analyser.fftSize = 1024; + this.analyser.smoothingTimeConstant = 0.65; + source.connect(this.analyser); + this.vadData = new Uint8Array(this.analyser.fftSize); + + const processor = this.audioContext.createScriptProcessor(4096, 1, 1); + const sink = this.audioContext.createGain(); + sink.gain.value = 0; + processor.onaudioprocess = event => { + const audioEvent = event as AudioProcessingEvent; + if (this.state !== "listening" || this.aborted) { + return; + } + const input = audioEvent.inputBuffer; + const sampleRate = input.sampleRate || this.audioContext?.sampleRate || 48000; + if (!sampleRate || input.length <= 0) { + return; + } + const mono = new Float32Array(input.length); + const channels = Math.max(1, input.numberOfChannels); + for (let channel = 0; channel < channels; channel++) { + const data = input.getChannelData(channel); + for (let index = 0; index < data.length; index++) { + mono[index] += data[index]! / channels; + } + } + const endMs = nowMs(); + const durationMs = (mono.length / sampleRate) * 1000; + this.pcmTimeline.push({ + samples: mono, + startMs: endMs - durationMs, + endMs, + sampleRate, + }); + this.trimPcmTimeline(endMs); + }; + source.connect(processor); + processor.connect(sink); + sink.connect(this.audioContext.destination); + this.pcmProcessor = processor; + this.pcmSink = sink; + } catch (error) { + assistantLogger.error("voice-agent", "Analyser setup failed", error); + } + } + + private resetListeningCalibration(): void { + this.speechActive = false; + this.speechOnFrames = 0; + this.speechPrimeFrames = 0; + this.vadSpeechStreakFrames = 0; + this.silenceMs = 0; + this.utteranceStartTime = 0; + this.utteranceBufferStartMs = 0; + this.recentSpeechDetectedAt = 0; + this.peakSpeechRms = 0; + this.ambientNoiseFloor = 0; + this.ambientSampleCount = 0; + this.currentVadThreshold = VAD_MIN_THRESHOLD; + this.emitVad(false); + } + + private computeRms(): number { + if (!this.analyser || !this.vadData) { + return 0; + } + this.analyser.getByteTimeDomainData(this.vadData); + let sum = 0; + for (let index = 0; index < this.vadData.length; index++) { + const value = (this.vadData[index]! - 128) / 128; + sum += value * value; + } + return Math.sqrt(sum / this.vadData.length); + } + + private computeRmsFromAnalyser(analyser: AnalyserNode, data: Uint8Array): number { + analyser.getByteTimeDomainData(data); + let sum = 0; + for (let index = 0; index < data.length; index++) { + const value = (data[index]! - 128) / 128; + sum += value * value; + } + return Math.sqrt(sum / data.length); + } + + private normalizeLevel(rms: number): number { + return Math.min(1, Math.max(0, rms * 7)); + } + + private observeAmbientNoise(rms: number): void { + if (this.speechActive) { + return; + } + const sample = + this.ambientSampleCount === 0 + ? rms + : this.ambientNoiseFloor * 0.92 + rms * 0.08; + this.ambientNoiseFloor = sample; + this.ambientSampleCount += 1; + const derivedThreshold = Math.max( + sample * VAD_THRESHOLD_MULTIPLIER, + sample + 0.006 + ); + this.currentVadThreshold = clamp( + derivedThreshold, + VAD_MIN_THRESHOLD, + VAD_MAX_THRESHOLD + ); + } + + private emitAudioLevels(): void { + let mic = 0; + let tts = 0; + if (this.state === "listening" && this.analyser) { + mic = this.normalizeLevel(this.computeRms()); + } else if ( + this.state === "speaking" && + this.ttsAnalyser && + this.ttsAnalyserData + ) { + tts = this.normalizeLevel( + this.computeRmsFromAnalyser(this.ttsAnalyser, this.ttsAnalyserData) + ); + } + this.emit({ type: "audio_level", mic, tts }); + } + + private ensureAudioLoop(): void { + if (this.audioLoopRunning) { + return; + } + this.audioLoopRunning = true; + this.lastVadFrameMs = nowMs(); + const tick = () => { + if (!this.audioLoopRunning || this.aborted) { + return; + } + + this.emitAudioLevels(); + + if (this.state === "listening") { + const now = nowMs(); + const dt = Math.min(120, now - this.lastVadFrameMs); + this.lastVadFrameMs = now; + + const rms = this.computeRms(); + this.observeAmbientNoise(rms); + const speech = rms > this.currentVadThreshold; + const primeSpeech = rms > PRECISE_START_RMS_THRESHOLD; + + if (this.captureMode === "precise") { + if (speech) { + this.recentSpeechDetectedAt = now; + this.peakSpeechRms = Math.max(this.peakSpeechRms, rms); + this.silenceMs = 0; + } + + if (!this.speechActive) { + if (primeSpeech) { + const next = advanceVadSpeechDebounce( + this.vadSpeechStreakFrames, + true, + VAD_SPEECH_DEBOUNCE_FRAMES + ); + this.vadSpeechStreakFrames = next.streak; + if (next.commit) { + this.beginUtteranceRecording(now, rms); + } + } else { + this.vadSpeechStreakFrames = 0; + } + } + } else if (speech) { + this.recentSpeechDetectedAt = now; + this.peakSpeechRms = Math.max(this.peakSpeechRms, rms); + this.silenceMs = 0; + this.speechOnFrames += 1; + if (!this.speechActive && this.speechOnFrames >= VAD_SPEECH_ON_FRAMES) { + this.beginUtteranceRecording(now, rms); + } + } else { + this.speechOnFrames = 0; + if (this.speechActive) { + this.silenceMs += dt; + if (this.silenceMs >= VAD_SILENCE_MS) { + void this.finishUtteranceRecording(); + } + } + } + } + + this.audioLoopId = requestAnimationFrame(tick); + }; + this.audioLoopId = requestAnimationFrame(tick); + } + + private stopAudioLoop(): void { + this.audioLoopRunning = false; + if (this.audioLoopId) { + cancelAnimationFrame(this.audioLoopId); + this.audioLoopId = 0; + } + } + + private trimChunkTimeline(now = nowMs()): void { + const keepSince = this.utteranceBufferStartMs + ? Math.max( + this.utteranceBufferStartMs - RECORDER_SLICE_MS, + now - MAX_CAPTURE_HISTORY_MS + ) + : now - PRE_ROLL_MS; + this.chunkTimeline = this.chunkTimeline.filter( + chunk => chunk.timestampMs >= keepSince + ); + } + + private trimPcmTimeline(now = nowMs()): void { + const keepSince = this.utteranceBufferStartMs + ? Math.max( + this.utteranceBufferStartMs - RECORDER_SLICE_MS, + now - MAX_CAPTURE_HISTORY_MS + ) + : now - PRE_ROLL_MS; + this.pcmTimeline = this.pcmTimeline.filter(chunk => chunk.endMs >= keepSince); + } + + private async startContinuousCapture(): Promise { + if (!this.micStream) { + return false; + } + if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") { + return true; + } + + const mimeType = this.pickMimeType(); + let recorder: MediaRecorder | null = null; + + try { + recorder = new MediaRecorder( + this.micStream, + mimeType + ? { mimeType, audioBitsPerSecond: 64000 } + : { audioBitsPerSecond: 64000 } + ); + } catch { + try { + recorder = new MediaRecorder( + this.micStream, + mimeType ? { mimeType } : {} + ); + } catch (error) { + assistantLogger.error("voice-agent", "MediaRecorder failed", error); + return false; + } + } + + this.chunkTimeline = []; + this.pcmTimeline = []; + this.mediaRecorder = recorder; + this.recorderMimeType = recorder.mimeType || mimeType || "audio/webm"; + this.recorderStartedAt = nowMs(); + recorder.ondataavailable = (event: Event) => { + const blob = eventBlob(event); + if (!blob || blob.size <= 0) { + return; + } + this.chunkTimeline.push({ + blob, + timestampMs: nowMs(), + }); + this.trimChunkTimeline(); + }; + + try { + recorder.start(RECORDER_SLICE_MS); + return true; + } catch (error) { + assistantLogger.error("voice-agent", "MediaRecorder.start failed", error); + this.mediaRecorder = null; + return false; + } + } + + private async stopContinuousCapture(): Promise { + const recorder = this.mediaRecorder; + this.mediaRecorder = null; + if (!recorder || recorder.state === "inactive") { + return; + } + + await new Promise(resolve => { + const handleStop = () => { + resolve(); + }; + recorder.addEventListener("stop", handleStop, { once: true }); + try { + recorder.stop(); + } catch { + resolve(); + } + }); + } + + private beginUtteranceRecording(now: number, rms: number): void { + this.speechActive = true; + this.utteranceStartTime = now; + this.utteranceBufferStartMs = Math.max( + this.recorderStartedAt, + now - PRE_ROLL_MS + ); + this.peakSpeechRms = Math.max(this.peakSpeechRms, rms); + this.emitVad(true); + } + + private resolveUtteranceStartMs(forceFlush: boolean): number { + if (this.utteranceBufferStartMs > 0) { + return this.utteranceBufferStartMs; + } + if (!forceFlush || this.chunkTimeline.length === 0) { + return 0; + } + if ( + this.recentSpeechDetectedAt <= 0 && + this.speechOnFrames === 0 && + !this.speechActive + ) { + return 0; + } + const latestTimestamp = + this.chunkTimeline[this.chunkTimeline.length - 1]?.timestampMs || nowMs(); + return Math.max( + this.recorderStartedAt, + latestTimestamp - MANUAL_FLUSH_LOOKBACK_MS + ); + } + + private buildUtteranceBlob(startMs: number): Blob { + const selectedChunks = this.chunkTimeline + .filter(chunk => chunk.timestampMs >= startMs - RECORDER_SLICE_MS) + .map(chunk => chunk.blob); + const mimeType = this.recorderMimeType || "audio/webm"; + return new Blob(selectedChunks, { type: mimeType }); + } + + private buildUtterancePcm(startMs: number): UtterancePcm | null { + const selected = this.pcmTimeline.filter( + chunk => chunk.endMs >= startMs - RECORDER_SLICE_MS + ); + if (selected.length === 0) { + return null; + } + const sampleRate = selected[0]?.sampleRate || this.audioContext?.sampleRate || 48000; + const trimmedChunks: Float32Array[] = []; + let totalLength = 0; + + for (const chunk of selected) { + let startIndex = 0; + if (chunk.startMs < startMs && chunk.endMs > startMs) { + startIndex = Math.max( + 0, + Math.min( + chunk.samples.length, + Math.floor(((startMs - chunk.startMs) / 1000) * chunk.sampleRate) + ) + ); + } else if (chunk.endMs <= startMs) { + continue; + } + const slice = chunk.samples.subarray(startIndex); + if (slice.length === 0) { + continue; + } + trimmedChunks.push(new Float32Array(slice)); + totalLength += slice.length; + } + + if (totalLength === 0) { + return null; + } + + const samples = new Float32Array(totalLength); + let offset = 0; + for (const chunk of trimmedChunks) { + samples.set(chunk, offset); + offset += chunk.length; + } + return { samples, sampleRate }; + } + + private resetUtteranceState(): void { + this.speechActive = false; + this.silenceMs = 0; + this.speechOnFrames = 0; + this.utteranceStartTime = 0; + this.utteranceBufferStartMs = 0; + this.peakSpeechRms = 0; + this.emitVad(false); + } + + private finishUtteranceRecording( + forceFlush = false, + manualStop = false + ): Promise { + if (this.finishUtterancePromise) { + return this.finishUtterancePromise; + } + + const promise = this.finishUtteranceRecordingInternal( + forceFlush, + manualStop + ).finally(() => { + if (this.finishUtterancePromise === promise) { + this.finishUtterancePromise = null; + } + }); + this.finishUtterancePromise = promise; + return promise; + } + + private async finishUtteranceRecordingInternal( + forceFlush = false, + manualStop = false + ): Promise { + const startMs = this.resolveUtteranceStartMs(forceFlush); + if (!startMs) { + this.resetUtteranceState(); + return; + } + + const durationMs = Math.max(0, nowMs() - startMs); + const rms = this.peakSpeechRms || undefined; + + await this.stopContinuousCapture(); + if (this.aborted) { + this.chunkTimeline = []; + this.pcmTimeline = []; + this.resetUtteranceState(); + return; + } + const audioBlob = this.buildUtteranceBlob(startMs); + const pcm = this.buildUtterancePcm(startMs); + this.chunkTimeline = []; + this.pcmTimeline = []; + this.resetUtteranceState(); + + if (this.aborted) { + return; + } + const minMs = manualStop ? MANUAL_STOP_MIN_UTTERANCE_MS : VAD_MIN_UTTERANCE_MS; + const minBytes = manualStop + ? MANUAL_STOP_MIN_UTTERANCE_BYTES + : this.captureMode === "precise" + ? AUTO_MIN_UTTERANCE_BYTES_PRECISE + : MIN_UTTERANCE_BYTES; + if (durationMs < minMs || audioBlob.size < minBytes) { + if (manualStop) { + this.emit({ + type: "error", + message: + "Recording was too short to transcribe. Hold the mic a moment longer, then tap the orb again.", + }); + } + if (!this.aborted) { + this.resumeListeningAfterTurn(); + } + return; + } + + await this.processUtteranceBlob(audioBlob, { durationMs, rms }, pcm, manualStop); + } + + private buildRawUtteranceBlob( + audioBlob: Blob, + details: { durationMs: number; rms?: number } + ): PreparedUtterance | null { + const mimeType = audioBlob.type || this.recorderMimeType || "audio/webm"; + if (audioBlob.size < 256) { + return null; + } + return { + blob: audioBlob, + captureMeta: { + preprocessed: false, + mimeType, + durationMs: details.durationMs, + ...(typeof details.rms === "number" ? { rms: details.rms } : {}), + }, + }; + } + + private async prepareUtteranceBlob( + audioBlob: Blob, + details: { durationMs: number; rms?: number }, + pcm?: UtterancePcm | null + ): Promise { + if (!pcm) { + assistantLogger.warn( + "voice-agent", + "PCM audio was unavailable; falling back to recorded audio upload", + { + originalMimeType: audioBlob.type || this.recorderMimeType || "audio/webm", + durationMs: details.durationMs, + } + ); + return this.buildRawUtteranceBlob(audioBlob, details); + } + + try { + const processedBlob = await this.preprocessPcmUtterance( + pcm.samples, + pcm.sampleRate + ); + if (!processedBlob || processedBlob.size < 256) { + assistantLogger.warn( + "voice-agent", + "PCM preprocessing produced no usable WAV; falling back to recorded audio upload", + { + originalMimeType: audioBlob.type || this.recorderMimeType || "audio/webm", + durationMs: details.durationMs, + pcmSampleRate: pcm.sampleRate, + pcmSamples: pcm.samples.length, + } + ); + return this.buildRawUtteranceBlob(audioBlob, details); + } + return { + blob: processedBlob, + captureMeta: { + preprocessed: true, + mimeType: processedBlob.type || "audio/wav", + durationMs: details.durationMs, + ...(typeof details.rms === "number" ? { rms: details.rms } : {}), + sampleRateHz: TARGET_TRANSCRIBE_SAMPLE_RATE, + channels: 1, + }, + }; + } catch (error) { + assistantLogger.warn( + "voice-agent", + "Audio preprocessing failed; falling back to recorded audio upload", + error + ); + return this.buildRawUtteranceBlob(audioBlob, details); + } + } + + private async preprocessPcmUtterance( + mono: Float32Array, + sampleRate: number + ): Promise { + if (!mono.length || !sampleRate) { + return null; + } + const frameCount = Math.max( + 1, + Math.ceil((mono.length / sampleRate) * TARGET_TRANSCRIBE_SAMPLE_RATE) + ); + const offline = new OfflineAudioContext( + 1, + frameCount, + TARGET_TRANSCRIBE_SAMPLE_RATE + ); + const inputBuffer = offline.createBuffer(1, mono.length, sampleRate); + inputBuffer.copyToChannel(mono, 0); + + const source = offline.createBufferSource(); + source.buffer = inputBuffer; + + const highPass = offline.createBiquadFilter(); + highPass.type = "highpass"; + highPass.frequency.value = 85; + highPass.Q.value = 0.707; + + const compressor = offline.createDynamicsCompressor(); + compressor.threshold.value = -24; + compressor.knee.value = 18; + compressor.ratio.value = 3; + compressor.attack.value = 0.003; + compressor.release.value = 0.25; + + source.connect(highPass); + highPass.connect(compressor); + compressor.connect(offline.destination); + source.start(0); + + const rendered = await offline.startRendering(); + return this.encodeWavBlob(rendered); + } + + private encodeWavBlob(buffer: AudioBuffer): Blob { + const samples = buffer.getChannelData(0); + let peak = 0; + for (let index = 0; index < samples.length; index++) { + peak = Math.max(peak, Math.abs(samples[index]!)); + } + const gain = peak > 0 ? Math.min(4, 0.92 / peak) : 1; + const bytesPerSample = 2; + const dataLength = samples.length * bytesPerSample; + const wav = new ArrayBuffer(44 + dataLength); + const view = new DataView(wav); + + const writeAscii = (offset: number, text: string) => { + for (let index = 0; index < text.length; index++) { + view.setUint8(offset + index, text.charCodeAt(index)); + } + }; + + writeAscii(0, "RIFF"); + view.setUint32(4, 36 + dataLength, true); + writeAscii(8, "WAVE"); + writeAscii(12, "fmt "); + view.setUint32(16, 16, true); + view.setUint16(20, 1, true); + view.setUint16(22, 1, true); + view.setUint32(24, buffer.sampleRate, true); + view.setUint32(28, buffer.sampleRate * bytesPerSample, true); + view.setUint16(32, bytesPerSample, true); + view.setUint16(34, 16, true); + writeAscii(36, "data"); + view.setUint32(40, dataLength, true); + + let offset = 44; + for (let index = 0; index < samples.length; index++) { + const sample = clamp(samples[index]! * gain, -1, 1); + view.setInt16( + offset, + sample < 0 ? sample * 0x8000 : sample * 0x7fff, + true + ); + offset += bytesPerSample; + } + + return new Blob([wav], { type: "audio/wav" }); + } + + private async processUtteranceBlob( + audioBlob: Blob, + details: { durationMs: number; rms?: number }, + pcm?: UtterancePcm | null, + manualStop = false + ): Promise { + if (this.aborted) { + return; + } + this.setState("transcribing"); + + try { + const prepared = await this.prepareUtteranceBlob(audioBlob, details, pcm); + if (!prepared) { + this.emit({ + type: "error", + message: "I couldn't process that audio. Please try again.", + }); + this.resumeListeningAfterTurn(); + return; + } + assistantLogger.info("voice-agent", "Audio preprocessing succeeded", { + ...prepared.captureMeta, + originalMimeType: audioBlob.type || this.recorderMimeType || "audio/webm", + }); + assistantLogger.info("voice-agent", "Submitting utterance for transcription", { + ...prepared.captureMeta, + originalMimeType: audioBlob.type || this.recorderMimeType || "audio/webm", + }); + + const { transcript } = await transcribeAudio(prepared.blob, { + captureMeta: prepared.captureMeta, + }); + if (!transcript || this.aborted) { + this.resumeListeningAfterTurn(); + return; + } + if (shouldDiscardAutoTranscript(transcript, manualStop)) { + this.emit({ + type: "error", + message: + "That was too short to interpret. Say a bit more, or tap the orb when you are done.", + }); + this.resumeListeningAfterTurn(); + return; + } + this.emit({ type: "userTranscript", text: transcript }); + await this.runTurn(transcript); + } catch (error) { + assistantLogger.error("voice-agent", "Transcription failed", error); + this.emit({ type: "error", message: transcribeFailureUserMessage(error) }); + this.resumeListeningAfterTurn(); + } + } + + async startListening(options?: { + source?: VoiceAgentListeningSource; + }): Promise { + if (this.state === "idle") { + await this.startConversation(options?.source || "user"); + } + } + + async finishListening(): Promise { + if (this.state !== "listening") { + return; + } + await this.finishUtteranceRecording(true, true); + } + + private resumeListeningAfterTurn(echoGuardMs = 0): void { + void this.resumeListeningAfterTurnInternal(echoGuardMs); + } + + private async resumeListeningAfterTurnInternal( + echoGuardMs = 0 + ): Promise { + if (this.aborted) { + return; + } + if (this.preferredListeningSource === "user") { + this.setState("idle"); + return; + } + if (echoGuardMs > 0) { + this.emitListeningPhase("echo_guard"); + await new Promise(resolve => { + setTimeout(resolve, echoGuardMs); + }); + if (this.aborted) { + return; + } + } + this.lastVadFrameMs = nowMs(); + this.resetListeningCalibration(); + this.setMicTracksEnabled(true); + if (this.audioContext?.state === "suspended") { + try { + await this.audioContext.resume(); + } catch (error) { + assistantLogger.error("voice-agent", "AudioContext.resume failed", error); + if (!this.aborted) { + this.stop(); + this.emit({ + type: "error", + message: "Tap the microphone button to enable listening.", + }); + } + return; + } + } + + const started = await this.startContinuousCapture(); + if (!started) { + if (!this.aborted) { + this.stop(); + this.emit({ + type: "error", + message: "Could not restart microphone capture.", + }); + } + return; + } + if (this.aborted) { + return; + } + this.setState("listening", this.preferredListeningSource); + this.ensureAudioLoop(); + this.emitListeningPhase("capturing"); + this.speechPrimeFrames = 0; + } + + private async runTurn(transcript: string): Promise { + if (!this.runAssistant) { + this.emit({ type: "error", message: "Assistant not connected." }); + this.resumeListeningAfterTurn(); + return; + } + + const useSpoken = this.voiceSpokenRepliesEnabled; + const win = globalThis as unknown as AssistantWindowLike; + + this.setState("thinking"); + this.setMicTracksEnabled(false); + + let aiMessageId: string | undefined; + if (!useSpoken && typeof win.oasisVoiceAssistantTurnBegin === "function") { + try { + aiMessageId = win.oasisVoiceAssistantTurnBegin(transcript); + } catch { + aiMessageId = undefined; + } + } + if (!useSpoken && !aiMessageId) { + aiMessageId = randomAssistantMessageId(); + } + + const onChunk = (chunk: string) => { + if (!useSpoken && aiMessageId && win.oasisVoiceAssistantStreamChunk) { + try { + win.oasisVoiceAssistantStreamChunk(aiMessageId, chunk); + } catch { + // ignore + } + } + }; + + const voiceDelivery: VoiceUiDelivery = useSpoken ? "spoken" : "text_chat"; + let fullResponse = ""; + try { + fullResponse = await this.runAssistant( + transcript, + onChunk, + "voice", + aiMessageId, + voiceDelivery + ); + } catch (error) { + assistantLogger.error("voice-agent", "Assistant failed", error); + this.emit({ type: "error", message: "Assistant error." }); + this.resumeListeningAfterTurn(); + return; + } + + if (this.aborted || !fullResponse.trim()) { + this.emit({ type: "turn_done" }); + this.resumeListeningAfterTurn(); + return; + } + + if (useSpoken) { + this.setState("speaking"); + try { + await this.speak(fullResponse); + } catch (error) { + assistantLogger.error("voice-agent", "TTS failed", error); + } + if (typeof win.oasisVoiceSpokenTurnMirror === "function") { + try { + win.oasisVoiceSpokenTurnMirror(transcript, fullResponse); + } catch { + // ignore + } + } + this.emit({ type: "assistant_reply_text", text: fullResponse }); + this.emit({ type: "turn_done" }); + this.resumeListeningAfterTurn(ECHO_GUARD_MS_AFTER_TTS); + return; + } + + this.emit({ type: "turn_done" }); + this.resumeListeningAfterTurn(ECHO_GUARD_MS_AFTER_TEXT_REPLY); + } + + private async speak(text: string): Promise { + const plain = normalizeTextForSpeech(makeSpeechFriendlyReply(text)); + if (!plain) { + return; + } + + const requestId = ++this.ttsRequestId; + window.dispatchEvent( + new CustomEvent(TTS_STOP_EVENT, { + detail: { source: "voice-agent" }, + }) + ); + + try { + const blob = await textToSpeech(plain); + if ( + this.aborted || + requestId !== this.ttsRequestId || + this.state !== "speaking" + ) { + return; + } + const url = URL.createObjectURL(blob); + this.ttsObjectUrl = url; + + return new Promise(resolve => { + let settled = false; + const finish = () => { + if (settled) { + return; + } + settled = true; + if (this.activeSpeakCleanup === finish) { + this.activeSpeakCleanup = null; + } + this.cleanupAudio(); + resolve(); + }; + const audio = new Audio(url); + this.ttsAudio = audio; + this.activeSpeakCleanup = finish; + this.disconnectTtsGraph(); + if (this.audioContext) { + try { + const source = this.audioContext.createMediaElementSource(audio); + const analyser = this.audioContext.createAnalyser(); + analyser.fftSize = 512; + analyser.smoothingTimeConstant = 0.55; + source.connect(analyser); + analyser.connect(this.audioContext.destination); + this.mediaElementSource = source; + this.ttsAnalyser = analyser; + this.ttsAnalyserData = new Uint8Array(analyser.fftSize); + } catch (error) { + assistantLogger.error("voice-agent", "TTS audio graph failed", error); + this.disconnectTtsGraph(); + } + } + audio.onended = finish; + audio.onerror = finish; + void audio.play().catch(finish); + }); + } catch { + if (requestId === this.ttsRequestId) { + this.activeSpeakCleanup = null; + } + this.cleanupAudio(); + } + } + + private disconnectTtsGraph(): void { + if (this.mediaElementSource) { + try { + this.mediaElementSource.disconnect(); + } catch { + // ignore + } + this.mediaElementSource = null; + } + if (this.ttsAnalyser) { + try { + this.ttsAnalyser.disconnect(); + } catch { + // ignore + } + this.ttsAnalyser = null; + } + this.ttsAnalyserData = null; + } + + stop() { + this.aborted = true; + this.preferredListeningSource = "handsfree"; + this.ttsRequestId += 1; + this.stopAudioLoop(); + const finish = this.activeSpeakCleanup; + this.activeSpeakCleanup = null; + if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") { + try { + this.mediaRecorder.stop(); + } catch { + // ignore + } + } + this.mediaRecorder = null; + this.chunkTimeline = []; + this.recorderMimeType = ""; + this.resetUtteranceState(); + this.releaseAudioContext(); + this.releaseMic(); + if (finish) { + finish(); + } else { + this.cleanupAudio(); + } + this.setState("idle"); + } + + stopSpeaking() { + this.ttsRequestId += 1; + const finish = this.activeSpeakCleanup; + this.activeSpeakCleanup = null; + if (finish) { + finish(); + } else { + this.cleanupAudio(); + } + if (this.state === "speaking") { + this.emit({ type: "turn_done" }); + this.resumeListeningAfterTurn(ECHO_GUARD_MS_AFTER_TTS_INTERRUPT); + } + } + + private releaseAudioContext(): void { + if (this.micSource) { + try { + this.micSource.disconnect(); + } catch { + } + this.micSource = null; + } + if (this.pcmProcessor) { + try { + this.pcmProcessor.disconnect(); + } catch { + } + this.pcmProcessor.onaudioprocess = null; + this.pcmProcessor = null; + } + if (this.pcmSink) { + try { + this.pcmSink.disconnect(); + } catch { + } + this.pcmSink = null; + } + if (this.audioContext) { + try { + void this.audioContext.close(); + } catch { + // ignore + } + this.audioContext = null; + } + this.analyser = null; + this.vadData = null; + this.pcmTimeline = []; + } + + private releaseMic() { + if (this.micStream) { + this.micStream.getTracks().forEach(track => track.stop()); + this.micStream = null; + } + } + + private cleanupAudio() { + this.disconnectTtsGraph(); + if (this.ttsAudio) { + this.ttsAudio.pause(); + this.ttsAudio = null; + } + if (this.ttsObjectUrl) { + URL.revokeObjectURL(this.ttsObjectUrl); + this.ttsObjectUrl = null; + } + } + + private pickMimeType(): string { + const types = [ + "audio/webm;codecs=opus", + "audio/webm", + "audio/ogg;codecs=opus", + "audio/ogg", + "audio/mp4", + ]; + for (const type of types) { + if (MediaRecorder.isTypeSupported(type)) { + return type; + } + } + return ""; + } +} + +const voiceAgent = new VoiceAgentService(); +export default voiceAgent; diff --git a/browser/base/content/assistant/build/src/services/voiceInput.ts b/browser/base/content/assistant/build/src/services/voiceInput.ts new file mode 100644 index 0000000000000..11dfac64cc650 --- /dev/null +++ b/browser/base/content/assistant/build/src/services/voiceInput.ts @@ -0,0 +1,152 @@ +/** Voice input service — microphone recording, audio blob creation, and transcription via the remote Lambda. */ +import { transcribeAudio } from "../proxyClient.js"; +import { assistantLogger } from "../utils/assistantLogger.js"; + +function eventBlob(event: Event): Blob | null { + const data = (event as { data?: unknown }).data; + return data instanceof Blob ? data : null; +} + +export class VoiceInputService { + private mediaRecorder: MediaRecorder | null = null; + private audioChunks: Blob[] = []; + private stream: MediaStream | null = null; + private composerUtteranceSeq = 0; + private activeComposerSeq = 0; + + async startRecording(): Promise { + try { + this.stream = await navigator.mediaDevices.getUserMedia({ + audio: { + echoCancellation: true, + noiseSuppression: true, + autoGainControl: true, + }, + }); + + this.composerUtteranceSeq += 1; + this.activeComposerSeq = this.composerUtteranceSeq; + const audioTracks = this.stream.getAudioTracks(); + const mimeType = this.getSupportedMimeType(); + assistantLogger.debug("voice-input", "recording_started", { + utteranceSeq: this.activeComposerSeq, + mimeType: mimeType || "(browser default)", + tracks: audioTracks.map(t => { + let deviceId = ""; + try { + deviceId = t.getSettings?.().deviceId ?? ""; + } catch { + // ignore + } + return { label: t.label || "", deviceId }; + }), + }); + + this.mediaRecorder = mimeType + ? new MediaRecorder(this.stream, { mimeType }) + : new MediaRecorder(this.stream); + + this.audioChunks = []; + + this.mediaRecorder.ondataavailable = (event: Event) => { + const blob = eventBlob(event); + if (blob && blob.size > 0) { + this.audioChunks.push(blob); + } + }; + + this.mediaRecorder.start(); + } catch (error) { + assistantLogger.error("voice-input", "Error starting recording", error); + throw new Error("Failed to access microphone. Please check permissions."); + } + } + + async stopRecording(): Promise { + return new Promise((resolve, reject) => { + if (!this.mediaRecorder) { + reject(new Error("No active recording")); + return; + } + + const seq = this.activeComposerSeq; + + this.mediaRecorder.onstop = async () => { + try { + if (this.stream) { + this.stream.getTracks().forEach(track => track.stop()); + } + + const mimeType = this.mediaRecorder?.mimeType || "audio/webm"; + const audioBlob = new Blob(this.audioChunks, { type: mimeType }); + + assistantLogger.debug("voice-input", "sending_transcribe", { + utteranceSeq: seq, + chunkCount: this.audioChunks.length, + blobBytes: audioBlob.size, + mimeType, + }); + + const result = await transcribeAudio(audioBlob, { + source: "composer", + utteranceSeq: seq, + }); + + // Lambda returns { transcript: "..." } + resolve(result.transcript || ""); + } catch (error) { + assistantLogger.error( + "voice-input", + "Error transcribing audio", + error + ); + reject(error); + } finally { + this.mediaRecorder = null; + this.audioChunks = []; + this.stream = null; + } + }; + + this.mediaRecorder.stop(); + }); + } + + isRecording(): boolean { + return this.mediaRecorder?.state === "recording"; + } + + cancelRecording(): void { + assistantLogger.debug("voice-input", "recording_cancelled", { + utteranceSeq: this.activeComposerSeq, + }); + if (this.mediaRecorder && this.mediaRecorder.state !== "inactive") { + this.mediaRecorder.stop(); + } + if (this.stream) { + this.stream.getTracks().forEach(track => track.stop()); + } + this.mediaRecorder = null; + this.audioChunks = []; + this.stream = null; + } + + private getSupportedMimeType(): string { + const types = [ + "audio/webm;codecs=opus", + "audio/webm", + "audio/ogg;codecs=opus", + "audio/mp4", + ]; + + for (const type of types) { + if (MediaRecorder.isTypeSupported(type)) { + return type; + } + } + + return ""; + } +} + +export default new VoiceInputService(); diff --git a/browser/base/content/assistant/build/src/shims/fs-promises-stub.mjs b/browser/base/content/assistant/build/src/shims/fs-promises-stub.mjs new file mode 100644 index 0000000000000..5f0dde3d06cb8 --- /dev/null +++ b/browser/base/content/assistant/build/src/shims/fs-promises-stub.mjs @@ -0,0 +1,10 @@ +/** Stub for railroad-memory FileStorage (unused in browser IndexedDB builds). */ +async function unavailable() { + throw new Error("FileStorage is not available in the Oasis browser bundle"); +} +export const readFile = unavailable; +export const writeFile = unavailable; +export const mkdir = unavailable; +export const unlink = unavailable; +export const access = unavailable; +export const readdir = unavailable; diff --git a/browser/base/content/assistant/build/src/shims/path-stub.mjs b/browser/base/content/assistant/build/src/shims/path-stub.mjs new file mode 100644 index 0000000000000..39ebc8c19deba --- /dev/null +++ b/browser/base/content/assistant/build/src/shims/path-stub.mjs @@ -0,0 +1,4 @@ +/** Minimal path.join for FileStorage stub (unused in browser). */ +export function join(...parts) { + return parts.filter(Boolean).join("/").replace(/\/+/g, "/"); +} diff --git a/browser/base/content/assistant/build/src/types/auth.ts b/browser/base/content/assistant/build/src/types/auth.ts new file mode 100644 index 0000000000000..c4d7d883cb5a3 --- /dev/null +++ b/browser/base/content/assistant/build/src/types/auth.ts @@ -0,0 +1,29 @@ +/** Auth types — UserProfile, UserSession, and AuthState interfaces for Supabase integration. */ +import { User, Session } from '@supabase/supabase-js'; + +export interface UserProfile { + user_id: string; + name?: string; + email: string; + created_at: string; + last_login?: string; + status: 'active' | 'suspended'; +} + +export interface UserSession { + session_id: string; + user_id: string; + started_at: string; + ended_at?: string; + device_info?: { + platform: string; + version: string; + userAgent?: string; + }; +} + +export interface AuthState { + user: User | null; + session: Session | null; + isAuthenticated: boolean; +} diff --git a/browser/base/content/assistant/build/src/types/runtime.ts b/browser/base/content/assistant/build/src/types/runtime.ts new file mode 100644 index 0000000000000..50dfac4976ca0 --- /dev/null +++ b/browser/base/content/assistant/build/src/types/runtime.ts @@ -0,0 +1,286 @@ +/** Type definitions for Firefox's privileged runtime objects: gBrowser, tabs, tab groups, PlacesUtils, Services, and the assistant's window interface. */ +import type { BaseMessage } from "@langchain/core/messages"; +import type SupabaseAuth from "../services/supabase.js"; +import type voiceInputService from "../services/voiceInput.js"; +import type { + OasisRecordToolActionStart, + OasisRecordToolActionUpdate, + PendingAmbiguityPayload, + PendingConfirmationPayload, + RunAssistantStream, +} from "../../../shared/contracts.js"; + +export type UnknownRecord = Record; + +export type BrowserUriLike = { + spec?: string; + href?: string; + toString?: () => string; +}; + +export type BrowserLinkedBrowserLike = { + currentURI?: BrowserUriLike; + contentTitle?: string; + loadURI?: (url: string, options?: unknown) => void; + contentDocument?: { + body?: { + innerText?: string; + }; + }; + browsingContext?: { + currentWindowContext?: { + getActor: (actorName: string) => { + getReaderModeContent?: () => Promise; + getText?: () => Promise; + } | null; + } | null; + }; +}; + +export type BrowserTabGroupLike = { + id?: string | number; + label?: string; + collapsed?: boolean; + tabs?: BrowserTabLike[]; + addTabs?: (tabs: BrowserTabLike[]) => void; +}; + +export type BrowserTabLike = { + label?: string; + pinned?: boolean; + group?: BrowserTabGroupLike | null; + splitview?: { + unsplitTabs?: () => void; + } | null; + linkedBrowser?: BrowserLinkedBrowserLike; + ownerGlobal?: { gBrowser?: GBrowserLike }; + [key: string]: unknown; +}; + +export type GBrowserLike = { + tabs: ArrayLike | BrowserTabLike[]; + selectedTab?: BrowserTabLike; + tabGroups?: ArrayLike | BrowserTabGroupLike[]; + getAllTabGroups?: () => + | ArrayLike + | BrowserTabGroupLike[]; + adoptTab?: (tab: BrowserTabLike, index: number) => void; + removeTab?: (tab: BrowserTabLike) => void; + addTrustedTab?: ( + url: string, + options?: { triggeringPrincipal?: unknown; relatedToCurrent?: boolean } + ) => BrowserTabLike; + addTabSplitView?: ( + tabs: BrowserTabLike[], + options?: { insertBefore?: BrowserTabLike } + ) => void; + addTabGroup?: ( + tabs: BrowserTabLike[], + options?: { label?: string } + ) => BrowserTabGroupLike; + ungroupTab?: (tab: BrowserTabLike) => void; + [key: string]: unknown; +}; + +type WindowMediatorLike = { + getMostRecentWindow: (windowType: string) => BrowserWindowLike | null; + getEnumerator?: (windowType: string) => { + hasMoreElements: () => boolean; + getNext: () => BrowserWindowLike; + }; +}; + +type ObserverLike = { + observe: (subject: unknown, topic: string, data: string | null) => void; +}; + +export type ServicesLike = { + wm?: WindowMediatorLike; + obs?: { + addObserver: ( + observer: ObserverLike, + topic: string, + ownsWeak?: boolean + ) => void; + }; + prefs?: { + getBoolPref?: (name: string, defaultValue?: boolean) => boolean; + }; + uriFixup?: { + getFixupURIInfo?: ( + input: string, + flags: number + ) => { + preferredURI?: BrowserUriLike; + }; + }; + scriptSecurityManager?: { + getSystemPrincipal?: () => unknown; + }; +}; + +export type PlacesBookmarkEntry = { + guid: string; + parentGuid?: string; + title?: string; + uri?: string; + url?: string | BrowserUriLike; + dateAdded?: number; + type?: number; +}; + +export type PlacesBookmarksLike = { + TYPE_FOLDER: number; + TYPE_BOOKMARK: number; + menuGuid: string; + toolbarGuid: string; + unfiledGuid: string; + search?: (query: { title?: string }) => Promise; + fetch: ( + query: string | { guid?: string; parentGuid?: string }, + onResult?: (bookmark: PlacesBookmarkEntry) => void + ) => Promise; + insert?: (details: { + parentGuid: string; + title?: string; + type?: number; + url?: string; + }) => Promise; + remove?: (guid: string) => Promise; + update?: (changes: { + guid: string; + title?: string; + }) => Promise; +}; + +export type PlacesHistoryResultRoot = { + containerOpen: boolean; + childCount: number; + getChild: (index: number) => { + uri?: string; + title?: string; + time?: number; + }; +}; + +export type PlacesHistoryOptions = { + SORT_BY_DATE_DESCENDING?: number; + sortingMode?: number; + maxResults?: number; + includeVisits?: boolean; + includeHidden?: boolean; +}; + +export type PlacesHistoryLike = { + getNewQueryOptions: () => PlacesHistoryOptions; + getNewQuery: () => unknown; + executeQuery: ( + query: unknown, + options: unknown + ) => { root: PlacesHistoryResultRoot }; +}; + +export type PlacesUtilsLike = { + bookmarks?: PlacesBookmarksLike; + history?: PlacesHistoryLike; + observers?: { + addListener?: ( + topics: string[], + listener: (events: unknown[]) => void + ) => void; + }; +}; + +export type BrowserWindowLike = Window & { + gBrowser?: GBrowserLike; + PlacesUtils?: PlacesUtilsLike; + Services?: ServicesLike; + OpenBrowserWindow?: () => BrowserWindowLike; + openTrustedLinkIn?: (url: string, where: string) => void; + SidebarController?: { + hide?: () => void; + }; + [key: string]: unknown; +}; + +export type AssistantSessionLike = { + readonly messages: unknown[]; + addTurn: (user: unknown, assistant: unknown) => void; + clear: () => void; + setSession: (messages: unknown[]) => void; +}; + +export type { OasisRecordToolActionStart, OasisRecordToolActionUpdate }; + +export type AssistantWindowLike = Window & { + supabaseAuth?: ReturnType; + voiceInputService?: typeof voiceInputService; + textToSpeech?: (text: string) => Promise; + voiceAgent?: { + on(listener: (event: unknown) => void): () => void; + getState(): string; + startConversation(): Promise; + startListening(opts?: { + source?: "user" | "continuous" | "handsfree"; + }): Promise; + finishListening(): Promise; + stop(): void; + stopSpeaking(): void; + setRunAssistant(fn: RunAssistantStream): void; + getListeningSource(): "user" | "continuous" | "handsfree" | null; + getUserSpeaking(): boolean; + getCaptureMode(): "continuous" | "precise"; + setCaptureMode(mode: "continuous" | "precise"): void; + getVoiceSpokenRepliesEnabled(): boolean; + setVoiceSpokenRepliesEnabled(enabled: boolean): void; + }; + marked?: unknown; + DOMPurify?: unknown; + resetAssistantSession?: () => void; + getAssistantHistory?: () => BaseMessage[]; + getOasisCapabilitiesMarkdown?: () => string; + oasisPushLocalChatTurn?: ( + userText: string, + assistantMarkdown: string + ) => void; + oasisSyncSessionFromPlainTurns?: ( + turns: Array<{ type: "human" | "ai"; content: string }> + ) => void; + /** Session id for Railroad memory (`userId:chatId`); set from UI. */ + oasisRailroadSessionKey?: string; + oasisSetRailroadSessionKey?: (key: string | null) => void; + runAssistantStream?: RunAssistantStream; + oasisRecordToolActionStart?: OasisRecordToolActionStart; + oasisRecordToolActionUpdate?: OasisRecordToolActionUpdate; + oasisSetPendingConfirmationRelay?: ( + confirmation: PendingConfirmationPayload | null + ) => void; + oasisGetPendingConfirmation?: () => PendingConfirmationPayload | null; + oasisClearPendingConfirmation?: () => void; + oasisGetPendingAmbiguity?: () => PendingAmbiguityPayload | null; + oasisVoiceAssistantTurnBegin?: (userTranscript: string) => string; + oasisVoiceAssistantStreamChunk?: (messageId: string, chunk: string) => void; + oasisVoiceSpokenTurnMirror?: ( + userTranscript: string, + assistantText: string + ) => void; + Services?: ServicesLike; + ChromeUtils?: { + importESModule?: (path: string) => Record; + import?: (path: string) => Record; + }; + PlacesUtils?: PlacesUtilsLike; +}; + +export function getBrowserWindow( + globalRef: typeof globalThis = globalThis +): BrowserWindowLike | null { + const maybeWindow = (globalRef as { window?: AssistantWindowLike }).window; + const win = maybeWindow || (globalRef as unknown as AssistantWindowLike); + const services = + win.Services || (win.top as AssistantWindowLike | undefined)?.Services; + if (services?.wm) { + return services.wm.getMostRecentWindow("navigator:browser"); + } + return (win.top as BrowserWindowLike | null) || (win as BrowserWindowLike); +} diff --git a/browser/base/content/assistant/build/src/types/vendor-modules.d.ts b/browser/base/content/assistant/build/src/types/vendor-modules.d.ts new file mode 100644 index 0000000000000..a54bc13075c6c --- /dev/null +++ b/browser/base/content/assistant/build/src/types/vendor-modules.d.ts @@ -0,0 +1,25 @@ +declare module "../../../../../../toolkit/content/vendor/marked/marked.mjs" { + export const marked: { + parse: (markdown: string) => string; + }; +} + +declare module "*/toolkit/content/vendor/marked/marked.mjs" { + export const marked: { + parse: (markdown: string) => string; + }; +} + +declare module "../../../../../../toolkit/content/vendor/dompurify/dompurify.mjs" { + const DOMPurify: { + sanitize: (value: string, options?: unknown) => string; + }; + export default DOMPurify; +} + +declare module "*/toolkit/content/vendor/dompurify/dompurify.mjs" { + const DOMPurify: { + sanitize: (value: string, options?: unknown) => string; + }; + export default DOMPurify; +} diff --git a/browser/base/content/assistant/build/src/utils/README.md b/browser/base/content/assistant/build/src/utils/README.md new file mode 100644 index 0000000000000..9119931906b4c --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/README.md @@ -0,0 +1,99 @@ +# utils/ — Deterministic Routing (Non-AI Fallback) + +This folder implements the rule-based routing system that works WITHOUT +the remote LLM. It's used as a fallback when the Assist API is +unavailable, and also as a guard/override layer on top of LLM routing +(e.g., for ambiguity detection). + +## Call Hierarchy + +Understanding which file calls which is the key to navigating this +folder. Here's the complete call chain: + +``` +deterministicRouter.ts ← Entry point (called from graph.ts) +│ Gets a routing state snapshot, then delegates to: +│ +└── decisionEngine.ts ← Orchestrator: tries resolvers in order + │ + ├── 1. intentParser.ts ← Classifies input as list/search/mutation/other + │ + ├── 2. Family-specific resolvers (one runs based on classification): + │ ├── manifestListResolver.ts ← "list tabs", "show my groups" + │ ├── manifestSearchResolver.ts ← "search X", "find X in Y folder" + │ └── manifestMutationResolver.ts ← "add X to Y", "delete X" + │ └── mutationExplicitResolver.ts ← Regex rules for mutations + │ + ├── 3. searchResultExplicitResolver.ts ← "open the first result" + ├── 4. summarizeExplicitResolver.ts ← "summarize this page" + └── 5. explicitRouteRules.ts ← "open google.com", "new window" +``` + +If none of these match, returns `no_match` and the supervisor routes +to the chat node. + +## Files by Purpose + +### Entry Points +- **deterministicRouter.ts** — Thin wrapper. Gets a state snapshot from + the cache and calls `decideDeterministicRoute()`. +- **decisionEngine.ts** — The orchestrator. Classifies the command + family, runs the appropriate resolver, falls through to explicit + rules, and returns a routing decision. + +### Intent Classification +- **intentParser.ts** — Regex-based NLP that classifies user text: + - `classifyCommandFamily()`: returns list/search/mutation/other + - `parseContainerAddIntent()`: "add X to Y" pattern extraction + - `parseCloseDeleteTargetIntent()`: "close/delete X" extraction + - `parseSearchMemoryIntent()`: "search X in Y folder" extraction + - `looksActionableText()`: does the text have an action verb + object? + +### Family Resolvers +- **manifestListResolver.ts** — Handles "list/show" commands. Parses + the target name, checks if it's a tab group or bookmark folder + via the routing state snapshot, returns the right args. +- **manifestSearchResolver.ts** — Handles "search/find" commands. + Extracts query and optional folder scope. Cross-references folder + names with the routing state to validate folder targets. +- **manifestMutationResolver.ts** — Handles "add/delete/rename/close" + commands. Delegates to mutationExplicitResolver for specific + pattern matching and to intentParser for container-add parsing. +- **mutationExplicitResolver.ts** — Array of regex rules for mutation + commands: split tabs, close tab, create group, rename folder, etc. + Each rule extracts specific args from the user text. + +### General Pattern Matchers +- **explicitRouteRules.ts** — Catches commands that don't fit a family: + "open ", "new window", "organize windows", "copy tab urls", + "show subscription". Each rule is a regex with an arg extractor. +- **searchResultExplicitResolver.ts** — Catches follow-up commands + like "open it", "open the first result", "open result 3". +- **summarizeExplicitResolver.ts** — Catches "summarize this page", + "summarize tab 3", etc. + +### Support Files +- **commandManifest.ts** — Static mapping of known phrases to command + names. E.g., "list bookmark folders" → `list_bookmark_folders`. + Used by `manifestResolver.ts` for phrase-based matching. +- **manifestResolver.ts** — Finds the best matching manifest entry + for a given input string. Used by all family resolvers. +- **manifestTypes.ts** — Type definitions for commandManifest entries. +- **routingStateCache.ts** — Caches current tab group and bookmark + folder names from the live browser. The resolvers use this to + verify that a target name like "Research" actually exists. +- **routerTypes.ts** — Type definitions for routing decisions, route + args, routing state snapshots, and intent families. +- **routingUtils.ts** — Small helpers: `looksLikeNewActionCommand()`, + `parseAmbiguityResolution()`. + +### Non-Routing Utils +- **assistantLogger.ts** — Structured logging with domain tags + (router, graph, search-memory, etc.). +- **streamGuards.ts** — Detects infinite loops in graph execution. + Tracks step count and same-step streaks. +- **localMemoryUtils.ts** — Helpers for localMemory.ts: dedupe key + computation, metadata field extraction. +- **searchMemoryUtils.ts** — Helpers for search_memory results: + bookmark folder URL map building, stale result filtering. +- **entityResolver.ts** — Resolves entity references in user text. diff --git a/browser/base/content/assistant/build/src/utils/assistantLogger.ts b/browser/base/content/assistant/build/src/utils/assistantLogger.ts new file mode 100644 index 0000000000000..0d029871eb452 --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/assistantLogger.ts @@ -0,0 +1,74 @@ +/** Structured logging with domain scopes. Debug/info logs are gated behind the browser.oasis.assistant.debug pref. */ +const DEBUG_PREF_NAME = "browser.oasis.assistant.debug"; + +type LogScope = string; +type LogMeta = unknown; + +type LoggerHost = { + window?: { + Services?: { + prefs?: { + getBoolPref?: (name: string, defaultValue?: boolean) => boolean; + }; + }; + }; + Services?: { + prefs?: { + getBoolPref?: (name: string, defaultValue?: boolean) => boolean; + }; + }; +}; + +function isDebugEnabled(globalRef: typeof globalThis = globalThis): boolean { + try { + const host = globalRef as unknown as LoggerHost; + const prefs = + host.window?.Services?.prefs || + host.Services?.prefs; + if (!prefs?.getBoolPref) { + return false; + } + return !!prefs.getBoolPref(DEBUG_PREF_NAME, false); + } catch { + return false; + } +} + +function formatPrefix(scope: LogScope, message: string): string { + return `[Assistant:${scope}] ${message}`; +} + +function write( + level: "debug" | "info" | "warn" | "error", + scope: LogScope, + message: string, + meta?: LogMeta +): void { + if ((level === "debug" || level === "info") && !isDebugEnabled()) { + return; + } + const text = formatPrefix(scope, message); + if (meta !== undefined) { + console[level](text, meta); + return; + } + console[level](text); +} + +export const assistantLogger = { + debug(scope: LogScope, message: string, meta?: LogMeta): void { + write("debug", scope, message, meta); + }, + info(scope: LogScope, message: string, meta?: LogMeta): void { + write("info", scope, message, meta); + }, + warn(scope: LogScope, message: string, meta?: LogMeta): void { + write("warn", scope, message, meta); + }, + error(scope: LogScope, message: string, meta?: LogMeta): void { + write("error", scope, message, meta); + }, + isDebugEnabled, +}; + +export { DEBUG_PREF_NAME }; diff --git a/browser/base/content/assistant/build/src/utils/commandManifest.ts b/browser/base/content/assistant/build/src/utils/commandManifest.ts new file mode 100644 index 0000000000000..205e3d4a61f25 --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/commandManifest.ts @@ -0,0 +1,167 @@ +/** + * Command manifest — static phrase-to-command mapping. + * + * Maps known natural language phrases to command names and families. + * E.g., "list bookmark folders" -> list_bookmark_folders (family: list). + * Each entry defines: id, family, commandName, phrases[], and optional + * slots[] and conditions. + * + * Used by manifestResolver.ts for fast phrase-based matching. + */ +import type { ManifestCommandDefinition } from "./manifestTypes.js"; + +export const COMMAND_MANIFEST: readonly ManifestCommandDefinition[] = [ + { + id: "list.bookmark.folders", + family: "list", + commandName: "list_bookmark_folders", + phrases: [ + "list bookmark folders", + "list my bookmark folders", + "list my bookmarks", + "list bookmarks", + "show bookmark folders", + "show my bookmark folders", + "show bookmarks", + "show my bookmarks", + "list folders", + "show folders", + "list hubs", + "show hubs", + ], + }, + { + id: "list.tab.groups", + family: "list", + commandName: "list_tab_groups", + phrases: [ + "list tab groups", + "show tab groups", + "list groups", + "show groups", + "list my tab groups", + "show my tab groups", + ], + }, + { + id: "list.window.tabs", + family: "list", + commandName: "list_tabs", + phrases: [ + "list tabs", + "show tabs", + "list my tabs", + "list my open tabs", + "what tabs do i have open", + "which tabs are open", + "what tabs are open", + "tabs do i have open", + ], + condition: context => context.hasOpenTabs, + }, + { + id: "list.container.tabs", + family: "list", + commandName: "list_tabs", + phrases: ["list tabs in", "show tabs in", "list my", "show my", "list the", "show the"], + slots: [ + { name: "name", type: "target_name", source: "rest", optional: true }, + { name: "scope", type: "scope", source: "rest", optional: true }, + ], + }, + { + id: "search.history", + family: "search", + commandName: "search_history", + priority: 2, + phrases: [ + "list my recent browsing history", + "list my browsing history", + "show my browsing history", + "show my recent browsing history", + "list recent browsing history", + "what is in my browsing history", + "whats in my browsing history", + "what pages did i visit", + "what did i read", + "what did i browse", + "find that article", + "find that page", + "find that site", + "what sites did i visit", + "pages i visited", + "articles i read", + "browsing history", + "search history", + "search my history", + "search my browser history", + "search my browsing history", + "find in my history", + "what was that page", + "what was that site", + "what was that article", + "did i visit", + "did i look at", + "did i read", + "did i browse", + ], + slots: [ + { + name: "query", + type: "string", + source: "quoted_or_rest", + optional: true, + }, + ], + }, + { + id: "search.memory", + family: "search", + commandName: "search_memory", + phrases: [ + "search", + "find", + "look up", + "have i visited", + "have i", + "what is in", + "do i have", + ], + slots: [ + { name: "query", type: "string", source: "quoted_or_rest" }, + { name: "folder", type: "target_name", source: "rest", optional: true }, + ], + }, + { + id: "mutation.container.add", + family: "mutation", + commandName: "add_tab_to_bookmark_folder", + phrases: ["add", "save", "move", "put"], + slots: [ + { name: "name", type: "target_name", source: "rest", optional: true }, + { name: "query", type: "string", source: "quoted_or_rest", optional: true }, + ], + }, + { + id: "mutation.target.delete", + family: "mutation", + commandName: "resolve_ambiguity", + phrases: ["close", "delete", "remove"], + slots: [{ name: "target", type: "target_name", source: "rest", optional: true }], + }, +] as const; + +export function validateCommandManifest( + manifest: readonly ManifestCommandDefinition[] = COMMAND_MANIFEST +): { ok: boolean; duplicateIds: string[] } { + const seen = new Set(); + const duplicateIds = new Set(); + for (const item of manifest) { + if (seen.has(item.id)) { + duplicateIds.add(item.id); + continue; + } + seen.add(item.id); + } + return { ok: duplicateIds.size === 0, duplicateIds: Array.from(duplicateIds) }; +} diff --git a/browser/base/content/assistant/build/src/utils/decisionEngine.ts b/browser/base/content/assistant/build/src/utils/decisionEngine.ts new file mode 100644 index 0000000000000..d95ac65a78ca8 --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/decisionEngine.ts @@ -0,0 +1,100 @@ +/** + * Decision engine — orchestrator for deterministic routing. + * + * Tries resolvers in this order: + * 1. Classify command family (list/search/mutation/other) + * 2. Run the matching family resolver (manifestList/Search/Mutation) + * 3. Try explicit route rules (regex patterns for URLs, commands) + * 4. Try search result and summarize resolvers + * 5. Check if text looks actionable but unrecognized + * 6. Return no_match (falls through to chat) + * + * Called by deterministicRouter.ts. + */ +import { classifyCommandFamily, looksActionableText } from "./intentParser.js"; +import { resolveExplicitRoute } from "./explicitRouteRules.js"; +import { resolveManifestListRoute } from "./manifestListResolver.js"; +import { resolveManifestSearchRoute } from "./manifestSearchResolver.js"; +import { resolveManifestMutationRoute } from "./manifestMutationResolver.js"; +import { resolveExplicitSearchResultRoute } from "./searchResultExplicitResolver.js"; +import { resolveExplicitSummarizeRoute } from "./summarizeExplicitResolver.js"; +import type { + DeterministicRouteDecision, + IntentFamily, + RoutingStateSnapshot, +} from "./routerTypes.js"; + +type FamilyDecisionHandler = ( + input: string, + snapshot: RoutingStateSnapshot +) => DeterministicRouteDecision | null; + +const FAMILY_HANDLERS: Readonly< + Record +> = { + list: resolveManifestListRoute, + search: resolveManifestSearchRoute, + mutation: resolveManifestMutationRoute, + other: null, +}; + +export function decideDeterministicRoute( + commandText: string, + snapshot: RoutingStateSnapshot +): DeterministicRouteDecision { + const input = String(commandText || "").trim(); + if (!input) { + return { type: "no_match", actionable: false, reason: "empty-input" }; + } + + const family = classifyCommandFamily(input); + const familyHandler = FAMILY_HANDLERS[family]; + if (familyHandler) { + const familyDecision = familyHandler(input, snapshot); + if (familyDecision) { + return familyDecision; + } + } + + const searchResultExplicit = resolveExplicitSearchResultRoute(input); + if (searchResultExplicit) { + return searchResultExplicit; + } + + const summarizeExplicit = resolveExplicitSummarizeRoute(input); + if (summarizeExplicit) { + return summarizeExplicit; + } + + const explicit = resolveExplicitRoute(input); + if (explicit) { + return explicit; + } + + if (family === "list" || family === "search" || family === "mutation") { + return { + type: "chat", + actionable: true, + reason: `${family}-family-unresolved`, + message: + family === "list" + ? "I am not sure what you want listed. Say whether you mean open tabs, a tab group, or a bookmarks folder. [Help](https://kahana.co/docs)" + : family === "search" + ? "I am not sure what to search for. Include what to find and, if it helps, where (for example a folder or source). [Help](https://kahana.co/docs)" + : "I am not sure which page or control you want to change. Say in plain language what should happen and where (for example which tab, site, or button). [Kahana documentation](https://kahana.co/docs)", + }; + } + + const actionable = looksActionableText(input); + if (actionable) { + return { + type: "chat", + actionable: true, + reason: "actionable-but-unsupported", + message: + "I could not match that to one clear, safe step in the browser. Describe what to change and where in more detail. [Help](https://kahana.co/docs)", + }; + } + + return { type: "no_match", actionable: false, reason: "non-actionable" }; +} diff --git a/browser/base/content/assistant/build/src/utils/deterministicRouter.ts b/browser/base/content/assistant/build/src/utils/deterministicRouter.ts new file mode 100644 index 0000000000000..cf3d3b5f3bff4 --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/deterministicRouter.ts @@ -0,0 +1,27 @@ +/** + * Deterministic router — entry point for non-AI routing. + * + * Called from graph.ts as a fallback when the LLM-based routing is + * unavailable. Gets a snapshot of the current browser state (tab + * groups, bookmark folders) and delegates to decisionEngine.ts. + */ +import { decideDeterministicRoute } from "./decisionEngine.js"; +import { routingStateCache } from "./routingStateCache.js"; +import type { + DeterministicRouteDecision, + RoutingStateMutation, +} from "./routerTypes.js"; + +export function routeDeterministically(commandText: string): DeterministicRouteDecision { + routingStateCache.ensureInitialized(); + const snapshot = routingStateCache.getSnapshotSync(); + return decideDeterministicRoute(commandText, snapshot); +} + +export function markRoutingStateDirty(reason: string): void { + routingStateCache.applyMutation({ kind: "dirty", reason }); +} + +export function applyRoutingStateMutation(mutation: RoutingStateMutation): void { + routingStateCache.applyMutation(mutation); +} diff --git a/browser/base/content/assistant/build/src/utils/entityResolver.ts b/browser/base/content/assistant/build/src/utils/entityResolver.ts new file mode 100644 index 0000000000000..0652d0a5e3338 --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/entityResolver.ts @@ -0,0 +1,36 @@ +/** Resolves a target name against live browser state: checks tab groups, bookmark folders, and matching open tabs. Used by manifestMutationResolver.ts for ambiguity detection. */ +import type { ResolutionResult, RoutingStateSnapshot } from "./routerTypes.js"; +import { normalizeRouteName } from "./intentParser.js"; +import { getBrowserWindow, type BrowserTabLike } from "../types/runtime.js"; + +export function resolveTargetName( + targetName: string, + snapshot: RoutingStateSnapshot +): ResolutionResult { + const normalizedTarget = normalizeRouteName(targetName); + const topWin = getBrowserWindow(); + const gBrowser = topWin?.gBrowser; + + const tabMatches: number[] = []; + if (gBrowser?.tabs && normalizedTarget) { + const tabs = Array.from(gBrowser.tabs || []); + for (let i = 0; i < tabs.length; i++) { + const tab = tabs[i] as BrowserTabLike; + const title = normalizeRouteName(tab?.label || ""); + const url = normalizeRouteName(tab?.linkedBrowser?.currentURI?.spec || ""); + if ( + title === normalizedTarget || + url === normalizedTarget || + (normalizedTarget.length > 2 && (title.includes(normalizedTarget) || url.includes(normalizedTarget))) + ) { + tabMatches.push(i + 1); + } + } + } + + return { + targetInFolders: snapshot.folderNames.has(normalizedTarget), + targetInGroups: snapshot.groupNames.has(normalizedTarget), + tabMatches, + }; +} diff --git a/browser/base/content/assistant/build/src/utils/explicitRouteRules.ts b/browser/base/content/assistant/build/src/utils/explicitRouteRules.ts new file mode 100644 index 0000000000000..b606f8e2a61c8 --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/explicitRouteRules.ts @@ -0,0 +1,330 @@ +/** + * Explicit route rules — regex patterns for non-family-specific commands. + * + * Catches commands that don't fit neatly into list/search/mutation: + * "open ", "new window", "copy tab urls", "show subscription", + * "open bookmark folder X as tab group", etc. + * + * Each rule has a regex + arg extractor. Tried after family resolvers + * fail. Called by decisionEngine.ts. + */ +import type { DeterministicRouteDecision, RouteArgs } from "./routerTypes.js"; +import { resolveKnownSiteToUrl } from "./knownSites.js"; + +type ExplicitRouteRule = { + next: string; + reason: string; + resolve: (input: string, lower: string) => RouteArgs | null; +}; + +function toolDecision( + next: string, + reason: string, + args: RouteArgs +): DeterministicRouteDecision { + return { type: "tool", next, args, reason }; +} + +function firstUrlLike(input: string): string | null { + const urlMatch = input.match(/\b(https?:\/\/[^\s]+)\b/i); + if (urlMatch?.[1]) { + return urlMatch[1].trim(); + } + const domainMatch = input.match(/\b([a-z0-9.-]+\.[a-z]{2,}(?:\/[^\s]*)?)\b/i); + if (domainMatch?.[1]) { + return domainMatch[1].trim(); + } + return null; +} + +function firstMatch( + input: string, + patterns: RegExp[] +): RegExpMatchArray | null { + for (const pattern of patterns) { + const match = input.match(pattern); + if (match) { + return match; + } + } + return null; +} + +function trimOpenTarget(raw: string): string { + return String(raw || "") + .trim() + .replace(/^["']|["']$/g, "") + .replace(/[.!?]+$/g, "") + .trim(); +} + +function resolveTargetForNewTab(targetRaw: string): RouteArgs | null { + const target = trimOpenTarget(targetRaw); + if (!target) { + return null; + } + const urlHit = firstUrlLike(target); + if (urlHit) { + return { url: urlHit }; + } + const siteUrl = resolveKnownSiteToUrl(target); + if (siteUrl) { + return { url: siteUrl }; + } + return { query: target }; +} + +const OPEN_TARGET_IN_NEW_TAB_RE = + /^(?:open|visit|go\s+to|launch)\s+(?.+?)\s+in\s+(?:a\s+)?new\s+tab\b/i; + +const EXPLICIT_ROUTE_RULES: ExplicitRouteRule[] = [ + { + next: "copy_tab_urls", + reason: "explicit-copy-tab-urls", + resolve: input => + /\bcopy\s+(?:all\s+)?tab\s+urls?\b/i.test(input) ? {} : null, + }, + { + next: "new_window", + reason: "explicit-new-window", + resolve: input => + /^\s*(?:new\s+window|open\s+(?:a\s+)?new\s+window|create\s+(?:a\s+)?new\s+window|make\s+(?:a\s+)?new\s+window)\b/i.test( + input + ) + ? {} + : null, + }, + { + next: "new_tab_to_right", + reason: "explicit-blank-new-tab", + resolve: input => { + const s = input + .trim() + .replace(/[.!?]+$/g, "") + .trim(); + if ( + /^\s*new\s+tab(?:\s+please)?\s*$/i.test(s) || + /^\s*(?:open\s+(?:up\s+)?(?:a\s+)?new\s+tab|(?:create|add)\s+(?:a\s+)?new\s+tab)(?:\s+please)?\s*$/i.test( + s + ) + ) { + return {}; + } + return null; + }, + }, + { + next: "organize_windows", + reason: "explicit-organize-windows", + resolve: input => (/\borganize\s+windows?\b/i.test(input) ? {} : null), + }, + { + next: "show_subscription", + reason: "explicit-show-subscription", + resolve: input => + /\b(?:show|check|view)\s+(?:my\s+)?subscription\b/i.test(input) + ? {} + : null, + }, + { + next: "show_url", + reason: "explicit-show-url", + resolve: input => { + const match = input.match( + /(?:show|open)\s+url\s+(?https?:\/\/[^\s]+|[a-z0-9.-]+\.[a-z]{2,}(?:\/[^\s]*)?)/i + ); + const url = match?.groups?.url?.trim(); + return url ? { url } : null; + }, + }, + { + next: "open_bookmark_folder", + reason: "explicit-open-folder-tabgroup", + resolve: input => { + const match = firstMatch(input, [ + /open\s+(?:the\s+)?(?:my\s+)?(?:bookmark\s+)?folder\s+"?(?[\w\s]+?)"?\s+(?:(?:as|in)\s+(?:a\s+)?(?:new\s+)?tab\s*group)/i, + /open\s+(?:my\s+)?"?(?[\w\s]+?)"?\s+(?:bookmark\s+)?folder\s+(?:(?:as|in)\s+(?:a\s+)?(?:new\s+)?tab\s*group)/i, + ]); + const name = match?.groups?.name?.trim(); + return name ? { name, where: "tabgroup" } : null; + }, + }, + { + next: "open_bookmark_folder", + reason: "explicit-open-folder-window", + resolve: input => { + const match = firstMatch(input, [ + /open\s+(?:the\s+)?(?:my\s+)?(?:bookmark\s+)?folder\s+"?(?[\w\s]+?)"?\s+(?:in\s+(?:a\s+)?(?:new\s+)?window)/i, + /open\s+(?:my\s+)?"?(?[\w\s]+?)"?\s+(?:bookmark\s+)?folder\s+(?:in\s+(?:a\s+)?(?:new\s+)?window)/i, + ]); + const name = match?.groups?.name?.trim(); + return name ? { name, where: "window" } : null; + }, + }, + { + next: "open_bookmark_folder", + reason: "explicit-open-folder", + resolve: input => { + const match = firstMatch(input, [ + /open\s+(?:the\s+)?(?:my\s+)?(?:bookmark\s+)?folder\s+"?(?[\w\s]+?)"?\s*$/i, + /open\s+(?:my\s+)?"?(?[\w\s]+?)"?\s+(?:bookmark\s+)?folder\s*$/i, + ]); + const name = match?.groups?.name?.trim(); + return name ? { name } : null; + }, + }, + { + next: "open_url", + reason: "explicit-open-target-in-new-tab-url", + resolve: input => { + const match = input.match(OPEN_TARGET_IN_NEW_TAB_RE); + const targetRaw = match?.groups?.target?.trim(); + if (!targetRaw) { + return null; + } + const args = resolveTargetForNewTab(targetRaw); + return args && "url" in args && args.url ? { url: args.url } : null; + }, + }, + { + next: "web_search", + reason: "explicit-open-target-in-new-tab-search", + resolve: input => { + const match = input.match(OPEN_TARGET_IN_NEW_TAB_RE); + const targetRaw = match?.groups?.target?.trim(); + if (!targetRaw) { + return null; + } + const args = resolveTargetForNewTab(targetRaw); + return args && "query" in args && args.query + ? { query: args.query } + : null; + }, + }, + { + next: "open_url", + reason: "explicit-open-url", + resolve: input => { + const match = input.match( + /open\s+(?:a\s+)?(?:new\s+)?tab\s+(?:to\s+|with\s+)?"?(?[^\s"']+)"?/i + ); + const url = match?.groups?.url?.trim(); + return url ? { url } : null; + }, + }, + { + next: "open_url", + reason: "open-url-like", + resolve: (input, lower) => { + if (!/^open\s+/i.test(lower)) { + return null; + } + const url = firstUrlLike(input); + return url ? { url } : null; + }, + }, + { + next: "web_search", + reason: "open-query-as-search", + resolve: input => { + const match = input.match( + /^open\s+(?:a\s+)?(?:new\s+)?tab\s+(?:for\s+|with\s+)?(?.+)$/i + ); + const query = match?.groups?.query?.trim(); + if (!query) { + return null; + } + if (firstUrlLike(query)) { + return null; + } + return { query }; + }, + }, + // ───────────────────────────────────────────────────────────────────────── + // BROWSING HISTORY SEARCH (search_history) + // Matches queries about pages the user VISITED (not bookmarked) + // Examples: "what did I read about X", "find that article I visited" + // ───────────────────────────────────────────────────────────────────────── + { + next: "search_history", + reason: "explicit-history-search", + resolve: input => { + const patterns: Array<{ re: RegExp; queryGroup?: string }> = [ + { re: /(?:what|which)\s+(?:was|were|is)\s+that\s+(?.+?)\s+(?:i\s+was|i've\s+been|i\s+have\s+been)\s+(?:reading|looking\s+at|browsing|viewing)/i }, + { re: /(?:pull|get|find|show)\s+(?:up\s+)?(?:me\s+)?(?:that\s+)?(?:page|article|site)\s+(?:about|on|regarding)\s+(?.+?)(?:\s+(?:from|in)\s+(?:my\s+)?history)?$/i }, + { re: /(?:pull|get|find|show|look)\s+(?:up\s+)?(?:for\s+)?(?:me\s+)?(?.+?)\s+(?:from|in)\s+(?:my\s+)?(?:browsing\s+)?history/i }, + { re: /(?:can\s+you\s+)?(?:pull|get|find|show|look)\s+(?:up\s+)?(?:for\s+)?(?:me\s+)?(?.+?)\s+(?:from|in)\s+(?:my\s+)?(?:browsing\s+)?history/i }, + { re: /(?:search|find|look\s*up)\s+(?:my\s+)?(?:browsing\s+)?history\s+(?:for|about)\s+(?.+)/i }, + { re: /(?:i\s+was\s+(?:reading|looking\s+at|browsing|viewing))\s+(?:something|a\s+page|an?\s+article|a\s+site)\s+(?:about|on|regarding)\s+(?.+)/i }, + { re: /what\s+(?:pages?|sites?|articles?)\s+(?:have\s+i|did\s+i|i)\s+(?:visited?|read|browsed?|looked?\s+at|viewed?|seen)\s+(?:about|on|regarding)\s+(?.+?)(?:\s+(?:recently|earlier|before|previously|yesterday))?$/i }, + { re: /what\s+(?:did\s+i|have\s+i)\s+(?:visit|read|browse|look\s+at|view)\s+(?:about\s+)?(?.+?)(?:\s+(?:recently|earlier|before|previously|yesterday))?$/i }, + { re: /what\s+(?:pages?|sites?|articles?)\s+(?:have\s+i|did\s+i)\s+(?:visited?|read|browsed?|viewed?|seen)(?:\s+(?:recently|earlier|before|previously|yesterday))?$/i, queryGroup: "recent browsing history" }, + ]; + for (const { re, queryGroup } of patterns) { + const match = input.match(re); + if (match) { + const query = match.groups?.query?.trim() || queryGroup || ""; + if (query) return { query }; + } + } + if (/\b(?:my|the)\s+(?:browsing\s+)?history\b/i.test(input)) { + const cleaned = input + .replace(/^(?:can\s+you\s+)?(?:search|find|look\s*(?:up|for)?|show|pull\s*up?|get)\s+/i, "") + .replace(/\s+(?:from|in)\s+(?:my\s+)?(?:browsing\s+)?history\b.*/i, "") + .replace(/\s*(?:my|the)\s+(?:browsing\s+)?history\s*/i, "") + .replace(/^(?:for|about|on|regarding)\s+/i, "") + .trim(); + return { query: cleaned || "recent browsing history" }; + } + return null; + }, + }, +]; +// { +// next: "search_history", +// reason: "explicit-history-search", +// resolve: input => { +// const patterns: Array<{ re: RegExp; queryGroup?: string }> = [ +// { re: /(?:what|which)\s+(?:was|were|is)\s+that\s+(?.+?)\s+(?:i\s+was|i've\s+been|i\s+have\s+been)\s+(?:reading|looking\s+at|browsing|viewing)/i }, +// { re: /(?:pull|get|find|show)\s+(?:up\s+)?(?:me\s+)?(?:that\s+)?(?:page|article|site)\s+(?:about|on|regarding)\s+(?.+?)(?:\s+(?:from|in)\s+(?:my\s+)?history)?$/i }, +// { re: /(?:pull|get|find|show|look)\s+(?:up\s+)?(?:for\s+)?(?:me\s+)?(?.+?)\s+(?:from|in)\s+(?:my\s+)?(?:browsing\s+)?history/i }, +// { re: /(?:can\s+you\s+)?(?:pull|get|find|show|look)\s+(?:up\s+)?(?:for\s+)?(?:me\s+)?(?.+?)\s+(?:from|in)\s+(?:my\s+)?(?:browsing\s+)?history/i }, +// { re: /(?:search|find|look\s*up)\s+(?:my\s+)?(?:browsing\s+)?history\s+(?:for|about)\s+(?.+)/i }, +// { re: /(?:i\s+was\s+(?:reading|looking\s+at|browsing|viewing))\s+(?:something|a\s+page|an?\s+article|a\s+site)\s+(?:about|on|regarding)\s+(?.+)/i }, +// { re: /what\s+(?:pages?|sites?|articles?)\s+(?:have\s+i|did\s+i|i)\s+(?:visited?|read|browsed?|looked?\s+at|viewed?|seen)\s+(?:about|on|regarding)\s+(?.+?)(?:\s+(?:recently|earlier|before|previously|yesterday))?$/i }, +// { re: /what\s+(?:did\s+i|have\s+i)\s+(?:visit|read|browse|look\s+at|view)\s+(?:about\s+)?(?.+?)(?:\s+(?:recently|earlier|before|previously|yesterday))?$/i }, +// { re: /what\s+(?:pages?|sites?|articles?)\s+(?:have\s+i|did\s+i)\s+(?:visited?|read|browsed?|viewed?|seen)(?:\s+(?:recently|earlier|before|previously|yesterday))?$/i, queryGroup: "recent browsing history" }, +// ]; +// for (const { re, queryGroup } of patterns) { +// const match = input.match(re); +// if (match) { +// const query = match.groups?.query?.trim() || queryGroup || ""; +// if (query) return { query }; +// } +// } +// if (/\b(?:my|the)\s+(?:browsing\s+)?history\b/i.test(input)) { +// const cleaned = input +// .replace(/^(?:can\s+you\s+)?(?:search|find|look\s*(?:up|for)?|show|pull\s*up?|get)\s+/i, "") +// .replace(/\s+(?:from|in)\s+(?:my\s+)?(?:browsing\s+)?history\b.*/i, "") +// .replace(/\s*(?:my|the)\s+(?:browsing\s+)?history\s*/i, "") +// .replace(/^(?:for|about|on|regarding)\s+/i, "") +// .trim(); +// return { query: cleaned || "recent browsing history" }; +// } +// return null; +// }, +// }, +// ]; + +export function resolveExplicitRoute( + input: string +): DeterministicRouteDecision | null { + const lower = input.toLowerCase(); + for (const rule of EXPLICIT_ROUTE_RULES) { + const args = rule.resolve(input, lower); + if (args) { + return toolDecision(rule.next, rule.reason, args); + } + } + return null; +} diff --git a/browser/base/content/assistant/build/src/utils/intentParser.ts b/browser/base/content/assistant/build/src/utils/intentParser.ts new file mode 100644 index 0000000000000..d44ca2ea510dd --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/intentParser.ts @@ -0,0 +1,322 @@ +/** + * Intent parser — regex-based NLP for classifying user input. + * + * Key functions: + * - classifyCommandFamily(): list / search / mutation / other + * - parseContainerAddIntent(): "add X to Y" pattern extraction + * - parseCloseDeleteTargetIntent(): "close/delete X" extraction + * - parseSearchMemoryIntent(): "search X in Y folder" extraction + * - looksActionableText(): has an action verb + browser object? + * + * Used by decisionEngine.ts and the family resolvers. + */ +import type { ContainerType, IntentFamily, ParsedIntent } from "./routerTypes.js"; + +const ACTION_WORD_RE = + /\b(?:open|close|delete|remove|create|make|new|add|save|move|put|rename|list|show|search|find|summarize|split|organize|copy)\b/i; + +const ACTION_OBJECT_RE = + /\b(?:tab|tabs|group|folder|bookmark|window|history|memory|page|url|result|split)\b/i; +const LIST_VERB_RE = /^list\b/i; +const SHOW_VERB_RE = /^show\b/i; +const LIST_OBJECT_RE = + /\b(?:tabs?|tab\s*groups?|groups?|bookmark\s*folders?|folders?|hubs?)\b/i; +const SEARCH_FAMILY_RE = + /^(?:search|find|look\s*up)\b|^have\s+i\s+(?:visited|been\s+to|seen|saved|bookmarked|read|looked\s+at)\b|^do\s+i\s+have\b|^what(?:'s|\s+is|\s+did\s+i\s+(?:save|read|visit|look\s+at|browse))\s+/i; +const HISTORY_FAMILY_RE = + /\b(?:visited|browsed|looked\s+at|read|viewed)\b.*\b(?:page|pages|site|sites|article|articles|earlier|before|recently|yesterday|last\s+week|previously)\b|\b(?:page|pages|site|sites|article|articles)\s+(?:i|i've|i\s+have)\s+(?:visited|read|seen|looked\s+at|browsed|viewed)\b|\b(?:pull|get|find|show)\s+that\s+(?:page|article|site)\b|\bwhat\s+(?:was|were|is)\s+that\s+.{2,}\s+(?:i\s+was|i've\s+been)\s+(?:reading|looking\s+at|browsing|viewing)\b|\b(?:my|the)\s+(?:browsing\s+)?history\b|\bpages\s+(?:i(?:'ve)?\s+)?visited\b|\bwhat\s+(?:did\s+i|have\s+i)\s+(?:visit|read|browse|look\s+at|view)\b/i; +const MUTATION_FAMILY_RE = + /^(?:add|save|move|put|close|delete|remove|rename|create|make|split|unsplit|ungroup)\b/i; + +const GROUP_LABEL_RE = /\btab\s*group\b|\bgroup\b/i; +const FOLDER_LABEL_RE = /\bbookmark\s*folder\b|\bfolder\b|\bhub\b|\bbookmarks?\b/i; +const GENERIC_FOLDER_NAME_RE = /^(?:bookmark(?:\s+folders?)?|folders?|hubs?)$/i; + +function cleanCaptured(text: string): string { + return String(text || "") + .replace(/["']/g, "") + .replace(/^\s*(?:my|the)\s+/i, "") + .trim(); +} + +function extractContainerType(text: string): ContainerType | null { + const hasGroup = GROUP_LABEL_RE.test(text); + const hasFolder = FOLDER_LABEL_RE.test(text); + if (hasGroup && hasFolder) { + return null; + } + if (hasGroup) { + return "tab-group"; + } + if (hasFolder) { + return "bookmark-folder"; + } + return null; +} + +function extractTargetName(raw: string): string { + let name = cleanCaptured(raw); + name = name.replace(/^bookmark\s+folder\s+/i, ""); + name = name.replace(/^bookmarks?\s+/i, ""); + name = name.replace(/^tab\s*group\s+/i, ""); + name = name.replace(/^folder\s+/i, ""); + name = name.replace(/^hub\s+/i, ""); + name = name.replace(/^group\s+/i, ""); + name = name.replace(/\s+bookmarks?\s*$/i, ""); + name = name.replace(/\s+bookmark\s+folder\s*$/i, ""); + name = name.replace(/\s+tab\s*group\s*$/i, ""); + name = name.replace(/\s+folder\s*$/i, ""); + name = name.replace(/\s+hub\s*$/i, ""); + name = name.replace(/\s+group\s*$/i, ""); + return name.trim(); +} + +function isNonContainerTarget(rawTarget: string): boolean { + return /\bnew\s+window\b|\bwindow\b|\bsplit\s*view\b/i.test(rawTarget); +} + +export function looksActionableText(text: string): boolean { + const input = String(text || ""); + return ACTION_WORD_RE.test(input) && ACTION_OBJECT_RE.test(input); +} + +const LIST_OPEN_TABS_QUESTION_RE = + /^(?:what|which)\s+tabs\b|\btabs\s+do\s+i\s+have\s+open\b|\btabs\s+are\s+open\b/i; + +export function classifyCommandFamily(commandText: string): IntentFamily { + const input = String(commandText || "").trim(); + if (!input) { + return "other"; + } + if (LIST_OPEN_TABS_QUESTION_RE.test(input)) { + return "list"; + } + if (LIST_VERB_RE.test(input)) { + return "list"; + } + if (SHOW_VERB_RE.test(input) && LIST_OBJECT_RE.test(input)) { + return "list"; + } + if (SEARCH_FAMILY_RE.test(input) || HISTORY_FAMILY_RE.test(input)) { + return "search"; + } + if (MUTATION_FAMILY_RE.test(input)) { + return "mutation"; + } + return "other"; +} + +export function normalizeRouteName(value: string): string { + return String(value || "").trim().toLowerCase(); +} + +export function parseContainerAddIntent(commandText: string): ParsedIntent | null { + const input = String(commandText || "").trim(); + if (!input) return null; + + const allMatch = input.match( + /^(?add|save|move|put)\s+all\s+(?:tabs?|existing\s+tabs?)\s+to\s+(?.+)$/i + ); + if (allMatch?.groups) { + if (isNonContainerTarget(allMatch.groups.target)) { + return null; + } + const explicitContainer = extractContainerType(allMatch.groups.target); + const targetName = extractTargetName(allMatch.groups.target); + if (!targetName) return null; + return { + rawText: input, + normalizedText: input.toLowerCase(), + verb: allMatch.groups.verb.toLowerCase(), + isActionLike: true, + explicitContainer, + targetName, + all: true, + kind: "container_add", + }; + } + + const currentMatch = input.match( + /^(?add|save|move|put)\s+(?:this|current|active)\s+tab\s+to\s+(?.+)$/i + ); + if (currentMatch?.groups) { + if (isNonContainerTarget(currentMatch.groups.target)) { + return null; + } + const explicitContainer = extractContainerType(currentMatch.groups.target); + const targetName = extractTargetName(currentMatch.groups.target); + if (!targetName) return null; + return { + rawText: input, + normalizedText: input.toLowerCase(), + verb: currentMatch.groups.verb.toLowerCase(), + isActionLike: true, + explicitContainer, + targetName, + current: true, + kind: "container_add", + }; + } + + const queryMatch = input.match( + /^(?add|save|move|put)\s+(?.+?)\s+to\s+(?.+)$/i + ); + if (queryMatch?.groups) { + if (isNonContainerTarget(queryMatch.groups.target)) { + return null; + } + const explicitContainer = extractContainerType(queryMatch.groups.target); + const targetName = extractTargetName(queryMatch.groups.target); + const query = cleanCaptured(queryMatch.groups.query); + if (!targetName || !query) return null; + return { + rawText: input, + normalizedText: input.toLowerCase(), + verb: queryMatch.groups.verb.toLowerCase(), + isActionLike: true, + explicitContainer, + targetName, + all: /^(?:all\s+tabs?|all\s+existing\s+tabs?)$/i.test(query), + current: /^(?:this|current|active)\s+tab$/i.test(query), + query, + kind: "container_add", + }; + } + + return null; +} + +export function parseCloseDeleteTargetIntent(commandText: string): ParsedIntent | null { + const input = String(commandText || "").trim(); + if (!input) return null; + + const match = input.match(/^(?close|delete|remove)\s+(?.+)$/i); + if (!match?.groups) return null; + + const verb = match.groups.verb.toLowerCase(); + const target = cleanCaptured(match.groups.target); + if (!target) return null; + + return { + rawText: input, + normalizedText: input.toLowerCase(), + verb, + isActionLike: true, + explicitContainer: extractContainerType(target), + targetName: extractTargetName(target), + kind: "close_delete_target", + }; +} + +export function parseSearchFolderSlots(commandText: string): + | { query: string; folder: string } + | null { + const input = String(commandText || "").trim(); + if (!input) return null; + + const quotedQueryFirst = input.match( + /^(?:search|find|look\s*up)\s+(?:for\s+)?(?.+?)\s+(?:in|inside|within|from)\s+(?:my\s+)?(?:the\s+)?["'](?[^"']+?)["']\s*(?:bookmark\s+folder|folder|hub|bookmarks?)?\s*$/i + ); + if (quotedQueryFirst?.groups) { + const folder = cleanCaptured(quotedQueryFirst.groups.folder); + if (!folder || GENERIC_FOLDER_NAME_RE.test(folder)) { + return null; + } + return { + query: cleanCaptured(quotedQueryFirst.groups.query), + folder, + }; + } + + const quotedFolderFirst = input.match( + /^(?:search|find|look\s*up)\s+(?:(?:in|inside|within|from)\s+)?(?:my\s+)?(?:the\s+)?["'](?[^"']+?)["']\s*(?:bookmark\s+folder|folder|hub|bookmarks?)?\s+(?:for\s+)?(?.+?)\s*$/i + ); + if (quotedFolderFirst?.groups) { + const folder = cleanCaptured(quotedFolderFirst.groups.folder); + if (!folder || GENERIC_FOLDER_NAME_RE.test(folder)) { + return null; + } + return { + query: cleanCaptured(quotedFolderFirst.groups.query), + folder, + }; + } + + const queryFirst = input.match( + /^(?:search|find|look\s*up)\s+(?:for\s+)?(?.+?)\s+(?:in|inside|within|from)\s+(?:my\s+)?(?:the\s+)?(?[\w\s-]+?)\s+(?:bookmark\s+folder|folder|hub|bookmarks?)\s*$/i + ); + if (queryFirst?.groups) { + const folder = cleanCaptured(queryFirst.groups.folder); + if (!folder || GENERIC_FOLDER_NAME_RE.test(folder)) { + return null; + } + return { + query: cleanCaptured(queryFirst.groups.query), + folder, + }; + } + + const folderFirst = input.match( + /^(?:search|find|look\s*up)\s+(?:(?:in|inside|within|from)\s+)?(?:my\s+)?(?:the\s+)?(?[\w\s-]+?)\s+(?:bookmark\s+folder|folder|hub|bookmarks?)\s+(?:for\s+)?(?.+?)\s*$/i + ); + if (folderFirst?.groups) { + const folder = cleanCaptured(folderFirst.groups.folder); + if (!folder || GENERIC_FOLDER_NAME_RE.test(folder)) { + return null; + } + return { + query: cleanCaptured(folderFirst.groups.query), + folder, + }; + } + + return null; +} + +export function parseSearchMemoryIntent(commandText: string): + | { query: string; folder?: string; source?: "bookmark-folder" } + | null { + const input = String(commandText || "").trim(); + if (!input) { + return null; + } + + const folderSourceScope = input.match( + /^(?:search|find|look\s*up)\s+(?:(?:in|inside|within|from)\s+)?(?:my\s+)?(?:the\s+)?(?:bookmark\s+folders?|folders?|hubs?|bookmarks?)\s+(?:for\s+)?(?.+?)\s*$/i + ); + if (folderSourceScope?.groups?.query) { + const scopedQuery = cleanCaptured(folderSourceScope.groups.query); + if (scopedQuery) { + return { query: scopedQuery, source: "bookmark-folder" }; + } + } + + const folderSlots = parseSearchFolderSlots(input); + if (folderSlots) { + return folderSlots; + } + + const wildcard = input.match( + /what(?:'s|\s+is|\s+did\s+i\s+save)\s+in\s+(?:my\s+)?(?:the\s+)?(?[\w\s-]+?)\s+(?:bookmark\s+folder|folder|hub|bookmarks?)\b/i + ); + const wildcardFolder = wildcard?.groups?.folder; + if (wildcardFolder) { + return { query: "*", folder: cleanCaptured(wildcardFolder) }; + } + + const queryMatch = + input.match( + /(?:search|find|look\s*up)\s+(?:for\s+)?(?:(?:in|inside|within|from)\s+(?:my\s+)?(?:history|bookmarks?|memory|tabs?)\s+)?"?(?.+?)"?\s*$/i + ) || + input.match( + /have\s+i\s+(?:visited|been\s+to|seen|saved|bookmarked)\s+(?:any\s+)?"?(?.+?)"?\s*$/i + ) || + input.match( + /(?:do\s+i\s+have)\s+(?:any(?:thing)?\s+(?:about|on|related\s+to)\s+)?"?(?.+?)"?\s*(?:saved|bookmarked|in\s+my)/i + ); + const query = cleanCaptured(queryMatch?.groups?.query || ""); + if (!query) { + return null; + } + return { query }; +} diff --git a/browser/base/content/assistant/build/src/utils/knownSites.ts b/browser/base/content/assistant/build/src/utils/knownSites.ts new file mode 100644 index 0000000000000..55f3177de9c5b --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/knownSites.ts @@ -0,0 +1,116 @@ +/** + * Known site names for routing: regex fragment for looksLikeNewActionCommand + * and URL map for "open X in a new tab" style commands. + */ + +const SITE_NAMES = [ + "youtube", + "google", + "gmail", + "github", + "twitter", + "instagram", + "facebook", + "reddit", + "netflix", + "spotify", + "amazon", + "wikipedia", + "slack", + "notion", + "linear", + "figma", + "jira", + "vercel", + "supabase", + "openai", + "anthropic", + "claude", + "chatgpt", + "linkedin", + "whatsapp", + "discord", + "twitch", + "tiktok", + "pinterest", + "dropbox", + "zoom", + "meet", + "calendar", + "drive", + "docs", + "sheets", + "maps", +] as const; + +export const KNOWN_SITE_NAMES_PATTERN = SITE_NAMES.join("|"); + +export const KNOWN_SITES_HINT_RE = new RegExp( + `\\b(?:${KNOWN_SITE_NAMES_PATTERN})\\b`, + "i" +); + +const DEFAULT_URLS: Record = { + youtube: "https://www.youtube.com", + google: "https://www.google.com", + gmail: "https://mail.google.com", + github: "https://github.com", + twitter: "https://twitter.com", + instagram: "https://www.instagram.com", + facebook: "https://www.facebook.com", + reddit: "https://www.reddit.com", + netflix: "https://www.netflix.com", + spotify: "https://open.spotify.com", + amazon: "https://www.amazon.com", + wikipedia: "https://www.wikipedia.org", + slack: "https://slack.com", + notion: "https://www.notion.so", + linear: "https://linear.app", + figma: "https://www.figma.com", + jira: "https://www.atlassian.com/software/jira", + vercel: "https://vercel.com", + supabase: "https://supabase.com", + openai: "https://chat.openai.com", + anthropic: "https://www.anthropic.com", + claude: "https://claude.ai", + chatgpt: "https://chatgpt.com", + linkedin: "https://www.linkedin.com", + whatsapp: "https://web.whatsapp.com", + discord: "https://discord.com", + twitch: "https://www.twitch.tv", + tiktok: "https://www.tiktok.com", + pinterest: "https://www.pinterest.com", + dropbox: "https://www.dropbox.com", + zoom: "https://zoom.us", + meet: "https://meet.google.com", + calendar: "https://calendar.google.com", + drive: "https://drive.google.com", + docs: "https://docs.google.com", + sheets: "https://sheets.google.com", + maps: "https://maps.google.com", +}; + +const TYPO_ALIASES: Record = { + youtub: "youtube", +}; + +const LOOKUP: ReadonlyMap = new Map([ + ...(Object.entries(DEFAULT_URLS) as [string, string][]), + ...Object.entries(TYPO_ALIASES).map( + ([typo, canon]): [string, string] => [ + typo, + DEFAULT_URLS[canon] ?? `https://www.${canon}.com`, + ] + ), +]); + +export function resolveKnownSiteToUrl(raw: string): string | null { + const key = String(raw || "") + .trim() + .toLowerCase() + .replace(/^["']|["']$/g, ""); + if (!key) { + return null; + } + return LOOKUP.get(key) ?? null; +} diff --git a/browser/base/content/assistant/build/src/utils/localMemoryUtils.ts b/browser/base/content/assistant/build/src/utils/localMemoryUtils.ts new file mode 100644 index 0000000000000..2dcd584f4e129 --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/localMemoryUtils.ts @@ -0,0 +1,67 @@ +/** Helpers for localMemory.ts: dedupe key computation, source/folder extraction, and type detection for memory documents. */ +export type MemoryMetadata = { + type?: string; + title?: string; + description?: string; + url?: string; + context?: string; + folderName?: string; + hubName?: string; + hub?: string; + bookmarkGuid?: string; + parentGuid?: string; + timestamp?: number; + [key: string]: unknown; +}; + +export type MemoryLikeDoc = { + text?: string; + url?: string; + metadata?: MemoryMetadata; + dedupeKey?: string; + timestamp?: number; +}; + +const BOOKMARK_FOLDER_TYPES = new Set(["hub_item", "bookmark_folder_item"]); + +function sanitizeKeyPart(value: string): string { + return value.replace(/\|/g, "%7C"); +} + +function normalizeTextForKey(text: string): string { + return text.toLowerCase().replace(/\s+/g, " ").trim().slice(0, 256); +} + +export function normalizeMemoryName(value: string): string { + return (value || "").trim().toLowerCase(); +} + +export function isBookmarkFolderType(rawType: string): boolean { + return BOOKMARK_FOLDER_TYPES.has((rawType || "").toLowerCase()); +} + +export function getMemoryDocSource(doc: Pick): string { + const rawType = String(doc?.metadata?.type || "memory").toLowerCase(); + if (isBookmarkFolderType(rawType)) { + return "bookmark-folder"; + } + return rawType; +} + +export function getMemoryDocFolderName(doc: Pick): string { + return normalizeMemoryName( + String(doc?.metadata?.folderName || doc?.metadata?.hubName || "") + ); +} + +export function getMemoryDocUrl(doc: Pick): string { + return String(doc?.url || doc?.metadata?.url || "").trim(); +} + +export function computeMemoryDedupeKey(doc: MemoryLikeDoc): string { + const source = getMemoryDocSource(doc); + const folder = getMemoryDocFolderName(doc); + const url = getMemoryDocUrl(doc); + const contentKey = url || `text:${normalizeTextForKey(String(doc?.text || ""))}`; + return `${sanitizeKeyPart(source)}|${sanitizeKeyPart(folder)}|${sanitizeKeyPart(contentKey)}`; +} diff --git a/browser/base/content/assistant/build/src/utils/manifestListResolver.ts b/browser/base/content/assistant/build/src/utils/manifestListResolver.ts new file mode 100644 index 0000000000000..0939ae8b27520 --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/manifestListResolver.ts @@ -0,0 +1,290 @@ +/** + * List-family resolver — handles "list/show" commands deterministically. + * + * Parses target names from inputs like "list tabs in Research group", + * cross-references with the routing state snapshot to determine if + * the target is a tab group, bookmark folder, or ambiguous. + * + * Returns: list_tabs (with scope + name args), list_bookmark_folders, + * list_tab_groups, or null if no match. + * Called by decisionEngine.ts for list-family commands. + */ +import { normalizeRouteName } from "./intentParser.js"; +import { resolveManifestCommand } from "./manifestResolver.js"; +import type { DeterministicRouteDecision, RoutingStateSnapshot } from "./routerTypes.js"; +import { getBrowserWindow } from "../types/runtime.js"; + +const WINDOW_SCOPE_ALIASES = new Set([ + "window", + "current window", + "this window", + "open tabs", + "all open tabs", + "tabs", + "all tabs", + "my tabs", + "current tabs", + "active tabs", +]); + +function cleanTargetName(value: string): string { + return String(value || "") + .replace(/["']/g, "") + .replace(/^\s*(?:my|the)\s+/i, "") + .replace(/\s+(?:please|now)\s*$/i, "") + .trim(); +} + +function isListBookmarkFoldersCommand(input: string): boolean { + return /^(?:list|show)\s+(?:all\s+)?(?:my\s+)?(?:bookmark\s+)?(?:bookmarks?|folders?|hubs?)\s*$/i.test( + String(input || "").trim() + ); +} + +function isListTabGroupsCommand(input: string): boolean { + return /^(?:list|show)\s+(?:all\s+)?(?:my\s+)?(?:tab\s+)?groups?\s*$/i.test( + String(input || "").trim() + ); +} + +function parseListTabsTarget( + input: string +): { targetName?: string; explicitContainer?: "tab-group" | "bookmark-folder" } | null { + const command = String(input || "").trim(); + if (!/^(?:list|show)\b/i.test(command)) { + return null; + } + + if ( + /\btab\s*groups?\b/i.test(command) && + !/\btabs?\s+(?:in|from)\b/i.test(command) + ) { + return null; + } + + const tabsWithTarget = command.match(/\btabs?\s+(?:in|from)\s+(?.+)$/i); + if (tabsWithTarget?.groups?.target) { + const rawTarget = cleanTargetName(tabsWithTarget.groups.target); + if (!rawTarget) { + return {}; + } + const hasGroup = /\btab\s*group\b|\bgroup\b/i.test(rawTarget); + const hasFolder = /\bbookmark\s*folder\b|\bfolder\b|\bhub\b|\bbookmarks?\b/i.test( + rawTarget + ); + const explicitContainer = + hasGroup && !hasFolder + ? "tab-group" + : hasFolder && !hasGroup + ? "bookmark-folder" + : undefined; + const targetName = cleanTargetName( + rawTarget.replace( + /\b(?:tab\s*group|bookmark\s*folder|group|folder|hub|bookmarks?)\b/gi, + " " + ) + ); + if (!targetName) { + return explicitContainer ? { explicitContainer } : {}; + } + return { targetName, explicitContainer }; + } + + if (/^(?:list|show)\s+(?:all\s+)?(?:my\s+)?tabs?\b/i.test(command)) { + return {}; + } + + const containerNameMatch = command.match( + /^(?:list|show)\s+(?:tabs?\s+(?:in|from)\s+)?(?:my\s+|the\s+)?(?.+?)\s+(?tab\s*group|group|bookmark\s*folder|folder|hub|bookmarks?)(?:\s+tabs?)?\s*$/i + ); + if (containerNameMatch?.groups?.container) { + const targetName = cleanTargetName(containerNameMatch.groups.name || ""); + const container = normalizeRouteName(containerNameMatch.groups.container); + const explicitContainer = + container.includes("group") ? "tab-group" : "bookmark-folder"; + if (!targetName) { + return { explicitContainer }; + } + return { targetName, explicitContainer }; + } + + const namedListMatch = command.match( + /^(?:list|show)\s+(?:my\s+|the\s+)?(?[\w\s-]+)\s*$/i + ); + if (!namedListMatch?.groups?.name) { + return null; + } + + const targetName = cleanTargetName(namedListMatch.groups.name); + if (!targetName) { + return null; + } + if ( + /^(?:tabs?|tab\s*groups?|groups?|bookmark\s*folders?|folders?|hubs?|bookmarks?)$/i.test( + targetName + ) + ) { + return null; + } + + return { targetName }; +} + +function isBrowsingHistoryListIntent(raw: string): boolean { + return /\b(?:list|show)\s+(?:my\s+|the\s+)?(?:recent\s+)?browsing\s+history\b/i.test( + String(raw || "").trim() + ); +} + +export function resolveManifestListRoute( + input: string, + snapshot: RoutingStateSnapshot +): DeterministicRouteDecision | null { + if (isBrowsingHistoryListIntent(input)) { + return { + type: "tool", + next: "search_history", + args: { query: "" }, + reason: "list-phrasing-for-browsing-history", + }; + } + const topWin = getBrowserWindow(); + const tabCount = topWin?.gBrowser?.tabs ? Array.from(topWin.gBrowser.tabs).length : 0; + const candidate = resolveManifestCommand(input, { + snapshot, + hasOpenTabs: tabCount > 0, + hasPendingConfirmation: false, + }); + if (!candidate || candidate.definition.family !== "list") { + return null; + } + + if ( + candidate.definition.id === "list.bookmark.folders" || + isListBookmarkFoldersCommand(input) + ) { + return { + type: "tool", + next: "list_bookmark_folders", + args: {}, + reason: "list-manifest-bookmark-folders", + }; + } + + if (candidate.definition.id === "list.tab.groups" || isListTabGroupsCommand(input)) { + return { + type: "tool", + next: "list_tab_groups", + args: {}, + reason: "list-manifest-tab-groups", + }; + } + + const parsed = parseListTabsTarget(input); + if (!parsed) { + if (candidate.definition.id === "list.window.tabs") { + return { + type: "tool", + next: "list_tabs", + args: {}, + reason: "list-manifest-open-window", + }; + } + return null; + } + + const targetName = parsed.targetName; + const explicitContainer = parsed.explicitContainer; + + if (explicitContainer === "tab-group") { + if (!targetName) { + return { + type: "chat", + actionable: true, + reason: "list-manifest-missing-group-name", + message: "Which tab group should I list tabs from?", + }; + } + return { + type: "tool", + next: "list_tabs", + args: { scope: "tab-group", name: targetName }, + reason: "list-manifest-explicit-group", + }; + } + + if (explicitContainer === "bookmark-folder") { + if (!targetName) { + return { + type: "chat", + actionable: true, + reason: "list-manifest-missing-folder-name", + message: "Which bookmark folder should I list tabs from?", + }; + } + return { + type: "tool", + next: "list_tabs", + args: { scope: "bookmark-folder", name: targetName }, + reason: "list-manifest-explicit-folder", + }; + } + + if (!targetName) { + return { + type: "tool", + next: "list_tabs", + args: {}, + reason: "list-manifest-open-window", + }; + } + + const normalizedTarget = normalizeRouteName(targetName); + if (WINDOW_SCOPE_ALIASES.has(normalizedTarget)) { + return { + type: "tool", + next: "list_tabs", + args: {}, + reason: "list-manifest-window-alias", + }; + } + + const targetInGroups = snapshot.groupNames.has(normalizedTarget); + const targetInFolders = snapshot.folderNames.has(normalizedTarget); + + if (targetInGroups && !targetInFolders) { + return { + type: "tool", + next: "list_tabs", + args: { scope: "tab-group", name: targetName }, + reason: "list-manifest-resolved-group", + }; + } + + if (targetInFolders && !targetInGroups) { + return { + type: "tool", + next: "list_tabs", + args: { scope: "bookmark-folder", name: targetName }, + reason: "list-manifest-resolved-folder", + }; + } + + if (targetInFolders && targetInGroups) { + return { + type: "chat", + actionable: true, + reason: "list-manifest-ambiguous-target", + message: + `I found both a tab group and a bookmark folder named "${targetName}". ` + + `Say "list tabs in tab group ${targetName}" or "list tabs in bookmark folder ${targetName}".`, + }; + } + + return { + type: "tool", + next: "list_tabs", + args: { name: targetName }, + reason: "list-manifest-runtime-resolve-target", + }; +} diff --git a/browser/base/content/assistant/build/src/utils/manifestMutationResolver.ts b/browser/base/content/assistant/build/src/utils/manifestMutationResolver.ts new file mode 100644 index 0000000000000..e52331554b61b --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/manifestMutationResolver.ts @@ -0,0 +1,217 @@ +/** + * Mutation-family resolver — handles add/delete/rename/close commands. + * + * Three resolution strategies tried in order: + * 1. Explicit mutation regex (mutationExplicitResolver.ts) + * 2. Container-add parsing: "add X to Y" with tab group/folder disambiguation + * 3. Close/delete target parsing: "delete Research" with entity resolution + * + * Cross-references target names with the routing state snapshot to + * detect ambiguity (same name in both groups and folders). + * Called by decisionEngine.ts for mutation-family commands. + */ +import { + normalizeRouteName, + parseCloseDeleteTargetIntent, + parseContainerAddIntent, +} from "./intentParser.js"; +import { resolveTargetName } from "./entityResolver.js"; +import { resolveExplicitMutationRoute } from "./mutationExplicitResolver.js"; +import type { + DeterministicRouteDecision, + PendingAmbiguityPayload, + RouteArgs, + RoutingStateSnapshot, +} from "./routerTypes.js"; + +function buildAmbiguityPayload( + name: string, + opts: { + kind?: "container_target" | "close_delete_target"; + query?: string; + all?: boolean; + originalText: string; + choices?: Array<"tab" | "tab-group" | "bookmark-folder">; + tabIndex?: number; + verb?: string; + } +): PendingAmbiguityPayload { + return { + kind: opts.kind || "container_target", + name, + query: opts.query, + all: opts.all, + choices: opts.choices, + tabIndex: opts.tabIndex, + verb: opts.verb, + originalText: opts.originalText, + }; +} + +function resolveContainerAddRoute( + input: string, + snapshot: RoutingStateSnapshot +): DeterministicRouteDecision | null { + const parsed = parseContainerAddIntent(input); + if (!parsed || !parsed.targetName) { + return null; + } + + const targetName = parsed.targetName; + const targetNorm = normalizeRouteName(targetName); + const targetInFolders = snapshot.folderNames.has(targetNorm); + const targetInGroups = snapshot.groupNames.has(targetNorm); + + const addArgs: RouteArgs = { name: targetName }; + if (parsed.all) { + addArgs.all = true; + } else if (parsed.query && !parsed.current) { + addArgs.query = parsed.query; + } + + if (parsed.explicitContainer === "tab-group") { + return { + type: "tool", + next: "add_tab_to_group", + args: addArgs, + reason: "container-add-explicit-group", + }; + } + + if (parsed.explicitContainer === "bookmark-folder") { + return { + type: "tool", + next: "add_tab_to_bookmark_folder", + args: addArgs, + reason: "container-add-explicit-folder", + }; + } + + if (targetInFolders && targetInGroups) { + return { + type: "tool", + next: "resolve_ambiguity", + args: {}, + reason: "container-add-name-collision", + pendingAmbiguity: buildAmbiguityPayload(targetName, { + query: parsed.query, + all: parsed.all, + originalText: parsed.rawText, + }), + }; + } + + if (!targetInFolders && targetInGroups) { + return { + type: "tool", + next: "resolve_ambiguity", + args: {}, + reason: "container-add-only-group-exists", + pendingAmbiguity: buildAmbiguityPayload(targetName, { + query: parsed.query, + all: parsed.all, + originalText: parsed.rawText, + }), + }; + } + + return { + type: "tool", + next: "add_tab_to_bookmark_folder", + args: addArgs, + reason: targetInFolders + ? "container-add-folder-exists" + : "container-add-default-folder", + }; +} + +function resolveCloseDeleteRoute( + input: string, + snapshot: RoutingStateSnapshot +): DeterministicRouteDecision | null { + const parsed = parseCloseDeleteTargetIntent(input); + if (!parsed?.targetName || !parsed.verb) { + return null; + } + + const normalized = parsed.normalizedText; + if ( + /\b(?:tab\s+group|bookmark\s+folder|split\s*view|from\s+(?:my\s+)?(?:the\s+)?(?:bookmark\s+)?folder|from\s+(?:its\s+)?(?:tab\s+)?group|current\s+tab|tab\s+\d+)\b/i.test( + normalized + ) + ) { + return null; + } + + const resolution = resolveTargetName(parsed.targetName, snapshot); + const hasTab = resolution.tabMatches.length > 0; + const hasGroup = resolution.targetInGroups; + const hasFolder = resolution.targetInFolders; + const matches = [hasTab, hasGroup, hasFolder].filter(Boolean).length; + + if (matches === 0) { + return null; + } + + if (matches > 1) { + const choices: Array<"tab" | "tab-group" | "bookmark-folder"> = []; + if (hasTab) { + choices.push("tab"); + } + if (hasGroup) { + choices.push("tab-group"); + } + if (hasFolder) { + choices.push("bookmark-folder"); + } + return { + type: "tool", + next: "resolve_ambiguity", + args: {}, + reason: "close-delete-ambiguous-target", + pendingAmbiguity: buildAmbiguityPayload(parsed.targetName, { + kind: "close_delete_target", + choices, + tabIndex: resolution.tabMatches[0], + verb: parsed.verb, + originalText: parsed.rawText, + }), + }; + } + + if (hasGroup) { + return { + type: "tool", + next: "delete_tab_group", + args: { name: parsed.targetName }, + reason: "close-delete-resolved-group", + }; + } + + if (hasFolder) { + return { + type: "tool", + next: "delete_bookmark_folder", + args: { name: parsed.targetName }, + reason: "close-delete-resolved-folder", + }; + } + + return { + type: "tool", + next: "close_tab", + args: { index: resolution.tabMatches[0] }, + reason: "close-delete-resolved-tab", + }; +} + +export function resolveManifestMutationRoute( + input: string, + snapshot: RoutingStateSnapshot +): DeterministicRouteDecision | null { + return ( + resolveExplicitMutationRoute(input) || + resolveContainerAddRoute(input, snapshot) || + resolveCloseDeleteRoute(input, snapshot) + ); +} diff --git a/browser/base/content/assistant/build/src/utils/manifestResolver.ts b/browser/base/content/assistant/build/src/utils/manifestResolver.ts new file mode 100644 index 0000000000000..bc9ba519cbb42 --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/manifestResolver.ts @@ -0,0 +1,88 @@ +/** + * Manifest resolver — finds the best matching manifest entry. + * + * Scores user input against all phrases in COMMAND_MANIFEST using + * normalized string matching (exact=1.0, prefix=0.9, contains=0.75). + * Returns the highest-scoring ManifestResolution or null. + * Used by manifestList/Search/MutationResolver to identify the + * command family and candidate command name. + */ +import { normalizeRouteName } from "./intentParser.js"; +import { COMMAND_MANIFEST } from "./commandManifest.js"; +import type { + ManifestCommandDefinition, + ManifestConditionContext, + ManifestResolution, +} from "./manifestTypes.js"; + +function phraseMatchScore(input: string, phrase: string): number { + const source = normalizeRouteName(input); + const target = normalizeRouteName(phrase); + if (!source || !target) { + return 0; + } + if (source === target) { + return 1; + } + if (source.startsWith(target)) { + return 0.9; + } + if (source.includes(target)) { + return 0.75; + } + return 0; +} + +function checkCondition( + definition: ManifestCommandDefinition, + context: ManifestConditionContext +): boolean { + if (!definition.condition) { + return true; + } + return definition.condition(context); +} + +export function resolveManifestCandidates( + input: string, + context: ManifestConditionContext, + manifest: readonly ManifestCommandDefinition[] = COMMAND_MANIFEST +): ManifestResolution[] { + const normalizedInput = normalizeRouteName(input); + if (!normalizedInput) { + return []; + } + + const candidates: ManifestResolution[] = []; + for (const definition of manifest) { + if (!checkCondition(definition, context)) { + continue; + } + let bestScore = 0; + for (const phrase of definition.phrases) { + const score = phraseMatchScore(normalizedInput, phrase); + if (score > bestScore) { + bestScore = score; + } + } + if (bestScore <= 0) { + continue; + } + candidates.push({ + definition, + args: {}, + score: bestScore + (definition.priority || 0) * 0.01, + }); + } + + return candidates.sort((a, b) => b.score - a.score); +} + +export function resolveManifestCommand( + input: string, + context: ManifestConditionContext, + manifest: readonly ManifestCommandDefinition[] = COMMAND_MANIFEST +): ManifestResolution | null { + const candidates = resolveManifestCandidates(input, context, manifest); + return candidates[0] || null; +} diff --git a/browser/base/content/assistant/build/src/utils/manifestSearchResolver.ts b/browser/base/content/assistant/build/src/utils/manifestSearchResolver.ts new file mode 100644 index 0000000000000..c1f32ded2b4a7 --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/manifestSearchResolver.ts @@ -0,0 +1,217 @@ +/** + * Search-family resolver — handles "search/find" commands deterministically. + * + * Extracts query and optional folder scope from inputs like + * "search python in my Docs folder" or "find amazon in Deals". + * Validates folder names against the routing state snapshot. + * + * Returns: search_memory (with query + folder args), search_history, + * or null if no match. Called by decisionEngine.ts for search-family. + */ +import { normalizeRouteName, parseSearchMemoryIntent } from "./intentParser.js"; +import { resolveManifestCommand } from "./manifestResolver.js"; +import type { DeterministicRouteDecision, RouteArgs, RoutingStateSnapshot } from "./routerTypes.js"; +import { getBrowserWindow } from "../types/runtime.js"; + +function cleanSearchTarget(value: string): string { + const cleaned = String(value || "") + .replace(/["']/g, "") + .replace(/^\s*(?:my|the)\s+/i, "") + .trim(); + return cleaned + .replace(/\s+(?:bookmark\s+folder|folder|hub|bookmarks?)\s*$/i, "") + .trim(); +} + +function cleanSearchQuery(value: string): string { + return String(value || "").replace(/["']/g, "").trim(); +} + +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +function parseFolderSearchMissingQuery( + input: string, + snapshot: RoutingStateSnapshot +): string | null { + const match = String(input || "").trim().match( + /^(?:search|find|look\s*up)\s+(?:(?:in|inside|within|from)\s+)?(?:my\s+|the\s+)?(?.+?)\s+(?:bookmark\s+folder|folder|hub|bookmarks?)\s*$/i + ); + if (!match?.groups?.target) { + return null; + } + const targetName = cleanSearchTarget(match.groups.target); + if (!targetName) { + return null; + } + const targetNorm = normalizeRouteName(targetName); + if (!targetNorm || !snapshot.folderNames.has(targetNorm)) { + return null; + } + return targetName; +} + +function parseImplicitFolderPrefixSearch( + input: string, + snapshot: RoutingStateSnapshot +): { query: string; folder: string } | null { + const body = String(input || "") + .trim() + .replace(/^(?:search|find|look\s*up)\s+/i, "") + .replace(/^\s*(?:my|the)\s+/i, "") + .trim(); + if (!body) { + return null; + } + if (/\bfor\b/i.test(body) || /\b(?:in|inside|within|from)\b/i.test(body)) { + return null; + } + + const folderNames = Array.from(snapshot.folderNames).sort( + (a, b) => b.length - a.length + ); + for (const folderNorm of folderNames) { + const pattern = new RegExp( + `^(?${escapeRegExp( + folderNorm + )})(?:\\s+(?:bookmark\\s+folder|folder|hub|bookmarks?))?\\s+(?.+)$`, + "i" + ); + const match = body.match(pattern); + if (!match?.groups) { + continue; + } + const folder = cleanSearchTarget(match.groups.folder); + const query = cleanSearchQuery(match.groups.query); + if (!folder || !query) { + continue; + } + return { query, folder }; + } + return null; +} + +function parseImplicitFolderSearch( + input: string, + snapshot: RoutingStateSnapshot +): { query: string; folder: string } | null { + const command = String(input || "").trim(); + const queryInTarget = command.match( + /^(?:search|find|look\s*up)\s+(?:for\s+)?(?.+?)\s+(?:in|inside|within|from)\s+(?:my\s+|the\s+)?(?.+?)\s*$/i + ); + if (queryInTarget?.groups) { + const targetName = cleanSearchTarget(queryInTarget.groups.target); + const query = cleanSearchQuery(queryInTarget.groups.query); + if (targetName && query) { + const targetNorm = normalizeRouteName(targetName); + if (targetNorm && snapshot.folderNames.has(targetNorm)) { + return { query, folder: targetName }; + } + } + } + + const queryWithTrailingFolder = command.match( + /^(?:search|find|look\s*up)\s+(?:my\s+|the\s+)?(?[\w\s-]+?)\s+for\s+(?.+?)\s+(?:bookmark\s+folder|folder|hub|bookmarks?)\s*$/i + ); + if (queryWithTrailingFolder?.groups) { + const targetName = cleanSearchTarget(queryWithTrailingFolder.groups.target); + const query = cleanSearchQuery(queryWithTrailingFolder.groups.query); + if (targetName && query) { + const targetNorm = normalizeRouteName(targetName); + if (targetNorm && snapshot.folderNames.has(targetNorm)) { + return { query, folder: targetName }; + } + } + } + + const match = command.match( + /^(?:search|find|look\s*up)\s+(?:my\s+|the\s+)?(?[\w\s-]+?)\s+for\s+(?.+?)\s*$/i + ); + if (!match?.groups) { + return null; + } + const targetName = cleanSearchTarget(match.groups.target); + const query = cleanSearchQuery(match.groups.query); + if (!targetName || !query) { + return null; + } + const targetNorm = normalizeRouteName(targetName); + if (!targetNorm) { + return null; + } + if (!snapshot.folderNames.has(targetNorm)) { + return null; + } + return { query, folder: targetName }; +} + +export function resolveManifestSearchRoute( + input: string, + snapshot: RoutingStateSnapshot +): DeterministicRouteDecision | null { + const topWin = getBrowserWindow(); + const tabCount = topWin?.gBrowser?.tabs ? Array.from(topWin.gBrowser.tabs).length : 0; + const candidate = resolveManifestCommand(input, { + snapshot, + hasOpenTabs: tabCount > 0, + hasPendingConfirmation: false, + }); + if (!candidate || candidate.definition.family !== "search") { + return null; + } + + // If the manifest resolved to search_history, route directly + if (candidate.definition.commandName === "search_history") { + const parsed = parseSearchMemoryIntent(input); + const query = parsed?.query || input.replace(/^(?:find|search|what|did\s+i)\s+/i, "").trim(); + return { + type: "tool", + next: "search_history", + args: { query }, + reason: "search-manifest-history", + }; + } + + const missingFolderQuery = parseFolderSearchMissingQuery(input, snapshot); + if (missingFolderQuery) { + return { + type: "chat", + reason: "search-manifest-folder-missing-query", + actionable: true, + message: `What should I search for in bookmark folder "${missingFolderQuery}"?`, + }; + } + + const parsed = parseSearchMemoryIntent(input); + const implicitFolder = + parseImplicitFolderSearch(input, snapshot) || + parseImplicitFolderPrefixSearch(input, snapshot); + const resolved = implicitFolder || parsed; + if (!resolved) { + return null; + } + + const args: RouteArgs = { query: resolved.query }; + if (resolved.folder) { + args.folder = resolved.folder; + } + if ("source" in resolved && resolved.source) { + args.source = resolved.source; + } + + const reason = implicitFolder + ? "search-manifest-implicit-folder" + : resolved.folder + ? "search-manifest-folder" + : "source" in resolved && resolved.source === "bookmark-folder" + ? "search-manifest-bookmark-folder-scope" + : "search-manifest-memory"; + + return { + type: "tool", + next: "search_memory", + args, + reason, + }; +} diff --git a/browser/base/content/assistant/build/src/utils/manifestTypes.ts b/browser/base/content/assistant/build/src/utils/manifestTypes.ts new file mode 100644 index 0000000000000..3d350ec860019 --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/manifestTypes.ts @@ -0,0 +1,46 @@ +/** Type definitions for the command manifest: slot definitions, condition contexts, command definitions, and resolution results. */ +import type { IntentFamily, RouteArgs, RoutingStateSnapshot } from "./routerTypes.js"; + +export type ManifestSlotSource = + | "rest" + | "quoted_or_rest" + | "number" + | "url"; + +export type ManifestSlotType = + | "string" + | "target_name" + | "tab_index" + | "url" + | "scope"; + +export type ManifestSlotDefinition = { + name: string; + type: ManifestSlotType; + optional?: boolean; + defaultValue?: string | number | boolean; + source?: ManifestSlotSource; + aliases?: readonly string[]; +}; + +export type ManifestConditionContext = { + snapshot: RoutingStateSnapshot; + hasOpenTabs: boolean; + hasPendingConfirmation: boolean; +}; + +export type ManifestCommandDefinition = { + id: string; + family: IntentFamily; + commandName: string; + phrases: readonly string[]; + slots?: readonly ManifestSlotDefinition[]; + priority?: number; + condition?: (context: ManifestConditionContext) => boolean; +}; + +export type ManifestResolution = { + definition: ManifestCommandDefinition; + args: RouteArgs; + score: number; +}; diff --git a/browser/base/content/assistant/build/src/utils/mutationExplicitResolver.ts b/browser/base/content/assistant/build/src/utils/mutationExplicitResolver.ts new file mode 100644 index 0000000000000..2cb47e04a60cb --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/mutationExplicitResolver.ts @@ -0,0 +1,333 @@ +/** + * Mutation explicit resolver — regex rules for destructive/creative commands. + * + * Array of regex patterns that extract args from mutation commands: + * split tabs, close tab, create/delete/rename bookmark folders and + * tab groups, move tab to window, remove split view, etc. + * + * Each rule produces { next, args } directly from named capture groups. + * Called by manifestMutationResolver.ts. + */ +import type { DeterministicRouteDecision, RouteArgs } from "./routerTypes.js"; + +type MutationRoute = { + next: string; + reason: string; + resolve: (input: string) => RouteArgs | null; +}; + +function toolDecision( + next: string, + reason: string, + args: RouteArgs +): DeterministicRouteDecision { + return { type: "tool", next, args, reason }; +} + +function firstMatch( + input: string, + patterns: RegExp[] +): RegExpMatchArray | null { + for (const pattern of patterns) { + const match = input.match(pattern); + if (match) { + return match; + } + } + return null; +} + +function numberArg(value: string | undefined): number | undefined { + if (!value) { + return undefined; + } + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : undefined; +} + +function extractIndices(input: string): number[] { + return (input.match(/\d+/g) || []) + .map(value => Number(value)) + .filter(value => Number.isFinite(value) && value > 0); +} + +const MUTATION_EXPLICIT_ROUTES: MutationRoute[] = [ + { + next: "split_tabs", + reason: "mutation-explicit-split-tabs", + resolve: input => { + const match = input.match(/split\s+tabs?\s+(?[\d,\sand]+)/i); + const indicesRaw = match?.groups?.indices; + if (!indicesRaw) { + return null; + } + const indices = extractIndices(indicesRaw); + return indices.length >= 2 ? { indices } : null; + }, + }, + { + next: "add_split_view", + reason: "mutation-explicit-add-split-view-two-tabs", + resolve: input => { + const match = + input.match( + /(?:split|splitview|add)\s+(?:tabs?\s+)?(?
    \d+)\s+(?:and|,|with)\s+(?:tab\s+)?(?\d+)/i + ) || + input.match( + /(?:add\s+)?tabs?\s+(?\d+)\s+(?:and|,|with)\s+(?:tab\s+)?(?\d+)\s+(?:to\s+)?(?:split\s*view|splitview)/i + ); + const a = numberArg(match?.groups?.a); + const b = numberArg(match?.groups?.b); + return a != null && b != null ? { indices: [a, b] } : null; + }, + }, + { + next: "remove_split_view", + reason: "mutation-explicit-remove-split-view", + resolve: input => + /(?:remove|disable|close)\s+split\s*view|unsplit\s+(?:tabs?|view)?/i.test( + input + ) + ? {} + : null, + }, + { + next: "add_split_view", + reason: "mutation-explicit-add-split-view-colloquial", + resolve: input => { + const lower = input.toLowerCase(); + if (/\b(remove|disable|close|unsplit|don't|do not)\b/.test(lower)) { + return null; + } + if ( + /\b(?:two|2)\s+tabs?\s+(?:side\s*by\s*side|at\s+once)\b/i.test(input) || + /\bshow\s+(?:two|2)\s+tabs?\s+(?:side\s*by\s*side|at\s+once)\b/i.test( + input + ) || + /\bopen\s+.{0,40}\bsplit\s*view\b/i.test(input) || + /\bsplitview\b/i.test(input) + ) { + return {}; + } + return null; + }, + }, + { + next: "add_split_view", + reason: "mutation-explicit-add-split-view", + resolve: input => { + if ( + !/(?:add|create|enable)\s+split\s*view|split\s+(?:this\s+)?(?:tab|view)/i.test( + input + ) + ) { + return null; + } + const withTabMatch = input.match( + /(?:with|and)\s+(?:tab\s+)?(?\d+)/i + ); + const withIndex = numberArg(withTabMatch?.groups?.index); + if (withIndex != null) { + return { withIndex }; + } + const withQueryMatch = input.match( + /(?:with|and)\s+(?:the\s+)?"?(?[^"\d][^"]+?)"?\s*(?:tab)?$/i + ); + const withQuery = withQueryMatch?.groups?.query?.trim(); + return withQuery ? { withQuery } : {}; + }, + }, + { + next: "move_tab_to_new_window", + reason: "mutation-explicit-move-tab-new-window", + resolve: input => { + const match = input.match( + /(?:move)\s+(?:the\s+)?(?:current\s+)?tab(?:\s+(?\d+))?\s+to\s+(?:a\s+)?new\s+window/i + ); + if (!match) { + return null; + } + const index = numberArg(match.groups?.index); + return index != null ? { index } : {}; + }, + }, + { + next: "close_tab", + reason: "mutation-explicit-close-tab", + resolve: input => { + const match = input.match( + /close\s+(?:the\s+)?(?:current\s+)?tab(?:\s+(?\d+))?/i + ); + if (!match) { + return null; + } + const index = numberArg(match.groups?.index); + return index != null ? { index } : {}; + }, + }, + { + next: "remove_tab_from_group", + reason: "mutation-explicit-remove-tab-from-group", + resolve: input => { + const match = input.match( + /(?:remove|ungroup)\s+(?:the\s+)?(?:this\s+|current\s+|active\s+)?tab(?:\s+(?\d+))?\s+from\s+(?:its\s+)?(?:tab\s+)?group/i + ); + if (!match) { + return null; + } + const index = numberArg(match.groups?.index); + return index != null ? { index } : {}; + }, + }, + { + next: "remove_tab_from_bookmark_folder", + reason: "mutation-explicit-remove-tab-from-folder", + resolve: input => { + const match = input.match( + /(?:remove|delete)\s+(?:this\s+)?(?:tab\s+)?from\s+(?:my\s+)?(?:the\s+)?(?:bookmark\s+)?folder\s+"?(?[\w\s]+?)"?\s*$/i + ); + const name = match?.groups?.name?.trim(); + return name ? { name } : null; + }, + }, + { + next: "create_bookmark_folder", + reason: "mutation-explicit-create-folder-with-current", + resolve: input => { + const match = input.match( + /(?:create|make|new)\s+(?:a\s+)?(?:new\s+)?(?:bookmark\s+)?folder\s+(?:called\s+|named\s+)?"?(?[\w\s]+?)"?\s+and\s+(?:add|save|include|put)\s+(?:the\s+)?(?:current|this|active)\s+tab/i + ); + const name = match?.groups?.name?.trim(); + return name ? { name, include: "current" } : null; + }, + }, + { + next: "create_bookmark_folder", + reason: "mutation-explicit-create-folder-with-all", + resolve: input => { + const match = input.match( + /(?:create|make|new)\s+(?:a\s+)?(?:new\s+)?(?:bookmark\s+)?folder\s+(?:called\s+|named\s+)?"?(?[\w\s]+?)"?\s+and\s+(?:add|save|include|put)\s+(?:all)\s+tabs/i + ); + const name = match?.groups?.name?.trim(); + return name ? { name, include: "all" } : null; + }, + }, + { + next: "create_bookmark_folder", + reason: "mutation-explicit-create-folder", + resolve: input => { + const match = input.match( + /(?:create|make|new)\s+(?:a\s+)?(?:new\s+)?(?:bookmark\s+)?folder\s+(?:called\s+|named\s+)?"?(?[\w\s]+?)"?\s*$/i + ); + const name = match?.groups?.name?.trim(); + return name ? { name } : null; + }, + }, + { + next: "delete_bookmark_folder", + reason: "mutation-explicit-delete-folder", + resolve: input => { + const match = firstMatch(input, [ + /(?:delete|remove)\s+(?:the\s+)?(?:bookmark\s+)?folder\s+"?(?[\w\s]+?)"?\s*$/i, + /(?:delete|remove)\s+(?:the\s+)?"?(?[\w\s]+?)"?\s+(?:bookmark\s+)?folder/i, + ]); + const name = match?.groups?.name?.trim(); + return name ? { name } : null; + }, + }, + { + next: "rename_bookmark_folder", + reason: "mutation-explicit-rename-folder", + resolve: input => { + const match = input.match( + /rename\s+(?:the\s+)?(?:bookmark\s+)?folder\s+"?(?[\w\s]+?)"?\s+(?:to|as)\s+"?(?[\w\s]+?)"?\s*$/i + ); + const from = match?.groups?.from?.trim(); + const to = match?.groups?.to?.trim(); + return from && to ? { from, to } : null; + }, + }, + { + next: "delete_tab_group", + reason: "mutation-explicit-delete-group", + resolve: input => { + const match = firstMatch(input, [ + /(?:delete|remove)\s+(?:tab\s+)?group\s+"?(?[^"\n]+?)"?\s*$/i, + /(?:delete|remove)\s+(?:the\s+)?"?(?[^"\n]+?)"?\s+(?:tab\s+)?group/i, + ]); + const name = match?.groups?.name?.trim(); + return name ? { name } : null; + }, + }, + { + next: "create_tab_group", + reason: "mutation-explicit-create-group", + resolve: input => { + const match = input.match( + /(?:create|make|new)\s+(?:a\s+)?(?:new\s+)?(?:tab\s+)?(?:group|gorup)\s+(?:called\s+|named\s+)?"?(?.+)$/i + ); + if (!match?.groups?.name) { + return null; + } + + let name = match.groups.name.trim(); + let openUrl: string | undefined; + + const openInIt = name.match( + /\s+and\s+(?:open|go\s+to)\s+(.+?)\s+(?:in\s+it|in\s+the\s+group|in\s+that\s+group|there)$/i + ); + if (openInIt?.[1]) { + openUrl = openInIt[1].trim(); + name = name.replace(/\s+and\s+(?:open|go\s+to)\s+.+$/i, "").trim(); + } + + name = name.replace(/\s+and\s+(?:add|open|put)\s+.+$/i, "").trim(); + name = name + .replace(/\s+(?:with|using|from|for)\s+.*$/i, "") + .replace(/["']/g, "") + .trim(); + if (!name) { + return null; + } + + const args: RouteArgs = { name }; + if (openUrl) { + args.openUrl = openUrl; + } + const indicesMatch = input.match( + /(?:with\s+)?tabs?\s+([\d,\s]+(?:and\s+\d+)?)/i + ); + if (indicesMatch?.[1]) { + const indices = extractIndices(indicesMatch[1]); + if (indices.length > 0) { + args.indices = indices; + } + } + return args; + }, + }, + { + next: "rename_tab_group", + reason: "mutation-explicit-rename-group", + resolve: input => { + const match = input.match( + /rename\s+(?:tab\s+)?group\s+"?(?[\w\s]+?)"?\s+(?:to|as)\s+"?(?[\w\s]+?)"?\s*$/i + ); + const from = match?.groups?.from?.trim(); + const to = match?.groups?.to?.trim(); + return from && to ? { from, to } : null; + }, + }, +]; + +export function resolveExplicitMutationRoute( + input: string +): DeterministicRouteDecision | null { + for (const rule of MUTATION_EXPLICIT_ROUTES) { + const args = rule.resolve(input); + if (args) { + return toolDecision(rule.next, rule.reason, args); + } + } + return null; +} diff --git a/browser/base/content/assistant/build/src/utils/oasisCapabilitiesFaq.ts b/browser/base/content/assistant/build/src/utils/oasisCapabilitiesFaq.ts new file mode 100644 index 0000000000000..b7882c91d8074 --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/oasisCapabilitiesFaq.ts @@ -0,0 +1,43 @@ +const OASIS_CAPABILITIES_REPLY = `I'm Oasis AI, your assistant in this browser. Here's what I focus on: + +**Browser tasks (first and foremost)** +- **Tabs and navigation:** Open sites in new tabs, run web searches, and move around your windows. +- **Organization:** Create and manage tab groups, and work with your tabs in bulk when you ask. +- **Your data:** Search your browsing history and bookmarks. +- **The page you're reading:** Summarize, translate, or rework text on normal web pages you have open. (Built-in pages like the new tab page can't be summarized the same way—open a regular website first.) + +**General help** +- Answer questions, brainstorm, explain ideas in plain language, and help you phrase something clearly. + +I don't take the place of a coding debugger or deep technical support. If you want something done in the browser, say what you're trying to do and I'll walk you through it. + +What would you like to try first?`; + +export function getOasisCapabilitiesReply(userText: string): string | null { + const t = userText.trim().toLowerCase(); + if (t.length < 12 || t.length > 220) { + return null; + } + if (!/\bwhat\b/.test(t)) { + return null; + } + if (!t.includes("oasis") && !t.includes("assistant")) { + return null; + } + const asksScope = + /\bcan\b/.test(t) || + /\bdo\b/.test(t) || + /\bcapabilities\b/.test(t) || + /\bhelp (with|me)\b/.test(t); + if (!asksScope) { + return null; + } + if ( + /\bwhat can i\b/.test(t) && + !t.includes("you") && + !t.includes("assistant") + ) { + return null; + } + return OASIS_CAPABILITIES_REPLY; +} diff --git a/browser/base/content/assistant/build/src/utils/quotaUserMessage.ts b/browser/base/content/assistant/build/src/utils/quotaUserMessage.ts new file mode 100644 index 0000000000000..cc588515fd232 --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/quotaUserMessage.ts @@ -0,0 +1,21 @@ +export function formatQuotaExceededMessage(raw: string): string { + const s = String(raw || "") + .trim() + .toLowerCase(); + if (!s) { + return "You have reached your AI usage limit for this plan."; + } + if (s.includes("daily_limit") || s === "daily_limit_exceeded") { + return "You have reached your daily AI usage limit. Your allocation resets every day."; + } + if (s.includes("monthly_limit") || s === "monthly_limit_exceeded") { + return "You have reached your monthly AI usage limit. Your allocation resets at the start of your next billing cycle."; + } + if (s.includes("quota_exceeded") || s.includes("quota exceeded")) { + return "You have reached your AI usage limit for this plan."; + } + if (/^[a-z0-9_]+$/.test(String(raw || "").trim())) { + return "You have reached your AI usage limit for this plan."; + } + return String(raw || "").trim(); +} diff --git a/browser/base/content/assistant/build/src/utils/routerTypes.ts b/browser/base/content/assistant/build/src/utils/routerTypes.ts new file mode 100644 index 0000000000000..59f8177ba4b9e --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/routerTypes.ts @@ -0,0 +1,100 @@ +/** + * Type definitions for the deterministic routing system. + * + * Key types: + * - IntentFamily: list | search | mutation | other + * - ParsedIntent: structured result of intent parsing + * - DeterministicRouteDecision: tool, chat, or no_match result + * - RoutingStateSnapshot: current tab group + folder names + * - RoutingStateMutation: change event for the routing state cache + */ +export type ContainerType = "bookmark-folder" | "tab-group"; +export type RouteArgs = Record; +export type RoutingEntityType = "folder" | "group"; +export type IntentFamily = "list" | "search" | "mutation" | "other"; + +export type ParsedIntent = { + rawText: string; + normalizedText: string; + verb: string | null; + isActionLike: boolean; + explicitContainer: ContainerType | null; + targetName?: string; + query?: string; + url?: string; + index?: number; + indices?: number[]; + all?: boolean; + current?: boolean; + kind: + | "container_add" + | "close_delete_target" + | "search" + | "explicit" + | "unknown"; +}; + +export type RoutingStateSnapshot = { + folderNames: Set; + groupNames: Set; + stale: boolean; +}; + +export type RoutingStateMutation = + | { + kind: "upsert"; + entity: RoutingEntityType; + name: string; + } + | { + kind: "delete"; + entity: RoutingEntityType; + name: string; + } + | { + kind: "rename"; + entity: RoutingEntityType; + from: string; + to: string; + } + | { + kind: "dirty"; + reason: string; + }; + +export type ResolutionResult = { + targetInFolders: boolean; + targetInGroups: boolean; + tabMatches: number[]; +}; + +export type PendingAmbiguityPayload = { + kind?: "container_target" | "close_delete_target"; + name: string; + query?: string; + all?: boolean; + choices?: Array<"tab" | "tab-group" | "bookmark-folder">; + tabIndex?: number; + verb?: string; + originalText: string; +}; + +export type DeterministicRouteDecision = + | { + type: "tool"; + next: string; + args: RouteArgs; + reason: string; + pendingAmbiguity?: PendingAmbiguityPayload; + } + | { + type: "chat"; + message: string; + reason: string; + actionable: boolean; + } + | { + type: "no_match"; + actionable: boolean; + reason: string; + }; diff --git a/browser/base/content/assistant/build/src/utils/routingStateCache.ts b/browser/base/content/assistant/build/src/utils/routingStateCache.ts new file mode 100644 index 0000000000000..8978d5a9a4d70 --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/routingStateCache.ts @@ -0,0 +1,255 @@ +/** + * Routing state cache — live snapshot of tab groups and bookmark folders. + * + * Caches the normalized names of all tab groups and bookmark folders + * from the browser. The deterministic resolvers use this to verify + * that a target name like "Research" actually exists before routing. + * + * Listens for TabGroupCreate, TabGroupRemoved, and bookmark folder + * change events. Auto-refreshes every 15 seconds. Supports instant + * mutations (upsert/delete/rename) after command execution. + */ +import { bookmarkFolders } from "../bookmarkFolders.js"; +import { getBrowserWindow } from "../types/runtime.js"; +import { + OASIS_EVENT_BOOKMARK_FOLDERS_CHANGED, + type BookmarkFoldersChangedDetail, +} from "../../../shared/contracts.js"; +import type { + RoutingStateMutation, + RoutingStateSnapshot, +} from "./routerTypes.js"; +import { normalizeRouteName } from "./intentParser.js"; +import { assistantLogger } from "./assistantLogger.js"; + +class RoutingStateCache { + private folderNames = new Set(); + private groupNames = new Set(); + private dirty = true; + private refreshing = false; + private initialized = false; + private lastRefresh = 0; + private refreshTimer: number | null = null; + private readonly refreshTtlMs = 15000; + + private normalizeEntityName(value: string): string | null { + const normalized = normalizeRouteName(value || ""); + return normalized || null; + } + + private markFresh(): void { + this.dirty = false; + this.lastRefresh = Date.now(); + } + + private refreshGroupsFromBrowser(reason: string): void { + const nextGroups = new Set(); + const topWin = getBrowserWindow(); + const gBrowser = topWin?.gBrowser; + const groups = gBrowser?.getAllTabGroups + ? gBrowser.getAllTabGroups() + : gBrowser?.tabGroups || []; + for (const group of Array.from(groups || [])) { + const normalized = normalizeRouteName(group?.label || ""); + if (normalized) { + nextGroups.add(normalized); + } + } + this.groupNames = nextGroups; + this.markFresh(); + assistantLogger.debug("routing-state", "Groups refreshed", { + reason, + groups: nextGroups.size, + }); + } + + private replaceFolderNames(names: string[], reason: string): void { + const nextFolders = new Set(); + for (const name of names) { + const normalized = this.normalizeEntityName(name); + if (normalized) { + nextFolders.add(normalized); + } + } + this.folderNames = nextFolders; + this.markFresh(); + assistantLogger.debug("routing-state", "Folders replaced", { + reason, + folders: nextFolders.size, + }); + } + + ensureInitialized(): void { + if (this.initialized) { + return; + } + this.initialized = true; + + const win = (globalThis as { window?: Window }).window; + if (win?.addEventListener) { + win.addEventListener( + "TabGroupCreate", + () => { + try { + this.refreshGroupsFromBrowser("tab-group-create-event"); + } catch (error) { + assistantLogger.warn( + "routing-state", + "TabGroupCreate fast refresh failed", + error + ); + this.markDirty("tab-group-create"); + } + }, + true + ); + win.addEventListener( + "TabGroupRemoved", + () => { + try { + this.refreshGroupsFromBrowser("tab-group-removed-event"); + } catch (error) { + assistantLogger.warn( + "routing-state", + "TabGroupRemoved fast refresh failed", + error + ); + this.markDirty("tab-group-removed"); + } + }, + true + ); + win.addEventListener( + OASIS_EVENT_BOOKMARK_FOLDERS_CHANGED, + (event: Event) => { + const detail = (event as CustomEvent).detail; + if (Array.isArray(detail?.folderNames)) { + this.replaceFolderNames(detail.folderNames, "bookmark-folders-event"); + return; + } + this.markDirty("bookmark-folders-event"); + } + ); + } + + this.scheduleRefresh("init"); + } + + markDirty(reason: string): void { + this.dirty = true; + this.scheduleRefresh(reason); + } + + applyMutation(mutation: RoutingStateMutation): void { + this.ensureInitialized(); + + if (mutation.kind === "dirty") { + this.markDirty(mutation.reason); + return; + } + + const setRef = mutation.entity === "folder" ? this.folderNames : this.groupNames; + + if (mutation.kind === "upsert") { + const normalized = this.normalizeEntityName(mutation.name); + if (normalized) { + setRef.add(normalized); + } + } else if (mutation.kind === "delete") { + const normalized = this.normalizeEntityName(mutation.name); + if (normalized) { + setRef.delete(normalized); + } + } else if (mutation.kind === "rename") { + const from = this.normalizeEntityName(mutation.from); + const to = this.normalizeEntityName(mutation.to); + if (from) { + setRef.delete(from); + } + if (to) { + setRef.add(to); + } + } + + this.markFresh(); + this.scheduleRefresh(`mutation-${mutation.kind}`); + assistantLogger.debug("routing-state", "Mutation applied", { + kind: mutation.kind, + entity: mutation.entity, + }); + } + + getSnapshotSync(): RoutingStateSnapshot { + this.ensureInitialized(); + + const now = Date.now(); + const stale = + this.dirty || now - this.lastRefresh > this.refreshTtlMs || this.lastRefresh === 0; + if (stale) { + this.scheduleRefresh("snapshot-stale"); + } + + return { + folderNames: new Set(this.folderNames), + groupNames: new Set(this.groupNames), + stale, + }; + } + + private scheduleRefresh(reason: string): void { + if (this.refreshTimer != null) { + return; + } + const timerHost = (globalThis as { window?: Window }).window; + if (!timerHost?.setTimeout) { + return; + } + this.refreshTimer = timerHost.setTimeout(() => { + this.refreshTimer = null; + void this.refreshNow(reason); + }, 120); + } + + private async refreshNow(reason: string): Promise { + if (this.refreshing) { + this.dirty = true; + return; + } + + this.refreshing = true; + try { + const nextFolders = new Set(); + const folderSnapshot = await bookmarkFolders.getAllReadOnly(); + if (folderSnapshot.ok) { + for (const folder of folderSnapshot.folders) { + const normalized = normalizeRouteName(folder.name); + if (normalized) { + nextFolders.add(normalized); + } + } + } + + const nextGroups = new Set(); + this.refreshGroupsFromBrowser("full-refresh"); + for (const groupName of this.groupNames) { + nextGroups.add(groupName); + } + + this.folderNames = nextFolders; + this.groupNames = nextGroups; + this.markFresh(); + assistantLogger.debug("routing-state", "State refreshed", { + reason, + folders: nextFolders.size, + groups: nextGroups.size, + }); + } catch (e) { + assistantLogger.warn("routing-state", "Refresh failed", e); + this.dirty = true; + } finally { + this.refreshing = false; + } + } +} + +export const routingStateCache = new RoutingStateCache(); diff --git a/browser/base/content/assistant/build/src/utils/routingUtils.ts b/browser/base/content/assistant/build/src/utils/routingUtils.ts new file mode 100644 index 0000000000000..bdd2811c79d2c --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/routingUtils.ts @@ -0,0 +1,55 @@ +/** + * Routing helpers — small utilities for routing decisions. + * + * - parseAmbiguityResolution(): parses "tab group" / "folder" / "cancel" + * from user responses to ambiguity prompts + * - looksLikeNewActionCommand(): detects if text has an action verb + * + a browser object (used to decide if a new routing cycle is needed) + */ +import { KNOWN_SITES_HINT_RE } from "./knownSites.js"; + +const CANCEL_RE = /^(?:no|cancel|nevermind|never\s+mind|stop)$/i; + +export function parseAmbiguityResolution( + text: string +): "bookmark-folder" | "tab-group" | "tab" | "cancel" | null { + const input = String(text || "").trim(); + if (!input) return null; + + if (CANCEL_RE.test(input)) { + return "cancel"; + } + + const hasTabGroup = /\btab\s*group\b/i.test(input); + const hasBookmarkFolder = /\bbookmark\s*folder\b/i.test(input); + if (hasTabGroup && hasBookmarkFolder) return null; + if (hasTabGroup) return "tab-group"; + if (hasBookmarkFolder) return "bookmark-folder"; + + const hasGroupWord = /\bgroup\b/i.test(input); + const hasFolderWord = /\bfolder\b/i.test(input); + const hasTabWord = /\btab\b/i.test(input); + if (hasGroupWord && hasFolderWord) return null; + if (hasGroupWord) return "tab-group"; + if (hasFolderWord) return "bookmark-folder"; + if (hasTabWord) return "tab"; + + return null; +} + +export function looksLikeNewActionCommand(text: string): boolean { + const input = String(text || ""); + const hasAction = + /\b(?:open|close|delete|remove|create|make|new|add|save|move|put|rename|list|show|search|find|summarize|split|go\s+to|navigate|visit)\b/i.test( + input + ); + const hasObjectOrTarget = + /\b(?:tab|tabs|group|folder|bookmark|window|history|memory|page|site|website|url|link)\b/i.test( + input + ) || + /\bhttps?:\/\/[^\s]+\b|\b[a-z0-9.-]+\.[a-z]{2,}(?:\/[^\s]*)?\b/i.test( + input + ) || + KNOWN_SITES_HINT_RE.test(input); + return hasAction && hasObjectOrTarget; +} diff --git a/browser/base/content/assistant/build/src/utils/searchMemoryUtils.ts b/browser/base/content/assistant/build/src/utils/searchMemoryUtils.ts new file mode 100644 index 0000000000000..c21db2ae996a0 --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/searchMemoryUtils.ts @@ -0,0 +1,71 @@ +/** Helpers for search_memory results: builds folder-URL maps and filters stale bookmark folder entries that no longer exist. */ +import { + getMemoryDocFolderName, + getMemoryDocSource, + getMemoryDocUrl, + isBookmarkFolderType, + type MemoryMetadata, + normalizeMemoryName, +} from "./localMemoryUtils.js"; + +export type SearchMemoryResult = { + text: string; + score: number; + metadata: MemoryMetadata; + url?: string; +}; + +export type FolderSnapshot = { + name: string; + items: Array<{ url: string }>; +}; + +export function hasBookmarkFolderCandidates(results: SearchMemoryResult[]): boolean { + return results.some((r) => { + const rawType = String(r.metadata?.type || "").toLowerCase(); + return isBookmarkFolderType(rawType); + }); +} + +export function buildFolderUrlMap(folders: FolderSnapshot[]): Map> { + const folderToUrls = new Map>(); + for (const folder of folders) { + const name = normalizeMemoryName(folder?.name || ""); + if (!name) continue; + const urls = new Set(); + for (const item of folder.items || []) { + const url = String(item?.url || "").trim(); + if (url) urls.add(url); + } + folderToUrls.set(name, urls); + } + return folderToUrls; +} + +export function filterStaleBookmarkFolderResults( + results: SearchMemoryResult[], + folderToUrls: Map> +): { results: SearchMemoryResult[]; dropped: number } { + let dropped = 0; + const filtered = results.filter((result) => { + if (getMemoryDocSource(result) !== "bookmark-folder") { + return true; + } + const folderName = getMemoryDocFolderName(result); + const folderUrls = folderToUrls.get(folderName); + if (!folderUrls) { + dropped++; + return false; + } + const url = getMemoryDocUrl(result); + if (!url) { + return true; + } + if (!folderUrls.has(url)) { + dropped++; + return false; + } + return true; + }); + return { results: filtered, dropped }; +} diff --git a/browser/base/content/assistant/build/src/utils/searchResultExplicitResolver.ts b/browser/base/content/assistant/build/src/utils/searchResultExplicitResolver.ts new file mode 100644 index 0000000000000..c464ebcb18558 --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/searchResultExplicitResolver.ts @@ -0,0 +1,72 @@ +/** Routes "open result #N" or "open the first result" follow-up commands to open_search_result. Parses ordinal and numeric index from user input. */ +import type { DeterministicRouteDecision, RouteArgs } from "./routerTypes.js"; + +type SearchResultRoute = { + reason: string; + resolve: (input: string) => RouteArgs | null; +}; + +function toolDecision( + next: string, + reason: string, + args: RouteArgs +): DeterministicRouteDecision { + return { type: "tool", next, args, reason }; +} + +function parseSearchResultIndex(input: string): number | undefined { + const lower = String(input || "").toLowerCase(); + if (/\b(?:first|1st)\b/.test(lower)) return 1; + if (/\b(?:second|2nd)\b/.test(lower)) return 2; + if (/\b(?:third|3rd)\b/.test(lower)) return 3; + if (/\b(?:fourth|4th)\b/.test(lower)) return 4; + if (/\b(?:fifth|5th)\b/.test(lower)) return 5; + + const numbered = lower.match(/(?:result\s*|number\s*|#)(\d+)/i); + if (!numbered?.[1]) { + return undefined; + } + const parsed = Number(numbered[1]); + return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined; +} + +const SEARCH_RESULT_ROUTES: readonly SearchResultRoute[] = [ + { + reason: "search-result-explicit-url", + resolve: input => { + const match = input.match( + /(?:open|go\s+to)\s+(?:the\s+)?(?:search\s+)?result(?:\s+url)?\s+(?https?:\/\/[^\s]+|[a-z0-9.-]+\.[a-z]{2,}(?:\/[^\s]*)?)/i + ); + const url = match?.groups?.url?.trim(); + return url ? { url } : null; + }, + }, + { + reason: "search-result-followup", + resolve: input => { + if (!/^(?:open|go\s+to)\b/i.test(input)) { + return null; + } + const index = parseSearchResultIndex(input); + if (index != null) { + return { index }; + } + if (!/\b(?:it|that|this|one|result|last)\b/i.test(input)) { + return null; + } + return {}; + }, + }, +]; + +export function resolveExplicitSearchResultRoute( + input: string +): DeterministicRouteDecision | null { + for (const route of SEARCH_RESULT_ROUTES) { + const args = route.resolve(input); + if (args) { + return toolDecision("open_search_result", route.reason, args); + } + } + return null; +} diff --git a/browser/base/content/assistant/build/src/utils/streamGuards.ts b/browser/base/content/assistant/build/src/utils/streamGuards.ts new file mode 100644 index 0000000000000..205f523c4670c --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/streamGuards.ts @@ -0,0 +1,60 @@ +/** + * Stream guards — infinite loop detection for graph execution. + * + * Tracks step count and same-step streaks during graph.stream(). + * If the graph exceeds 36 total steps or repeats the same node + * 8+ times, execution is halted to prevent runaway loops. + * Used by stream.ts. + */ +export type StreamGuardConfig = { + maxStreamSteps: number; + maxSameStepStreak: number; +}; + +export type StreamGuardState = { + stepCount: number; + previousStepName: string; + sameStepStreak: number; +}; + +export const STREAM_GUARD_DEFAULTS: StreamGuardConfig = { + maxStreamSteps: 36, + maxSameStepStreak: 8, +}; + +export function createStreamGuardState(): StreamGuardState { + return { + stepCount: 0, + previousStepName: "", + sameStepStreak: 0, + }; +} + +export function advanceStreamGuard( + state: StreamGuardState, + stepName: string +): StreamGuardState { + const nextStepCount = state.stepCount + 1; + if (stepName === state.previousStepName) { + return { + stepCount: nextStepCount, + previousStepName: state.previousStepName, + sameStepStreak: state.sameStepStreak + 1, + }; + } + return { + stepCount: nextStepCount, + previousStepName: stepName, + sameStepStreak: 1, + }; +} + +export function shouldStopForStreamGuard( + state: StreamGuardState, + config: StreamGuardConfig = STREAM_GUARD_DEFAULTS +): boolean { + return ( + state.stepCount > config.maxStreamSteps || + state.sameStepStreak > config.maxSameStepStreak + ); +} diff --git a/browser/base/content/assistant/build/src/utils/summarizeExplicitResolver.ts b/browser/base/content/assistant/build/src/utils/summarizeExplicitResolver.ts new file mode 100644 index 0000000000000..19a04a52d2991 --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/summarizeExplicitResolver.ts @@ -0,0 +1,80 @@ +/** Routes "summarize this page" / "summarize tab N" commands to summarize_page. Supports current tab, tab index, tab query, and generic summarize patterns. */ +import type { DeterministicRouteDecision, RouteArgs } from "./routerTypes.js"; + +type SummarizeRoute = { + reason: string; + resolve: (input: string) => RouteArgs | null; +}; + +function toolDecision( + next: string, + reason: string, + args: RouteArgs +): DeterministicRouteDecision { + return { type: "tool", next, args, reason }; +} + +function numberArg(value: string | undefined): number | undefined { + if (!value) { + return undefined; + } + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : undefined; +} + +const SUMMARIZE_ROUTES: readonly SummarizeRoute[] = [ + { + reason: "summarize-current-tab", + resolve: input => + /summarize\s+(?:the\s+)?(?:current|this|active)\s+tab/i.test(input) + ? {} + : null, + }, + { + reason: "summarize-tab-index", + resolve: input => { + const match = + input.match(/summarize\s+(?:the\s+)?tab\s+(?\d+)/i) || + input.match(/summarize\s+(?:the\s+)?(?:first|1st)\s+tab/i); + if (!match) { + return null; + } + const index = numberArg(match.groups?.index) ?? 1; + return { index }; + }, + }, + { + reason: "summarize-tab-query", + resolve: input => { + const match = input.match( + /summarize\s+(?:the\s+)?"?(?[^"\d][^"]+?)"?\s*tab/i + ); + const query = match?.groups?.query?.trim(); + if (!query || /^(?:current|this|active)$/i.test(query)) { + return null; + } + return { query }; + }, + }, + { + reason: "summarize-page", + resolve: input => + /summarize\s+(?:this\s+)?(?:page|article|website|site)?|(?:what\s+is|tell\s+me\s+about)\s+this\s+(?:page|article|website|site)|give\s+(?:me\s+)?(?:a\s+)?summary/i.test( + input + ) + ? {} + : null, + }, +]; + +export function resolveExplicitSummarizeRoute( + input: string +): DeterministicRouteDecision | null { + for (const route of SUMMARIZE_ROUTES) { + const args = route.resolve(input); + if (args) { + return toolDecision("summarize_page", route.reason, args); + } + } + return null; +} diff --git a/browser/base/content/assistant/build/src/utils/voiceUtteranceGuards.test.ts b/browser/base/content/assistant/build/src/utils/voiceUtteranceGuards.test.ts new file mode 100644 index 0000000000000..5db1852188541 --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/voiceUtteranceGuards.test.ts @@ -0,0 +1,34 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + MIN_AUTO_TRANSCRIPT_LENGTH, + shouldDiscardAutoTranscript, +} from "./voiceUtteranceGuards.js"; + +test("manual stop never discards", () => { + assert.equal(shouldDiscardAutoTranscript("a", true), false); + assert.equal(shouldDiscardAutoTranscript("", true), false); +}); + +test("empty does not discard via guard", () => { + assert.equal(shouldDiscardAutoTranscript("", false), false); +}); + +test("long enough never discards", () => { + assert.equal(shouldDiscardAutoTranscript("hello", false), false); + assert.equal( + shouldDiscardAutoTranscript("a".repeat(MIN_AUTO_TRANSCRIPT_LENGTH), false), + false + ); +}); + +test("allowlisted short phrases", () => { + assert.equal(shouldDiscardAutoTranscript("ok", false), false); + assert.equal(shouldDiscardAutoTranscript("back", false), false); + assert.equal(shouldDiscardAutoTranscript(" Tab ", false), false); +}); + +test("very short non-allowlist auto discards", () => { + assert.equal(shouldDiscardAutoTranscript("hi", false), true); + assert.equal(shouldDiscardAutoTranscript("um", false), true); +}); diff --git a/browser/base/content/assistant/build/src/utils/voiceUtteranceGuards.ts b/browser/base/content/assistant/build/src/utils/voiceUtteranceGuards.ts new file mode 100644 index 0000000000000..ac4259935144f --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/voiceUtteranceGuards.ts @@ -0,0 +1,24 @@ +export const MIN_AUTO_TRANSCRIPT_LENGTH = 5; + +const SHORT_TRANSCRIPT_ALLOWLIST = + /^(no|yes|ok|tab|stop|undo|redo|back|refresh|forward|close)$/i; + +export function shouldDiscardAutoTranscript( + transcript: string, + manualStop: boolean +): boolean { + if (manualStop) { + return false; + } + const t = transcript.replace(/\s+/g, " ").trim(); + if (t.length === 0) { + return false; + } + if (t.length >= MIN_AUTO_TRANSCRIPT_LENGTH) { + return false; + } + if (SHORT_TRANSCRIPT_ALLOWLIST.test(t)) { + return false; + } + return true; +} diff --git a/browser/base/content/assistant/build/src/utils/voiceVadDebounce.test.ts b/browser/base/content/assistant/build/src/utils/voiceVadDebounce.test.ts new file mode 100644 index 0000000000000..c61f26bd97882 --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/voiceVadDebounce.test.ts @@ -0,0 +1,32 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { advanceVadSpeechDebounce } from "./voiceVadDebounce.js"; + +test("resets streak when not speech", () => { + assert.deepEqual(advanceVadSpeechDebounce(2, false, 3), { + streak: 0, + commit: false, + }); +}); + +test("increments until commit", () => { + assert.deepEqual(advanceVadSpeechDebounce(0, true, 3), { + streak: 1, + commit: false, + }); + assert.deepEqual(advanceVadSpeechDebounce(1, true, 3), { + streak: 2, + commit: false, + }); + assert.deepEqual(advanceVadSpeechDebounce(2, true, 3), { + streak: 0, + commit: true, + }); +}); + +test("commit on first frame when debounce is 1", () => { + assert.deepEqual(advanceVadSpeechDebounce(0, true, 1), { + streak: 0, + commit: true, + }); +}); diff --git a/browser/base/content/assistant/build/src/utils/voiceVadDebounce.ts b/browser/base/content/assistant/build/src/utils/voiceVadDebounce.ts new file mode 100644 index 0000000000000..4ad310762e6c9 --- /dev/null +++ b/browser/base/content/assistant/build/src/utils/voiceVadDebounce.ts @@ -0,0 +1,14 @@ +export function advanceVadSpeechDebounce( + streak: number, + speechFrame: boolean, + debounceFrames: number +): { streak: number; commit: boolean } { + if (!speechFrame) { + return { streak: 0, commit: false }; + } + const next = streak + 1; + if (next >= debounceFrames) { + return { streak: 0, commit: true }; + } + return { streak: next, commit: false }; +} diff --git a/browser/base/content/assistant/build/src/voiceLambdaIamFetch.ts b/browser/base/content/assistant/build/src/voiceLambdaIamFetch.ts new file mode 100644 index 0000000000000..ad882c0bdc859 --- /dev/null +++ b/browser/base/content/assistant/build/src/voiceLambdaIamFetch.ts @@ -0,0 +1,77 @@ +import { Sha256 } from "@aws-crypto/sha256-js"; +import { fromCognitoIdentityPool } from "@aws-sdk/credential-provider-cognito-identity"; +import { HttpRequest } from "@aws-sdk/protocol-http"; +import { SignatureV4 } from "@aws-sdk/signature-v4"; + +const region = process.env.AWS_REGION ?? ""; +const identityPoolId = process.env.COGNITO_IDENTITY_POOL_ID ?? ""; + +function cognitoCredentials() { + if (!region || !identityPoolId) { + throw new Error( + "Missing AWS_REGION or COGNITO_IDENTITY_POOL_ID for voice Lambda signing." + ); + } + return fromCognitoIdentityPool({ + clientConfig: { region }, + identityPoolId, + }); +} + +let signerPromise: Promise | null = null; + +function getSigner(): Promise { + if (!signerPromise) { + signerPromise = Promise.resolve( + new SignatureV4({ + credentials: cognitoCredentials(), + region, + service: "lambda", + sha256: Sha256, + applyChecksum: false, + }) + ); + } + return signerPromise; +} + +export async function postVoiceLambdaWithIam( + endpoint: string, + body: string, + jwtAccessToken?: string +): Promise { + const url = new URL( + endpoint.startsWith("http") ? endpoint : `https://${endpoint}` + ); + const path = url.pathname && url.pathname.length > 0 ? url.pathname : "/"; + const headers: Record = { + host: url.host, + "content-type": "application/json", + }; + if (jwtAccessToken) { + headers["x-oasis-authorization"] = `Bearer ${jwtAccessToken}`; + } + + const req = new HttpRequest({ + protocol: url.protocol, + hostname: url.hostname, + port: url.port ? parseInt(url.port, 10) : undefined, + method: "POST", + path, + headers, + body, + }); + + const signer = await getSigner(); + const signed = await signer.sign(req); + const portPart = + signed.port != null && signed.port !== 80 && signed.port !== 443 + ? `:${signed.port}` + : ""; + const signedUrl = `${signed.protocol}//${signed.hostname}${portPart}${signed.path}`; + return fetch(signedUrl, { + method: signed.method, + headers: signed.headers as HeadersInit, + body: signed.body, + }); +} diff --git a/browser/base/content/assistant/build/tests/agentLoopEval.test.ts b/browser/base/content/assistant/build/tests/agentLoopEval.test.ts new file mode 100644 index 0000000000000..81363b4dee37e --- /dev/null +++ b/browser/base/content/assistant/build/tests/agentLoopEval.test.ts @@ -0,0 +1,140 @@ +/** + * Lightweight eval for streamAgentLoop (driver semantics, step ordering, caps). + * Run: npm run eval:agent-loop + */ +import test from "node:test"; +import assert from "node:assert/strict"; +import { AIMessage, HumanMessage } from "@langchain/core/messages"; + +import { + AGENT_END, + streamAgentLoop, + type AgentState, +} from "../src/assistant/agentLoopDriver.js"; + +test("eval: supervisor → tool → supervisor → chat → __end__", async () => { + let supervisorCalls = 0; + const supervisorNode = async (_state: AgentState) => { + supervisorCalls += 1; + if (supervisorCalls === 1) { + return { + next: "mock_tool", + args: { step: 1 }, + lastWorker: "supervisor", + }; + } + return { next: "chat", args: {}, commandQueue: [] }; + }; + + const chatNode = async () => ({ + messages: [new AIMessage("Chat reply.")], + lastWorker: "chat", + commandQueue: [], + }); + + const toolAgents = { + mock_tool: async (state: AgentState) => ({ + messages: [ + new AIMessage({ + content: "Tool done.", + name: "mock_tool", + }), + ], + lastWorker: "mock_tool", + next: "supervisor", + args: {}, + commandQueue: state.commandQueue, + }), + }; + + const yielded: string[] = []; + for await (const chunk of streamAgentLoop({ + initialMessages: [new HumanMessage("Hello")], + maxSteps: 24, + supervisorNode, + chatNode, + toolAgents, + memberNames: ["mock_tool"], + })) { + if ("__end__" in chunk && (chunk as { __end__?: boolean }).__end__) { + yielded.push("__end__"); + break; + } + const key = Object.keys(chunk).find(k => k !== "__end__"); + if (key) { + yielded.push(key); + } + } + + assert.deepEqual(yielded, ["mock_tool", "chat", "__end__"]); + assert.equal(supervisorCalls, 2); +}); + +test("eval: maxSteps stops ping-pong (no silent hang)", async () => { + const supervisorNode = async () => ({ + next: "mock_tool", + args: {}, + lastWorker: "supervisor", + }); + const chatNode = async () => ({ + messages: [new AIMessage("unused")], + lastWorker: "chat", + commandQueue: [], + }); + const toolAgents = { + mock_tool: async (state: AgentState) => ({ + messages: [new AIMessage({ content: ".", name: "mock_tool" })], + lastWorker: "mock_tool", + next: "supervisor", + args: {}, + commandQueue: state.commandQueue, + }), + }; + + let end = false; + let iterations = 0; + for await (const chunk of streamAgentLoop({ + initialMessages: [new HumanMessage("x")], + maxSteps: 6, + supervisorNode, + chatNode, + toolAgents, + memberNames: ["mock_tool"], + })) { + iterations += 1; + if ("__end__" in chunk && (chunk as { __end__?: boolean }).__end__) { + end = true; + break; + } + } + + assert.equal(end, true); + assert.ok(iterations <= 12); +}); + +test("eval: supervisor can end immediately", async () => { + const supervisorNode = async () => ({ + next: AGENT_END, + args: {}, + lastWorker: "supervisor", + }); + const chatNode = async () => ({ + messages: [new AIMessage("no")], + lastWorker: "chat", + commandQueue: [], + }); + const out: string[] = []; + for await (const chunk of streamAgentLoop({ + initialMessages: [new HumanMessage("stop")], + maxSteps: 8, + supervisorNode, + chatNode, + toolAgents: {}, + memberNames: [], + })) { + if ("__end__" in chunk && (chunk as { __end__?: boolean }).__end__) { + out.push("__end__"); + } + } + assert.deepEqual(out, ["__end__"]); +}); diff --git a/browser/base/content/assistant/build/tests/assistUsageMeta.test.ts b/browser/base/content/assistant/build/tests/assistUsageMeta.test.ts new file mode 100644 index 0000000000000..46d3624156e01 --- /dev/null +++ b/browser/base/content/assistant/build/tests/assistUsageMeta.test.ts @@ -0,0 +1,33 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { + extractTokenCountsFromAssistPayload, + extractTokenCountsFromUsageMetadata, +} from "../src/assistant/messageUtils.js"; + +test("extractTokenCountsFromUsageMetadata: snake_case", () => { + const t = extractTokenCountsFromUsageMetadata({ + prompt_token_count: 12, + candidates_token_count: 34, + }); + assert.equal(t.input_tokens, 12); + assert.equal(t.output_tokens, 34); +}); + +test("extractTokenCountsFromUsageMetadata: camelCase", () => { + const t = extractTokenCountsFromUsageMetadata({ + promptTokenCount: 5, + candidatesTokenCount: 7, + }); + assert.equal(t.input_tokens, 5); + assert.equal(t.output_tokens, 7); +}); + +test("extractTokenCountsFromAssistPayload reads usage_metadata", () => { + const t = extractTokenCountsFromAssistPayload({ + next: "chat", + usage_metadata: { prompt_token_count: 1, candidates_token_count: 2 }, + }); + assert.equal(t.input_tokens, 1); + assert.equal(t.output_tokens, 2); +}); diff --git a/browser/base/content/assistant/build/tests/capabilitiesOverview.test.ts b/browser/base/content/assistant/build/tests/capabilitiesOverview.test.ts new file mode 100644 index 0000000000000..d2ff5e8a78b48 --- /dev/null +++ b/browser/base/content/assistant/build/tests/capabilitiesOverview.test.ts @@ -0,0 +1,89 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { + buildCapabilitiesOverviewMarkdown, + summarizeForUser, +} from "../src/assistant/capabilitiesOverview.js"; +import { + CAPABILITIES_BLOCK_DELIMITER, + CAPABILITIES_OVERVIEW_FIRST_LINE, + OASIS_CAPABILITIES_FEATURES_URL, + OASIS_CAPABILITIES_FEEDBACK_URL, + OASIS_CAPABILITIES_FEEDBACK_LINK_LABEL, +} from "../../shared/capabilitiesOverviewConstants.js"; + +const listTabsDesc = + "List tabs. Accepts optional arguments: { scope?: 'window'|'tab-group'|'bookmark-folder', name?: string }. If name is provided without scope, resolves tab-group vs bookmark-folder by runtime state."; + +const closeTabDesc = + "Close the active tab (or a tab by index). Accepts arguments: { index?: number, confirmed?: boolean } (1-based)."; + +test("summarizeForUser strips Accepts optional arguments", () => { + const s = summarizeForUser(listTabsDesc); + assert.ok(!/accepts optional arguments/i.test(s)); + assert.ok(!/accepts arguments/i.test(s)); + assert.ok(s.length <= 200); + assert.match(s, /list tabs/i); +}); + +test("summarizeForUser strips Accepts arguments", () => { + const s = summarizeForUser(closeTabDesc); + assert.ok(!/accepts arguments/i.test(s)); + assert.ok(s.length <= 200); +}); + +test("summarizeForUser removes Args JSON tail", () => { + const s = summarizeForUser( + "Open a URL. Accepts arguments: { url: string } Args JSON: {\"url\":\"https://x\"}" + ); + assert.ok(!/args json/i.test(s)); + assert.ok(!/\{[^}]*url[^}]*\}/i.test(s)); +}); + +test("summarizeForUser strips Accepts no arguments", () => { + const s = summarizeForUser( + "Copy all tab URLs in the current window to the clipboard (one per line). Accepts no arguments." + ); + assert.ok(!/accepts no arguments/i.test(s)); + assert.match(s, /clipboard/i); +}); + +test("capabilities markdown uses headings, code, links; no legacy delimiter", () => { + const md = buildCapabilitiesOverviewMarkdown([ + { name: "list_tabs", description: listTabsDesc }, + { name: "close_tab", description: closeTabDesc }, + ]); + assert.ok(!md.includes(CAPABILITIES_BLOCK_DELIMITER)); + assert.ok(md.startsWith(CAPABILITIES_OVERVIEW_FIRST_LINE)); + assert.ok(md.includes("### Support and feedback")); + assert.ok(!md.includes("### More")); + assert.ok(!md.includes("### Account and confirmations")); + assert.ok(md.includes("`What tabs do I have open?`")); + assert.ok(md.includes(`](${OASIS_CAPABILITIES_FEATURES_URL})`)); + assert.ok(md.includes(`](${OASIS_CAPABILITIES_FEEDBACK_URL})`)); + assert.ok(!md.includes("- close_tab")); + assert.ok(!md.includes("- list_tabs")); + assert.ok(!/tally/i.test(OASIS_CAPABILITIES_FEEDBACK_LINK_LABEL)); + assert.ok(!md.includes("Tile my windows")); + assert.ok(!md.includes("Split these two tabs side by side")); + assert.ok(!md.includes("What cooking sites")); + assert.ok(!md.includes("Show my subscription")); + const iWeb = md.indexOf("### Web and search"); + const iGen = md.indexOf("### General questions"); + const iNav = md.indexOf("### Navigation"); + const iSum = md.indexOf("### Summarization"); + assert.ok(iWeb > 0 && iGen > iWeb && iSum > iGen && iNav > iSum); + assert.ok(md.includes("`Who is the president of Djibouti?`")); + assert.ok(md.includes("`What is the square root of 256?`")); + assert.ok(md.includes("Use your imagination")); + assert.ok(/thumb/i.test(md)); + assert.ok(md.includes("training")); +}); + +test("capabilities digest has no bookmark wording", () => { + const md = buildCapabilitiesOverviewMarkdown([ + { name: "list_tabs", description: listTabsDesc }, + { name: "list_bookmark_folders", description: "List all managed bookmark folders. Accepts no arguments." }, + ]); + assert.ok(!/bookmark/i.test(md)); +}); diff --git a/browser/base/content/assistant/build/tests/explicitRouteRules.test.ts b/browser/base/content/assistant/build/tests/explicitRouteRules.test.ts new file mode 100644 index 0000000000000..9bde09f45e775 --- /dev/null +++ b/browser/base/content/assistant/build/tests/explicitRouteRules.test.ts @@ -0,0 +1,90 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { resolveExplicitRoute } from "../src/utils/explicitRouteRules.js"; +import { decideDeterministicRoute } from "../src/utils/decisionEngine.js"; + +const emptySnapshot = { + folderNames: new Set(), + groupNames: new Set(), + stale: false, +}; + +test("resolveExplicitRoute: open youtube in a new tab -> open_url", () => { + const r = resolveExplicitRoute("open youtube in a new tab"); + assert.equal(r?.type, "tool"); + assert.equal(r?.next, "open_url"); + assert.equal((r?.args as { url: string }).url, "https://www.youtube.com"); +}); + +test("resolveExplicitRoute: typo youtub -> open_url", () => { + const r = resolveExplicitRoute("open youtub in a new tab"); + assert.equal(r?.type, "tool"); + assert.equal(r?.next, "open_url"); + assert.equal((r?.args as { url: string }).url, "https://www.youtube.com"); +}); + +test("resolveExplicitRoute: https URL in new tab phrase -> open_url", () => { + const r = resolveExplicitRoute("open https://example.com in a new tab"); + assert.equal(r?.type, "tool"); + assert.equal(r?.next, "open_url"); + assert.equal((r?.args as { url: string }).url, "https://example.com"); +}); + +test("resolveExplicitRoute: unknown site -> web_search", () => { + const r = resolveExplicitRoute("open zebra site in a new tab"); + assert.equal(r?.type, "tool"); + assert.equal(r?.next, "web_search"); + assert.equal((r?.args as { query: string }).query, "zebra site"); +}); + +test("resolveExplicitRoute: show subscription unchanged", () => { + const r = resolveExplicitRoute("show subscription"); + assert.equal(r?.type, "tool"); + assert.equal(r?.next, "show_subscription"); +}); + +test("resolveExplicitRoute: open a new tab (no URL) -> new_tab_to_right", () => { + for (const phrase of [ + "open a new tab", + "Open a new tab.", + "open new tab", + "new tab", + "create a new tab please", + ]) { + const r = resolveExplicitRoute(phrase); + assert.equal(r?.type, "tool", phrase); + assert.equal(r?.next, "new_tab_to_right", phrase); + assert.deepEqual(r?.args, {}, phrase); + } +}); + +test("resolveExplicitRoute: open a new tab group does not match blank-tab rule", () => { + const r = resolveExplicitRoute("open a new tab group called Videos"); + assert.notEqual(r?.next, "new_tab_to_right"); +}); + +test("decideDeterministicRoute: open YouTube in a new tab (cased, period)", () => { + const d = decideDeterministicRoute( + "Open YouTube in a new tab.", + emptySnapshot + ); + assert.equal(d.type, "tool"); + assert.equal(d.next, "open_url"); + assert.equal((d.args as { url: string }).url, "https://www.youtube.com"); +}); + +test("decideDeterministicRoute: visit github in a new tab", () => { + const d = decideDeterministicRoute( + "visit github in a new tab", + emptySnapshot + ); + assert.equal(d.type, "tool"); + assert.equal(d.next, "open_url"); + assert.equal((d.args as { url: string }).url, "https://github.com"); +}); + +test("decideDeterministicRoute: open a new tab -> new_tab_to_right", () => { + const d = decideDeterministicRoute("open a new tab", emptySnapshot); + assert.equal(d.type, "tool"); + assert.equal(d.next, "new_tab_to_right"); +}); diff --git a/browser/base/content/assistant/build/tsconfig.json b/browser/base/content/assistant/build/tsconfig.json new file mode 100644 index 0000000000000..19ad2d1d02825 --- /dev/null +++ b/browser/base/content/assistant/build/tsconfig.json @@ -0,0 +1,10 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "skipLibCheck": true + }, + "include": ["src/**/*.ts", "src/**/*.d.ts", "../shared/capabilitiesOverviewConstants.ts"] +} diff --git a/browser/base/content/assistant/dist/assistant.ui.bundle.css b/browser/base/content/assistant/dist/assistant.ui.bundle.css new file mode 100644 index 0000000000000..039a94148b714 --- /dev/null +++ b/browser/base/content/assistant/dist/assistant.ui.bundle.css @@ -0,0 +1 @@ +html{height:100%;background:var(--assistant-sidebar-bg)}#assistant-preact-root{height:100%;display:flex;flex-direction:column;min-height:0;background:var(--assistant-sidebar-bg)}:root{color-scheme:light dark;--space-xxsmall: 2px;--space-xsmall: 4px;--space-small: 8px;--space-medium: 12px;--space-large: 16px;--space-xlarge: 24px;--space-xxlarge: 32px;--surface-default: #f8faf2;--surface-page: #ffffff;--primary-green: #7a9200;--assistant-sidebar-bg: color-mix(in srgb, var(--surface-default) 92%, var(--primary-green) 8%);--primary-light: #f8faf2;--primary-50: #f2f4e5;--text-body: #666;--text-headings: #333;--text-secondary: #5b6b4b;--neutral-500: #999;--neutral-600: #737373;--chat-ai-fg: #333;--chat-ai-heading-fg: #111;--chat-ai-muted-fg: #666;--chat-ai-code-bg: rgba(0, 0, 0, .06);--chat-ai-code-fg: var(--chat-ai-fg);--chat-ai-pre-bg: #f6f8fa;--chat-ai-pre-fg: #333;--chat-ai-bubble-bg: var(--surface-page);--chat-ai-bubble-fg: var(--chat-ai-fg);--chat-ai-bubble-border: rgba(0, 0, 0, .05);--chat-user-bubble-bg-top: #f8faf2;--chat-user-bubble-bg-bottom: #f2f4e5;--chat-user-bubble-fg: #2f3a20;--border-radius-xlg: 16px;--border-radius-lg: 12px;--border-radius-large: 10px;--border-radius-circle: 50%;--size-item-small: 16px;--size-item-large: 32px;--icon-size-medium: 20px;--composer-toolbar-gap: var(--space-small);--composer-action-gap: 11px;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--assistant-sidebar-bg);--composer-dock-radius: var(--border-radius-large);--composer-invite-sun-a: rgba(255, 250, 230, .52);--composer-invite-sun-b: rgba(255, 255, 255, .28);--composer-invite-sun-c: rgba(255, 248, 220, .38);--composer-invite-sun-focus: rgba(255, 252, 235, .75);--composer-input-bg: color-mix(in srgb, var(--surface-default) 78%, #3d4a2a 14%);--composer-input-text: #1a1f14;--composer-placeholder: #5a6350;--header-title-color: #495800;--header-badge-bg: var(--primary-50);--header-badge-text: #495800;--dropdown-surface: var(--surface-page);--dropdown-border-color: #eeeeee;--dropdown-header-bg: #fafafa;--dropdown-muted-text: #888888;--dropdown-item-text: #333333;--dropdown-item-hover: #f5f5f5;--icon-accent-color: var(--primary-green);--icon-accent-hover-bg: color-mix(in srgb, var(--primary-green) 18%, transparent);--auth-on-primary: #ffffff}body{margin:0;height:100%;font:14px Geist,system-ui,-apple-system,sans-serif;background:var(--assistant-sidebar-bg);color:var(--text-body);-webkit-font-smoothing:antialiased;overflow:hidden}.assistant-theme-picker button:hover{background:var(--dropdown-item-hover)!important}.assistant-container{flex:1;min-height:0;height:100%;max-height:100%;display:flex;flex-direction:column;background:var(--assistant-sidebar-bg);padding:var(--space-large);gap:var(--space-large);box-sizing:border-box;border-radius:var(--border-radius-xlg);overflow:hidden}.assistant-main{flex:1;min-height:0;display:flex;flex-direction:column;gap:var(--space-medium)}.assistant-main--auth{gap:var(--space-large)}.assistant-onboarding-top{flex-shrink:0;width:100%;box-sizing:border-box}.oasis-chat-history-trigger:focus{outline:2px solid var(--primary-green);outline-offset:2px}.oasis-chat-history-trigger:focus:not(:focus-visible){outline-color:color-mix(in srgb,var(--primary-green) 58%,transparent)}.assistant-main--empty-signed-chat .chat-log--empty-signed-in{flex:0 0 auto;min-height:0;padding:var(--space-small) var(--space-large);gap:0}.assistant-main--empty-signed-chat .input-bar--empty-signed-chat{box-shadow:0 4px 18px #0000000f,0 0 40px var(--composer-invite-sun-a),0 0 72px var(--composer-invite-sun-b),0 0 1px #7a920014}.assistant-main--empty-signed-chat .input-bar--empty-signed-chat .composer-input-wrap{min-height:120px}.assistant-main--empty-signed-chat .input-bar--empty-signed-chat .composer-input-wrap .input-field{min-height:120px;box-shadow:inset 0 1px 2px #0000000d,0 0 28px var(--composer-invite-sun-c),0 0 52px var(--composer-invite-sun-b),0 0 0 1px #7a92000f}.assistant-main--empty-signed-chat .input-bar--empty-signed-chat .composer-input-wrap .input-field:focus{box-shadow:inset 0 1px 2px #0000000d,0 0 0 2px #7a920024,0 0 32px var(--composer-invite-sun-a),0 0 56px var(--composer-invite-sun-b)}.assistant-main--empty-signed-chat .input-bar--empty-signed-chat .composer-inline-chip{box-shadow:0 0 14px var(--composer-invite-sun-c),0 0 28px var(--composer-invite-sun-b)}.assistant-main--empty-signed-chat .input-bar--empty-signed-chat .composer-inline-chip:hover:not(:disabled){box-shadow:0 0 18px var(--composer-invite-sun-a),0 0 36px var(--composer-invite-sun-b)}.assistant-scroll{flex:1;min-height:0;overflow-x:hidden;overflow-y:auto;display:flex;flex-direction:column;background:transparent}.assistant-scroll--auth{scroll-padding-bottom:240px;padding-bottom:var(--space-xlarge)}.assistant-chat-stack{display:flex;flex-direction:column;flex:1;min-height:0}.auth-screen{flex:1;display:flex;flex-direction:column;align-items:stretch;justify-content:flex-start;padding:var(--space-medium) var(--space-medium) var(--space-medium);gap:var(--space-medium);width:100%;max-width:320px;margin:0 auto;box-sizing:border-box}.auth-screen--signin{border-top:1px solid color-mix(in srgb,var(--primary-green) 35%,transparent)}.auth-screen--signup{border-top:1px solid color-mix(in srgb,var(--primary-green) 42%,transparent)}.auth-mode-tablist{display:flex;width:100%;flex-shrink:0;gap:var(--space-xxsmall);padding:var(--space-xxsmall);box-sizing:border-box;background:var(--primary-50);border-radius:var(--border-radius-lg)}.auth-mode-tab{flex:1;border:none;background:transparent;padding:var(--space-xsmall) var(--space-small);font-size:13px;font-weight:var(--font-weight-semibold);font-family:inherit;color:var(--text-secondary);border-radius:var(--border-radius-lg);cursor:pointer}.auth-mode-tab--active{background:var(--surface-page);color:var(--primary-green);box-shadow:0 1px 3px color-mix(in srgb,var(--text-headings) 8%,transparent)}.auth-tabpanel-stack{display:flex;flex-direction:column;gap:var(--space-small);align-items:stretch;flex:1;min-height:0;width:100%;padding-top:var(--space-large);box-sizing:border-box}.auth-screen-header{text-align:center;margin-bottom:var(--space-medium)}.auth-screen-title{font-size:22px;font-weight:var(--font-weight-semibold);color:var(--primary-green);margin:0 0 var(--space-xxsmall);font-family:ui-serif,Georgia,serif}.auth-screen-subtitle{color:var(--text-body);margin:0;font-size:13px;line-height:1.35}.auth-oauth-row{width:100%;display:flex;gap:10px;justify-content:center}.auth-oauth-provider-btn{flex:1;height:36px;border-radius:999px;border:1px solid var(--dropdown-border-color);background:var(--surface-page);display:flex;align-items:center;justify-content:center;cursor:pointer;outline-offset:2px;box-sizing:border-box;padding:0;margin:0;font:inherit}.auth-oauth-provider-btn:disabled{cursor:wait;opacity:.88}.auth-oauth-row>button svg{width:var(--size-item-small);height:var(--size-item-small);display:block}.auth-screen--email-focus{gap:var(--space-medium)}.auth-screen--email-focus .auth-screen-header{display:none}.auth-screen--email-focus .auth-tabpanel-stack{gap:var(--space-medium);padding-top:var(--space-medium)}.auth-oauth-details{width:100%;border-radius:var(--border-radius-lg);border:1px solid var(--dropdown-border-color);background:var(--primary-light);padding:var(--space-xxsmall) var(--space-small) var(--space-small);box-sizing:border-box}.auth-oauth-details-summary{cursor:pointer;font-size:13px;font-weight:var(--font-weight-semibold);color:var(--text-headings);padding:var(--space-small) var(--space-xsmall);font-family:inherit;list-style:none;display:flex;align-items:center;justify-content:center}.auth-oauth-details-summary-inner{display:flex;flex-wrap:wrap;align-items:center;justify-content:center;gap:var(--space-xsmall);width:100%}.auth-oauth-details-summary-icons{display:flex;align-items:center;gap:6px;flex-shrink:0}.auth-oauth-details-summary-icon-wrap svg{width:var(--size-item-small);height:var(--size-item-small);display:block;opacity:.92}.auth-oauth-details-summary-label{text-align:center;flex:1 1 auto;min-width:0}.auth-oauth-details-summary::-webkit-details-marker{display:none}.auth-oauth-details[open] .auth-oauth-details-summary{margin-bottom:var(--space-xsmall)}.auth-email-password-trigger{width:100%;padding:var(--space-small) var(--space-medium);margin-bottom:0;border-radius:12px;border:1px solid var(--dropdown-border-color);background:var(--surface-page);color:var(--text-headings);font-size:12px;font-weight:var(--font-weight-semibold);cursor:pointer;font-family:inherit}.auth-email-password-trigger:hover{background:var(--primary-light)}.auth-form-minimal{width:100%;display:flex;flex-direction:column;gap:var(--space-medium)}.auth-field-minimal{display:flex;flex-direction:column;gap:var(--space-xsmall);border-bottom:1px solid var(--dropdown-border-color);padding-bottom:6px}.auth-field-minimal-label{font-size:11px;font-weight:var(--font-weight-semibold);letter-spacing:.04em;color:var(--neutral-500);text-transform:lowercase}.auth-field-minimal-input{width:100%;border:none;background:transparent;padding:var(--space-xsmall) 0 var(--space-xxsmall);font-size:15px;color:var(--text-headings);font-family:inherit;outline:none;box-sizing:border-box}.auth-field-minimal-input::placeholder{color:var(--composer-placeholder)}.auth-password-label-row{display:flex;justify-content:space-between;align-items:baseline;gap:var(--space-small)}.auth-link-inline{background:none;border:none;color:var(--primary-green);font-size:12px;cursor:pointer;padding:0;font-family:inherit;text-decoration:underline;text-underline-offset:2px}.auth-submit-btn{background:var(--primary-green);color:var(--auth-on-primary);border:none;padding:var(--space-small) var(--space-medium);border-radius:12px;font-size:13px;font-weight:var(--font-weight-semibold);cursor:pointer;font-family:inherit;margin-top:var(--space-xsmall)}.auth-submit-btn:disabled{opacity:.7;cursor:wait}.auth-message{font-size:13px;padding:var(--space-small);border-radius:var(--border-radius-medium)}.auth-message-error{color:color-mix(in srgb,#fecaca 88%,#7f1d1d);background:color-mix(in srgb,#7f1d1d 22%,var(--surface-page))}.auth-message-success{color:color-mix(in srgb,#bbf7d0 88%,#14532d);background:color-mix(in srgb,#14532d 22%,var(--surface-page))}.auth-footer-links{font-size:13px;color:var(--text-body);text-align:center}.auth-link-standalone{background:none;border:none;color:var(--primary-green);font-weight:var(--font-weight-semibold);cursor:pointer;padding:0;font-family:inherit;text-decoration:underline;text-underline-offset:2px}.assistant-sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.onboarding-import-step-header{display:flex;align-items:flex-start;gap:10px;width:100%;padding:10px var(--space-small);margin:0;box-sizing:border-box;background:#fafcf5}.onboarding-import-step-header--done{align-items:center}.onboarding-import-card-head{flex:1;min-width:0;display:flex;flex-wrap:wrap;align-items:center;gap:var(--space-xsmall);justify-content:space-between}.onboarding-import-card-from{font-size:13px;font-weight:var(--font-weight-semibold);color:#333;line-height:1.3}.onboarding-import-done-label{font-size:13px;font-weight:var(--font-weight-semibold);color:#3d4a2f;line-height:1.3}.onboarding-import-expand{padding:0 var(--space-small) var(--space-small) var(--space-small)}.onboarding-import-primary-btn{display:inline-flex;align-items:center;justify-content:center;gap:var(--space-xsmall);font-family:inherit}.onboarding-import-primary-btn-icon{flex-shrink:0;display:block}.onboarding-import-brand-imgs{display:flex;align-items:center;gap:6px;flex-shrink:0}.onboarding-import-brand-imgs--header{gap:var(--space-small)}.onboarding-import-brand-imgs img{width:var(--size-item-small);height:var(--size-item-small);object-fit:contain;display:block}.onboarding-import-callout{display:flex;gap:var(--space-small);align-items:flex-start;padding:var(--space-small);margin-bottom:var(--space-small);border-radius:var(--border-radius-lg);border:1px solid #d4e0c0;background:linear-gradient(135deg,#f4f8ec,#eef3e4);box-sizing:border-box}.onboarding-import-callout-shield{flex-shrink:0;line-height:0;margin-top:var(--space-xxsmall)}.onboarding-import-callout-main{flex:1;min-width:0}.onboarding-import-callout-text{margin:0 0 var(--space-xsmall);font-size:12px;font-weight:var(--font-weight-semibold);color:#3d4a2f;line-height:1.4}.onboarding-import-learn-more{display:inline-block;font-size:11px;font-weight:var(--font-weight-semibold);color:#5a7000;text-decoration:underline;text-underline-offset:2px;font-family:inherit;cursor:pointer}.onboarding-import-learn-more:hover{color:#3d4a00}.quota-limit-callout{display:flex;gap:var(--space-small);align-items:flex-start;padding:var(--space-small);margin:0;border-radius:var(--border-radius-lg);border:1px solid #d4e0c0;background:linear-gradient(135deg,#f4f8ec,#eef3e4);box-sizing:border-box}.quota-limit-callout-main{flex:1;min-width:0}.quota-limit-callout-title{margin:0 0 var(--space-xsmall);font-size:13px;font-weight:var(--font-weight-semibold);color:#2d3a24;line-height:1.35}.quota-limit-callout-body{margin:0 0 var(--space-small);font-size:12px;font-weight:400;color:#3d4a2f;line-height:1.45}.quota-limit-callout-cta{margin:0}.quota-limit-callout-link{display:inline-block;font-size:12px;font-weight:var(--font-weight-semibold);color:#5a7000;text-decoration:underline;text-underline-offset:2px;font-family:inherit;cursor:pointer}.quota-limit-callout-link:hover{color:#3d4a00}.onboarding-import-actions{display:flex;flex-wrap:wrap;align-items:center;gap:var(--space-xsmall);row-gap:var(--space-xxsmall)}.assistant-onboarding-dock{flex-shrink:0;padding-top:var(--space-xsmall);margin-top:var(--space-xxsmall);border-top:1px solid rgba(0,0,0,.06)}.assistant-onboarding-dock--collapsed{padding-top:var(--space-xsmall);margin-top:var(--space-xxsmall)}.onboarding-checklist-compact{display:flex;flex-direction:column;gap:var(--space-small);width:100%;margin:0;padding:var(--space-small) 10px;border:1px solid #e2e8d0;border-radius:10px;background:#f6f8ef;box-sizing:border-box;cursor:pointer;font:inherit;text-align:left;color:inherit}.onboarding-checklist-compact:hover{background:#f0f4e8}.onboarding-checklist-compact-top{display:flex;align-items:center;gap:var(--space-small);width:100%}.onboarding-checklist-compact-icon{display:flex;flex-shrink:0;align-items:center;justify-content:center}.onboarding-checklist-compact-title{flex:1;min-width:0;font-size:13px;font-weight:var(--font-weight-semibold);color:var(--header-title-color)}.onboarding-checklist-compact-count{flex-shrink:0;font-size:12px;color:#6b7280}.onboarding-checklist-compact-bar{height:3px;border-radius:3px;background:#e2e8d0;overflow:hidden}.onboarding-checklist-compact-bar-fill{height:100%;border-radius:3px;background:#7a9200;transition:width .25s ease}.chat-log{flex:1;min-height:0;padding:var(--space-large);padding-bottom:20px;overflow:auto;background:transparent;color:var(--text-body);border-radius:var(--border-radius-lg);line-height:1.6;display:flex;flex-direction:column;scrollbar-width:none;gap:var(--space-large)}.chat-log::-webkit-scrollbar{display:none}.chat-empty-state{text-align:center;margin-top:var(--space-small);margin-bottom:var(--space-small);display:flex;flex-direction:column;align-items:center;gap:var(--space-small);width:100%;padding:var(--space-small);box-sizing:border-box;flex-shrink:0}.chat-empty-state__welcome{color:var(--neutral-500);font-size:13px;line-height:1.4;margin:0}.chat-empty-state__chips{display:flex;flex-wrap:wrap;justify-content:center;gap:5px;max-width:280px;padding:0 var(--space-xsmall);box-sizing:border-box}.chat-empty-state__art{width:75%;max-width:200px;min-width:100px;flex-shrink:0}.chat-empty-state__art img{width:100%;height:auto;max-height:min(120px,22vh);object-fit:contain;display:block}.composer-prompt-stack{flex:1;min-width:0;min-height:0;align-self:stretch;display:flex;flex-direction:column;gap:var(--space-xsmall);cursor:text}.composer-input-wrap{position:relative;flex:1;min-width:0;min-height:88px;align-self:stretch;display:flex;flex-direction:column}.composer-typewriter-hint{position:absolute;left:0;right:0;top:0;padding:var(--space-medium) var(--space-large);font-family:inherit;font-size:14px;font-weight:400;line-height:1.4;color:var(--composer-placeholder);opacity:1;pointer-events:none;user-select:none;white-space:pre-wrap;word-break:break-word;text-align:left;z-index:2}.composer-input-wrap .input-field{position:relative;z-index:1;flex:1;min-height:88px;background:var(--composer-input-bg);color:var(--composer-input-text);border:1px solid rgba(0,0,0,.1);border-radius:18px;box-shadow:inset 0 1px 2px #0000000f,inset 0 0 0 1px #ffffff59}.composer-input-wrap .input-field::placeholder{color:var(--composer-placeholder);opacity:1}.composer-input-wrap .input-field:focus{border-color:#7a920080;box-shadow:inset 0 1px 2px #0000000f,0 0 0 2px #7a92002e;outline:none}.composer-inline-chips{display:flex;flex-wrap:wrap;gap:var(--space-xsmall);padding:0 0 var(--space-xsmall);width:100%;box-sizing:border-box}.composer-inline-chips--pulse{padding:var(--space-xsmall);margin:calc(-1 * var(--space-xsmall)) 0 0;border-radius:var(--border-radius-lg);outline:2px solid var(--composer-invite-sun-focus);outline-offset:2px;box-shadow:0 0 20px var(--composer-invite-sun-c)}.composer-inline-chips--pulse .composer-inline-chip{animation:composer-invite-chip-pulse 1.15s ease-in-out infinite}@keyframes composer-invite-chip-pulse{0%,to{border-color:#fff8dc73;box-shadow:0 0 0 0 var(--composer-invite-sun-b)}50%{border-color:#fffcebbf;box-shadow:0 0 10px 1px var(--composer-invite-sun-c)}}@media(prefers-reduced-motion:reduce){.composer-inline-chips--pulse .composer-inline-chip{animation:none}.composer-inline-chips--pulse{outline-width:2px}}.composer-inline-chip{max-width:100%;padding:var(--space-xxsmall) 7px;font:inherit;font-size:9px;line-height:1.25;color:var(--text-secondary);background:#7a92000f;border:1px solid rgba(122,146,0,.2);border-radius:999px;cursor:pointer;text-align:left}.composer-inline-chip:hover:not(:disabled){background:#7a92001a;border-color:#7a920059}.composer-inline-chip:disabled{opacity:.55;cursor:not-allowed}.composer-typewriter-caret{margin-left:1px;opacity:.75;animation:composer-caret-blink 1.4s step-end infinite}@keyframes composer-caret-blink{0%,to{opacity:1}50%{opacity:0}}@media(prefers-reduced-motion:reduce){.composer-typewriter-caret{animation:none;opacity:1}}.message-bubble{display:flex;flex-direction:column;max-width:100%;animation:fadeIn .22s ease-in}@keyframes fadeIn{0%{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}.message-user{align-items:flex-end}.message-ai{align-items:flex-start}.message-content{position:relative;padding:var(--space-medium) var(--space-large);border-radius:18px;font-size:14px;line-height:1.5;overflow-wrap:break-word;word-wrap:break-word;word-break:break-word;max-width:85%;box-shadow:0 2px 8px #0000000a;transition:background .12s ease,transform .12s ease}.message-user .message-content{background:linear-gradient(180deg,var(--chat-user-bubble-bg-top),var(--chat-user-bubble-bg-bottom));color:var(--chat-user-bubble-fg);text-align:left;border-radius:18px 18px var(--border-radius-small) 18px;margin-left:auto}.message-ai .message-content{background:var(--chat-ai-bubble-bg);color:var(--chat-ai-bubble-fg);text-align:left;border-radius:18px 18px 18px var(--border-radius-small);border:1px solid var(--chat-ai-bubble-border);margin-right:auto}.input-bar{flex-shrink:0;display:flex;flex-direction:column;gap:var(--space-xsmall);padding:var(--space-medium) var(--space-large) var(--space-medium) var(--space-large);padding-right:var(--space-large);border:1px solid rgba(0,0,0,.07);background:var(--composer-bar-bg);border-radius:24px;box-shadow:0 4px 20px #00000014;z-index:100}.input-bar.composer-dock{background:var(--composer-dock-bg);overflow:hidden;border:1px solid color-mix(in srgb,var(--primary-green) 22%,transparent);box-shadow:0 4px 18px #00000012;border-radius:var(--composer-dock-radius);padding-top:var(--space-xsmall);padding-left:var(--space-large);padding-right:var(--space-large);padding-bottom:var(--space-medium)}.composer-train-latest-hint{display:flex;align-items:flex-start;justify-content:space-between;gap:var(--space-small);padding:var(--space-xsmall) var(--space-small);margin-bottom:var(--space-xxsmall);font-size:12px;line-height:1.4;color:var(--neutral-600);background:color-mix(in srgb,var(--primary-50) 65%,var(--surface-default) 35%);border-radius:var(--border-radius-medium);border:1px solid color-mix(in srgb,var(--primary-green) 20%,transparent)}.composer-train-latest-hint-dismiss{flex-shrink:0;border:none;background:transparent;color:var(--neutral-500);font-size:18px;line-height:1;cursor:pointer;padding:0 var(--space-xxsmall);border-radius:var(--border-radius-small)}.composer-train-latest-hint-dismiss:hover{color:var(--text-headings)}.input-bar--busy{border-top:3px solid var(--primary-green);background:linear-gradient(180deg,var(--primary-50) 0%,var(--composer-bar-bg) 20px)}.input-bar.composer-dock.input-bar--busy{background:linear-gradient(180deg,var(--primary-50) 0%,var(--composer-dock-bg) 22px)}.composer-dock .composer-input-wrap .input-field{background:var(--composer-dock-bg);border-color:transparent;border-radius:var(--border-radius-large);box-shadow:none}.composer-dock .composer-input-wrap .input-field:focus{border-color:color-mix(in srgb,var(--primary-green) 22%,transparent);box-shadow:0 0 0 1px #ffffff47,0 0 0 2px color-mix(in srgb,var(--primary-green) 12%,transparent);outline:none}.token-usage-bar{flex-shrink:0;margin:0;padding:var(--space-small) var(--space-medium);background:var(--assistant-sidebar-bg);border:1px solid color-mix(in srgb,var(--primary-green) 22%,transparent);border-radius:var(--border-radius-lg);box-sizing:border-box}.token-usage-bar--embedded{background:transparent;border:none;border-radius:0;border-bottom:1px solid color-mix(in srgb,var(--primary-green) 18%,transparent);padding-inline:0;padding-block:var(--space-xsmall)}.token-usage-bar--collapsed{padding:var(--space-xsmall) var(--space-small)}.token-usage-bar--embedded.token-usage-bar--collapsed{padding-block:var(--space-xsmall);padding-inline:0}.token-usage-bar__header{display:flex;align-items:center;justify-content:space-between;gap:var(--space-small);margin-bottom:var(--space-xsmall)}.token-usage-bar__title{font-size:12px;font-weight:var(--font-weight-semibold);color:var(--text-headings)}.token-usage-bar__panel{display:flex;flex-direction:column;gap:var(--space-xsmall)}.token-usage-bar__track{height:6px;border-radius:999px;background:#00000014;overflow:hidden}.token-usage-bar__fill{height:100%;border-radius:999px;background:linear-gradient(90deg,var(--primary-green),#94a833);transition:width .35s ease,background .25s ease}.token-usage-bar__fill--warn{background:linear-gradient(90deg,#9a8b00,#c4a000)}.token-usage-bar__fill--high{background:linear-gradient(90deg,#b35c00,#c9781a)}.token-usage-bar__stats{margin:0;font-size:11px;line-height:1.35;color:var(--text-secondary)}.token-usage-bar__bonus-note{margin:0;font-size:11px;line-height:1.35;color:var(--text-secondary);font-style:italic}.token-usage-bar__reassurance{margin:0;font-size:11px;line-height:1.4;color:var(--text-body)}.token-usage-bar__earn-hint{margin:0 0 var(--space-xsmall);font-size:11px;line-height:1.45;color:var(--text-secondary)}.token-usage-bar__training-cta{align-self:flex-start;margin:var(--space-xxsmall) 0 0;padding:var(--space-xsmall) var(--space-medium);border:1px solid rgba(122,146,0,.45);border-radius:var(--border-radius-large);background:#7a920014;color:var(--text-headings);font-size:12px;font-weight:var(--font-weight-semibold);font-family:inherit;cursor:pointer}.token-usage-bar__training-cta:hover{background:#7a920024;border-color:#7a92008c}.token-usage-bar__training-cta:focus{outline:none;box-shadow:0 0 0 2px #7a920040}.token-usage-bar__collapse-toggle{display:flex;align-items:center;gap:var(--space-small);width:100%;margin:0;padding:var(--space-xsmall) var(--space-small);border:none;border-radius:var(--border-radius-large);background:transparent;cursor:pointer;font:inherit;color:var(--text-headings);text-align:left}.token-usage-bar__collapse-toggle:hover{background:#0000000d}.token-usage-bar__collapse-toggle--inline{width:auto;padding:var(--space-xxsmall);color:var(--header-title-color)}.token-usage-bar__collapsed-label{font-size:12px;font-weight:var(--font-weight-semibold);flex:1;min-width:0}.token-usage-bar__collapsed-metrics{display:flex;align-items:baseline;gap:var(--space-xsmall);flex-shrink:0}.token-usage-bar__collapsed-pct{font-size:12px;font-variant-numeric:tabular-nums;color:var(--primary-green)}.token-usage-bar__collapsed-used-word{font-size:11px;font-weight:var(--font-weight-semibold);color:var(--text-secondary)}.token-usage-bar__collapsed-bonus{font-size:10px;font-weight:var(--font-weight-semibold);padding:1px 5px;border-radius:999px;background:#7a92001f;color:var(--primary-green)}.token-usage-bar__collapsed-pct--muted{color:var(--text-secondary)}.assistant-busy-bar{flex-shrink:0;margin:0;padding:var(--space-small) var(--space-medium);background:var(--surface-page);border:1px solid rgba(122,146,0,.25);border-radius:var(--border-radius-lg);box-shadow:0 2px 10px #0000000f}.assistant-busy-bar-inner{display:flex;align-items:flex-start;gap:var(--space-small)}.assistant-busy-bar-spinner{flex-shrink:0;margin-top:var(--space-xxsmall)}.assistant-busy-bar-text{flex:1;min-width:0;display:flex;flex-direction:column;gap:var(--space-xsmall)}.assistant-busy-bar-primary{font-size:13px;font-weight:var(--font-weight-semibold);color:var(--text-headings);line-height:1.35}.assistant-busy-bar-tool{font-size:12px;color:var(--primary-green);line-height:1.35}.assistant-busy-bar-tier{font-size:12px;color:var(--text-secondary);line-height:1.4}@keyframes assistant-send-busy-pulse{0%,to{opacity:1}50%{opacity:.35}}.composer-send-btn--busy svg rect{animation:assistant-send-busy-pulse 1s ease-in-out infinite}.composer-toolbar{display:flex;flex-flow:row nowrap;align-items:center;gap:var(--space-xsmall);width:100%;min-height:28px;min-width:0;box-sizing:border-box;padding-block:var(--space-xsmall);overflow-x:auto;overflow-y:hidden;-webkit-overflow-scrolling:touch;scrollbar-width:thin}.composer-feedback-btn{flex-shrink:0;display:flex;align-items:center;justify-content:center;width:28px;height:28px;padding:0;border:none;border-radius:var(--border-radius-circle);background:transparent;color:var(--primary-green);cursor:pointer;transition:background .15s ease}.composer-feedback-btn:hover{background:#00000012}.input-bar .composer-toolbar .send-btn.composer-tool-btn:hover{background:#00000012;transform:none;opacity:1}.composer-toolbar-spacer{flex:1;min-width:4px;display:flex;align-items:center;justify-content:flex-end}.composer-toolbar-wave{flex-shrink:0;margin-right:var(--space-xxsmall)}.composer-toolbar-actions{display:flex;flex-flow:row nowrap;flex-shrink:0;align-items:center;gap:var(--space-small)}.composer-voice-agent-icon,.composer-dictation-icon{display:block;flex-shrink:0}.input-field{flex:0 1 auto;align-self:stretch;width:100%;min-width:0;min-height:var(--icon-size-medium);max-height:120px;box-sizing:border-box;padding:var(--space-medium) var(--space-large);border:none;border-radius:var(--border-radius-lg);font-size:14px;background:transparent;color:var(--text-body);font-family:inherit;resize:none;overflow-y:auto;line-height:1.4}.input-field:focus{outline:none}.input-field:disabled{opacity:.6;cursor:not-allowed}button.input-field.input-field-signin-prompt{display:block;width:100%;cursor:pointer;color:var(--neutral-500);opacity:1}button.input-field.input-field-signin-prompt:hover:not(:disabled){color:var(--text-body)}button.input-field.input-field-signin-prompt:disabled{opacity:.6;cursor:not-allowed}.composer-guest-signin{display:flex;flex-direction:column;align-self:stretch;width:100%;min-width:0;gap:var(--space-xsmall)}.composer-full-signin-link{align-self:flex-start;padding:0;margin:0 0 0 var(--space-xxsmall);border:none;background:none;font-size:12px;font-weight:var(--font-weight-semibold);color:#7a9200;cursor:pointer;font-family:inherit;text-decoration:underline;text-underline-offset:2px}.composer-full-signin-link:hover:not(:disabled){color:var(--header-title-color)}.composer-full-signin-link:disabled{opacity:.6;cursor:not-allowed}.send-btn{padding:0;width:28px;height:28px;border-radius:var(--border-radius-large);border:none;background:transparent;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all .2s ease}.send-btn:hover{transform:translateY(-1px);opacity:.9}.send-btn.composer-tool-btn{width:28px;height:28px;border-radius:var(--border-radius-large)}.send-btn.composer-send-btn{width:28px;height:28px;border-radius:var(--border-radius-large);margin-inline-start:var(--space-small);flex-shrink:0}.starter-prompt-cluster{margin:0 auto}.starter-prompt-cluster--pulse{padding:var(--space-xsmall);margin:calc(-1 * var(--space-xsmall)) auto;border-radius:var(--border-radius-lg);outline:2px solid rgba(122,146,0,.45);outline-offset:2px}@keyframes starter-prompt-chip-pulse{0%,to{border-color:#7a920059;box-shadow:0 0 #7a920033}50%{border-color:#7a9200bf;box-shadow:0 0 0 3px #7a92001f}}.starter-prompt-cluster--pulse .starter-prompt-chip{animation:starter-prompt-chip-pulse 1.15s ease-in-out infinite}@media(prefers-reduced-motion:reduce){.starter-prompt-cluster--pulse .starter-prompt-chip{animation:none}.starter-prompt-cluster--pulse{outline-width:3px}}.starter-prompt-chip{font:inherit;font-size:11px;line-height:1.25;color:var(--header-title-color);background:var(--primary-50);border:1px solid rgba(122,146,0,.35);border-radius:999px;padding:5px 9px;cursor:pointer;text-align:center;max-width:100%;transition:background .15s ease,border-color .15s ease}.starter-prompt-chip:hover{background:#e8ecd4;border-color:#7a92008c}.starter-prompt-chip:active{background:#dde2c8}.message-content p{margin:0 0 var(--space-small) 0}.message-content p:last-child{margin-bottom:0}.message-content ul,.message-content ol{margin:var(--space-xsmall) 0 var(--space-small) 0;padding-left:20px}.message-content pre{background:#0000000f;padding:var(--space-medium);border-radius:var(--border-radius-medium);overflow-x:auto}.message-content code{background:#0000000f;padding:var(--space-xxsmall) var(--space-xsmall);border-radius:var(--border-radius-small)}.signed-in-banner{display:flex;align-items:center;justify-content:space-between;background-color:var(--primary-50);padding:var(--space-small) var(--space-large);border-radius:var(--border-radius-lg);margin-bottom:var(--space-small);animation:slideDown .3s ease-out}@keyframes slideDown{0%{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}.banner-content{display:flex;gap:var(--space-small);align-items:center;font-size:12px}.banner-label{color:var(--neutral-500)}.banner-email{color:gray;text-decoration:underline;cursor:pointer}.banner-close{background:none;border:none;color:#999;cursor:pointer;padding:var(--space-xsmall);display:flex;align-items:center;justify-content:center;border-radius:var(--border-radius-circle);transition:background .2s}.banner-close:hover{background:#0000000d;color:#666}.ai-response-container{width:100%;padding:var(--space-xsmall) 0 var(--space-small) 0;color:var(--chat-ai-fg);line-height:1.6;font-size:14px;animation:fadeIn .22s ease-in}.markdown-body{font-family:Geist,system-ui,-apple-system,sans-serif}.markdown-body p{margin-bottom:var(--space-medium)}.markdown-body h1,.markdown-body h2,.markdown-body h3,.markdown-body h4{font-weight:var(--font-weight-semibold);margin-top:var(--space-large);margin-bottom:var(--space-small);color:var(--chat-ai-heading-fg)}.markdown-body ul,.markdown-body ol{padding-left:20px;margin-bottom:var(--space-medium)}.markdown-body li{margin-bottom:var(--space-xsmall)}.markdown-body code{font-family:monospace;background-color:var(--chat-ai-code-bg);color:var(--chat-ai-code-fg);padding:var(--space-xxsmall) var(--space-xsmall);border-radius:var(--border-radius-small);font-size:.9em}.markdown-body pre{background-color:var(--chat-ai-pre-bg);color:var(--chat-ai-pre-fg);padding:var(--space-medium);border-radius:var(--border-radius-medium);overflow-x:auto;margin-bottom:var(--space-medium)}.markdown-body pre code{background-color:transparent;color:inherit;padding:0}.markdown-body a{color:var(--primary-green);text-decoration:none}.markdown-body a:hover{text-decoration:underline}.markdown-body blockquote{border-left:3px solid var(--primary-green);margin:0 0 var(--space-medium) 0;padding-left:var(--space-medium);color:var(--chat-ai-muted-fg)}.markdown-body.capabilities-markdown ul{list-style-type:disc;padding-left:1.25em}.markdown-body.capabilities-markdown li{margin-bottom:var(--space-xsmall)}.markdown-body.capabilities-markdown :not(pre)>code{background-color:var(--chat-ai-code-bg);color:var(--chat-ai-code-fg);padding:.12em .4em;border-radius:6px;font-size:.88em}.markdown-body.capabilities-markdown a{font-weight:var(--font-weight-semibold)}.feedback-container{margin-top:var(--space-xsmall);width:100%;animation:fadeIn .22s ease-in}.capabilities-overview-stack{display:flex;flex-direction:column;gap:var(--space-small);max-width:85%;align-self:flex-start}.capabilities-overview-stack .capabilities-block{margin:0;max-width:100%}.ai-message-wrapper{display:flex;flex-direction:column;width:100%;position:relative}.feedback-options{display:flex;align-items:center;flex-wrap:wrap;gap:var(--space-xsmall);color:var(--neutral-500);font-size:11px;opacity:.92;transition:opacity .2s ease;margin-left:var(--space-xsmall);min-height:var(--size-item-medium)}.feedback-train-hover-zone{display:inline-flex;align-items:center;flex-wrap:wrap;gap:var(--space-small);position:relative;max-width:100%}.feedback-train-row{display:inline-flex;align-items:center;flex-wrap:nowrap;gap:var(--space-small);max-width:100%}.feedback-train-hover-group{display:inline-flex;align-items:center}.feedback-train-label-pill{display:inline-flex;align-items:center;justify-content:center;box-sizing:border-box;padding:var(--space-xxsmall) var(--space-small);border-radius:999px;border:1px solid color-mix(in srgb,var(--surface-default) 70%,rgba(0,0,0,.12) 30%);background:color-mix(in srgb,var(--surface-default) 88%,var(--neutral-500) 12%)}.feedback-train-actions{display:inline-flex;align-items:center;gap:var(--space-xxsmall)}.feedback-train-hover-zone .training-hint-bubble{margin-left:0}.feedback-train-hover-group.feedback-train-badge{border-radius:999px;background:color-mix(in srgb,var(--surface-default) 88%,var(--neutral-500) 12%);border:1px solid color-mix(in srgb,var(--surface-default) 70%,rgba(0,0,0,.12) 30%);box-sizing:border-box;box-shadow:0 0 0 1px color-mix(in srgb,var(--primary-green) 12%,transparent),0 2px 14px color-mix(in srgb,var(--primary-green) 16%,transparent);transition:box-shadow .2s ease,border-color .2s ease}.feedback-train-hover-group.feedback-train-badge:hover{box-shadow:0 0 0 1px color-mix(in srgb,var(--primary-green) 22%,transparent),0 3px 18px color-mix(in srgb,var(--primary-green) 22%,transparent)}.feedback-train-hover-group.feedback-train-badge:focus-within{box-shadow:0 0 0 2px color-mix(in srgb,var(--primary-green) 35%,transparent),0 3px 20px color-mix(in srgb,var(--primary-green) 26%,transparent)}.feedback-train-badge{display:inline-flex;align-items:center;gap:var(--space-xsmall);padding:var(--space-xxsmall) var(--space-xsmall);border-radius:999px;box-sizing:border-box}.feedback-training-learn-btn{background:none;border:none;color:var(--neutral-500);cursor:pointer;padding:var(--space-xxsmall);min-width:28px;min-height:28px;display:inline-flex;align-items:center;justify-content:center;border-radius:var(--border-radius-circle)}.feedback-training-learn-btn svg{display:block;line-height:0}.feedback-training-learn-btn:hover{background:color-mix(in srgb,var(--surface-default) 60%,rgba(0,0,0,.06) 40%)}.feedback-training-learn-btn:focus-visible{outline:none}.feedback-train-badge .feedback-btn{border-radius:var(--border-radius-circle);min-width:28px;min-height:28px}.feedback-train-badge .feedback-btn:hover{background:color-mix(in srgb,var(--surface-default) 60%,rgba(0,0,0,.06) 40%)}.feedback-train-badge .feedback-btn:focus-visible{outline:none}.feedback-train-label{font-size:12px;line-height:1.25;letter-spacing:.01em;color:var(--neutral-500);font-weight:var(--font-weight-semibold)}.feedback-label-stack{display:flex;flex-direction:column;gap:var(--space-xxsmall);min-width:0;flex:1}.feedback-label-sub{font-size:10px;line-height:1.35;color:var(--neutral-500);font-weight:400}.ai-message-wrapper:hover .feedback-options{opacity:1}.feedback-btn{background:none;border:none;color:var(--neutral-500);cursor:pointer;padding:var(--space-xxsmall);display:flex;align-items:center;justify-content:center;border-radius:var(--border-radius-small);transition:all .2s;flex-shrink:0}.feedback-btn:hover{background:#0000000d;color:var(--text-body)}.training-hint-bubble{margin-left:var(--space-xsmall);display:inline-flex;align-items:center;gap:var(--space-xsmall);max-width:280px;padding:var(--space-xxsmall) var(--space-small);border-radius:var(--border-radius-large);border:1px solid rgba(122,146,0,.25);background:#f8faf2f2;color:var(--text-secondary);line-height:1.3;animation:trainingHintIn .22s ease-out}.training-hint-bubble--promo{border-color:color-mix(in srgb,var(--primary-green) 42%,rgba(122,146,0,.22));background:linear-gradient(145deg,color-mix(in srgb,var(--surface-default) 72%,var(--primary-green) 28%),color-mix(in srgb,var(--surface-page) 90%,var(--primary-green) 10%));box-shadow:0 0 0 1px color-mix(in srgb,var(--primary-green) 20%,transparent),0 2px 18px color-mix(in srgb,var(--primary-green) 18%,transparent);color:var(--text-body);padding:var(--space-xsmall) var(--space-small);animation:trainingHintPromoIn .28s ease-out}.training-hint-bubble--promo .training-hint-bubble__amount{font-weight:var(--font-weight-semibold);color:var(--text-headings);font-variant-numeric:tabular-nums}.feedback-train-earn-hover-hint{margin-left:var(--space-small);max-width:min(240px,42vw);font-size:11px;line-height:1.35;color:var(--neutral-500);opacity:0;visibility:hidden;transition:opacity .2s ease,visibility .2s ease}.feedback-train-hover-zone:hover .feedback-train-earn-hover-hint,.feedback-train-hover-zone:focus-within .feedback-train-earn-hover-hint{opacity:1;visibility:visible}.training-hint-close{border:none;background:transparent;color:var(--neutral-500);padding:0;width:var(--size-item-small);height:var(--size-item-small);border-radius:var(--border-radius-circle);cursor:pointer;line-height:1;display:inline-flex;align-items:center;justify-content:center}.training-hint-close:hover{background:#0000000d;color:var(--text-body)}@keyframes trainingHintIn{0%{opacity:0;transform:translateY(2px)}to{opacity:1;transform:translateY(0)}}@keyframes trainingHintPromoIn{0%{opacity:0;transform:translateY(3px) scale(.98)}to{opacity:1;transform:translateY(0) scale(1)}}@media(max-width:420px){.training-hint-bubble{max-width:210px}.feedback-train-earn-hover-hint{max-width:min(200px,55vw)}}.feedback-overlay{position:fixed;inset:0;z-index:20000;display:flex;align-items:center;justify-content:center;padding:var(--space-large);box-sizing:border-box;background:#00000073}.feedback-overlay-dialog{width:100%;max-width:460px;max-height:min(90vh,640px);min-height:0;overflow:hidden;background:var(--surface-page);border-radius:var(--border-radius-lg);padding:var(--space-large);display:flex;flex-direction:column;gap:var(--space-small);box-shadow:0 12px 40px #0000002e;border:1px solid rgba(0,0,0,.06);box-sizing:border-box}.feedback-dialog-header-block{flex-shrink:0;display:flex;flex-direction:column;gap:var(--space-small);position:relative;z-index:2}.feedback-training-info-anchor{display:flex;align-items:center}.feedback-training-info-btn{background:none;border:none;padding:var(--space-xxsmall);border-radius:var(--border-radius-circle);color:var(--neutral-500);cursor:pointer;display:flex;align-items:center;justify-content:center}.feedback-training-info-btn:hover{background:#0000000f;color:var(--primary-green)}.feedback-training-info-btn[aria-expanded=true]{color:var(--primary-green)}.feedback-training-info-popover{width:100%;max-width:100%;box-sizing:border-box;flex-shrink:0;padding:var(--space-small);background:var(--surface-page);border:1px solid color-mix(in srgb,var(--text-body) 14%,transparent);border-radius:var(--border-radius-large);box-shadow:0 10px 28px #00000024;z-index:20}.feedback-training-info-popover__p{margin:0 0 var(--space-xsmall);font-size:11px;line-height:1.45;color:var(--text-body)}.feedback-training-timeline{padding:0;min-width:0}.feedback-training-timeline__list{list-style:none;margin:0;padding:0;display:flex;flex-direction:row;align-items:stretch;justify-content:space-between;gap:var(--space-xxsmall)}.feedback-training-timeline__item{position:relative;flex:1;min-width:0;display:flex;flex-direction:column;align-items:center;gap:4px;padding:0 var(--space-xxsmall)}.feedback-training-timeline__item:not(:last-child){border-right:1px solid color-mix(in srgb,var(--text-body) 12%,transparent)}.feedback-training-timeline__dot{flex-shrink:0;width:8px;height:8px;border-radius:50%;box-sizing:border-box;background:var(--surface-page);border:2px solid color-mix(in srgb,var(--text-body) 22%,transparent)}.feedback-training-timeline__item--done .feedback-training-timeline__dot{background:color-mix(in srgb,var(--primary-green) 35%,var(--surface-page));border-color:var(--primary-green)}.feedback-training-timeline__label{font-size:11px;font-weight:600;line-height:1.2;text-align:center;color:var(--text-secondary)}.feedback-training-timeline__item--done .feedback-training-timeline__label{color:var(--primary-green)}.feedback-detail-field{flex-shrink:0;display:flex;flex-direction:column;gap:var(--space-xsmall);padding:var(--space-small);border-radius:var(--border-radius-large);background:color-mix(in srgb,var(--surface-default) 88%,var(--primary-green) 12%);border:1px solid color-mix(in srgb,var(--primary-green) 18%,transparent);box-sizing:border-box}.feedback-detail-field__label{font-size:12px;font-weight:var(--font-weight-semibold);color:var(--text-headings)}.feedback-char-meter__track{height:6px;border-radius:999px;background:color-mix(in srgb,var(--text-body) 10%,var(--surface-page));overflow:hidden}.feedback-char-meter__fill{height:100%;border-radius:999px;background:linear-gradient(90deg,color-mix(in srgb,var(--primary-green) 75%,#5a6a20),var(--primary-green));transition:width .15s ease-out}@media(prefers-reduced-motion:reduce){.feedback-char-meter__fill{transition:none}}.feedback-char-meter__text{margin:4px 0 0;font-size:11px;font-weight:600;color:var(--text-secondary);text-align:right}.feedback-pricing-link{margin:0;padding:0;border:none;background:none;font:inherit;font-size:11px;font-weight:var(--font-weight-semibold);color:var(--primary-green);cursor:pointer;text-decoration:underline;text-underline-offset:2px}.feedback-pricing-link:hover{opacity:.88}.feedback-pricing-link:focus-visible{outline:2px solid var(--primary-green);outline-offset:2px;border-radius:var(--border-radius-xsmall)}.feedback-dialog-scroll{flex:1;min-height:0;overflow-y:auto;display:flex;flex-direction:column;gap:var(--space-small);padding-right:var(--space-xxsmall);margin-right:calc(-1 * var(--space-xxsmall))}.feedback-context-card{display:flex;flex-direction:column;gap:var(--space-xsmall);padding:var(--space-small);border-radius:var(--border-radius-medium);background:var(--surface-default);border:1px solid rgba(0,0,0,.06);box-sizing:border-box}.feedback-context-card .feedback-context-section{gap:var(--space-xxsmall)}.feedback-context-card .feedback-context-block{background:var(--surface-page);max-height:100px}.feedback-context-section{display:flex;flex-direction:column;gap:var(--space-xxsmall);min-width:0}.feedback-context-label{font-size:11px;font-weight:var(--font-weight-semibold);letter-spacing:.03em;text-transform:uppercase;color:var(--text-secondary)}.feedback-context-block{margin:0;max-height:120px;overflow:auto;padding:var(--space-small);border-radius:var(--border-radius-medium);background:var(--surface-default);border:1px solid rgba(0,0,0,.06);font-size:12px;line-height:1.45;color:var(--text-body);white-space:pre-wrap;word-break:break-word;font-family:inherit}.feedback-context-hint{font-size:11px;color:var(--neutral-500);width:100%}.feedback-badges--optional{flex-direction:column;align-items:flex-start;gap:var(--space-xsmall)}.feedback-badges-inner{display:flex;flex-wrap:wrap;gap:var(--space-xsmall);width:100%}.feedback-overlay-thanks{padding:var(--space-large) var(--space-medium);text-align:center;flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:var(--space-xsmall)}.feedback-overlay-thanks-text{margin:0;font-size:15px;color:var(--primary-green)}.feedback-overlay-thanks-bonus{margin:0;max-width:320px;font-size:12px;line-height:1.45;color:var(--text-secondary)}.feedback-overlay-thanks .feedback-pricing-link{font-size:12px}@media(prefers-reduced-motion:reduce){.feedback-overlay-thanks{animation:feedbackThanksSoft .55s ease-out 1}}@keyframes feedbackThanksSoft{0%{opacity:.65}to{opacity:1}}.feedback-header{display:flex;justify-content:space-between;align-items:center;gap:var(--space-small);color:var(--text-headings);font-size:14px;font-weight:var(--font-weight-semibold)}.feedback-header-trailing{display:flex;align-items:center;gap:var(--space-xxsmall);flex-shrink:0}.feedback-header #feedback-dialog-title{flex:1;min-width:0;line-height:1.35}.feedback-badges-lead{margin:0;font-size:11px;font-weight:var(--font-weight-semibold);letter-spacing:.03em;text-transform:uppercase;color:var(--text-secondary)}.feedback-validation-slot{flex-shrink:0;min-height:2.85rem;padding:var(--space-xsmall) 0;box-sizing:border-box}.feedback-validation-hint{margin:0;padding:var(--space-xsmall) var(--space-small);font-size:12px;color:#b45309;line-height:1.45;background:color-mix(in srgb,#ffedd5 55%,var(--surface-page));border:1px solid color-mix(in srgb,#b45309 28%,transparent);border-radius:var(--border-radius-medium);box-sizing:border-box}.feedback-close-btn{background:none;border:none;color:var(--neutral-500);cursor:pointer;padding:var(--space-small);border-radius:var(--border-radius-circle);display:flex}.feedback-close-btn:hover{background:#0000000d}.feedback-badges{display:flex;flex-wrap:wrap;gap:var(--space-xsmall)}.feedback-badge{background:color-mix(in srgb,var(--surface-default) 82%,var(--primary-green) 8%);border:1px solid color-mix(in srgb,var(--text-body) 18%,transparent);padding:5px var(--space-small);border-radius:var(--border-radius-large);font-size:11px;line-height:1.25;font-weight:var(--font-weight-semibold);color:var(--text-headings);cursor:pointer;display:flex;align-items:center;gap:4px;transition:border-color .15s ease,box-shadow .15s ease,background .15s ease;box-shadow:0 1px 2px #0000000d}.feedback-badge:hover{border-color:color-mix(in srgb,var(--primary-green) 42%,transparent);box-shadow:0 1px 4px #7a92001a}.feedback-badge:focus-visible{outline:2px solid var(--primary-green);outline-offset:2px}.feedback-badge.selected{background:var(--primary-50);border-color:var(--primary-green);color:var(--primary-green);box-shadow:0 1px 5px #7a92001f}@media(prefers-reduced-motion:reduce){.feedback-badge{transition:none}}.feedback-textarea{width:100%;min-height:88px;padding:var(--space-medium);border:1px solid color-mix(in srgb,var(--text-body) 16%,transparent);border-radius:var(--border-radius-large);font-size:13px;line-height:1.45;font-family:inherit;resize:vertical;box-sizing:border-box;background:var(--surface-page);color:var(--text-headings)}.feedback-textarea:focus{outline:none;border-color:var(--primary-green);box-shadow:0 0 0 2px color-mix(in srgb,var(--primary-green) 22%,transparent)}.feedback-footer{display:flex;justify-content:flex-end;flex-shrink:0;padding-top:var(--space-small);margin-top:auto;border-top:1px solid rgba(0,0,0,.06)}.feedback-submit-btn{background:var(--primary-green);color:#fff;border:none;padding:var(--space-xsmall) var(--space-medium);border-radius:64px;font-size:14px;font-weight:var(--font-weight-semibold);cursor:pointer;transition:opacity .2s ease}.feedback-submit-btn:hover{opacity:.92}@media(prefers-reduced-motion:reduce){.feedback-submit-btn{transition:none}}.feedback-submit-btn--muted{opacity:1;cursor:not-allowed;background:color-mix(in srgb,var(--primary-green) 32%,var(--surface-default));color:color-mix(in srgb,white 55%,var(--text-body));box-shadow:none}.feedback-submit-btn--muted:hover{opacity:1;background:color-mix(in srgb,var(--primary-green) 32%,var(--surface-default))}.feedback-submitted{padding:var(--space-medium);background:var(--primary-50);color:var(--primary-green);border-radius:12px;font-size:14px;text-align:center;margin-top:var(--space-small);display:flex;flex-direction:column;align-items:center;gap:var(--space-xsmall)}.feedback-submitted-line{font-weight:var(--font-weight-semibold)}.feedback-submitted-bonus{font-size:12px;font-weight:400;color:var(--text-secondary);line-height:1.4}.feedback-submitted .feedback-pricing-link{font-size:12px;color:var(--primary-green)}.training-gallery-overlay{position:fixed;inset:0;z-index:21000;display:flex;align-items:center;justify-content:center;padding:var(--space-large);background:#00000073}.training-gallery-dialog{width:min(520px,100%);max-height:min(90vh,760px);overflow-y:auto;display:flex;flex-direction:column;gap:var(--space-medium);background:var(--surface-page);border-radius:var(--border-radius-lg);border:1px solid rgba(0,0,0,.08);box-shadow:0 18px 48px #0003;padding:var(--space-large);box-sizing:border-box}.training-gallery-fetch-err{margin:0;font-size:13px;line-height:1.45;color:var(--neutral-600)}.training-gallery-head{display:flex;align-items:center;justify-content:space-between;gap:var(--space-small)}.training-gallery-head h2{margin:0;font-size:18px;color:var(--text-headings)}.training-gallery-close{border:none;background:transparent;color:var(--neutral-500);font-size:20px;line-height:1;width:28px;height:28px;border-radius:var(--border-radius-circle);display:inline-flex;align-items:center;justify-content:center;cursor:pointer}.training-gallery-close:hover{background:#0000000d;color:var(--text-body)}.training-gallery-stats{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:var(--space-small)}.training-gallery-streak-note{margin:0;font-size:11px;line-height:1.45;color:var(--text-secondary)}.training-gallery-footer-hint{margin:0;font-size:11px;line-height:1.45;color:var(--text-secondary);padding-top:var(--space-xsmall);border-top:1px solid rgba(0,0,0,.06)}.training-stat-card{background:var(--surface-default);border:1px solid rgba(0,0,0,.06);border-radius:var(--border-radius-medium);padding:var(--space-small);display:flex;flex-direction:column;gap:var(--space-xxsmall)}.training-stat-label{font-size:11px;color:var(--text-secondary);text-transform:uppercase;letter-spacing:.03em}.training-stat-value{font-size:16px;color:var(--text-headings)}.training-gallery-milestones{display:flex;flex-direction:column;gap:var(--space-small)}.training-milestone-card{background:#f9fbf4;border:1px solid #d8e3c0;border-radius:var(--border-radius-medium);padding:var(--space-small);display:flex;flex-direction:column;gap:var(--space-xsmall)}.training-milestone-row{display:flex;align-items:center;justify-content:space-between;gap:var(--space-small);font-size:12px;color:var(--text-body)}.training-progress-track{width:100%;height:7px;border-radius:999px;background:#d9e4c2;overflow:hidden}.training-progress-fill{display:block;height:100%;background:linear-gradient(90deg,#7a9200,#a6c03e)}.training-gallery-badges h3{margin:0 0 var(--space-small);font-size:14px;color:var(--text-headings)}.training-badge-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--space-small)}.training-badge-card{display:flex;gap:var(--space-small);align-items:flex-start;border-radius:var(--border-radius-medium);border:1px solid #e5ebd4;background:#fafcf6;padding:var(--space-small);opacity:.7}.training-badge-card--earned{opacity:1;border-color:#c9dba4;box-shadow:0 0 0 1px #7a920014}.training-badge-icon{width:30px;height:30px;border-radius:var(--border-radius-circle);background:#dce8be;color:#536600;font-size:11px;font-weight:var(--font-weight-semibold);display:flex;align-items:center;justify-content:center;flex-shrink:0}.training-badge-copy{display:flex;flex-direction:column;gap:var(--space-xxsmall);min-width:0}.training-badge-copy strong{font-size:12px;color:var(--text-headings)}.training-badge-copy p{margin:0;font-size:11px;color:var(--text-body);line-height:1.35}.training-badge-copy span{font-size:10px;color:#6e7f4d}@media(max-width:430px){.training-gallery-stats,.training-badge-grid{grid-template-columns:1fr}}.wave-bar{animation:wave-pulse 1.2s ease-in-out infinite}@keyframes wave-pulse{0%,to{height:8px}50%{height:18px}}.voice-agent-overlay{position:fixed;inset:0;z-index:20000;display:flex;flex-direction:column;background:linear-gradient(170deg,#1a1f0e,#0f1208 40%,#161b0d);animation:va-fade-in .3s ease-out;transition:box-shadow .35s ease,background .35s ease}.voice-agent-overlay-phase-idle{box-shadow:inset 0 0 80px #7a92000a}.voice-agent-overlay-phase-you{box-shadow:inset 0 0 100px #7a92001f}.voice-agent-overlay-phase-assistant{box-shadow:inset 0 0 90px #c8b46414}@keyframes va-fade-in{0%{opacity:0}to{opacity:1}}.voice-agent-close{position:absolute;top:var(--space-large);right:var(--space-large);z-index:20001;background:#ffffff14;border:1px solid rgba(255,255,255,.1);color:#ffffffb3;width:40px;height:40px;border-radius:var(--border-radius-circle);display:flex;align-items:center;justify-content:center;cursor:pointer;transition:all .2s}.voice-agent-close:hover{background:#ffffff26;color:#fff}.voice-input-push-hint{box-sizing:border-box;width:100%;padding:var(--space-small) 10px 6px;margin-bottom:var(--space-xsmall);font-size:12px;line-height:1.4;color:var(--text-body, #2f3a20);background:#7a92001a;border-radius:var(--border-radius-md, var(--border-radius-medium));border:1px solid rgba(122,146,0,.25)}.voice-input-push-hint-sub{display:block;margin-top:6px;font-size:11px;line-height:1.35;color:var(--text-secondary, #5b6b4b)}.voice-input-code-hint{font-size:10px;word-break:break-all}.voice-agent-content{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:48px var(--space-xlarge) 0;overflow-y:auto;gap:var(--space-medium);min-height:0}.voice-aura-wrap{width:100%;max-width:420px;min-height:200px;display:flex;align-items:center;justify-content:center}.voice-aura-canvas{display:block;width:100%;height:200px}.voice-agent-recording-pill{font-size:12px;font-weight:var(--font-weight-semibold);letter-spacing:.12em;text-transform:uppercase;color:#b4dc78f2;padding:6px 14px;border-radius:999px;border:1px solid rgba(122,146,0,.45);background:#7a92001f;animation:va-rec-pulse 1.2s ease-in-out infinite}@keyframes va-rec-pulse{0%,to{opacity:.85}50%{opacity:1}}.voice-agent-recording-pill-active{border-color:#c8dc8ca6;background:#7a920038;color:#e6f5c8fa}.voice-agent-transcript{max-width:340px;text-align:center;font-size:16px;line-height:1.6;animation:va-text-in .3s ease-out;max-height:200px;overflow-y:auto;scrollbar-width:none}.voice-agent-transcript::-webkit-scrollbar{display:none}@keyframes va-text-in{0%{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}.voice-agent-user-text{color:#ffffff80;font-size:14px}.voice-agent-assistant-text{color:#ffffffe6;font-size:16px;font-weight:400}.voice-agent-error{color:#e57373;font-size:14px}.voice-agent-error-row{display:flex;flex-direction:column;align-items:center;gap:var(--space-small);max-width:340px}.voice-agent-error-dismiss{background:#ffffff14;border:1px solid rgba(255,255,255,.15);color:#ffffffbf;font-size:12px;padding:6px var(--space-medium);border-radius:999px;cursor:pointer}.voice-agent-error-dismiss:hover{background:#ffffff24;color:#fff}.voice-agent-echo-hint{display:flex;flex-wrap:wrap;align-items:center;justify-content:center;gap:10px;max-width:320px;padding:10px 14px;font-size:13px;line-height:1.45;color:#ffffff8c;text-align:center;border-radius:12px;border:1px solid rgba(122,146,0,.35);background:#7a92001a}.voice-agent-echo-hint-dismiss{background:transparent;border:none;color:#b4dc78f2;font-size:12px;font-weight:var(--font-weight-semibold);text-decoration:underline;cursor:pointer;padding:0}.voice-agent-capture-toggle{display:flex;flex-wrap:wrap;align-items:center;justify-content:center;gap:var(--space-small);margin-bottom:var(--space-xsmall)}.voice-agent-capture-label{font-size:11px;font-weight:var(--font-weight-semibold);letter-spacing:.14em;text-transform:uppercase;color:#ffffff59;width:100%;text-align:center}.voice-agent-capture-option{background:#ffffff0f;border:1px solid rgba(255,255,255,.12);color:#ffffffa6;font-size:13px;padding:var(--space-small) var(--space-large);border-radius:999px;cursor:pointer;transition:background .15s,border-color .15s,color .15s}.voice-agent-capture-option:hover{background:#ffffff1a;color:#ffffffd9}.voice-agent-capture-option-active{border-color:#7a9200a6;background:#7a920038;color:#e6f5c8fa}.voice-agent-bottom{display:flex;flex-direction:column;align-items:center;gap:20px;padding:0 var(--space-xlarge) 48px}.voice-agent-status-block{display:flex;flex-direction:column;align-items:center;gap:6px;max-width:280px;text-align:center}.voice-agent-status{color:#ffffffeb;font-size:15px;font-weight:var(--font-weight-semibold);letter-spacing:.02em}.voice-agent-hint{color:#ffffff73;font-size:14px;line-height:1.45;font-weight:400}.voice-agent-orb{width:80px;height:80px;border-radius:var(--border-radius-circle);border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;position:relative;background:radial-gradient(circle at 35% 35%,#a3b82e,#7a9200 60%,#5a6e00);color:#fff;box-shadow:0 0 30px #7a920040,0 0 60px #7a92001a;transition:transform .2s,box-shadow .2s;-webkit-tap-highlight-color:transparent;touch-action:none;user-select:none}.voice-agent-orb:hover{transform:scale(1.05)}.voice-agent-orb:active,.voice-agent-orb-listening{transform:scale(.95)}.voice-agent-orb-listening{animation:va-pulse 1.5s ease-in-out infinite;box-shadow:0 0 40px #7a920066,0 0 80px #7a920033}@keyframes va-pulse{0%,to{box-shadow:0 0 30px #7a920066,0 0 60px #7a920026}50%{box-shadow:0 0 50px #7a920099,0 0 100px #7a920040}}.voice-agent-orb-busy{opacity:.85;cursor:pointer;animation:va-spin-glow 2s linear infinite}@keyframes va-spin-glow{0%,to{box-shadow:0 0 30px #7a920033}50%{box-shadow:0 0 45px #7a920059}}.voice-agent-orb-speaking{animation:va-speak-pulse .8s ease-in-out infinite}@keyframes va-speak-pulse{0%,to{transform:scale(1)}50%{transform:scale(1.06)}}.voice-agent-orb:disabled{cursor:pointer}.voice-agent-orb-icon{pointer-events:none}html[data-oasis-theme=neutral-light]{color-scheme:light;--surface-default: #f1f5f9;--surface-page: #ffffff;--primary-green: #2563eb;--assistant-sidebar-bg: color-mix(in srgb, var(--surface-default) 94%, var(--primary-green) 6%);--primary-light: #f8fafc;--primary-50: #e2e8f0;--text-body: #475569;--text-headings: #0f172a;--text-secondary: #334155;--neutral-500: #64748b;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--assistant-sidebar-bg);--composer-invite-sun-a: rgba(219, 234, 254, .55);--composer-invite-sun-b: rgba(255, 255, 255, .35);--composer-invite-sun-c: rgba(191, 219, 254, .4);--composer-invite-sun-focus: rgba(239, 246, 255, .85);--composer-input-bg: color-mix(in srgb, var(--surface-default) 82%, #1e3a5f 12%);--composer-input-text: #0f172a;--composer-placeholder: #64748b;--header-title-color: var(--text-headings);--header-badge-bg: var(--primary-50);--header-badge-text: var(--text-headings);--dropdown-surface: var(--surface-page);--dropdown-border-color: #e2e8f0;--dropdown-header-bg: #f8fafc;--dropdown-muted-text: #64748b;--dropdown-item-text: var(--text-headings);--dropdown-item-hover: #f1f5f9;--icon-accent-color: var(--primary-green);--icon-accent-hover-bg: color-mix(in srgb, var(--primary-green) 14%, transparent);--neutral-600: #64748b;--chat-ai-fg: var(--text-body);--chat-ai-heading-fg: var(--text-headings);--chat-ai-muted-fg: #64748b;--chat-ai-code-bg: rgba(15, 23, 42, .08);--chat-ai-code-fg: var(--text-headings);--chat-ai-pre-bg: #f1f5f9;--chat-ai-pre-fg: #0f172a;--chat-ai-bubble-bg: var(--surface-page);--chat-ai-bubble-fg: var(--chat-ai-fg);--chat-ai-bubble-border: color-mix(in srgb, var(--text-headings) 10%, transparent);--chat-user-bubble-bg-top: #e2e8f0;--chat-user-bubble-bg-bottom: #cbd5e1;--chat-user-bubble-fg: #0f172a}html[data-oasis-theme=forest-dark]{color-scheme:dark;--surface-default: #1a2218;--surface-page: #243020;--primary-green: #9ccc65;--assistant-sidebar-bg: color-mix(in srgb, var(--surface-default) 88%, var(--primary-green) 12%);--primary-light: #2d3b28;--primary-50: #2f3d29;--text-body: #c5d1c0;--text-headings: #eef5ea;--text-secondary: #b8c9b0;--neutral-500: #8a9a84;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--assistant-sidebar-bg);--composer-invite-sun-a: rgba(156, 204, 101, .18);--composer-invite-sun-b: rgba(255, 255, 255, .06);--composer-invite-sun-c: rgba(156, 204, 101, .12);--composer-invite-sun-focus: rgba(156, 204, 101, .28);--composer-input-bg: color-mix(in srgb, var(--surface-page) 75%, #0d120b 25%);--composer-input-text: #eef5ea;--composer-placeholder: #8a9a84;--header-title-color: var(--text-headings);--header-badge-bg: var(--primary-50);--header-badge-text: var(--text-headings);--dropdown-surface: var(--surface-page);--dropdown-border-color: #3d4f38;--dropdown-header-bg: var(--primary-50);--dropdown-muted-text: var(--neutral-500);--dropdown-item-text: var(--text-headings);--dropdown-item-hover: #2f4030;--icon-accent-color: var(--primary-green);--icon-accent-hover-bg: color-mix(in srgb, var(--primary-green) 22%, transparent);--neutral-600: #9aaa93;--chat-ai-fg: #dce6d8;--chat-ai-heading-fg: #f3faf0;--chat-ai-muted-fg: #a8baa0;--chat-ai-code-bg: rgba(255, 255, 255, .1);--chat-ai-code-fg: #eef5ea;--chat-ai-pre-bg: #141c12;--chat-ai-pre-fg: #e5ede3;--chat-ai-bubble-bg: var(--surface-page);--chat-ai-bubble-fg: var(--chat-ai-fg);--chat-ai-bubble-border: color-mix(in srgb, #ffffff 14%, transparent);--chat-user-bubble-bg-top: #2a3826;--chat-user-bubble-bg-bottom: #1f291c;--chat-user-bubble-fg: #eef5ea}html[data-oasis-theme=slate-dark]{color-scheme:dark;--surface-default: #0f172a;--surface-page: #1e293b;--primary-green: #38bdf8;--assistant-sidebar-bg: color-mix(in srgb, var(--surface-default) 90%, var(--primary-green) 10%);--primary-light: #1e293b;--primary-50: #334155;--text-body: #cbd5e1;--text-headings: #f1f5f9;--text-secondary: #94a3b8;--neutral-500: #94a3b8;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--assistant-sidebar-bg);--composer-invite-sun-a: rgba(56, 189, 248, .15);--composer-invite-sun-b: rgba(255, 255, 255, .05);--composer-invite-sun-c: rgba(56, 189, 248, .1);--composer-invite-sun-focus: rgba(56, 189, 248, .25);--composer-input-bg: color-mix(in srgb, var(--surface-page) 70%, #020617 30%);--composer-input-text: #f8fafc;--composer-placeholder: #94a3b8;--header-title-color: var(--text-headings);--header-badge-bg: var(--primary-50);--header-badge-text: var(--text-headings);--dropdown-surface: var(--surface-page);--dropdown-border-color: #475569;--dropdown-header-bg: #1e293b;--dropdown-muted-text: var(--neutral-500);--dropdown-item-text: var(--text-headings);--dropdown-item-hover: #334155;--icon-accent-color: var(--primary-green);--icon-accent-hover-bg: color-mix(in srgb, var(--primary-green) 22%, transparent);--neutral-600: #94a3b8;--chat-ai-fg: #cbd5e1;--chat-ai-heading-fg: #f8fafc;--chat-ai-muted-fg: #94a3b8;--chat-ai-code-bg: rgba(248, 250, 252, .1);--chat-ai-code-fg: #f1f5f9;--chat-ai-pre-bg: #0f172a;--chat-ai-pre-fg: #e2e8f0;--chat-ai-bubble-bg: var(--surface-page);--chat-ai-bubble-fg: var(--chat-ai-fg);--chat-ai-bubble-border: color-mix(in srgb, #ffffff 12%, transparent);--chat-user-bubble-bg-top: #334155;--chat-user-bubble-bg-bottom: #1e293b;--chat-user-bubble-fg: #f1f5f9}html[data-oasis-theme=high-contrast]{color-scheme:dark;--surface-default: #000000;--surface-page: #0a0a0a;--primary-green: #ffea00;--assistant-sidebar-bg: #000000;--primary-light: #141414;--primary-50: #1a1a1a;--text-body: #f5f5f5;--text-headings: #ffffff;--text-secondary: #e5e5e5;--neutral-500: #d4d4d4;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--surface-default);--composer-invite-sun-a: rgba(255, 234, 0, .2);--composer-invite-sun-b: rgba(255, 255, 255, .08);--composer-invite-sun-c: rgba(255, 234, 0, .15);--composer-invite-sun-focus: rgba(255, 234, 0, .35);--composer-input-bg: #0a0a0a;--composer-input-text: #ffffff;--composer-placeholder: #a3a3a3;--header-title-color: #ffffff;--header-badge-bg: #1a1a1a;--header-badge-text: #ffea00;--dropdown-surface: #0a0a0a;--dropdown-border-color: #ffffff;--dropdown-header-bg: #000000;--dropdown-muted-text: #d4d4d4;--dropdown-item-text: #ffffff;--dropdown-item-hover: #262626;--icon-accent-color: #ffea00;--icon-accent-hover-bg: rgba(255, 234, 0, .22);--neutral-600: #e5e5e5;--auth-on-primary: #0a0a0a;--chat-ai-fg: #ffffff;--chat-ai-heading-fg: #ffffff;--chat-ai-muted-fg: #d4d4d4;--chat-ai-code-bg: #000000;--chat-ai-code-fg: #ffffff;--chat-ai-pre-bg: #000000;--chat-ai-pre-fg: #ffffff;--chat-ai-bubble-bg: #0a0a0a;--chat-ai-bubble-fg: #ffffff;--chat-ai-bubble-border: #ffffff;--chat-user-bubble-bg-top: #262626;--chat-user-bubble-bg-bottom: #171717;--chat-user-bubble-fg: #ffffff}html[data-oasis-theme=clean-light]{color-scheme:light;--surface-default: #f4f4f5;--surface-page: #ffffff;--primary-green: #6b7f00;--assistant-sidebar-bg: color-mix(in srgb, var(--surface-default) 94%, var(--primary-green) 6%);--primary-light: #fafafa;--primary-50: #e4e4e7;--text-body: #52525b;--text-headings: #18181b;--text-secondary: #3f3f46;--neutral-500: #71717a;--neutral-600: #52525b;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--assistant-sidebar-bg);--composer-invite-sun-a: rgba(244, 244, 245, .85);--composer-invite-sun-b: rgba(255, 255, 255, .5);--composer-invite-sun-c: rgba(228, 228, 231, .6);--composer-invite-sun-focus: rgba(255, 255, 255, .95);--composer-input-bg: color-mix(in srgb, var(--surface-default) 85%, #3f3f46 10%);--composer-input-text: #18181b;--composer-placeholder: #71717a;--header-title-color: var(--text-headings);--header-badge-bg: var(--primary-50);--header-badge-text: var(--text-headings);--dropdown-surface: var(--surface-page);--dropdown-border-color: #e4e4e7;--dropdown-header-bg: #fafafa;--dropdown-muted-text: #71717a;--dropdown-item-text: var(--text-headings);--dropdown-item-hover: #f4f4f5;--icon-accent-color: var(--primary-green);--icon-accent-hover-bg: color-mix(in srgb, var(--primary-green) 14%, transparent);--chat-ai-fg: var(--text-body);--chat-ai-heading-fg: var(--text-headings);--chat-ai-muted-fg: #71717a;--chat-ai-code-bg: rgba(24, 24, 27, .07);--chat-ai-code-fg: var(--text-headings);--chat-ai-pre-bg: #f4f4f5;--chat-ai-pre-fg: #18181b;--chat-ai-bubble-bg: var(--surface-page);--chat-ai-bubble-fg: var(--chat-ai-fg);--chat-ai-bubble-border: color-mix(in srgb, var(--text-headings) 10%, transparent);--chat-user-bubble-bg-top: #e4e4e7;--chat-user-bubble-bg-bottom: #d4d4d8;--chat-user-bubble-fg: #18181b}html[data-oasis-theme=warm-light]{color-scheme:light;--surface-default: #f5f1e8;--surface-page: #fffdf6;--primary-green: #758a00;--assistant-sidebar-bg: color-mix(in srgb, var(--surface-default) 92%, var(--primary-green) 8%);--primary-light: #faf6ed;--primary-50: #ebe4d6;--text-body: #5c5749;--text-headings: #2e2a22;--text-secondary: #4a453c;--neutral-500: #8a8475;--neutral-600: #6d6758;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--assistant-sidebar-bg);--composer-invite-sun-a: rgba(255, 248, 220, .55);--composer-invite-sun-b: rgba(255, 255, 255, .32);--composer-invite-sun-c: rgba(255, 240, 200, .42);--composer-invite-sun-focus: rgba(255, 252, 238, .9);--composer-input-bg: color-mix(in srgb, var(--surface-default) 78%, #4a453c 12%);--composer-input-text: #2e2a22;--composer-placeholder: #8a8475;--header-title-color: #4d5a00;--header-badge-bg: var(--primary-50);--header-badge-text: #4d5a00;--dropdown-surface: var(--surface-page);--dropdown-border-color: #e8e2d4;--dropdown-header-bg: #faf6ed;--dropdown-muted-text: #8a8475;--dropdown-item-text: var(--text-headings);--dropdown-item-hover: #f0ebe0;--icon-accent-color: var(--primary-green);--icon-accent-hover-bg: color-mix(in srgb, var(--primary-green) 18%, transparent);--chat-ai-fg: var(--text-body);--chat-ai-heading-fg: var(--text-headings);--chat-ai-muted-fg: #8a8475;--chat-ai-code-bg: rgba(46, 42, 34, .07);--chat-ai-code-fg: var(--text-headings);--chat-ai-pre-bg: #f0ebe0;--chat-ai-pre-fg: #2e2a22;--chat-ai-bubble-bg: var(--surface-page);--chat-ai-bubble-fg: var(--chat-ai-fg);--chat-ai-bubble-border: rgba(46, 42, 34, .08);--chat-user-bubble-bg-top: #f0ebe0;--chat-user-bubble-bg-bottom: #e5dcc8;--chat-user-bubble-fg: #2e2a22}html[data-oasis-theme=traditional-light]{color-scheme:light;--surface-default: #fafafa;--surface-page: #ffffff;--primary-green: #64748b;--assistant-sidebar-bg: color-mix(in srgb, var(--surface-default) 94%, var(--primary-green) 6%);--primary-light: #ffffff;--primary-50: #f1f5f9;--text-body: #52525b;--text-headings: #18181b;--text-secondary: #3f3f46;--neutral-500: #71717a;--neutral-600: #52525b;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--assistant-sidebar-bg);--composer-invite-sun-a: rgba(241, 245, 249, .75);--composer-invite-sun-b: rgba(255, 255, 255, .45);--composer-invite-sun-c: rgba(226, 232, 240, .55);--composer-invite-sun-focus: rgba(255, 255, 255, .92);--composer-input-bg: color-mix(in srgb, var(--surface-default) 86%, #3f3f46 10%);--composer-input-text: #18181b;--composer-placeholder: #71717a;--header-title-color: var(--text-headings);--header-badge-bg: var(--primary-50);--header-badge-text: var(--text-headings);--dropdown-surface: var(--surface-page);--dropdown-border-color: #e4e4e7;--dropdown-header-bg: #fafafa;--dropdown-muted-text: #71717a;--dropdown-item-text: var(--text-headings);--dropdown-item-hover: #f4f4f5;--icon-accent-color: var(--primary-green);--icon-accent-hover-bg: color-mix(in srgb, var(--primary-green) 14%, transparent);--chat-ai-fg: var(--text-body);--chat-ai-heading-fg: var(--text-headings);--chat-ai-muted-fg: #71717a;--chat-ai-code-bg: rgba(24, 24, 27, .07);--chat-ai-code-fg: var(--text-headings);--chat-ai-pre-bg: #f4f4f5;--chat-ai-pre-fg: #18181b;--chat-ai-bubble-bg: var(--surface-page);--chat-ai-bubble-fg: var(--chat-ai-fg);--chat-ai-bubble-border: color-mix(in srgb, var(--text-headings) 10%, transparent);--chat-user-bubble-bg-top: #e4e4e7;--chat-user-bubble-bg-bottom: #d4d4d8;--chat-user-bubble-fg: #18181b}html[data-oasis-theme=ide-light]{color-scheme:light;--surface-default: #f6f8fa;--surface-page: #fcfcfc;--primary-green: #0969da;--assistant-sidebar-bg: color-mix(in srgb, var(--surface-default) 92%, var(--primary-green) 8%);--primary-light: #ffffff;--primary-50: #eaeef2;--text-body: #424a53;--text-headings: #1f2328;--text-secondary: #57606a;--neutral-500: #656d76;--neutral-600: #424a53;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--assistant-sidebar-bg);--composer-invite-sun-a: rgba(208, 215, 222, .45);--composer-invite-sun-b: rgba(255, 255, 255, .5);--composer-invite-sun-c: rgba(9, 105, 218, .12);--composer-invite-sun-focus: rgba(9, 105, 218, .18);--composer-input-bg: color-mix(in srgb, var(--surface-default) 84%, #1f2328 10%);--composer-input-text: #1f2328;--composer-placeholder: #656d76;--header-title-color: var(--text-headings);--header-badge-bg: var(--primary-50);--header-badge-text: var(--text-headings);--dropdown-surface: var(--surface-page);--dropdown-border-color: #d0d7de;--dropdown-header-bg: #f6f8fa;--dropdown-muted-text: #656d76;--dropdown-item-text: var(--text-headings);--dropdown-item-hover: #eaeef2;--icon-accent-color: var(--primary-green);--icon-accent-hover-bg: color-mix(in srgb, var(--primary-green) 14%, transparent);--chat-ai-fg: var(--text-body);--chat-ai-heading-fg: var(--text-headings);--chat-ai-muted-fg: #656d76;--chat-ai-code-bg: rgba(31, 35, 40, .08);--chat-ai-code-fg: var(--text-headings);--chat-ai-pre-bg: #eaeef2;--chat-ai-pre-fg: #1f2328;--chat-ai-bubble-bg: var(--surface-page);--chat-ai-bubble-fg: var(--chat-ai-fg);--chat-ai-bubble-border: color-mix(in srgb, var(--text-headings) 9%, transparent);--chat-user-bubble-bg-top: #dff2ff;--chat-user-bubble-bg-bottom: #cae9fc;--chat-user-bubble-fg: #1f2328}html[data-oasis-theme=vs-light]{color-scheme:light;--surface-default: #f3f3f3;--surface-page: #ffffff;--primary-green: #0078d4;--assistant-sidebar-bg: color-mix(in srgb, var(--surface-default) 92%, var(--primary-green) 8%);--primary-light: #ffffff;--primary-50: #e8e8e8;--text-body: #3b3b3b;--text-headings: #1e1e1e;--text-secondary: #2d2d2d;--neutral-500: #767676;--neutral-600: #505050;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--assistant-sidebar-bg);--composer-invite-sun-a: rgba(0, 120, 212, .12);--composer-invite-sun-b: rgba(255, 255, 255, .45);--composer-invite-sun-c: rgba(0, 120, 212, .1);--composer-invite-sun-focus: rgba(0, 120, 212, .2);--composer-input-bg: color-mix(in srgb, var(--surface-default) 82%, #1e1e1e 10%);--composer-input-text: #1e1e1e;--composer-placeholder: #767676;--header-title-color: var(--text-headings);--header-badge-bg: var(--primary-50);--header-badge-text: var(--text-headings);--dropdown-surface: var(--surface-page);--dropdown-border-color: #e5e5e5;--dropdown-header-bg: #f3f3f3;--dropdown-muted-text: #767676;--dropdown-item-text: var(--text-headings);--dropdown-item-hover: #ececec;--icon-accent-color: var(--primary-green);--icon-accent-hover-bg: color-mix(in srgb, var(--primary-green) 14%, transparent);--chat-ai-fg: var(--text-body);--chat-ai-heading-fg: var(--text-headings);--chat-ai-muted-fg: #767676;--chat-ai-code-bg: rgba(30, 30, 30, .07);--chat-ai-code-fg: var(--text-headings);--chat-ai-pre-bg: #f3f3f3;--chat-ai-pre-fg: #1e1e1e;--chat-ai-bubble-bg: var(--surface-page);--chat-ai-bubble-fg: var(--chat-ai-fg);--chat-ai-bubble-border: color-mix(in srgb, var(--text-headings) 10%, transparent);--chat-user-bubble-bg-top: #e3f2fd;--chat-user-bubble-bg-bottom: #bbdefb;--chat-user-bubble-fg: #1e1e1e}html[data-oasis-theme=light-modern]{color-scheme:light;--surface-default: #f8f8f8;--surface-page: #ffffff;--primary-green: #005fb8;--assistant-sidebar-bg: color-mix(in srgb, var(--surface-default) 93%, var(--primary-green) 7%);--primary-light: #ffffff;--primary-50: #e8ecf0;--text-body: #3d3d3d;--text-headings: #1a1a1a;--text-secondary: #2c2c2c;--neutral-500: #6e6e6e;--neutral-600: #4a4a4a;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--assistant-sidebar-bg);--composer-invite-sun-a: rgba(0, 95, 184, .12);--composer-invite-sun-b: rgba(255, 255, 255, .48);--composer-invite-sun-c: rgba(0, 95, 184, .1);--composer-invite-sun-focus: rgba(0, 95, 184, .22);--composer-input-bg: color-mix(in srgb, var(--surface-default) 84%, #1a1a1a 9%);--composer-input-text: #1a1a1a;--composer-placeholder: #6e6e6e;--header-title-color: var(--text-headings);--header-badge-bg: var(--primary-50);--header-badge-text: var(--text-headings);--dropdown-surface: var(--surface-page);--dropdown-border-color: #e0e0e0;--dropdown-header-bg: #f8f8f8;--dropdown-muted-text: #6e6e6e;--dropdown-item-text: var(--text-headings);--dropdown-item-hover: #f0f0f0;--icon-accent-color: var(--primary-green);--icon-accent-hover-bg: color-mix(in srgb, var(--primary-green) 14%, transparent);--chat-ai-fg: var(--text-body);--chat-ai-heading-fg: var(--text-headings);--chat-ai-muted-fg: #6e6e6e;--chat-ai-code-bg: rgba(26, 26, 26, .07);--chat-ai-code-fg: var(--text-headings);--chat-ai-pre-bg: #f0f0f0;--chat-ai-pre-fg: #1a1a1a;--chat-ai-bubble-bg: var(--surface-page);--chat-ai-bubble-fg: var(--chat-ai-fg);--chat-ai-bubble-border: color-mix(in srgb, var(--text-headings) 9%, transparent);--chat-user-bubble-bg-top: #e3f0ff;--chat-user-bubble-bg-bottom: #cce4ff;--chat-user-bubble-fg: #1a1a1a}html[data-oasis-theme=light-plus]{color-scheme:light;--surface-default: #f3f3f3;--surface-page: #ffffff;--primary-green: #0000cc;--assistant-sidebar-bg: color-mix(in srgb, var(--surface-default) 94%, var(--primary-green) 6%);--primary-light: #ffffff;--primary-50: #e8e8f0;--text-body: #333333;--text-headings: #000000;--text-secondary: #1a1a1a;--neutral-500: #6a6a6a;--neutral-600: #444444;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--assistant-sidebar-bg);--composer-invite-sun-a: rgba(0, 0, 204, .1);--composer-invite-sun-b: rgba(255, 255, 255, .5);--composer-invite-sun-c: rgba(0, 0, 204, .08);--composer-invite-sun-focus: rgba(0, 0, 204, .16);--composer-input-bg: color-mix(in srgb, var(--surface-default) 82%, #000000 8%);--composer-input-text: #000000;--composer-placeholder: #6a6a6a;--header-title-color: var(--text-headings);--header-badge-bg: var(--primary-50);--header-badge-text: var(--text-headings);--dropdown-surface: var(--surface-page);--dropdown-border-color: #d4d4d4;--dropdown-header-bg: #f3f3f3;--dropdown-muted-text: #6a6a6a;--dropdown-item-text: var(--text-headings);--dropdown-item-hover: #ececec;--icon-accent-color: var(--primary-green);--icon-accent-hover-bg: color-mix(in srgb, var(--primary-green) 14%, transparent);--chat-ai-fg: var(--text-body);--chat-ai-heading-fg: var(--text-headings);--chat-ai-muted-fg: #6a6a6a;--chat-ai-code-bg: rgba(0, 0, 0, .06);--chat-ai-code-fg: var(--text-headings);--chat-ai-pre-bg: #f3f3f3;--chat-ai-pre-fg: #000000;--chat-ai-bubble-bg: var(--surface-page);--chat-ai-bubble-fg: var(--chat-ai-fg);--chat-ai-bubble-border: color-mix(in srgb, var(--text-headings) 8%, transparent);--chat-user-bubble-bg-top: #e8e8f0;--chat-user-bubble-bg-bottom: #d8d8e8;--chat-user-bubble-fg: #000000}html[data-oasis-theme=quiet-light]{color-scheme:light;--surface-default: #f5f5f5;--surface-page: #ffffff;--primary-green: #7049a3;--assistant-sidebar-bg: color-mix(in srgb, var(--surface-default) 92%, var(--primary-green) 8%);--primary-light: #fafafa;--primary-50: #e8e4ee;--text-body: #555555;--text-headings: #333333;--text-secondary: #444444;--neutral-500: #777777;--neutral-600: #555555;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--assistant-sidebar-bg);--composer-invite-sun-a: rgba(112, 73, 163, .12);--composer-invite-sun-b: rgba(255, 255, 255, .45);--composer-invite-sun-c: rgba(112, 73, 163, .1);--composer-invite-sun-focus: rgba(112, 73, 163, .2);--composer-input-bg: color-mix(in srgb, var(--surface-default) 82%, #3d2d52 10%);--composer-input-text: #333333;--composer-placeholder: #777777;--header-title-color: var(--text-headings);--header-badge-bg: var(--primary-50);--header-badge-text: var(--text-headings);--dropdown-surface: var(--surface-page);--dropdown-border-color: #e0dce8;--dropdown-header-bg: #faf8fc;--dropdown-muted-text: #777777;--dropdown-item-text: var(--text-headings);--dropdown-item-hover: #f0ecf8;--icon-accent-color: var(--primary-green);--icon-accent-hover-bg: color-mix(in srgb, var(--primary-green) 14%, transparent);--chat-ai-fg: var(--text-body);--chat-ai-heading-fg: var(--text-headings);--chat-ai-muted-fg: #777777;--chat-ai-code-bg: rgba(51, 51, 51, .07);--chat-ai-code-fg: var(--text-headings);--chat-ai-pre-bg: #ece8f2;--chat-ai-pre-fg: #333333;--chat-ai-bubble-bg: var(--surface-page);--chat-ai-bubble-fg: var(--chat-ai-fg);--chat-ai-bubble-border: color-mix(in srgb, var(--text-headings) 9%, transparent);--chat-user-bubble-bg-top: #e8e4ee;--chat-user-bubble-bg-bottom: #dcd4e8;--chat-user-bubble-fg: #333333}html[data-oasis-theme=solarized-light]{color-scheme:light;--surface-default: #eee8d5;--surface-page: #fdf6e3;--primary-green: #268bd2;--assistant-sidebar-bg: color-mix(in srgb, var(--surface-page) 88%, var(--primary-green) 12%);--primary-light: #fdf6e3;--primary-50: #eee8d5;--text-body: #586e75;--text-headings: #073642;--text-secondary: #657b83;--neutral-500: #93a1a1;--neutral-600: #586e75;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--assistant-sidebar-bg);--composer-invite-sun-a: rgba(38, 139, 210, .15);--composer-invite-sun-b: rgba(253, 246, 227, .55);--composer-invite-sun-c: rgba(133, 153, 0, .12);--composer-invite-sun-focus: rgba(38, 139, 210, .22);--composer-input-bg: color-mix(in srgb, var(--surface-page) 78%, #073642 14%);--composer-input-text: #073642;--composer-placeholder: #93a1a1;--header-title-color: #073642;--header-badge-bg: var(--primary-50);--header-badge-text: #073642;--dropdown-surface: var(--surface-page);--dropdown-border-color: #d9cfb8;--dropdown-header-bg: #eee8d5;--dropdown-muted-text: #93a1a1;--dropdown-item-text: #073642;--dropdown-item-hover: #e8e2cf;--icon-accent-color: var(--primary-green);--icon-accent-hover-bg: color-mix(in srgb, var(--primary-green) 14%, transparent);--chat-ai-fg: var(--text-body);--chat-ai-heading-fg: var(--text-headings);--chat-ai-muted-fg: #93a1a1;--chat-ai-code-bg: rgba(7, 54, 66, .08);--chat-ai-code-fg: #073642;--chat-ai-pre-bg: #eee8d5;--chat-ai-pre-fg: #073642;--chat-ai-bubble-bg: var(--surface-page);--chat-ai-bubble-fg: var(--chat-ai-fg);--chat-ai-bubble-border: color-mix(in srgb, #073642 12%, transparent);--chat-user-bubble-bg-top: #e8dfc8;--chat-user-bubble-bg-bottom: #ddd3b8;--chat-user-bubble-fg: #073642}html[data-oasis-theme=traditional-dark]{color-scheme:dark;--surface-default: #141414;--surface-page: #1c1c1c;--primary-green: #9ca3af;--assistant-sidebar-bg: color-mix(in srgb, var(--surface-default) 92%, var(--primary-green) 8%);--primary-light: #242424;--primary-50: #2a2a2a;--text-body: #c7c7c7;--text-headings: #fafafa;--text-secondary: #d4d4d4;--neutral-500: #a3a3a3;--neutral-600: #c7c7c7;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--assistant-sidebar-bg);--composer-invite-sun-a: rgba(255, 255, 255, .06);--composer-invite-sun-b: rgba(255, 255, 255, .04);--composer-invite-sun-c: rgba(156, 163, 175, .12);--composer-invite-sun-focus: rgba(156, 163, 175, .22);--composer-input-bg: color-mix(in srgb, var(--surface-page) 72%, #000000 28%);--composer-input-text: #fafafa;--composer-placeholder: #a3a3a3;--header-title-color: var(--text-headings);--header-badge-bg: var(--primary-50);--header-badge-text: var(--text-headings);--dropdown-surface: var(--surface-page);--dropdown-border-color: #3f3f3f;--dropdown-header-bg: #242424;--dropdown-muted-text: var(--neutral-500);--dropdown-item-text: var(--text-headings);--dropdown-item-hover: #2f2f2f;--icon-accent-color: var(--primary-green);--icon-accent-hover-bg: color-mix(in srgb, var(--primary-green) 22%, transparent);--chat-ai-fg: #e0e0e0;--chat-ai-heading-fg: #fafafa;--chat-ai-muted-fg: #a3a3a3;--chat-ai-code-bg: rgba(255, 255, 255, .1);--chat-ai-code-fg: #fafafa;--chat-ai-pre-bg: #0f0f0f;--chat-ai-pre-fg: #e8e8e8;--chat-ai-bubble-bg: var(--surface-page);--chat-ai-bubble-fg: var(--chat-ai-fg);--chat-ai-bubble-border: color-mix(in srgb, #ffffff 12%, transparent);--chat-user-bubble-bg-top: #2f2f2f;--chat-user-bubble-bg-bottom: #222222;--chat-user-bubble-fg: #fafafa}html[data-oasis-theme=violet-dark]{color-scheme:dark;--surface-default: #16121f;--surface-page: #1e1628;--primary-green: #c084fc;--assistant-sidebar-bg: color-mix(in srgb, var(--surface-default) 88%, var(--primary-green) 12%);--primary-light: #2a1f36;--primary-50: #342640;--text-body: #d4c4e8;--text-headings: #f5edff;--text-secondary: #c4b5d8;--neutral-500: #a898bc;--neutral-600: #d4c4e8;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--assistant-sidebar-bg);--composer-invite-sun-a: rgba(192, 132, 252, .16);--composer-invite-sun-b: rgba(255, 255, 255, .05);--composer-invite-sun-c: rgba(192, 132, 252, .1);--composer-invite-sun-focus: rgba(192, 132, 252, .26);--composer-input-bg: color-mix(in srgb, var(--surface-page) 70%, #0f0a14 30%);--composer-input-text: #f5edff;--composer-placeholder: #a898bc;--header-title-color: var(--text-headings);--header-badge-bg: var(--primary-50);--header-badge-text: var(--text-headings);--dropdown-surface: var(--surface-page);--dropdown-border-color: #4a3d5c;--dropdown-header-bg: #2a1f36;--dropdown-muted-text: var(--neutral-500);--dropdown-item-text: var(--text-headings);--dropdown-item-hover: #342640;--icon-accent-color: var(--primary-green);--icon-accent-hover-bg: color-mix(in srgb, var(--primary-green) 22%, transparent);--chat-ai-fg: #e8ddf5;--chat-ai-heading-fg: #f5edff;--chat-ai-muted-fg: #c4b5d8;--chat-ai-code-bg: rgba(245, 237, 255, .1);--chat-ai-code-fg: #f5edff;--chat-ai-pre-bg: #120d18;--chat-ai-pre-fg: #ebe3f7;--chat-ai-bubble-bg: var(--surface-page);--chat-ai-bubble-fg: var(--chat-ai-fg);--chat-ai-bubble-border: color-mix(in srgb, #c084fc 22%, transparent);--chat-user-bubble-bg-top: #3d2f4d;--chat-user-bubble-bg-bottom: #2a1f36;--chat-user-bubble-fg: #f5edff}html[data-oasis-theme=cool-dark]{color-scheme:dark;--surface-default: #1e2127;--surface-page: #282c34;--primary-green: #528bff;--assistant-sidebar-bg: color-mix(in srgb, var(--surface-default) 90%, var(--primary-green) 10%);--primary-light: #2c313a;--primary-50: #323842;--text-body: #abb2bf;--text-headings: #e6e8ee;--text-secondary: #9da5b4;--neutral-500: #848b98;--neutral-600: #abb2bf;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--assistant-sidebar-bg);--composer-invite-sun-a: rgba(82, 139, 255, .14);--composer-invite-sun-b: rgba(255, 255, 255, .05);--composer-invite-sun-c: rgba(82, 139, 255, .1);--composer-invite-sun-focus: rgba(82, 139, 255, .24);--composer-input-bg: color-mix(in srgb, var(--surface-page) 68%, #000000 32%);--composer-input-text: #e6e8ee;--composer-placeholder: #848b98;--header-title-color: var(--text-headings);--header-badge-bg: var(--primary-50);--header-badge-text: var(--text-headings);--dropdown-surface: var(--surface-page);--dropdown-border-color: #3e4451;--dropdown-header-bg: #2c313a;--dropdown-muted-text: var(--neutral-500);--dropdown-item-text: var(--text-headings);--dropdown-item-hover: #323842;--icon-accent-color: var(--primary-green);--icon-accent-hover-bg: color-mix(in srgb, var(--primary-green) 22%, transparent);--chat-ai-fg: #c8ced9;--chat-ai-heading-fg: #e6e8ee;--chat-ai-muted-fg: #9da5b4;--chat-ai-code-bg: rgba(255, 255, 255, .08);--chat-ai-code-fg: #e6e8ee;--chat-ai-pre-bg: #1e2127;--chat-ai-pre-fg: #d7dce6;--chat-ai-bubble-bg: var(--surface-page);--chat-ai-bubble-fg: var(--chat-ai-fg);--chat-ai-bubble-border: color-mix(in srgb, #ffffff 10%, transparent);--chat-user-bubble-bg-top: #3a3f4b;--chat-user-bubble-bg-bottom: #2c313a;--chat-user-bubble-fg: #e6e8ee}html[data-oasis-theme=midnight-dark]{color-scheme:dark;--surface-default: #0d1117;--surface-page: #161b22;--primary-green: #58a6ff;--assistant-sidebar-bg: color-mix(in srgb, var(--surface-default) 90%, var(--primary-green) 10%);--primary-light: #161b22;--primary-50: #21262d;--text-body: #c9d1d9;--text-headings: #f0f6fc;--text-secondary: #8b949e;--neutral-500: #8b949e;--neutral-600: #c9d1d9;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--assistant-sidebar-bg);--composer-invite-sun-a: rgba(88, 166, 255, .14);--composer-invite-sun-b: rgba(255, 255, 255, .04);--composer-invite-sun-c: rgba(88, 166, 255, .1);--composer-invite-sun-focus: rgba(88, 166, 255, .26);--composer-input-bg: color-mix(in srgb, var(--surface-page) 65%, #010409 35%);--composer-input-text: #f0f6fc;--composer-placeholder: #8b949e;--header-title-color: var(--text-headings);--header-badge-bg: var(--primary-50);--header-badge-text: var(--text-headings);--dropdown-surface: var(--surface-page);--dropdown-border-color: #30363d;--dropdown-header-bg: #161b22;--dropdown-muted-text: var(--neutral-500);--dropdown-item-text: var(--text-headings);--dropdown-item-hover: #21262d;--icon-accent-color: var(--primary-green);--icon-accent-hover-bg: color-mix(in srgb, var(--primary-green) 22%, transparent);--chat-ai-fg: #c9d1d9;--chat-ai-heading-fg: #f0f6fc;--chat-ai-muted-fg: #8b949e;--chat-ai-code-bg: rgba(240, 246, 252, .08);--chat-ai-code-fg: #f0f6fc;--chat-ai-pre-bg: #0d1117;--chat-ai-pre-fg: #e6edf3;--chat-ai-bubble-bg: var(--surface-page);--chat-ai-bubble-fg: var(--chat-ai-fg);--chat-ai-bubble-border: color-mix(in srgb, #ffffff 12%, transparent);--chat-user-bubble-bg-top: #30363d;--chat-user-bubble-bg-bottom: #21262d;--chat-user-bubble-fg: #f0f6fc}html[data-oasis-theme=vs-dark]{color-scheme:dark;--surface-default: #252526;--surface-page: #1e1e1e;--primary-green: #007acc;--assistant-sidebar-bg: color-mix(in srgb, var(--surface-default) 90%, var(--primary-green) 10%);--primary-light: #2d2d2d;--primary-50: #3c3c3c;--text-body: #cccccc;--text-headings: #ffffff;--text-secondary: #bbbbbb;--neutral-500: #969696;--neutral-600: #cccccc;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--assistant-sidebar-bg);--composer-invite-sun-a: rgba(0, 122, 204, .16);--composer-invite-sun-b: rgba(255, 255, 255, .05);--composer-invite-sun-c: rgba(0, 122, 204, .1);--composer-invite-sun-focus: rgba(0, 122, 204, .26);--composer-input-bg: color-mix(in srgb, var(--surface-page) 70%, #000000 30%);--composer-input-text: #ffffff;--composer-placeholder: #969696;--header-title-color: var(--text-headings);--header-badge-bg: var(--primary-50);--header-badge-text: var(--text-headings);--dropdown-surface: var(--surface-page);--dropdown-border-color: #555555;--dropdown-header-bg: #2d2d2d;--dropdown-muted-text: var(--neutral-500);--dropdown-item-text: var(--text-headings);--dropdown-item-hover: #3c3c3c;--icon-accent-color: var(--primary-green);--icon-accent-hover-bg: color-mix(in srgb, var(--primary-green) 22%, transparent);--chat-ai-fg: #d4d4d4;--chat-ai-heading-fg: #ffffff;--chat-ai-muted-fg: #969696;--chat-ai-code-bg: rgba(255, 255, 255, .1);--chat-ai-code-fg: #ffffff;--chat-ai-pre-bg: #1a1a1a;--chat-ai-pre-fg: #e5e5e5;--chat-ai-bubble-bg: var(--surface-page);--chat-ai-bubble-fg: var(--chat-ai-fg);--chat-ai-bubble-border: color-mix(in srgb, #ffffff 12%, transparent);--chat-user-bubble-bg-top: #3c3c3c;--chat-user-bubble-bg-bottom: #2d2d2d;--chat-user-bubble-fg: #ffffff}html[data-oasis-theme=dark-modern]{color-scheme:dark;--surface-default: #1f1f1f;--surface-page: #2c2c2c;--primary-green: #0078d4;--assistant-sidebar-bg: color-mix(in srgb, var(--surface-default) 90%, var(--primary-green) 10%);--primary-light: #2c2c2c;--primary-50: #383838;--text-body: #cccccc;--text-headings: #ffffff;--text-secondary: #b3b3b3;--neutral-500: #9a9a9a;--neutral-600: #cccccc;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--assistant-sidebar-bg);--composer-invite-sun-a: rgba(0, 120, 212, .14);--composer-invite-sun-b: rgba(255, 255, 255, .05);--composer-invite-sun-c: rgba(0, 120, 212, .1);--composer-invite-sun-focus: rgba(0, 120, 212, .24);--composer-input-bg: color-mix(in srgb, var(--surface-page) 68%, #000000 32%);--composer-input-text: #ffffff;--composer-placeholder: #9a9a9a;--header-title-color: var(--text-headings);--header-badge-bg: var(--primary-50);--header-badge-text: var(--text-headings);--dropdown-surface: var(--surface-page);--dropdown-border-color: #505050;--dropdown-header-bg: #2c2c2c;--dropdown-muted-text: var(--neutral-500);--dropdown-item-text: var(--text-headings);--dropdown-item-hover: #383838;--icon-accent-color: var(--primary-green);--icon-accent-hover-bg: color-mix(in srgb, var(--primary-green) 22%, transparent);--chat-ai-fg: #d0d0d0;--chat-ai-heading-fg: #ffffff;--chat-ai-muted-fg: #9a9a9a;--chat-ai-code-bg: rgba(255, 255, 255, .09);--chat-ai-code-fg: #ffffff;--chat-ai-pre-bg: #1a1a1a;--chat-ai-pre-fg: #e8e8e8;--chat-ai-bubble-bg: var(--surface-page);--chat-ai-bubble-fg: var(--chat-ai-fg);--chat-ai-bubble-border: color-mix(in srgb, #ffffff 11%, transparent);--chat-user-bubble-bg-top: #404040;--chat-user-bubble-bg-bottom: #323232;--chat-user-bubble-fg: #ffffff}html[data-oasis-theme=dark-plus]{color-scheme:dark;--surface-default: #252526;--surface-page: #1e1e1e;--primary-green: #4ec9b0;--assistant-sidebar-bg: color-mix(in srgb, var(--surface-default) 90%, var(--primary-green) 10%);--primary-light: #2d2d2d;--primary-50: #3c3c3c;--text-body: #d4d4d4;--text-headings: #ffffff;--text-secondary: #c8c8c8;--neutral-500: #9d9d9d;--neutral-600: #d4d4d4;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--assistant-sidebar-bg);--composer-invite-sun-a: rgba(78, 201, 176, .14);--composer-invite-sun-b: rgba(255, 255, 255, .05);--composer-invite-sun-c: rgba(78, 201, 176, .1);--composer-invite-sun-focus: rgba(78, 201, 176, .24);--composer-input-bg: color-mix(in srgb, var(--surface-page) 70%, #000000 30%);--composer-input-text: #ffffff;--composer-placeholder: #9d9d9d;--header-title-color: var(--text-headings);--header-badge-bg: var(--primary-50);--header-badge-text: var(--text-headings);--dropdown-surface: var(--surface-page);--dropdown-border-color: #555555;--dropdown-header-bg: #2d2d2d;--dropdown-muted-text: var(--neutral-500);--dropdown-item-text: var(--text-headings);--dropdown-item-hover: #3c3c3c;--icon-accent-color: var(--primary-green);--icon-accent-hover-bg: color-mix(in srgb, var(--primary-green) 22%, transparent);--chat-ai-fg: #d4d4d4;--chat-ai-heading-fg: #ffffff;--chat-ai-muted-fg: #9d9d9d;--chat-ai-code-bg: rgba(255, 255, 255, .1);--chat-ai-code-fg: #ffffff;--chat-ai-pre-bg: #1a1a1a;--chat-ai-pre-fg: #e5e5e5;--chat-ai-bubble-bg: var(--surface-page);--chat-ai-bubble-fg: var(--chat-ai-fg);--chat-ai-bubble-border: color-mix(in srgb, #ffffff 12%, transparent);--chat-user-bubble-bg-top: #3c3c3c;--chat-user-bubble-bg-bottom: #2d2d2d;--chat-user-bubble-fg: #ffffff}html[data-oasis-theme=abyss]{color-scheme:dark;--surface-default: #000c18;--surface-page: #051a2e;--primary-green: #6688cc;--assistant-sidebar-bg: color-mix(in srgb, var(--surface-default) 88%, var(--primary-green) 12%);--primary-light: #0a1f35;--primary-50: #0f2844;--text-body: #b8c9e8;--text-headings: #dde9ff;--text-secondary: #9eb6de;--neutral-500: #7a93b8;--neutral-600: #b8c9e8;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--assistant-sidebar-bg);--composer-invite-sun-a: rgba(102, 136, 204, .18);--composer-invite-sun-b: rgba(255, 255, 255, .04);--composer-invite-sun-c: rgba(102, 136, 204, .12);--composer-invite-sun-focus: rgba(102, 136, 204, .28);--composer-input-bg: color-mix(in srgb, var(--surface-page) 72%, #000000 28%);--composer-input-text: #dde9ff;--composer-placeholder: #7a93b8;--header-title-color: var(--text-headings);--header-badge-bg: var(--primary-50);--header-badge-text: var(--text-headings);--dropdown-surface: var(--surface-page);--dropdown-border-color: #1a3a5c;--dropdown-header-bg: #0f2844;--dropdown-muted-text: var(--neutral-500);--dropdown-item-text: var(--text-headings);--dropdown-item-hover: #123a5c;--icon-accent-color: var(--primary-green);--icon-accent-hover-bg: color-mix(in srgb, var(--primary-green) 22%, transparent);--chat-ai-fg: #c8d8f0;--chat-ai-heading-fg: #dde9ff;--chat-ai-muted-fg: #9eb6de;--chat-ai-code-bg: rgba(255, 255, 255, .08);--chat-ai-code-fg: #dde9ff;--chat-ai-pre-bg: #000c18;--chat-ai-pre-fg: #d0dff5;--chat-ai-bubble-bg: var(--surface-page);--chat-ai-bubble-fg: var(--chat-ai-fg);--chat-ai-bubble-border: color-mix(in srgb, #6688cc 25%, transparent);--chat-user-bubble-bg-top: #123a5c;--chat-user-bubble-bg-bottom: #0c2844;--chat-user-bubble-fg: #dde9ff}html[data-oasis-theme=kimbie-dark]{color-scheme:dark;--surface-default: #221a0f;--surface-page: #362712;--primary-green: #f06431;--assistant-sidebar-bg: color-mix(in srgb, var(--surface-default) 88%, var(--primary-green) 12%);--primary-light: #42321c;--primary-50: #4a3a24;--text-body: #d3af86;--text-headings: #f5e6c8;--text-secondary: #c49a6c;--neutral-500: #a88b68;--neutral-600: #d3af86;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--assistant-sidebar-bg);--composer-invite-sun-a: rgba(240, 100, 49, .16);--composer-invite-sun-b: rgba(255, 255, 255, .05);--composer-invite-sun-c: rgba(240, 100, 49, .1);--composer-invite-sun-focus: rgba(240, 100, 49, .26);--composer-input-bg: color-mix(in srgb, var(--surface-page) 72%, #1a1208 28%);--composer-input-text: #f5e6c8;--composer-placeholder: #a88b68;--header-title-color: var(--text-headings);--header-badge-bg: var(--primary-50);--header-badge-text: var(--text-headings);--dropdown-surface: var(--surface-page);--dropdown-border-color: #5c4a32;--dropdown-header-bg: #42321c;--dropdown-muted-text: var(--neutral-500);--dropdown-item-text: var(--text-headings);--dropdown-item-hover: #4a3a24;--icon-accent-color: var(--primary-green);--icon-accent-hover-bg: color-mix(in srgb, var(--primary-green) 22%, transparent);--chat-ai-fg: #e8d4b8;--chat-ai-heading-fg: #f5e6c8;--chat-ai-muted-fg: #c49a6c;--chat-ai-code-bg: rgba(255, 255, 255, .08);--chat-ai-code-fg: #f5e6c8;--chat-ai-pre-bg: #221a0f;--chat-ai-pre-fg: #edd9c0;--chat-ai-bubble-bg: var(--surface-page);--chat-ai-bubble-fg: var(--chat-ai-fg);--chat-ai-bubble-border: color-mix(in srgb, #f5e6c8 14%, transparent);--chat-user-bubble-bg-top: #5c4a32;--chat-user-bubble-bg-bottom: #42321c;--chat-user-bubble-fg: #f5e6c8}html[data-oasis-theme=monokai]{color-scheme:dark;--surface-default: #272822;--surface-page: #3e3d32;--primary-green: #a6e22e;--assistant-sidebar-bg: color-mix(in srgb, var(--surface-default) 88%, var(--primary-green) 12%);--primary-light: #49483e;--primary-50: #75715e;--text-body: #cfcfc2;--text-headings: #f8f8f2;--text-secondary: #b8b4a8;--neutral-500: #908e85;--neutral-600: #cfcfc2;--composer-bar-bg: var(--surface-default);--composer-dock-bg: var(--assistant-sidebar-bg);--composer-invite-sun-a: rgba(166, 226, 46, .14);--composer-invite-sun-b: rgba(255, 255, 255, .04);--composer-invite-sun-c: rgba(166, 226, 46, .1);--composer-invite-sun-focus: rgba(166, 226, 46, .24);--composer-input-bg: color-mix(in srgb, var(--surface-page) 68%, #1e1f1c 32%);--composer-input-text: #f8f8f2;--composer-placeholder: #908e85;--header-title-color: var(--text-headings);--header-badge-bg: var(--primary-50);--header-badge-text: var(--text-headings);--dropdown-surface: var(--surface-page);--dropdown-border-color: #75715e;--dropdown-header-bg: #49483e;--dropdown-muted-text: var(--neutral-500);--dropdown-item-text: var(--text-headings);--dropdown-item-hover: #57564a;--icon-accent-color: var(--primary-green);--icon-accent-hover-bg: color-mix(in srgb, var(--primary-green) 22%, transparent);--chat-ai-fg: #e2e2dc;--chat-ai-heading-fg: #f8f8f2;--chat-ai-muted-fg: #b8b4a8;--chat-ai-code-bg: rgba(255, 255, 255, .08);--chat-ai-code-fg: #f8f8f2;--chat-ai-pre-bg: #272822;--chat-ai-pre-fg: #f0f0ea;--chat-ai-bubble-bg: var(--surface-page);--chat-ai-bubble-fg: var(--chat-ai-fg);--chat-ai-bubble-border: color-mix(in srgb, #f8f8f2 10%, transparent);--chat-user-bubble-bg-top: #57564a;--chat-user-bubble-bg-bottom: #49483e;--chat-user-bubble-fg: #f8f8f2} diff --git a/browser/base/content/assistant/dist/assistant.ui.bundle.js b/browser/base/content/assistant/dist/assistant.ui.bundle.js new file mode 100644 index 0000000000000..f645e6fa29e55 --- /dev/null +++ b/browser/base/content/assistant/dist/assistant.ui.bundle.js @@ -0,0 +1,8 @@ +"use strict";var AssistantUI=(()=>{var mt,V,ma,rn,Pe,pa,ha,va,xa,Ut,Bt,zt,nn,Ze={},ya=[],on=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Qe=Array.isArray;function Ce(e,t){for(var r in t)e[r]=t[r];return e}function Wt(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function Ae(e,t,r){var n,o,i,s={};for(i in t)i=="key"?n=t[i]:i=="ref"?o=t[i]:s[i]=t[i];if(arguments.length>2&&(s.children=arguments.length>3?mt.call(arguments,2):r),typeof e=="function"&&e.defaultProps!=null)for(i in e.defaultProps)s[i]===void 0&&(s[i]=e.defaultProps[i]);return ft(e,s,n,o,null)}function ft(e,t,r,n,o){var i={type:e,props:t,key:r,ref:n,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o==null?++ma:o,__i:-1,__u:0};return o==null&&V.vnode!=null&&V.vnode(i),i}function ht(){return{current:null}}function te(e){return e.children}function xe(e,t){this.props=e,this.context=t}function He(e,t){if(t==null)return e.__?He(e.__,e.__i+1):null;for(var r;tc&&Pe.sort(va),e=Pe.shift(),c=Pe.length,e.__d&&(r=void 0,n=void 0,o=(n=(t=e).__v).__e,i=[],s=[],t.__P&&((r=Ce({},n)).__v=n.__v+1,V.vnode&&V.vnode(r),Ft(t.__P,r,n,t.__n,t.__P.namespaceURI,32&n.__u?[o]:null,i,o==null?He(n):o,!!(32&n.__u),s),r.__v=n.__v,r.__.__k[r.__i]=r,Sa(i,r,s),n.__e=n.__=null,r.__e!=o&&_a(r)));bt.__r=0}function wa(e,t,r,n,o,i,s,c,u,d,m){var l,b,p,f,k,C,g,S=n&&n.__k||ya,N=t.length;for(u=sn(r,t,S,u,N),l=0;l0?s=e.__k[i]=ft(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[i]=s,u=i+b,s.__=e,s.__b=e.__b+1,c=null,(d=s.__i=ln(s,r,u,l))!=-1&&(l--,(c=r[d])&&(c.__u|=2)),c==null||c.__v==null?(d==-1&&(o>m?b--:ou?b--:b++,s.__u|=4))):e.__k[i]=null;if(l)for(i=0;i(m?1:0)){for(o=r-1,i=r+1;o>=0||i=0?o--:i++])!=null&&(2&d.__u)==0&&c==d.key&&u==d.type)return s}return-1}function fa(e,t,r){t[0]=="-"?e.setProperty(t,r==null?"":r):e[t]=r==null?"":typeof r!="number"||on.test(t)?r:r+"px"}function gt(e,t,r,n,o){var i,s;e:if(t=="style")if(typeof r=="string")e.style.cssText=r;else{if(typeof n=="string"&&(e.style.cssText=n=""),n)for(t in n)r&&t in r||fa(e.style,t,"");if(r)for(t in r)n&&r[t]==n[t]||fa(e.style,t,r[t])}else if(t[0]=="o"&&t[1]=="n")i=t!=(t=t.replace(xa,"$1")),s=t.toLowerCase(),t=s in e||t=="onFocusOut"||t=="onFocusIn"?s.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+i]=r,r?n?r.u=n.u:(r.u=Ut,e.addEventListener(t,i?zt:Bt,i)):e.removeEventListener(t,i?zt:Bt,i);else{if(o=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=r==null?"":r;break e}catch{}typeof r=="function"||(r==null||r===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&r==1?"":r))}}function ba(e){return function(t){if(this.l){var r=this.l[t.type+e];if(t.t==null)t.t=Ut++;else if(t.t0?e:Qe(e)?e.map(Ca):Ce({},e)}function cn(e,t,r,n,o,i,s,c,u){var d,m,l,b,p,f,k,C=r.props||Ze,g=t.props,S=t.type;if(S=="svg"?o="http://www.w3.org/2000/svg":S=="math"?o="http://www.w3.org/1998/Math/MathML":o||(o="http://www.w3.org/1999/xhtml"),i!=null){for(d=0;d=r.__.length&&r.__.push({}),r.__[e]}function y(e){return at=1,Da(Ba,e)}function Da(e,t,r){var n=xt(Ue++,2);if(n.t=e,!n.__c&&(n.__=[r?r(t):Ba(void 0,t),function(c){var u=n.__N?n.__N[0]:n.__[0],d=n.t(u,c);u!==d&&(n.__N=[d,n.__[1]],n.__c.setState({}))}],n.__c=oe,!oe.__f)){var o=function(c,u,d){if(!n.__c.__H)return!0;var m=n.__c.__H.__.filter(function(b){return!!b.__c});if(m.every(function(b){return!b.__N}))return!i||i.call(this,c,u,d);var l=n.__c.props!==c;return m.forEach(function(b){if(b.__N){var p=b.__[0];b.__=b.__N,b.__N=void 0,p!==b.__[0]&&(l=!0)}}),i&&i.call(this,c,u,d)||l};oe.__f=!0;var i=oe.shouldComponentUpdate,s=oe.componentWillUpdate;oe.componentWillUpdate=function(c,u,d){if(this.__e){var m=i;i=void 0,o(c,u,d),i=m}s&&s.call(this,c,u,d)},oe.shouldComponentUpdate=o}return n.__N||n.__}function P(e,t){var r=xt(Ue++,3);!ie.__s&&Kt(r.__H,t)&&(r.__=e,r.u=t,oe.__H.__h.push(r))}function rt(e,t){var r=xt(Ue++,4);!ie.__s&&Kt(r.__H,t)&&(r.__=e,r.u=t,oe.__h.push(r))}function G(e){return at=5,be(function(){return{current:e}},[])}function be(e,t){var r=xt(Ue++,7);return Kt(r.__H,t)&&(r.__=e(),r.__H=t,r.__h=e),r.__}function j(e,t){return at=8,be(function(){return e},t)}function un(){for(var e;e=Ra.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(vt),e.__H.__h.forEach($t),e.__H.__h=[]}catch(t){e.__H.__h=[],ie.__e(t,e.__v)}}ie.__b=function(e){oe=null,Ea&&Ea(e)},ie.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Pa&&Pa(e,t)},ie.__r=function(e){Ia&&Ia(e),Ue=0;var t=(oe=e.__c).__H;t&&(jt===oe?(t.__h=[],oe.__h=[],t.__.forEach(function(r){r.__N&&(r.__=r.__N),r.u=r.__N=void 0})):(t.__h.forEach(vt),t.__h.forEach($t),t.__h=[],Ue=0)),jt=oe},ie.diffed=function(e){Na&&Na(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Ra.push(t)!==1&&Ta===ie.requestAnimationFrame||((Ta=ie.requestAnimationFrame)||pn)(un)),t.__H.__.forEach(function(r){r.u&&(r.__H=r.u),r.u=void 0})),jt=oe=null},ie.__c=function(e,t){t.some(function(r){try{r.__h.forEach(vt),r.__h=r.__h.filter(function(n){return!n.__||$t(n)})}catch(n){t.some(function(o){o.__h&&(o.__h=[])}),t=[],ie.__e(n,r.__v)}}),Ma&&Ma(e,t)},ie.unmount=function(e){La&&La(e);var t,r=e.__c;r&&r.__H&&(r.__H.__.forEach(function(n){try{vt(n)}catch(o){t=o}}),r.__H=void 0,t&&ie.__e(t,r.__v))};var Oa=typeof requestAnimationFrame=="function";function pn(e){var t,r=function(){clearTimeout(n),Oa&&cancelAnimationFrame(t),setTimeout(e)},n=setTimeout(r,35);Oa&&(t=requestAnimationFrame(r))}function vt(e){var t=oe,r=e.__c;typeof r=="function"&&(e.__c=void 0,r()),oe=t}function $t(e){var t=oe;e.__c=e.__(),oe=t}function Kt(e,t){return!e||e.length!==t.length||t.some(function(r,n){return r!==e[n]})}function Ba(e,t){return typeof t=="function"?t(e):t}var gn=0;function a(e,t,r,n,o,i){t||(t={});var s,c,u=t;if("ref"in u)for(c in u={},t)c=="ref"?s=t[c]:u[c]=t[c];var d={type:e,props:u,key:r,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--gn,__i:-1,__u:0,__source:o,__self:i};if(typeof e=="function"&&(s=e.defaultProps))for(c in s)u[c]===void 0&&(u[c]=s[c]);return V.vnode&&V.vnode(d),d}function za(e){return Math.min(1,Math.max(0,e))}function Ha({agent:e,agentState:t}){let r=G(null),n=G(0),o=G(0),i=G(0),s=G(t);return P(()=>{s.current=t},[t]),P(()=>e.on(u=>{u.type==="audio_level"&&(n.current=u.mic,o.current=u.tts)}),[e]),P(()=>{let c=r.current;if(!c)return;let u=c.getContext("2d");if(!u)return;let d=0,m=typeof window!="undefined"&&window.devicePixelRatio||1,l=()=>{let f=c.parentElement,k=f?f.clientWidth:320,C=200;c.width=Math.floor(k*m),c.height=Math.floor(C*m),c.style.width=`${k}px`,c.style.height=`${C}px`,u.setTransform(m,0,0,m,0,0)};l();let b=null;try{b=new ResizeObserver(l),c.parentElement&&b.observe(c.parentElement)}catch{l()}let p=f=>{i.current=f*.001;let k=c.clientWidth||320,C=c.clientHeight||200;u.clearRect(0,0,k,C);let g=s.current,S=g==="thinking"||g==="transcribing"?.22+Math.sin(f*.0022)*.08:g==="idle"?.08+Math.sin(f*.0015)*.04:0,N=za(n.current+S*.35),M=za(o.current),H=Math.max(N,M,S),_=k*.5,v=C*.42,T=k*.38,h=12+H*55,J=[{phase:0,alpha:.45,w:2.2},{phase:.4,alpha:.65,w:1.8},{phase:-.35,alpha:.85,w:1.4}];for(let B of J){let W=i.current*1.2+B.phase;u.save(),u.lineWidth=B.w,u.lineCap="round",u.shadowBlur=18+H*28,u.shadowColor=g==="speaking"?`rgba(160, 200, 255, ${.35+M*.45})`:`rgba(140, 200, 90, ${.35+N*.45})`;let Q=u.createLinearGradient(0,0,k,0);Q.addColorStop(0,`rgba(80, 220, 160, ${B.alpha})`),Q.addColorStop(.45,`rgba(100, 180, 255, ${B.alpha})`),Q.addColorStop(1,`rgba(220, 120, 255, ${B.alpha})`),u.strokeStyle=Q,u.globalAlpha=.75+H*.2,u.beginPath();let ue=48;for(let R=0;R<=ue;R++){let $=R/ue,z=_-T+$*T*2,F=Math.sin($*Math.PI+W)*h*(.35+.65*H)+Math.sin($*Math.PI*3+W*2)*(3+H*12)*B.alpha,E=v+F+Math.sin(W+$*4)*H*6;R===0?u.moveTo(z,E):u.lineTo(z,E)}u.stroke(),u.restore()}d=requestAnimationFrame(p)};return d=requestAnimationFrame(p),()=>{cancelAnimationFrame(d),b==null||b.disconnect()}},[e]),a("div",{className:"voice-aura-wrap",children:a("canvas",{ref:r,className:"voice-aura-canvas","aria-hidden":!0})})}function fn(e){let t=new Date(e);return t.setHours(0,0,0,0),t.getTime()}function bn(e){let t=fn(new Date),r=t-7*864e5,n=[],o=[],i=[];for(let s of e){let c=s.updatedAt;c>=t?n.push(s):c>=r?o.push(s):i.push(s)}return{today:n,last7:o,older:i}}var Ua="oasis-chat-history-panel";function Wa({conversations:e,activeId:t,onSelectConversation:r,onNewChat:n,onDeleteConversation:o}){var F;let[i,s]=y(!1),[c,u]=y(""),[d,m]=y(!1),[l,b]=y(null),p=G(null),f=G(null),k=G(null),C=G(null),[g,S]=y(null),N=G(""),M=G(0),H=be(()=>{let E=c.replace(/\s+/g," ").trim().toLowerCase();return E?e.filter(I=>(I.title||"New chat").toLowerCase().includes(E)):e},[e,c]),{today:_,last7:v,older:T}=be(()=>bn(H),[H]),h=j(()=>{s(!1),u(""),b(null),requestAnimationFrame(()=>{var E;(E=k.current)==null||E.focus()})},[]),J=j(async()=>{if(!l)return;let{id:E}=l;try{await Promise.resolve(o(E)),h()}catch(I){console.error("oasis delete chat",I)}},[l,o,h]),B=j(E=>{E.preventDefault(),E.stopPropagation(),s(I=>!I)},[]);P(()=>{if(!i){m(!1);return}let E=window.setTimeout(()=>{var I;(I=C.current)==null||I.focus()},0);return()=>window.clearTimeout(E)},[i]);let W=j(()=>{let E=p.current,I=k.current;if(!E||!I)return;let ee=E.closest(".assistant-container");if(!ee){N.current="",S(null);return}let K=8,w=ee.getBoundingClientRect(),X=I.getBoundingClientRect(),U=Math.max(160,Math.min(280,Math.floor(w.width-K*2))),se=Math.round(window.innerWidth-w.right+K),pe=Math.round(X.bottom+6),Me=window.innerWidth-se-U,Le=w.left+K,Ee=Me{if(!i){N.current="",S(null),M.current&&(cancelAnimationFrame(M.current),M.current=0);return}let E=()=>{M.current&&cancelAnimationFrame(M.current),M.current=requestAnimationFrame(()=>{M.current=0,W()})};W();let I=p.current,ee=I==null?void 0:I.closest(".assistant-container"),K=new ResizeObserver(()=>{E()});return ee&&K.observe(ee),window.addEventListener("resize",E),()=>{K.disconnect(),window.removeEventListener("resize",E),M.current&&(cancelAnimationFrame(M.current),M.current=0)}},[i,W]),P(()=>{if(!i)return;function E(ee){let K=p.current;K&&!K.contains(ee.target)&&h()}function I(ee){ee.key==="Escape"&&h()}return document.addEventListener("mousedown",E),document.addEventListener("keydown",I),()=>{document.removeEventListener("mousedown",E),document.removeEventListener("keydown",I)}},[i,h]);let Q=E=>({display:"flex",alignItems:"center",gap:"2px",width:"100%",borderRadius:"var(--border-radius-large)",boxSizing:"border-box",background:E?"color-mix(in srgb, var(--primary-green) 14%, var(--surface-page))":"transparent"}),ue={display:"flex",alignItems:"center",gap:"8px",flex:1,minWidth:0,padding:"8px 4px 8px 12px",border:"none",background:"transparent",color:"var(--text-headings)",font:"inherit",fontSize:"13px",textAlign:"left",cursor:"pointer",borderRadius:"var(--border-radius-large)",boxSizing:"border-box"},R={flexShrink:0,width:"32px",height:"36px",display:"flex",alignItems:"center",justifyContent:"center",border:"none",background:"transparent",color:"var(--text-secondary)",cursor:"pointer",borderRadius:"var(--border-radius-large)",padding:0},$=(E,I)=>I.length===0?null:a("div",{role:"group","aria-label":E,children:[a("div",{style:{fontSize:"11px",fontWeight:600,letterSpacing:"0.04em",textTransform:"uppercase",color:"var(--text-secondary)",padding:"10px 12px 4px"},children:E}),a("ul",{role:"list",style:{listStyle:"none",margin:0,padding:"0 4px 8px"},children:I.map(ee=>{var X;let K=ee.id===t,w=((X=ee.title)==null?void 0:X.trim())||"New chat";return a("li",{style:{margin:0,padding:0},children:a("div",{style:Q(K),onMouseEnter:U=>{K||(U.currentTarget.style.background="rgba(122, 146, 0, 0.08)")},onMouseLeave:U=>{U.currentTarget.style.background=K?"color-mix(in srgb, var(--primary-green) 14%, var(--surface-page))":"transparent"},children:[a("button",{type:"button","aria-current":K?"true":void 0,style:ue,title:w,onClick:U=>{U.preventDefault(),U.stopPropagation(),r(ee.id),h()},children:[K?a("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"var(--primary-green)",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:a("path",{d:"M20 6L9 17l-5-5"})}):a("span",{style:{width:"14px",flexShrink:0},"aria-hidden":!0}),a("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:w})]}),a("button",{type:"button","aria-label":`Delete chat: ${w}`,title:"Delete chat",style:R,onMouseDown:U=>{U.preventDefault(),U.stopPropagation()},onClick:U=>{U.preventDefault(),U.stopPropagation(),b({id:ee.id,title:w})},onMouseEnter:U=>{U.currentTarget.style.color="var(--primary-green)",U.currentTarget.style.background="rgba(122, 146, 0, 0.1)"},onMouseLeave:U=>{U.currentTarget.style.color="var(--text-secondary)",U.currentTarget.style.background="transparent"},children:a("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:a("path",{d:"M3 6h18M8 6V4h8v2M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6M10 11v6M14 11v6"})})})]})},ee.id)})})]},E),z=_.length>0||v.length>0||T.length>0;return a("div",{ref:p,className:"oasis-chat-history-wrap",style:{position:"relative",flexShrink:0},children:[a("button",{ref:k,type:"button",className:"oasis-chat-history-trigger",title:"Chat history","aria-label":"Open chat history","aria-expanded":i,"aria-controls":Ua,"aria-haspopup":"dialog",onClick:B,style:{border:"none",background:"transparent",cursor:"pointer",padding:"2px",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--primary-green)",flexShrink:0},onMouseEnter:E=>E.currentTarget.style.backgroundColor="rgba(122, 146, 0, 0.12)",onMouseLeave:E=>E.currentTarget.style.backgroundColor="transparent",children:a("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[a("circle",{cx:"12",cy:"12",r:"10"}),a("path",{d:"M12 6v6l4 2"})]})}),i?a("div",{ref:f,id:Ua,role:"dialog","aria-label":"Chat history",className:"oasis-chat-history-panel dropdown-menu",style:{position:"fixed",top:g?`${g.top}px`:0,right:g?`${g.right}px`:0,width:g?`${g.width}px`:260,maxHeight:(F=g==null?void 0:g.maxHeight)!=null?F:"min(320px, 55vh)",display:"flex",flexDirection:"column",background:"var(--surface-page)",border:"1px solid color-mix(in srgb, var(--text-body) 18%, transparent)",borderRadius:"var(--border-radius-lg)",boxShadow:"0 8px 28px rgba(0, 0, 0, 0.12)",zIndex:1001,overflow:"hidden",transform:g==null?void 0:g.transform,opacity:g?1:0,pointerEvents:g?"auto":"none"},onMouseDown:E=>E.stopPropagation(),children:[a("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"10px 10px 8px",borderBottom:"1px solid color-mix(in srgb, var(--text-body) 12%, transparent)",flexShrink:0},children:[a("input",{ref:C,type:"search",placeholder:"Search chats\u2026",value:c,onInput:E=>u(E.target.value),onFocus:()=>m(!0),onBlur:()=>m(!1),"aria-label":"Search chats",style:{flex:1,minWidth:0,font:"inherit",fontSize:"13px",padding:"6px 10px",borderRadius:"var(--border-radius-large)",border:d?"1px solid var(--primary-green)":"1px solid color-mix(in srgb, var(--text-body) 20%, transparent)",background:"var(--surface-default)",color:"var(--text-headings)",boxSizing:"border-box",outline:"none",boxShadow:d?"0 0 0 2px color-mix(in srgb, var(--primary-green) 28%, transparent)":"none",WebkitAppearance:"none",appearance:"none"}}),a("button",{type:"button",title:"New chat","aria-label":"Start new chat",onClick:E=>{E.preventDefault(),E.stopPropagation(),n(),h()},style:{flexShrink:0,width:"32px",height:"32px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"var(--border-radius-large)",border:"1px solid var(--primary-green)",background:"color-mix(in srgb, var(--primary-green) 10%, var(--surface-page))",color:"var(--primary-green)",cursor:"pointer",padding:0},children:a("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":!0,children:a("path",{d:"M12 5v14M5 12h14"})})})]}),l?a("div",{style:{flexShrink:0,padding:"10px 12px",borderBottom:"1px solid color-mix(in srgb, var(--text-body) 12%, transparent)",background:"color-mix(in srgb, var(--primary-green) 8%, var(--surface-page))"},children:[a("div",{style:{fontSize:"12px",color:"var(--text-headings)",marginBottom:"10px",lineHeight:1.35},children:`Delete "${l.title}"? This cannot be undone.`}),a("div",{style:{display:"flex",gap:"8px",justifyContent:"flex-end"},children:[a("button",{type:"button",onClick:()=>b(null),style:{font:"inherit",fontSize:"13px",padding:"6px 12px",borderRadius:"var(--border-radius-large)",border:"1px solid color-mix(in srgb, var(--text-body) 22%, transparent)",background:"var(--surface-page)",color:"var(--text-headings)",cursor:"pointer"},children:"Cancel"}),a("button",{type:"button",onClick:()=>{J()},style:{font:"inherit",fontSize:"13px",padding:"6px 12px",borderRadius:"var(--border-radius-large)",border:"1px solid color-mix(in srgb, #c62828 35%, transparent)",background:"color-mix(in srgb, #ffebee 55%, var(--surface-page))",color:"#c62828",cursor:"pointer",fontWeight:600},children:"Delete"})]})]}):null,a("div",{"aria-label":"Conversations",style:{overflowY:"auto",flex:1,minHeight:0,padding:"4px 0 8px"},children:z?a(te,{children:[$("Today",_),$("Previous 7 days",v),$("Older",T)]}):a("div",{style:{padding:"16px 14px",fontSize:"13px",color:"var(--text-secondary)",textAlign:"center"},children:c.trim()?"No chats match your search.":"No saved chats yet."})})]}):null]})}function nt(e){let t=window.assistantBridge;try{if(typeof(t==null?void 0:t.postOasisOverlayChromeMessage)=="function"&&t.postOasisOverlayChromeMessage(e))return}catch{}try{window.parent.postMessage(e,"*")}catch{}}function Fa(){let e=window.assistantBridge;try{return typeof(e==null?void 0:e.runOasisAssistantLayoutToggle)=="function"&&e.runOasisAssistantLayoutToggle()}catch{return!1}}var Gt=[{id:"traditional-light",label:"Traditional light",description:"Cool neutral white and gray with slate accent",scheme:"light",order:0},{id:"default",label:"Oasis (default)",description:"Warm off-white with Oasis green accent",scheme:"light",order:1},{id:"neutral-light",label:"Oasis neutral light",description:"Cool gray UI with saturated blue accent",scheme:"light",order:2},{id:"clean-light",label:"Oasis clean light",description:"Near-white zinc surfaces with olive accent",scheme:"light",order:3},{id:"warm-light",label:"Oasis warm light",description:"Cream paper tones with muted green accent",scheme:"light",order:4},{id:"ide-light",label:"IDE light",description:"Cool gray-white with GitHub-style blue accent",scheme:"light",order:5},{id:"vs-light",label:"Light (Visual Studio)",description:"Light gray chrome with classic VS blue accent",scheme:"light",order:6},{id:"light-modern",label:"Light Modern",description:"Bright white with modern blue focus ring accent",scheme:"light",order:7},{id:"light-plus",label:"Light+",description:"High-contrast white with deep blue link accent",scheme:"light",order:8},{id:"quiet-light",label:"Quiet light",description:"Soft gray surfaces with muted purple accent",scheme:"light",order:9},{id:"solarized-light",label:"Solarized light",description:"Warm cream base3 with cyan and green accents",scheme:"light",order:10},{id:"traditional-dark",label:"Traditional dark",description:"Charcoal neutrals with soft gray accent",scheme:"dark",order:0},{id:"violet-dark",label:"Violet dark",description:"Charcoal panels with purple accent",scheme:"dark",order:1},{id:"forest-dark",label:"Oasis forest dark",description:"Olive green panels with lime green accent",scheme:"dark",order:2},{id:"slate-dark",label:"Oasis slate dark",description:"Blue-gray panels with cyan accent",scheme:"dark",order:3},{id:"high-contrast",label:"Oasis high contrast",description:"Black UI with yellow accent and white text",scheme:"dark",order:4},{id:"cool-dark",label:"Cool dark",description:"Blue-gray IDE panels with periwinkle accent",scheme:"dark",order:5},{id:"midnight-dark",label:"Midnight dark",description:"GitHub-style blue-black with bright blue accent",scheme:"dark",order:6},{id:"vs-dark",label:"Dark (Visual Studio)",description:"VS dark gray chrome with blue accent",scheme:"dark",order:7},{id:"dark-modern",label:"Dark Modern",description:"Dark gray UI with saturated blue accent",scheme:"dark",order:8},{id:"dark-plus",label:"Dark+",description:"VS Dark+ charcoal with teal accent",scheme:"dark",order:9},{id:"abyss",label:"Abyss",description:"Deep navy with periwinkle blue accent",scheme:"dark",order:10},{id:"kimbie-dark",label:"Kimbie dark",description:"Warm brown wood with orange accent",scheme:"dark",order:11},{id:"monokai",label:"Monokai",description:"Charcoal with Monokai green accent",scheme:"dark",order:12}],mn=Gt.map(e=>e.id),hn=new Set(mn),vn=new Map(Gt.map(e=>[e.id,e.scheme]));function Va(e){return hn.has(e)}function qt(e){var t;return(t=vn.get(e))!=null?t:null}function Xt(e){return Gt.filter(t=>t.scheme===e).slice().sort((t,r)=>t.order-r.order)}function xn(e){return!e||e==="default"||!Va(e)?"default":e}function ot(e){let t=xn(e),r=document.documentElement;t==="default"?r.removeAttribute("data-oasis-theme"):r.setAttribute("data-oasis-theme",t)}var We=window,yn=Xt("light"),_n=Xt("dark"),Yt="https://kahana.co/docs",ja=380;function wn(e){if(e.preventDefault(),e.stopPropagation(),typeof We.openWebLinkIn=="function"){We.openWebLinkIn(Yt,"tab",{});return}if(window.top&&typeof window.top.openWebLinkIn=="function"){window.top.openWebLinkIn(Yt,"tab",{});return}window.open(Yt,"_blank","noopener,noreferrer")}function Ka({auth:e,onShowAuth:t,onOpenTrainingGallery:r,chatHistory:n=null}){let[o,i]=y(!1),[s,c]=y(!1),[u,d]=y("light"),[m,l]=y(()=>{var v,T;try{let h=(T=(v=We.assistantBridge)==null?void 0:v.getAssistantTheme)==null?void 0:T.call(v);return typeof h=="string"?h:"default"}catch{return"default"}}),[b,p]=y(!1),f=G(null),k=G(null),C=G(null),g=e.user&&typeof e.user!="string"?e.user.email:void 0;P(()=>{function v(T){let h=T.target;k.current&&!k.current.contains(h)&&i(!1),C.current&&!C.current.contains(h)&&c(!1)}return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]),P(()=>{var v;s&&d((v=qt(m))!=null?v:"light")},[s,m]),rt(()=>{let v=f.current;if(!v)return;let T=new ResizeObserver(()=>{p(v.getBoundingClientRect().widthT.disconnect()},[]);let S=v=>{let T=v.target;T.closest("button")||T.closest(".dropdown-menu")||T.closest(".oasis-chat-history-wrap")||T.closest(".assistant-theme-picker")||v.button===0&&(v.preventDefault(),v.stopPropagation(),nt({type:"oasisOverlayDragStart",screenX:v.screenX,screenY:v.screenY}))},N=async()=>{We.supabaseAuth&&(await We.supabaseAuth.signOut(),i(!1))},M=v=>{var h,J;ot(v),l(v),(J=(h=We.assistantBridge)==null?void 0:h.setAssistantTheme)==null||J.call(h,v);let T=qt(v);T&&d(T),c(!1)},H=b?6:8,_=b?6:8;return a("div",{ref:f,onPointerDown:S,style:{height:"44px",display:"flex",justifyContent:"space-between",alignItems:"center",gap:`${H}px`,padding:"0 8px",background:"transparent",cursor:"grab",zIndex:1e3,boxSizing:"border-box",userSelect:"none",flexShrink:0,minWidth:0},children:[a("div",{style:{display:"flex",alignItems:"center",gap:`${_}px`,flex:1,minWidth:0,overflow:"hidden"},children:[a("button",{type:"button",title:b?"Training progress \u2014 Oasis Beta":"Training progress","aria-label":"Open training badges and streak progress",onClick:v=>{v.preventDefault(),v.stopPropagation(),r()},style:{width:32,height:32,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",border:"none",background:"transparent",cursor:"pointer",borderRadius:"50%",padding:0},onMouseEnter:v=>v.currentTarget.style.backgroundColor="var(--icon-accent-hover-bg)",onMouseLeave:v=>v.currentTarget.style.backgroundColor="transparent",children:a("svg",{width:"32",height:"32",viewBox:"0 0 32 32",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a("ellipse",{cx:"16.5",cy:"16",rx:"12.5",ry:"10.5",fill:"var(--text-secondary)"}),a("ellipse",{cx:"16.5",cy:"18",rx:"10.5",ry:"8.5",fill:"var(--surface-default)"}),a("ellipse",{cx:"10.3268",cy:"18.7453",rx:"2.45004",ry:"5.0274",transform:"rotate(46.2818 10.3268 18.7453)",fill:"var(--text-secondary)"}),a("circle",{cx:"1",cy:"1",r:"1",transform:"matrix(1 0 0 -1 12 17.5)",fill:"var(--surface-default)"}),a("ellipse",{cx:"2.45004",cy:"5.0274",rx:"2.45004",ry:"5.0274",transform:"matrix(-0.691112 0.722747 0.722747 0.691112 20.7329 13.5)",fill:"var(--text-secondary)"}),a("circle",{cx:"1",cy:"1",r:"1",transform:"matrix(1 0 0 -1 19 17.5)",fill:"var(--surface-default)"})]})}),a("span",{style:{fontSize:"20px",fontWeight:600,color:"var(--header-title-color)",fontFamily:"system-ui, -apple-system, sans-serif",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:b?"Oasis":"Oasis AI"}),b?null:a("div",{style:{background:"var(--header-badge-bg)",padding:"1px 8px",borderRadius:"32px",display:"flex",alignItems:"center",flexShrink:1,minWidth:0,overflow:"hidden"},children:a("span",{style:{fontSize:"12px",color:"var(--header-badge-text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"Beta"})})]}),a("div",{style:{display:"flex",alignItems:"center",gap:"4px",flexShrink:0},children:[a("button",{type:"button",onClick:wn,title:"Help \u2014 Oasis documentation","aria-label":"Oasis AI help, opens documentation in a new tab",style:{border:"none",background:"transparent",cursor:"pointer",padding:"2px",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--icon-accent-color)",flexShrink:0},onMouseEnter:v=>v.currentTarget.style.backgroundColor="var(--icon-accent-hover-bg)",onMouseLeave:v=>v.currentTarget.style.backgroundColor="transparent",children:a("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[a("circle",{cx:"12",cy:"12",r:"10"}),a("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),a("circle",{cx:"12",cy:"17",r:"1.35",fill:"currentColor",stroke:"none"})]})}),a("div",{style:{position:"relative"},ref:C,children:[a(Jt,{onClick:v=>{v.preventDefault(),v.stopPropagation(),c(T=>!T),i(!1)},title:"Color theme",ariaLabel:"Choose assistant color theme",children:a("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[a("path",{d:"M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0L12 2.69z",stroke:"currentColor",fill:"none"}),a("circle",{cx:"8.5",cy:"9.5",r:"1.2",fill:"currentColor",stroke:"none"}),a("circle",{cx:"12",cy:"7",r:"1.2",fill:"currentColor",stroke:"none"}),a("circle",{cx:"15.5",cy:"9.5",r:"1.2",fill:"currentColor",stroke:"none"})]})}),s?a("div",{className:"assistant-theme-picker dropdown-menu",style:{position:"absolute",top:"32px",right:"0",width:"min(300px, 78vw)",maxHeight:"min(420px, 58vh)",display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--dropdown-surface)",border:"1px solid var(--dropdown-border-color)",borderRadius:"12px",boxShadow:"0 4px 20px rgba(0,0,0,0.12)",zIndex:1001,padding:"8px 0 0"},children:[a("div",{style:{padding:"6px 14px 8px",fontSize:"11px",fontWeight:600,letterSpacing:"0.04em",textTransform:"uppercase",color:"var(--dropdown-muted-text)"},children:"Color theme"}),a("div",{role:"group","aria-label":"Light or dark themes",style:{display:"flex",margin:"0 12px 8px",borderRadius:"8px",border:"1px solid var(--dropdown-border-color)",overflow:"hidden"},children:[a("button",{type:"button",role:"tab","aria-selected":u==="light","aria-pressed":u==="light",onClick:()=>d("light"),style:{flex:1,border:"none",margin:0,padding:"8px 10px",font:"inherit",fontSize:"12px",fontWeight:600,cursor:"pointer",background:u==="light"?"var(--dropdown-item-hover)":"var(--dropdown-header-bg)",color:"var(--dropdown-item-text)",boxSizing:"border-box"},children:"Light"}),a("button",{type:"button",role:"tab","aria-selected":u==="dark","aria-pressed":u==="dark",onClick:()=>d("dark"),style:{flex:1,border:"none",borderLeft:"1px solid var(--dropdown-border-color)",margin:0,padding:"8px 10px",font:"inherit",fontSize:"12px",fontWeight:600,cursor:"pointer",background:u==="dark"?"var(--dropdown-item-hover)":"var(--dropdown-header-bg)",color:"var(--dropdown-item-text)",boxSizing:"border-box"},children:"Dark"})]}),a("div",{style:{flex:1,minHeight:0,maxHeight:"min(320px, 50vh)",overflowY:"auto",paddingBottom:"8px"},children:(u==="light"?yn:_n).map(v=>a("button",{type:"button",onClick:()=>M(v.id),style:{display:"block",width:"100%",textAlign:"left",border:"none",borderLeft:m===v.id?"3px solid var(--icon-accent-color)":"3px solid transparent",background:m===v.id?"var(--dropdown-item-hover)":"transparent",padding:"10px 14px 10px 11px",cursor:"pointer",font:"inherit",boxSizing:"border-box"},children:[a("div",{style:{fontSize:"13px",fontWeight:600,color:"var(--dropdown-item-text)"},children:v.label}),a("div",{style:{fontSize:"11px",color:"var(--dropdown-muted-text)",marginTop:"2px",lineHeight:1.35},children:v.description})]},v.id))})]}):null]}),n?a(Wa,{conversations:n.conversations,activeId:n.activeId,onSelectConversation:n.onSelectConversation,onNewChat:n.onNewChat,onDeleteConversation:n.onDeleteConversation}):null,a("div",{style:{position:"relative"},ref:k,children:[a(Jt,{onClick:()=>{i(!o),c(!1)},title:"Account",ariaLabel:"Account menu, sign in or sign up",children:a("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[a("circle",{cx:"12",cy:"8",r:"4"}),a("path",{d:"M5 20c0-3.9 3.1-7 7-7s7 3.1 7 7"})]})}),o&&a("div",{className:"dropdown-menu",style:{position:"absolute",top:"32px",right:"0",background:"var(--dropdown-surface)",border:"1px solid var(--dropdown-border-color)",borderRadius:"12px",boxShadow:"0 4px 20px rgba(0,0,0,0.1)",width:"200px",overflow:"hidden",zIndex:1e3},children:e.isAuthenticated?a("div",{children:[a("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--dropdown-border-color)",background:"var(--dropdown-header-bg)"},children:[a("div",{style:{fontSize:"11px",color:"var(--dropdown-muted-text)",marginBottom:"2px"},children:"Signed in as"}),a("div",{style:{fontSize:"13px",fontWeight:500,color:"var(--dropdown-item-text)",overflow:"hidden",textOverflow:"ellipsis"},children:g})]}),a($a,{onClick:N,style:{color:"#e53935"},children:"Sign Out"})]}):a("div",{children:a($a,{onClick:()=>{t(),i(!1)},children:"Sign In / Sign Up"})})})]}),a(Jt,{onClick:v=>{v.preventDefault(),v.stopPropagation(),Fa()||nt({type:"oasisOverlayToggleSidebar"})},title:"Toggle Sidebar",children:a("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:a("path",{d:"M6 21C5.20435 21 4.44129 20.6839 3.87868 20.1213C3.31607 19.5587 3 18.7956 3 18V6C3 5.20435 3.31607 4.44129 3.87868 3.87868C4.44129 3.31607 5.20435 3 6 3H18C18.7956 3 19.5587 3.31607 20.1213 3.87868C20.6839 4.44129 21 5.20435 21 6V18C21 18.7956 20.6839 19.5587 20.1213 20.1213C19.5587 20.6839 18.7956 21 18 21H6ZM18 5H10V19H18C18.2652 19 18.5196 18.8946 18.7071 18.7071C18.8946 18.5196 19 18.2652 19 18V6C19 5.73478 18.8946 5.48043 18.7071 5.29289C18.5196 5.10536 18.2652 5 18 5Z",fill:"currentColor"})})})]})]})}function Jt({onClick:e,title:t,children:r,hoverColor:n,ariaLabel:o}){return a("button",{onClick:e,title:t,"aria-label":o!=null?o:t,style:{border:0,background:"transparent",cursor:"pointer",borderRadius:"50%",width:"28px",height:"28px",display:"flex",alignItems:"center",justifyContent:"center",transition:"background 0.2s",color:"var(--icon-accent-color)"},onMouseEnter:i=>i.currentTarget.style.backgroundColor=n||"var(--icon-accent-hover-bg)",onMouseLeave:i=>i.currentTarget.style.backgroundColor="transparent",children:r})}function $a({onClick:e,children:t,style:r}){return a("div",{onClick:e,style:{padding:"10px 16px",fontSize:"13px",color:"var(--dropdown-item-text)",cursor:"pointer",transition:"background 0.1s",...r},onMouseEnter:n=>n.currentTarget.style.backgroundColor="var(--dropdown-item-hover)",onMouseLeave:n=>n.currentTarget.style.backgroundColor="var(--dropdown-surface)",children:t})}var kn=window;function Ga(){return a("svg",{width:"18",height:"18",viewBox:"0 0 24 24","aria-hidden":"true",children:[a("path",{fill:"#EA4335",d:"M12 10.2v3.9h5.4c-.2 1.3-1.5 3.9-5.4 3.9-3.3 0-6-2.7-6-6s2.7-6 6-6c1.9 0 3.2.8 3.9 1.5l2.7-2.6C16.9 3.2 14.7 2.2 12 2.2 6.6 2.2 2.2 6.6 2.2 12S6.6 21.8 12 21.8c6.9 0 9.2-4.8 9.2-7.3 0-.5 0-.9-.1-1.3H12Z"}),a("path",{fill:"#34A853",d:"M2.2 12c0 2 .8 3.8 2.1 5.1l3.4-2.6c-.9-.7-1.5-1.8-1.5-3.1s.5-2.4 1.5-3.1L4.3 5.7C3 7 2.2 9.1 2.2 12Z"}),a("path",{fill:"#FBBC05",d:"M12 21.8c2.7 0 4.9-.9 6.5-2.5l-3.2-2.5c-.9.6-2 1-3.3 1-2.5 0-4.6-1.7-5.4-4l-3.4 2.6c1.7 3.2 5 5.4 8.8 5.4Z"}),a("path",{fill:"#4285F4",d:"M18.5 19.3c1.9-1.8 2.7-4.4 2.7-6.6 0-.7-.1-1.2-.2-1.7H12v3.9h5.4c-.3 1.5-1.1 2.8-2.3 3.7l3.4 2.7Z"})]})}function qa(){return a("svg",{width:"18",height:"18",viewBox:"0 0 24 24","aria-hidden":"true",children:a("path",{fill:"#111",d:"M16.7 12.8c0-2.1 1.8-3.1 1.9-3.2-1-1.5-2.7-1.7-3.3-1.7-1.4-.1-2.8.9-3.5.9-.8 0-1.9-.9-3.1-.9-1.6 0-3 .9-3.9 2.2-1.7 2.9-.4 7.2 1.2 9.4.8 1.1 1.7 2.4 2.9 2.3 1.1 0 1.6-.7 3-.7 1.5 0 1.9.7 3 .7 1.2 0 2-.9 2.8-2 .9-1.3 1.3-2.5 1.3-2.6-.1 0-2.3-.9-2.3-4.4Zm-2.3-6.3c.6-.8 1-1.8.9-2.9-.9 0-2.1.6-2.8 1.4-.6.7-1.1 1.8-.9 2.8 1 0 2.1-.5 2.8-1.3Z"})})}function Xa(){return a("svg",{width:"18",height:"18",viewBox:"0 0 24 24","aria-hidden":"true",children:[a("path",{fill:"#F25022",d:"M3 3h8.6v8.6H3z"}),a("path",{fill:"#7FBA00",d:"M12.4 3H21v8.6h-8.6z"}),a("path",{fill:"#00A4EF",d:"M3 12.4h8.6V21H3z"}),a("path",{fill:"#FFB900",d:"M12.4 12.4H21V21h-8.6z"})]})}function Ya({onSuccess:e,onEmailPasswordOpen:t}){let r=G(!1),[n,o]=y("signin"),[i,s]=y(""),[c,u]=y(""),[d,m]=y(!1),[l,b]=y(!1),[p,f]=y(null),[k,C]=y(null),[g,S]=y(!1);P(()=>{S(!1)},[n]);let N=g&&n!=="forgotPassword";P(()=>{if(!N)return;let R=window.requestAnimationFrame(()=>{var $,z;($=document.getElementById("auth-email-input"))==null||$.focus(),(z=document.getElementById("oasis-auth-email-form"))==null||z.scrollIntoView({block:"nearest",behavior:"smooth"})});return()=>window.cancelAnimationFrame(R)},[N]),P(()=>{let R=$=>{let z=$.detail,F=(z==null?void 0:z.description)||(z==null?void 0:z.error);F&&(f(F),C(null))};return window.addEventListener("oasis-auth-error",R),()=>{window.removeEventListener("oasis-auth-error",R)}},[]);let M=async R=>{var z,F,E,I,ee;if(r.current)return;r.current=!0,f(null),C(null),m(!0);try{(F=(z=kn.assistantBridge)==null?void 0:z.markOauthSignInStarted)==null||F.call(z)}catch{}let $=window.supabaseAuth;if(!$){f("Auth service not available"),r.current=!1,m(!1);return}try{let K=await $[R](),w=((E=K==null?void 0:K.error)==null?void 0:E.message)||"",X=["GOOGLE_OAUTH_URL:","AZURE_OAUTH_URL:","APPLE_OAUTH_URL:"].find(U=>w.startsWith(U));if(X){let U=w.slice(X.length);((ee=(I=window.assistantBridge)==null?void 0:I.openTab)==null?void 0:ee.call(I,U))?C("Finish sign-in in the opened tab. Oasis will complete sign-in automatically."):f("Failed to open the OAuth tab. Please try again."),m(!1);return}if(K!=null&&K.error){let U=$.handleAuthError?$.handleAuthError(K.error):K.error.message||"An error occurred";f(U)}else K!=null&&K.user&&e()}catch(K){let w=$.handleAuthError?$.handleAuthError(K):K.message||"An error occurred";f(w)}finally{r.current=!1,m(!1)}},H=async R=>{R.preventDefault(),f(null),C(null),b(!0);let $=window.supabaseAuth;if(!$){f("Auth service not available"),b(!1);return}try{let z=null;if(n==="signup")z=await $.signUp(i,c);else if(n==="signin")z=await $.signInWithEmail(i,c);else if(n==="forgotPassword"){let I=await $.resetPasswordForEmail(i);if(!I.error){C("Password reset email sent. Please check your inbox."),b(!1);return}z={user:null,error:I.error}}if(!z){f("An error occurred");return}let{user:F,error:E}=z;if(E){let I=$.handleAuthError?$.handleAuthError(E):E.message||"An error occurred";f(I);return}F?e():n==="signup"&&f("Please check your email for a confirmation link.")}catch(z){let F=window.supabaseAuth,E=F!=null&&F.handleAuthError?F.handleAuthError(z):z&&typeof z=="object"&&"message"in z?String(z.message||"An error occurred"):"An error occurred";f(E)}finally{b(!1)}},_=()=>{switch(n){case"signup":return"Create Account";case"signin":return"Welcome Back";case"forgotPassword":return"Reset Password"}},v=()=>{switch(n){case"signup":return"Create a new Oasis account.";case"signin":return"Sign in to your Oasis account.";case"forgotPassword":return"Enter your email to receive a reset link."}},T=R=>{o(R),f(null),C(null)},h=()=>{if(l)return"Processing...";switch(n){case"signup":return"Sign Up";case"signin":return"Sign In";case"forgotPassword":return"Send Reset Link"}},J=v(),B=n==="forgotPassword"||g,W=(n==="forgotPassword"?"auth-screen":n==="signup"?"auth-screen auth-screen--signup":"auth-screen auth-screen--signin")+(N?" auth-screen--email-focus":""),Q=a("div",{className:"auth-oauth-row",children:[a("button",{type:"button","aria-label":"Continue with Google",onClick:()=>M("signInWithGoogle"),disabled:d,className:"auth-oauth-provider-btn",children:a(Ga,{})}),a("button",{type:"button","aria-label":"Continue with Microsoft",onClick:()=>M("signInWithAzure"),disabled:d,className:"auth-oauth-provider-btn",children:a(Xa,{})}),a("button",{type:"button","aria-label":"Continue with Apple",onClick:()=>M("signInWithApple"),disabled:d,className:"auth-oauth-provider-btn",children:a(qa,{})})]}),ue=(n==="signup"?"Sign up":"Sign in")+" with Google, Microsoft, or Apple";return a("div",{id:"oasis-auth-panel",className:W,children:[n!=="forgotPassword"&&a("div",{className:"auth-mode-tablist",role:"tablist","aria-label":"Sign in or create account",children:[a("button",{type:"button",role:"tab",className:`auth-mode-tab${n==="signin"?" auth-mode-tab--active":""}`,"aria-selected":n==="signin","aria-controls":"auth-tabpanel",id:"auth-tab-signin",onClick:()=>T("signin"),children:"Sign In"}),a("button",{type:"button",role:"tab",className:`auth-mode-tab${n==="signup"?" auth-mode-tab--active":""}`,"aria-selected":n==="signup","aria-controls":"auth-tabpanel",id:"auth-tab-signup",onClick:()=>T("signup"),children:"Create account"})]}),a("div",{className:"auth-tabpanel-stack",role:n==="forgotPassword"?void 0:"tabpanel",id:n==="forgotPassword"?void 0:"auth-tabpanel","aria-labelledby":n==="forgotPassword"?void 0:n==="signup"?"auth-tab-signup":"auth-tab-signin",children:[a("div",{className:"auth-screen-header",children:[a("h2",{className:"auth-screen-title",id:"auth-screen-heading",children:_()}),J?a("p",{className:"auth-screen-subtitle",id:"auth-screen-subtitle",children:J}):null]}),n!=="forgotPassword"&&(g?a("details",{className:"auth-oauth-details",children:[a("summary",{className:"auth-oauth-details-summary",children:a("span",{className:"auth-oauth-details-summary-inner",children:[a("span",{className:"auth-oauth-details-summary-icons","aria-hidden":"true",children:[a("span",{className:"auth-oauth-details-summary-icon-wrap",children:a(Ga,{})}),a("span",{className:"auth-oauth-details-summary-icon-wrap",children:a(Xa,{})}),a("span",{className:"auth-oauth-details-summary-icon-wrap",children:a(qa,{})})]}),a("span",{className:"auth-oauth-details-summary-label",children:ue})]})}),Q]}):Q),n!=="forgotPassword"&&!g&&a("button",{type:"button",className:"auth-email-password-trigger",onClick:()=>{t==null||t(),S(!0)},children:"Email and password"}),B&&a("form",{id:"oasis-auth-email-form",className:"auth-form-minimal",onSubmit:H,children:[a("div",{className:"auth-field-minimal",children:[a("label",{className:"auth-field-minimal-label",htmlFor:"auth-email-input",children:"email"}),a("input",{id:"auth-email-input",type:"email",value:i,onInput:R=>s(R.currentTarget.value),required:!0,className:"auth-field-minimal-input",autoComplete:"email"})]}),n!=="forgotPassword"&&a("div",{className:"auth-field-minimal",children:[a("div",{className:"auth-password-label-row",children:[a("label",{className:"auth-field-minimal-label",htmlFor:"auth-password-input",children:"password"}),n==="signin"&&a("button",{type:"button",className:"auth-link-inline",onClick:()=>{o("forgotPassword"),f(null),C(null)},children:"Forgot password?"})]}),a("input",{id:"auth-password-input",type:"password",value:c,onInput:R=>u(R.currentTarget.value),required:!0,className:"auth-field-minimal-input",autoComplete:n==="signup"?"new-password":"current-password"})]}),p&&a("div",{className:"auth-message auth-message-error",children:p}),k&&a("div",{className:"auth-message auth-message-success",children:k}),a("button",{type:"submit",className:"auth-submit-btn",disabled:l,children:h()})]}),n==="forgotPassword"&&a("div",{className:"auth-footer-links",children:a("button",{type:"button",className:"auth-link-standalone",onClick:()=>T("signin"),children:"Back to Sign In"})})]})]})}function Ja({data:e,onConfirm:t,onCancel:r}){return a("div",{className:"confirmation-overlay",style:{position:"fixed",top:0,left:0,right:0,bottom:0,background:"rgba(0, 0, 0, 0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e4},children:a("div",{className:"confirmation-modal",style:{background:"#fff",borderRadius:"12px",padding:"24px",maxWidth:"400px",width:"90%",boxShadow:"0 4px 20px rgba(0, 0, 0, 0.15)",textAlign:"center"},children:[a("div",{style:{width:"48px",height:"48px",background:"#FFF8E1",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",margin:"0 auto 16px auto"},children:a("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"var(--primary-green)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:a("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}),a("h3",{style:{margin:"0 0 8px 0",fontSize:"18px",fontWeight:600,color:"#333"},children:"Confirm Action"}),a("p",{style:{margin:"0 0 16px 0",fontSize:"14px",color:"#666"},children:e.description}),a("div",{style:{background:"#E8F5E9",borderRadius:"8px",padding:"8px 12px",marginBottom:"20px",fontSize:"13px",color:"#2E7D32"},children:["Command: ",e.command]}),a("div",{style:{display:"flex",gap:"12px"},children:[a("button",{onClick:r,style:{flex:1,padding:"12px 16px",border:"1px solid #ddd",borderRadius:"8px",background:"#fff",color:"#333",fontSize:"14px",fontWeight:500,cursor:"pointer"},children:"Cancel"}),a("button",{onClick:t,style:{flex:1,padding:"12px 16px",border:"none",borderRadius:"8px",background:"var(--primary-green)",color:"#fff",fontSize:"14px",fontWeight:500,cursor:"pointer"},children:"Approve"})]})]})})}function Cn(e,t){for(var r in t)e[r]=t[r];return e}function Za(e,t){for(var r in e)if(r!=="__source"&&!(r in t))return!0;for(var n in t)if(n!=="__source"&&e[n]!==t[n])return!0;return!1}function Qa(e,t){this.props=e,this.context=t}(Qa.prototype=new xe).isPureReactComponent=!0,Qa.prototype.shouldComponentUpdate=function(e,t){return Za(this.props,e)||Za(this.state,t)};var er=V.__b;V.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),er&&er(e)};var Ti=typeof Symbol!="undefined"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;var An=V.__e;V.__e=function(e,t,r,n){if(e.then){for(var o,i=t;i=i.__;)if((o=i.__c)&&o.__c)return t.__e==null&&(t.__e=r.__e,t.__k=r.__k),o.__c(e,t)}An(e,t,r,n)};var tr=V.unmount;function sr(e,t,r){return e&&(e.__c&&e.__c.__H&&(e.__c.__H.__.forEach(function(n){typeof n.__c=="function"&&n.__c()}),e.__c.__H=null),(e=Cn({},e)).__c!=null&&(e.__c.__P===r&&(e.__c.__P=t),e.__c.__e=!0,e.__c=null),e.__k=e.__k&&e.__k.map(function(n){return sr(n,t,r)})),e}function lr(e,t,r){return e&&r&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(n){return lr(n,t,r)}),e.__c&&e.__c.__P===t&&(e.__e&&r.appendChild(e.__e),e.__c.__e=!0,e.__c.__P=r)),e}function Zt(){this.__u=0,this.o=null,this.__b=null}function cr(e){var t=e.__.__c;return t&&t.__a&&t.__a(e)}function yt(){this.i=null,this.l=null}V.unmount=function(e){var t=e.__c;t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),tr&&tr(e)},(Zt.prototype=new xe).__c=function(e,t){var r=t.__c,n=this;n.o==null&&(n.o=[]),n.o.push(r);var o=cr(n.__v),i=!1,s=function(){i||(i=!0,r.__R=null,o?o(c):c())};r.__R=s;var c=function(){if(!--n.__u){if(n.state.__a){var u=n.state.__a;n.__v.__k[0]=lr(u,u.__c.__P,u.__c.__O)}var d;for(n.setState({__a:n.__b=null});d=n.o.pop();)d.forceUpdate()}};n.__u++||32&t.__u||n.setState({__a:n.__b=n.__v.__k[0]}),e.then(s,s)},Zt.prototype.componentWillUnmount=function(){this.o=[]},Zt.prototype.render=function(e,t){if(this.__b){if(this.__v.__k){var r=document.createElement("div"),n=this.__v.__k[0].__c;this.__v.__k[0]=sr(this.__b,r,n.__O=n.__P)}this.__b=null}var o=t.__a&&Ae(te,null,e.fallback);return o&&(o.__u&=-33),[Ae(te,null,t.__a?null:e.children),o]};var ar=function(e,t,r){if(++r[1]===r[0]&&e.l.delete(t),e.props.revealOrder&&(e.props.revealOrder[0]!=="t"||!e.l.size))for(r=e.i;r;){for(;r.length>3;)r.pop()();if(r[1]>>1,1),t.h.removeChild(o)}}}tt(Ae(Tn,{context:t.context},e.__v),t.v)}function dr(e,t){var r=Ae(En,{__v:e,h:t});return r.containerInfo=t,r}(yt.prototype=new xe).__a=function(e){var t=this,r=cr(t.__v),n=t.l.get(e);return n[0]++,function(o){var i=function(){t.props.revealOrder?(n.push(o),ar(t,e,n)):o()};r?r(i):i()}},yt.prototype.render=function(e){this.i=null,this.l=new Map;var t=et(e.children);e.revealOrder&&e.revealOrder[0]==="b"&&t.reverse();for(var r=t.length;r--;)this.l.set(t[r],this.i=[1,0,this.i]);return e.children},yt.prototype.componentDidUpdate=yt.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,r){ar(e,r,t)})};var In=typeof Symbol!="undefined"&&Symbol.for&&Symbol.for("react.element")||60103,Nn=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,Mn=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Ln=/[A-Z0-9]/g,Pn=typeof document!="undefined",On=function(e){return(typeof Symbol!="undefined"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};xe.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(xe.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var rr=V.event;function Rn(){}function Dn(){return this.cancelBubble}function Bn(){return this.defaultPrevented}V.event=function(e){return rr&&(e=rr(e)),e.persist=Rn,e.isPropagationStopped=Dn,e.isDefaultPrevented=Bn,e.nativeEvent=e};var ur,zn={enumerable:!1,configurable:!0,get:function(){return this.class}},nr=V.vnode;V.vnode=function(e){typeof e.type=="string"&&(function(t){var r=t.props,n=t.type,o={},i=n.indexOf("-")===-1;for(var s in r){var c=r[s];if(!(s==="value"&&"defaultValue"in r&&c==null||Pn&&s==="children"&&n==="noscript"||s==="class"||s==="className")){var u=s.toLowerCase();s==="defaultValue"&&"value"in r&&r.value==null?s="value":s==="download"&&c===!0?c="":u==="translate"&&c==="no"?c=!1:u[0]==="o"&&u[1]==="n"?u==="ondoubleclick"?s="ondblclick":u!=="onchange"||n!=="input"&&n!=="textarea"||On(r.type)?u==="onfocus"?s="onfocusin":u==="onblur"?s="onfocusout":Mn.test(s)&&(s=u):u=s="oninput":i&&Nn.test(s)?s=s.replace(Ln,"-$&").toLowerCase():c===null&&(c=void 0),u==="oninput"&&o[s=u]&&(s="oninputCapture"),o[s]=c}}n=="select"&&o.multiple&&Array.isArray(o.value)&&(o.value=et(r.children).forEach(function(d){d.props.selected=o.value.indexOf(d.props.value)!=-1})),n=="select"&&o.defaultValue!=null&&(o.value=et(r.children).forEach(function(d){d.props.selected=o.multiple?o.defaultValue.indexOf(d.props.value)!=-1:o.defaultValue==d.props.value})),r.class&&!r.className?(o.class=r.class,Object.defineProperty(o,"className",zn)):(r.className&&!r.class||r.class&&r.className)&&(o.class=o.className=r.className),t.props=o})(e),e.$$typeof=In,nr&&nr(e)};var or=V.__r;V.__r=function(e){or&&or(e),ur=e.__c};var ir=V.diffed;V.diffed=function(e){ir&&ir(e);var t=e.props,r=e.__e;r!=null&&e.type==="textarea"&&"value"in t&&t.value!==r.value&&(r.value=t.value==null?"":t.value),ur=null};function pr(){var p;if(typeof document=="undefined"||typeof window=="undefined")return;let e=(p=window.matchMedia)==null?void 0:p.call(window,"(prefers-reduced-motion: reduce)");if(e!=null&&e.matches)return;let t=document.createElement("canvas");t.setAttribute("aria-hidden","true"),t.style.cssText="position:fixed;inset:0;pointer-events:none;z-index:20001;width:100%;height:100%",document.body.appendChild(t);let r=t.getContext("2d");if(!r){t.remove();return}let n=r,o=Math.min(window.devicePixelRatio||1,2),i=window.innerWidth,s=window.innerHeight;t.width=i*o,t.height=s*o,n.scale(o,o);let c=["#7a9200","#94a82e","#5a7000","#c5d49a","#4a5c00","#e8f0c8"],u=[],d=(f,k,C,g,S,N)=>{for(let M=0;M{d(72,i/2,s*.57,Math.PI*1.45,3.2,10.2)},190);let m=0,l=2150;function b(f){m||(m=f);let k=f-m;n.clearRect(0,0,i,s);let C=!1;for(let g of u){if(g.life>=g.max)continue;C=!0,g.life+=1,g.vy+=g.g,g.x+=g.vx,g.y+=g.vy,g.rot+=g.vr;let S=1-g.life/g.max;n.save(),n.globalAlpha=Math.max(0,S*.95),n.translate(g.x,g.y),n.rotate(g.rot),n.fillStyle=g.color,g.shape==="dot"?(n.beginPath(),n.arc(0,0,g.r*.48,0,Math.PI*2),n.fill()):n.fillRect(-g.r*.65,-g.r*.25,g.r*1.3,g.r*.5),n.restore()}C&&k=0?Math.floor(r.totalSubmissions):0,currentStreakDays:typeof r.currentStreakDays=="number"&&r.currentStreakDays>=0?Math.floor(r.currentStreakDays):0,longestStreakDays:typeof r.longestStreakDays=="number"&&r.longestStreakDays>=0?Math.floor(r.longestStreakDays):0,lastSubmissionDate:typeof r.lastSubmissionDate=="string"?r.lastSubmissionDate:null,earnedBadgeIds:Array.isArray(r.earnedBadgeIds)?r.earnedBadgeIds.filter(o=>it.some(i=>i.id===o)):[],badgeLevels:{streak_master:typeof n.streak_master=="number"?Math.max(0,Math.floor(n.streak_master)):0,streak_guardian:typeof n.streak_guardian=="number"?Math.max(0,Math.floor(n.streak_guardian)):0,training_volume:typeof n.training_volume=="number"?Math.max(0,Math.floor(n.training_volume)):0,training_accelerator:typeof n.training_accelerator=="number"?Math.max(0,Math.floor(n.training_accelerator)):0}}}function Hn(e){let t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${n}`}function br(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;let r=Number(t[1]),n=Number(t[2]),o=Number(t[3]),i=new Date(r,n-1,o);return i.getFullYear()!==r||i.getMonth()!==n-1||i.getDate()!==o?null:i}function Un(e,t){let r=new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime(),n=new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime();return Math.round((n-r)/864e5)}function Wn(e,t,r){if(!e)return 1;if(e===t)return r>0?r:1;let n=br(e),o=br(t);return!n||!o?1:Un(n,o)===1?Math.max(1,r+1):1}function hr(e,t){let r=0;for(let n of t)e>=n&&(r+=1);return r}function Qt(e,t,r,n){let o=mr();for(let s of it){let c=s.track==="streak"?t:e;o[s.id]=hr(c,[...s.milestones])}let i=Object.keys(o).filter(s=>o[s]>0);return{totalSubmissions:Math.max(0,Math.floor(e)),currentStreakDays:Math.max(0,Math.floor(t)),longestStreakDays:Math.max(0,Math.floor(r)),lastSubmissionDate:n,earnedBadgeIds:i,badgeLevels:o}}function Fn(e){let t=[];for(let r of it){let n=r.track==="streak"?e.currentStreakDays:e.totalSubmissions,o=hr(n,r.milestones),i=e.badgeLevels[r.id]||0;if(o>i){for(let s=i+1;s<=o;s++)t.push({id:r.id,toLevel:s,threshold:r.milestones[s-1]||r.milestones[r.milestones.length-1],title:r.title});e.badgeLevels[r.id]=o,e.earnedBadgeIds.includes(r.id)||e.earnedBadgeIds.push(r.id)}}return t}var ea={load(){try{let e=window.localStorage.getItem(gr);return e?fr(JSON.parse(e)):Fe()}catch{return Fe()}},save(e){try{window.localStorage.setItem(gr,JSON.stringify(fr(e)))}catch(t){console.warn("[trainingProgress] localStorage save failed",t)}}};function Vn(e=ea){return e.load()}function jn(e,t=ea){t.save(e)}function vr(e=new Date,t=ea){let r=Vn(t),n=Hn(e);r.totalSubmissions+=1,r.currentStreakDays=Wn(r.lastSubmissionDate,n,r.currentStreakDays),r.longestStreakDays=Math.max(r.longestStreakDays,r.currentStreakDays),r.lastSubmissionDate=n;let o=Fn(r);return jn(r,t),{progress:r,unlockedBadges:o}}function ta(e,t){for(let r of t)if(e{m(!1),b(null),f([]),C(""),S(!1),T(!1),J(!1),W(!1)},[]);P(()=>{if(!d)return;let D=document.body.style.overflow;document.body.style.overflow="hidden";let ae=ge=>{if(ge.key==="Escape"){if(ge.preventDefault(),B){W(!1);return}R()}};return document.addEventListener("keydown",ae),()=>{document.body.style.overflow=D,document.removeEventListener("keydown",ae)}},[d,B,R]),P(()=>{if(!d||!B)return;function D(ae){let ge=u.current;ge&&!ge.contains(ae.target)&&W(!1)}return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[d,B]),P(()=>{!i||d||requestAnimationFrame(()=>{var D;(D=c.current)==null||D.focus()})},[i,d]);let $=j(()=>{ue(!0);try{window.localStorage.setItem(kr,"1")}catch{}},[]),z=D=>{f(ae=>ae.includes(D)?ae.filter(ge=>ge!==D):[...ae,D]),T(!1)},F=(D,ae={})=>{s.mpTrack&&s.mpTrack(D,ae)},E=()=>{if(typeof s.openWebLinkIn=="function"){s.openWebLinkIn(kt,"tab",{});return}if(window.top&&typeof window.top.openWebLinkIn=="function"){window.top.openWebLinkIn(kt,"tab",{});return}window.open(kt,"_blank")},I=D=>{var ge;D.preventDefault(),D.stopPropagation();let ae=xr;if((ge=s.assistantBridge)!=null&&ge.openTab&&s.assistantBridge.openTab(ae)){F("training_amplifier_doc_click",{});return}if(typeof s.openWebLinkIn=="function"){s.openWebLinkIn(ae,"tab",{}),F("training_amplifier_doc_click",{});return}if(window.top&&typeof window.top.openWebLinkIn=="function"){window.top.openWebLinkIn(ae,"tab",{}),F("training_amplifier_doc_click",{});return}window.open(ae,"_blank"),F("training_amplifier_doc_click",{})},ee=(D,ae=!1)=>{ae&&console.error(`[Feedback] ${D}`)},K=async(D,ae,ge,Se)=>{var A,O,L;let Ie=(A=s.supabaseAuth)==null?void 0:A.supabase,x=((L=(O=s.supabaseAuth)==null?void 0:O.currentSession)==null?void 0:L.session_id)||null;if(!Ie)return ee("Training could not be saved (service unavailable).",!0),!1;try{let{data:{user:q}}=await Ie.auth.getUser();if(!q)return ee("Please sign in to save training.",!0),!1;let re={user_id:q.id,session_id:x,reported_at:new Date().toISOString(),negative_rating:D,category:ae,additional_info:{badges:p,comment:ge,include_context:!0,contact_me:!1,sentiment:Se,user_prompt:t.trim()||null,assistant_reply:r,..._r(e)?{}:{client_message_id:e}}};re.message_id=_r(e)?e:null;let{error:Y}=await Ie.from("feedback_events").insert(re);return Y?(console.error("Feedback insert failed:",Y),F("feedback_submit_error",{message:Y.message||String(Y)}),ee("Training could not be saved. Please try again.",!0),!1):(F("feedback_submit_success",{negative_rating:D,category:ae}),!0)}catch(q){return console.error("Feedback submission exception:",q),!1}},w=D=>{b(D),f([]),C(""),S(!1),T(!1),J(!1),W(!1),m(!0),D==="up"?F("feedback_thumb_up",{messageId:e}):F("feedback_thumb_down",{messageId:e})},X=async()=>{var Se,Ie;if(!l||p.length<1||k.trim().length<30)return;M(!0);let D=k.trim(),ae="Helpful";if(l==="down"?ae=p.length>0?p[0]:"Other":p.length>0&&(ae=p[0]),await K(l==="down",ae,D,l)){let x=vr(new Date);pr(),F("training_progress_updated",{total_submissions:x.progress.totalSubmissions,current_streak_days:x.progress.currentStreakDays,longest_streak_days:x.progress.longestStreakDays,unlocked_count:x.unlockedBadges.length});for(let A of x.unlockedBadges)F("training_badge_unlocked",{badge_id:A.id,level:A.toLevel,threshold:A.threshold});o==null||o({messageId:e,sentiment:l,progress:x.progress,unlockedBadges:x.unlockedBadges}),(Ie=(Se=s.subscriptionService)==null?void 0:Se.appendOptimisticTrainingBonus)==null||Ie.call(Se,1e3),window.dispatchEvent(new CustomEvent("oasis-usage-update",{bubbles:!0,detail:{immediate:!0}})),(async()=>{var A,O;try{await((O=(A=s.subscriptionService)==null?void 0:A.forceRefresh)==null?void 0:O.call(A))}catch{}window.dispatchEvent(new CustomEvent("oasis-usage-update"))})(),window.setTimeout(()=>{(async()=>{var A,O;try{await((O=(A=s.subscriptionService)==null?void 0:A.forceRefresh)==null?void 0:O.call(A))}catch{}window.dispatchEvent(new CustomEvent("oasis-usage-update"))})()},400),Ct(),S(!0),setTimeout(()=>{n&&n(),R(),_(!0),setTimeout(()=>_(!1),3200)},2e3)}M(!1)},U=t.trim()||"Not available",se=`Earn ${1e3.toLocaleString()} tokens each time you train.`,pe=!Q&&!d,Re=k.trim().length,Me=p.length>=1,Le=h,Ee=Re>=30,De=(Me?1:0)+(Le?1:0)+(Ee?1:0),Be=Math.min(100,Re/30*100),ze=N||p.length<1||k.trim().length<30,Rt=()=>{if(!N){if(ze){T(!0);return}X()}},Dt=d&&dr(a("div",{className:"feedback-overlay",role:"presentation",onMouseDown:D=>{D.target===D.currentTarget&&R()},children:a("div",{className:"feedback-overlay-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"feedback-dialog-title",onMouseDown:D=>D.stopPropagation(),children:g?a("div",{className:"feedback-overlay-thanks",children:[a("p",{className:"feedback-overlay-thanks-text",children:"Thanks \u2014 your training was saved!"}),a("p",{className:"feedback-overlay-thanks-bonus",children:["+",1e3.toLocaleString()," bonus tokens have been added to your daily token allowance (UTC day)."]}),a("button",{type:"button",className:"feedback-pricing-link",onClick:E,children:"View plans and limits"})]}):a(te,{children:[a("div",{className:"feedback-dialog-header-block",ref:u,children:[a("div",{className:"feedback-header",children:[a("span",{id:"feedback-dialog-title",children:l==="up"?"Train on a good answer":"Train on a miss"}),a("div",{className:"feedback-header-trailing",children:[a("div",{className:"feedback-training-info-anchor",children:a("button",{type:"button",className:"feedback-training-info-btn","aria-expanded":B,"aria-controls":wr,"aria-label":"Why training and bonus tokens",onClick:()=>W(D=>!D),children:a("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[a("circle",{cx:"12",cy:"12",r:"10"}),a("path",{d:"M12 16v-4M12 8h.01"})]})})}),a("button",{type:"button",className:"feedback-close-btn","aria-label":"Close",onClick:R,children:a("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[a("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),B?a("div",{id:wr,className:"feedback-training-info-popover",role:"region","aria-label":"Training overview",onMouseDown:D=>D.stopPropagation(),children:[a("p",{className:"feedback-training-info-popover__p",children:l==="up"?"Your input helps Oasis respond faster and more accurately over time.":"Showing us what missed the mark teaches the assistant to do better next time."}),a("p",{className:"feedback-training-info-popover__p",children:["Each qualifying training submission earns +",1e3.toLocaleString()," bonus tokens for today (UTC). Unused bonus allowance does not roll over."]}),a("button",{type:"button",className:"feedback-pricing-link",onClick:E,children:"View plans and limits"})]}):null,a("div",{className:"feedback-training-timeline",role:"progressbar","aria-valuemin":0,"aria-valuemax":3,"aria-valuenow":De,"aria-label":"Training form completion: categories, details field, and minimum length.",children:a("ol",{className:"feedback-training-timeline__list",children:[a("li",{className:`feedback-training-timeline__item${Me?" feedback-training-timeline__item--done":""}`,children:[a("span",{className:"feedback-training-timeline__dot","aria-hidden":!0}),a("span",{className:"feedback-training-timeline__label",children:"Categories"})]}),a("li",{className:`feedback-training-timeline__item${Le?" feedback-training-timeline__item--done":""}`,children:[a("span",{className:"feedback-training-timeline__dot","aria-hidden":!0}),a("span",{className:"feedback-training-timeline__label",children:"Details"})]}),a("li",{className:`feedback-training-timeline__item${Ee?" feedback-training-timeline__item--done":""}`,children:[a("span",{className:"feedback-training-timeline__dot","aria-hidden":!0}),a("span",{className:"feedback-training-timeline__label",children:"Ready"})]})]})})]}),a("div",{className:"feedback-dialog-scroll",children:[a("div",{className:"feedback-context-card",children:[a("div",{className:"feedback-context-section",children:[a("div",{className:"feedback-context-label",children:"Your message"}),a("pre",{className:"feedback-context-block",children:U})]}),a("div",{className:"feedback-context-section",children:[a("div",{className:"feedback-context-label",children:"Assistant reply"}),a("pre",{className:"feedback-context-block",children:r})]})]}),l==="down"?a(te,{children:[a("p",{className:"feedback-badges-lead",id:"feedback-badges-label-down",children:"What went wrong? (choose one or more)"}),a("div",{className:"feedback-badges",role:"group","aria-labelledby":"feedback-badges-label-down",children:qn.map(D=>a("button",{type:"button",className:`feedback-badge ${p.includes(D)?"selected":""}`,onClick:()=>z(D),children:[D,p.includes(D)&&a("span",{className:"badge-remove",children:a("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[a("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},D))})]}):a(te,{children:[a("p",{className:"feedback-badges-lead",id:"feedback-badges-label-up",children:"What stood out?"}),a("div",{className:"feedback-badges",role:"group","aria-labelledby":"feedback-badges-label-up",children:Gn.map(D=>a("button",{type:"button",className:`feedback-badge ${p.includes(D)?"selected":""}`,onClick:()=>z(D),children:[D,p.includes(D)&&a("span",{className:"badge-remove",children:a("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[a("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},D))})]}),a("div",{className:"feedback-detail-field",children:[a("label",{className:"feedback-detail-field__label",htmlFor:"feedback-training-detail",children:"Details (required)"}),a("textarea",{id:"feedback-training-detail",className:"feedback-textarea",placeholder:l==="up"?"What stood out, and what could be even better?":"What went wrong, and what would a better answer look like?",value:k,"aria-describedby":"feedback-training-char-status",onFocus:()=>J(!0),onInput:D=>{C(D.currentTarget.value),T(!1)}}),a("div",{id:"feedback-training-char-status","aria-live":"polite",children:[a("div",{className:"feedback-char-meter__track",children:a("div",{className:"feedback-char-meter__fill",style:{width:`${Be}%`}})}),a("p",{className:"feedback-char-meter__text",children:[Re," / ",30," characters"]})]})]}),a("div",{className:"feedback-validation-slot","aria-live":"polite","aria-relevant":"additions text",children:v?a("p",{className:"feedback-validation-hint",children:["Choose at least one category and write at least ",30," ","characters about what you expected or what could be better."]}):null})]}),a("div",{className:"feedback-footer",children:a("button",{type:"button",className:`feedback-submit-btn ${ze?"feedback-submit-btn--muted":""}`,onClick:Rt,"aria-busy":N,children:N?"Saving\u2026":"Submit training"})})]})})}),document.body);return H?a("div",{className:"feedback-container",children:a("div",{className:"feedback-submitted",children:[a("span",{className:"feedback-submitted-line",children:"Thanks \u2014 your training was saved!"}),a("span",{className:"feedback-submitted-bonus",children:["+",1e3.toLocaleString()," bonus tokens added to your daily allowance (UTC)."]}),a("button",{type:"button",className:"feedback-pricing-link",onClick:E,children:"View plans and limits"})]})}):a("div",{className:"feedback-container",children:[Dt,a("div",{className:"feedback-options",children:a("div",{className:"feedback-train-hover-zone",children:[a("div",{className:"feedback-train-row",role:"presentation",children:[a("div",{className:"feedback-train-label-pill",children:a("span",{className:"feedback-train-label",children:"Train"})}),a("div",{className:"feedback-train-hover-group feedback-train-badge",children:a("div",{className:"feedback-train-actions",children:[a("button",{type:"button",className:"feedback-training-learn-btn",onClick:I,"aria-label":"Learn more about training (opens in a new tab)",title:"Learn more about training",children:a("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[a("circle",{cx:"12",cy:"12",r:"10"}),a("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),a("path",{d:"M12 17h.01"})]})}),a("button",{type:"button",ref:c,className:"feedback-btn thumbs-up",onClick:()=>w("up"),disabled:N,title:`Train on a good answer \u2014 earn up to ${1e3.toLocaleString()} bonus tokens`,"aria-label":"Mark as helpful for training",children:a("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:a("path",{d:"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3"})})}),a("button",{type:"button",className:"feedback-btn thumbs-down",onClick:()=>w("down"),disabled:N,title:`Train on a miss \u2014 earn up to ${1e3.toLocaleString()} bonus tokens`,"aria-label":"Mark as not helpful for training",children:a("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:a("path",{d:"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zM17 2h3a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2h-3"})})})]})})]}),pe?a("div",{className:"training-hint-bubble training-hint-bubble--promo",role:"note","aria-live":"polite",children:[a("span",{children:["Earn"," ",a("strong",{className:"training-hint-bubble__amount",children:1e3.toLocaleString()})," ","tokens each time you train."]}),a("button",{type:"button",className:"training-hint-close","aria-label":"Dismiss",onClick:$,children:"\xD7"})]}):null,Q?a("span",{className:"feedback-train-earn-hover-hint","aria-hidden":"true",children:se}):null]})})]})}function Cr({label:e}){return a("div",{style:{display:"flex",alignItems:"center",gap:"8px",color:"var(--primary-green)",fontSize:"13px",margin:"8px 0",paddingLeft:"4px"},children:[a("svg",{width:"12",height:"12",viewBox:"0 0 50 50",children:[a("circle",{cx:"25",cy:"25",r:"20",stroke:"var(--primary-green)",strokeWidth:"4",fill:"none",opacity:"0.2"}),a("circle",{cx:"25",cy:"25",r:"20",stroke:"var(--primary-green)",strokeWidth:"4",fill:"none",strokeDasharray:"31.4 94.2",strokeLinecap:"round",children:a("animateTransform",{attributeName:"transform",type:"rotate",from:"0 25 25",to:"360 25 25",dur:"1s",repeatCount:"indefinite"})})]}),a("span",{children:e})]})}var Ar="https://kahana.co/oasis-pricing";function Tr(e){let t=String(e||"").trim();if(!t)return null;let r=t.toLowerCase();return r.includes("daily_limit_exceeded")||r.includes("daily_limit")||r.includes("you have reached your daily ai usage")||r.includes("you've reached your daily ai usage")?"daily":r.includes("monthly_limit_exceeded")||r.includes("monthly_limit")||r.includes("you have reached your monthly ai usage")||r.includes("you've reached your monthly ai usage")?"monthly":r.includes("quota_exceeded")||r.includes("you have reached your ai usage limit for this plan")||r.includes("you've reached your ai usage limit for this plan")||r.includes("please upgrade your plan via the menu")?"generic":null}function Xn(e){switch(e){case"daily":return"You have used your included AI commands for today. Your limit resets each day, or you can upgrade for more.";case"monthly":return"You have used your included AI commands for this billing period. Upgrade anytime for a higher monthly allowance.";default:return"You have reached the usage cap for your current plan."}}function Yn(e){switch(e){case"daily":return"Daily limit reached";case"monthly":return"Monthly limit reached";default:return"Usage limit reached"}}function Er({variant:e}){return a("div",{className:"quota-limit-callout",role:"status",children:a("div",{className:"quota-limit-callout-main",children:[a("p",{className:"quota-limit-callout-title",children:Yn(e)}),a("p",{className:"quota-limit-callout-body",children:Xn(e)}),a("p",{className:"quota-limit-callout-cta",children:a("a",{className:"quota-limit-callout-link",href:Ar,target:"_blank",rel:"noopener noreferrer",children:"View plans and upgrade"})})]})})}var At="What Oasis can do in this build",aa=` +<<>> +`,je="https://kahana.co/features/oasis-assistant",Tt="Oasis assistant on Kahana",$e="https://tally.so/r/3jkNN6",Et="Send feedback";var It=window;function Jn(e){let t=e.trimEnd(),r=!1,n=!1;return t.endsWith($e)&&(t=t.slice(0,-$e.length).trimEnd(),r=!0),t.endsWith(je)&&(t=t.slice(0,-je.length).trimEnd(),n=!0),{body:t.trimEnd(),showKahana:n,showTally:r}}function Zn(e){var c;let t=e.split(aa);if(t.length===0)return{blocks:[],showKahana:!1,showTally:!1};let r=t.length-1,{body:n,showKahana:o,showTally:i}=Jn((c=t[r])!=null?c:"");return{blocks:[...t.slice(0,r),n].filter(u=>u.trim().length>0),showKahana:o,showTally:i}}function Qn(e,t){for(let r=t-1;r>=0;r--)if(e[r].role==="user")return e[r].content;return""}function Ir({messages:e,isAuthenticated:t,busy:r,activeToolLabel:n,responseStreaming:o,onLinkClick:i,speakingMsgId:s,onTtsClick:c,onTrainingSubmitted:u,trainingFocusTick:d,trainingFocusMessageId:m}){let l=G(null),b=G(null);P(()=>{let f=l.current;if(!f)return;let k=e[e.length-1];if(!r&&!o&&!n&&(k==null?void 0:k.role)==="ai"&&k.content.length>0){requestAnimationFrame(()=>{var g;(g=b.current)==null||g.scrollIntoView({block:"start",behavior:"auto",inline:"nearest"})});return}f.scrollTop=f.scrollHeight},[e,r,n,o]),P(()=>{let f=d!=null?d:0,k=m!=null?m:"";if(f===0||!k)return;let C=requestAnimationFrame(()=>{let g=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(k):k.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),S=document.querySelector(`[data-oasis-assistant-msg="${g}"]`);if(!S||!(S instanceof HTMLElement))return;let N=l.current;S.scrollIntoView({behavior:"smooth",block:"end",inline:"nearest"}),requestAnimationFrame(()=>{N==null||N.scrollTo({top:N.scrollHeight,behavior:"smooth"})})});return()=>{cancelAnimationFrame(C)}},[d,m]);let p=e.length===0&&t;return a("div",{className:`chat-log${p?" chat-log--empty-signed-in":""}`,ref:l,children:[e.length===0&&!t&&a("div",{className:"chat-empty-state",children:[a("p",{className:"chat-empty-state__welcome",children:"Try a suggestion in the box below, or type your own request."}),a("div",{className:"chat-empty-state__art",children:a("img",{src:"chrome://browser/content/assistant/images/empty-state-bg.png",alt:"",decoding:"async"})})]}),e.map((f,k)=>{let C=k===e.length-1;if(f.role==="user")return a("div",{className:"message-bubble message-user",children:a("div",{className:"message-content",style:{whiteSpace:"pre-wrap"},children:f.content})},f.id);if(f.role==="ai"){let g=Tr(f.content);if(g)return a(te,{children:a("div",{ref:C?b:void 0,className:"ai-message-wrapper","data-oasis-assistant-msg":f.id,children:a("div",{className:"ai-response-container",onClick:i,children:a(Er,{variant:g})})})},f.id);let S=f.content.startsWith(At)||f.content.startsWith("## What Oasis can do"),N=S&&f.content.includes(aa),M=!!(It.marked&&It.DOMPurify&&!(S&&N)),H="";if(M)try{let T=It.marked.parse(f.content);H=It.DOMPurify.sanitize(T)}catch{M=!1}let _=N?Zn(f.content):null,v=S&&!N?"markdown-body capabilities-markdown":"markdown-body";return a(te,{children:a("div",{ref:C?b:void 0,className:"ai-message-wrapper","data-oasis-assistant-msg":f.id,children:[a("div",{className:"ai-response-container",onClick:i,children:M&&H?a("div",{className:v,dangerouslySetInnerHTML:{__html:H}}):N&&_?a("div",{className:"capabilities-overview-stack",children:_.blocks.map((T,h)=>{let B=h===_.blocks.length-1&&(_.showKahana||_.showTally);return a("div",{className:"message-content capabilities-block",style:{whiteSpace:"pre-wrap",background:"transparent",border:"none",padding:0},children:[T,B?a(te,{children:[` + +`,_.showKahana?a("a",{href:je,target:"_blank",rel:"noopener noreferrer",children:Tt}):null,_.showKahana&&_.showTally?a(te,{children:` +`}):null,_.showTally?a("a",{href:$e,target:"_blank",rel:"noopener noreferrer",children:Et}):null]}):null]},h)})}):a("div",{className:"message-content",style:{whiteSpace:"pre-wrap",background:"transparent",border:"none",padding:0},children:f.content})}),a("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[!r&&f.content&&c&&a("button",{className:"tts-btn",type:"button",onClick:()=>{s===f.id?c(f.id,""):c(f.id,f.content)},title:s===f.id?"Stop speaking":"Read aloud",style:{background:"none",border:"none",cursor:"pointer",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"4px",color:s===f.id?"var(--primary-green)":"var(--neutral-500)"},children:s===f.id?a("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a("rect",{x:"6",y:"4",width:"4",height:"16"}),a("rect",{x:"14",y:"4",width:"4",height:"16"})]}):a("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),a("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),a("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]})}),f.content&&(!C||!r)?a(Sr,{messageId:f.id,userPrompt:Qn(e,k),assistantReply:f.content,onTrainingSubmitted:u,inlineAutofocusTick:m===f.id&&d!=null?d:0}):null]})]})},f.id)}return null}),(r||n)&&a(Cr,{label:n||"Thinking..."})]})}var ra=window,Mr="oasis.assistant.tokenUsageBarCollapsed";function eo(){try{return sessionStorage.getItem(Mr)!=="0"}catch{return!0}}function Nr(e){try{sessionStorage.setItem(Mr,e?"1":"0")}catch{}}function to(e){return e>=85?"token-usage-bar__fill token-usage-bar__fill--high":e>=65?"token-usage-bar__fill token-usage-bar__fill--warn":"token-usage-bar__fill"}function ao(e,t){return t<=0||e>=100?"Today's allowance is used up. Qualifying training can still add bonus tokens.":e>=85?"Running low on tokens today.":e>=55?"You have used a solid share of today's allowance.":"You're in good shape today."}function Lr({isAuthenticated:e,embedded:t,onOpenTraining:r}){var H;let[n,o]=y(eo),[i,s]=y(null),[c,u]=y(e),d=j(async()=>{let _=ra.subscriptionService;if(!(_!=null&&_.getUsageBarData)){s(null),u(!1);return}u(!0);try{let v=await _.getUsageBarData();s(v)}catch{s(null)}finally{u(!1)}},[]);P(()=>{if(!e){s(null),u(!1);return}u(!0),d()},[e,d]),P(()=>{if(!e)return;let _=window.setInterval(()=>{d()},45e3);return()=>window.clearInterval(_)},[e,d]),P(()=>{if(!e)return;let _=v=>{let T=v.detail;if(T!=null&&T.immediate){let h=ra.subscriptionService;h!=null&&h.getUsageBarSnapshot?(s(h.getUsageBarSnapshot()),u(!1)):h!=null&&h.getDailyTokenUsageForDisplay&&(s(h.getDailyTokenUsageForDisplay()),u(!1));return}d()};return window.addEventListener("oasis-usage-update",_),()=>window.removeEventListener("oasis-usage-update",_)},[e,d]);let m=()=>{let _=!n;o(_),Nr(_)};if(!e)return null;let l=!!((H=ra.subscriptionService)!=null&&H.getUsageBarData),b=i!=null&&!c?Math.min(100,Math.round(i.percentUsed)):null,p=c||!i||!l?"token-usage-bar__collapsed-pct token-usage-bar__collapsed-pct--muted":"token-usage-bar__collapsed-pct",f=l?c?"\u2026":i?`${b}%`:"\u2014":"\u2014",k=!l||c||!i?"Daily tokens, show usage details":`Daily tokens, ${b} percent of today's allowance used. Show details.`,C=i!=null&&i.limit>0?Math.min(100,i.used/i.limit*100):0,g=i!=null?Math.min(100,Math.round(i.percentUsed)):0,S=i!=null?`${Math.round(i.percentUsed)} percent of today's token allowance used, ${i.remaining.toLocaleString()} tokens remaining`:"",N=t?" token-usage-bar--embedded":"",M=()=>{o(!0),Nr(!0),r==null||r()};return n?a("div",{className:`token-usage-bar token-usage-bar--collapsed${N}`,children:a("button",{type:"button",className:"token-usage-bar__collapse-toggle",onClick:m,"aria-expanded":"false","aria-label":k,title:"Show daily token usage",children:[a("span",{className:"token-usage-bar__collapsed-label",children:"Daily tokens"}),a("span",{className:"token-usage-bar__collapsed-metrics",children:[a("span",{className:p,children:f}),i!=null&&!c&&l?a("span",{className:"token-usage-bar__collapsed-used-word",children:"used"}):null,i!=null&&!c&&i.bonusTokens>0?a("span",{className:"token-usage-bar__collapsed-bonus",children:"+bonus"}):null]}),a("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:a("path",{d:"M6 9l6 6 6-6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})]})}):a("div",{className:`token-usage-bar${N}`,children:[a("div",{className:"token-usage-bar__header",children:[a("span",{className:"token-usage-bar__title",id:"token-usage-bar-label",children:"Daily tokens"}),a("button",{type:"button",className:"token-usage-bar__collapse-toggle token-usage-bar__collapse-toggle--inline",onClick:m,"aria-expanded":"true","aria-controls":"token-usage-bar-panel",title:"Hide usage bar",children:a("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:a("path",{d:"M6 15l6-6 6 6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),a("div",{id:"token-usage-bar-panel",className:"token-usage-bar__panel",role:"group","aria-labelledby":"token-usage-bar-label",children:l?c?a("p",{className:"token-usage-bar__stats",role:"status",children:"Loading usage\u2026"}):i?a(te,{children:[a("div",{className:"token-usage-bar__track",role:"progressbar","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":g,"aria-valuetext":S,children:a("div",{className:to(i.percentUsed),style:{width:`${C}%`}})}),a("p",{className:"token-usage-bar__stats","aria-live":"polite",children:[i.used.toLocaleString()," / ",i.limit.toLocaleString()," used (",i.remaining.toLocaleString()," left)"]}),a("p",{className:"token-usage-bar__reassurance",children:ao(i.percentUsed,i.remaining)}),a("p",{className:"token-usage-bar__earn-hint",children:["Up to ",1e3.toLocaleString()," bonus tokens per qualifying training (see Training). Be specific about what worked or missed; daily limits follow your Oasis plan."]}),i.bonusTokens>0?a("p",{className:"token-usage-bar__bonus-note",children:["Includes ",i.bonusTokens.toLocaleString()," bonus from training feedback today (base ",i.baseLimit.toLocaleString(),")."]}):null,r?a("button",{type:"button",className:"token-usage-bar__training-cta",onClick:M,children:"Train latest reply"}):null]}):a("p",{className:"token-usage-bar__stats",role:"status",children:"Could not load usage. Try again later."}):a("p",{className:"token-usage-bar__stats",role:"status",children:"Usage is unavailable in this build."})})]})}var na="What can Oasis do?",st="How does Oasis work?",Pr=[{label:na,message:na},{label:st,action:"commandReferenceMarkdown"}],Or=[na,st,"Ask in plain English"];var ro=88,no=3200,oo=52,io=900;function Rr(){let[e,t]=y(!1);return P(()=>{if(typeof window.matchMedia!="function")return;let r=window.matchMedia("(prefers-reduced-motion: reduce)");if(!r)return;let n=()=>t(r.matches);return n(),r.addEventListener("change",n),()=>r.removeEventListener("change",n)},[]),e}function Dr(e,t,r){let[n,o]=y("");return P(()=>{if(!t||e.length===0){o("");return}if(r){o(`Try: ${e[0]}`);return}let i=!1,s=0,c=0,u="type",d=0,m=(b,p)=>{d=window.setTimeout(p,b)},l=()=>{if(i)return;let b=e[s%e.length];if(u==="type"){c0?(c-=1,o(b.slice(0,c)),m(oo,l)):(u="pauseEmpty",s+=1,m(io,l));return}u==="pauseEmpty"&&(u="type",l())};return c=0,o(""),m(0,l),()=>{i=!0,window.clearTimeout(d)}},[t,r,e]),n}var so="Send follow-up",lo="Message composer. Type a request, use the Up arrow to recall previous commands, or tap a suggestion chip.";function Br({input:e,busy:t,isAuthenticated:r,chatIsEmpty:n,ttsEnabled:o,inputRef:i,showInlineChips:s,inlineSuggestions:c,highlightInlineChips:u,onInlineSuggestionSend:d,onInput:m,onKeyDown:l,onSend:b,onResetSession:p,onFeedback:f,onToggleTts:k,onOpenVoiceAgent:C,onRequestSignIn:g,onOpenTraining:S,showTrainLatestComposerHint:N,onDismissTrainLatestHint:M,onInsertCapabilities:H}){let[_,v]=y(!1),T=Rr(),h=n&&r&&!t&&e===""&&!_,J=Dr(Or,h,T),B=h?"":so,W=r&&!!s&&!t&&c&&c.length>0,Q=R=>{if(d){d(R);return}m(R),requestAnimationFrame(()=>{if(i&&typeof i=="object"&&"current"in i){let $=i.current;$&&$.focus()}})},ue=r&&n;return a("div",{id:"oasis-assistant-composer",className:`input-bar composer-dock${t?" input-bar--busy":""}${ue?" input-bar--empty-signed-chat":""}`,children:[N?a("div",{className:"composer-train-latest-hint",role:"status",children:[a("span",{children:"Ask Oasis something first, then use Train on the reply to earn bonus tokens."}),a("button",{type:"button",className:"composer-train-latest-hint-dismiss",onClick:()=>M==null?void 0:M(),"aria-label":"Dismiss",children:"\xD7"})]}):null,r&&a(Lr,{isAuthenticated:!0,embedded:!0,onOpenTraining:S}),r?a("div",{className:"composer-prompt-stack",onMouseDown:R=>{var z;if(t)return;let $=R.target;!$||$.closest("button")||$.closest("textarea")||i&&typeof i=="object"&&"current"in i&&((z=i.current)==null||z.focus())},children:[a("div",{className:"composer-input-wrap",children:[h&&a("div",{className:"composer-typewriter-hint","aria-hidden":"true",children:[J,!T&&a("span",{className:"composer-typewriter-caret",children:"|"})]}),a("textarea",{ref:i,className:"input-field",value:e,onInput:R=>{let $=R.currentTarget;m($.value)},onKeyDown:l,onFocus:()=>v(!0),onBlur:()=>v(!1),placeholder:B,"aria-label":lo,disabled:t||!r,rows:1,style:{minHeight:ue?"120px":"88px",fontSize:"14px"}})]}),W&&a("div",{className:`composer-inline-chips${u?" composer-inline-chips--pulse":""}`,children:c.map(R=>a("button",{type:"button",className:"composer-inline-chip",disabled:t,onClick:()=>{if("action"in R&&R.action==="commandReferenceMarkdown"){H==null||H();return}"message"in R&&Q(R.message)},children:R.label},R.label))})]}):a("div",{className:"composer-guest-signin",children:[a("button",{type:"button",className:"input-field input-field-signin-prompt",onClick:()=>g==null?void 0:g(),disabled:t,"aria-label":"Sign in or create an account to use the assistant",children:"Please sign in..."}),a("button",{type:"button",className:"composer-full-signin-link",onClick:()=>g==null?void 0:g(),disabled:t,children:"Full sign-in screen"})]}),a("div",{className:"composer-toolbar",children:[a("button",{type:"button",className:"composer-feedback-btn",onClick:f,title:"Send feedback","aria-label":"Send feedback",children:a("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:a("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),a("div",{className:"composer-toolbar-spacer"}),a("div",{className:"composer-toolbar-actions",children:[a("button",{className:"send-btn composer-tool-btn",onClick:p,title:"Clear Chat History",style:{color:"#666"},children:a("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a("path",{d:"M23 4v6h-6"}),a("path",{d:"M1 20v-6h6"}),a("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]})}),a("button",{className:"send-btn composer-tool-btn",onClick:k,title:o?"Disable auto read-aloud":"Enable auto read-aloud",style:{background:"none",color:o?"var(--primary-green)":"var(--neutral-500)"},children:o?a("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),a("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),a("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):a("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),a("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),a("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})}),a("button",{className:"send-btn composer-tool-btn",onClick:C,disabled:t||!r,title:"Voice conversation (hands-free)",children:a("svg",{className:"composer-voice-agent-icon",width:"22",height:"22",viewBox:"0 0 36 36",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:[a("rect",{width:"36",height:"36",rx:"18",fill:"#F8FAF2"}),a("path",{d:"M18 10a3 3 0 0 0-3 3v5a3 3 0 0 0 6 0v-5a3 3 0 0 0-3-3z",fill:"#94A833"}),a("path",{d:"M23 17v1a5 5 0 0 1-10 0v-1",stroke:"#94A833",strokeWidth:"1.5",strokeLinecap:"round"}),a("line",{x1:"18",y1:"23",x2:"18",y2:"26",stroke:"#94A833",strokeWidth:"1.5",strokeLinecap:"round"}),a("line",{x1:"15",y1:"26",x2:"21",y2:"26",stroke:"#94A833",strokeWidth:"1.5",strokeLinecap:"round"})]})}),a("button",{type:"button",className:`send-btn composer-send-btn${t?" composer-send-btn--busy":""}`,onClick:b,disabled:t||!r,title:"Send",children:t?a("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"var(--primary-green)",strokeWidth:"2",children:a("rect",{x:"9",y:"9",width:"6",height:"6"})}):a("svg",{width:"26",height:"26",viewBox:"0 0 36 36",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:[a("circle",{cx:"18",cy:"18",r:"18",fill:"var(--primary-green)"}),a("path",{d:"M18 24V12M18 12L24 18M18 12L12 18",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})})]})]})]})}var co={streak_master:"SM",streak_guardian:"CG",training_volume:"TV",training_accelerator:"AC"};function zr(e,t,r){let n=Math.max(1,r-t),o=Math.min(n,Math.max(0,e-t));return Math.round(o/n*100)}function Hr({open:e,onClose:t}){let[r,n]=y(()=>Fe()),[o,i]=y(!1),[s,c]=y(!1),u=j(async()=>{i(!0),c(!1);try{let p=await yr();p?n(p):(c(!0),n(Fe()))}finally{i(!1)}},[]);if(P(()=>{e&&u()},[e,u]),P(()=>{let p=()=>{e&&u()};return window.addEventListener(St,p),()=>window.removeEventListener(St,p)},[e,u]),P(()=>{if(!e)return;let p=document.body.style.overflow,f=k=>{k.key==="Escape"&&(k.preventDefault(),t())};return document.body.style.overflow="hidden",document.addEventListener("keydown",f),()=>{document.body.style.overflow=p,document.removeEventListener("keydown",f)}},[e,t]),!e)return null;let d=ta(r.currentStreakDays,_t),m=ta(r.totalSubmissions,wt),l=_t.slice().reverse().find(p=>p<=r.currentStreakDays)||0,b=wt.slice().reverse().find(p=>p<=r.totalSubmissions)||0;return a("div",{className:"training-gallery-overlay",role:"presentation",onMouseDown:p=>{p.target===p.currentTarget&&t()},children:a("div",{className:"training-gallery-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"training-gallery-title",onMouseDown:p=>p.stopPropagation(),children:[a("div",{className:"training-gallery-head",children:[a("h2",{id:"training-gallery-title",children:"Training progress"}),a("button",{type:"button",className:"training-gallery-close",onClick:t,"aria-label":"Close training progress",children:"\xD7"})]}),s?a("p",{className:"training-gallery-fetch-err",role:"status",children:"Could not load training stats. Check your connection and try again."}):null,a("div",{className:"training-gallery-stats","aria-busy":o,children:[a("div",{className:"training-stat-card",children:[a("span",{className:"training-stat-label",children:"Current streak"}),a("strong",{className:"training-stat-value",children:o?"\u2026":`${r.currentStreakDays} days`})]}),a("div",{className:"training-stat-card",children:[a("span",{className:"training-stat-label",children:"Longest streak"}),a("strong",{className:"training-stat-value",children:o?"\u2026":`${r.longestStreakDays} days`})]}),a("div",{className:"training-stat-card",children:[a("span",{className:"training-stat-label",children:"Total trainings"}),a("strong",{className:"training-stat-value",children:o?"\u2026":r.totalSubmissions})]})]}),a("p",{className:"training-gallery-streak-note",children:"Streak counts consecutive UTC calendar days with at least one qualifying training (same rules as bonus tokens). Multiple trainings the same UTC day still add to total trainings above."}),a("div",{className:"training-gallery-milestones",children:[a("div",{className:"training-milestone-card",children:[a("div",{className:"training-milestone-row",children:[a("span",{children:"Streak milestone"}),a("strong",{children:d?`${d-r.currentStreakDays} days to ${d}`:"Max tier reached"})]}),d?a("div",{className:"training-progress-track","aria-hidden":"true",children:a("span",{className:"training-progress-fill",style:{width:`${zr(r.currentStreakDays,l,d)}%`}})}):null]}),a("div",{className:"training-milestone-card",children:[a("div",{className:"training-milestone-row",children:[a("span",{children:"Submission milestone"}),a("strong",{children:m?`${m-r.totalSubmissions} to ${m}`:"Max tier reached"})]}),m?a("div",{className:"training-progress-track","aria-hidden":"true",children:a("span",{className:"training-progress-fill",style:{width:`${zr(r.totalSubmissions,b,m)}%`}})}):null]})]}),a("div",{className:"training-gallery-badges",children:[a("h3",{children:"Badge gallery"}),a("div",{className:"training-badge-grid",children:it.map(p=>{let f=r.badgeLevels[p.id]||0,k=f>0;return a("article",{className:`training-badge-card${k?" training-badge-card--earned":""}`,children:[a("div",{className:"training-badge-icon",children:co[p.id]||"BG"}),a("div",{className:"training-badge-copy",children:[a("strong",{children:p.title}),a("p",{children:p.description}),a("span",{children:["Level ",f,"/",p.milestones.length]})]})]},p.id)})})]}),a("p",{className:"training-gallery-footer-hint",children:"Train the assistant from chat to earn bonus AI commands toward your daily allowance."})]})})}var uo=6500,po=24e3;function Ur({busy:e,activeToolLabel:t,responseStreaming:r}){let[n,o]=y(0),i=G(null),s=G(null),{primaryLine:c,tier1Line:u,tier2Line:d}=be(()=>{let m=r?"Writing response.":"Oasis is working on your request.",l=n>=1?"Still working. This can take a moment for web or tab actions.":"",b=n>=2?"Taking longer than usual. You can clear the chat using the refresh icon below if nothing changes.":"";return{primaryLine:m,tier1Line:l,tier2Line:b}},[n,r]);return P(()=>{if(!e){o(0),i.current=null,s.current!=null&&(clearInterval(s.current),s.current=null);return}i.current=Date.now(),o(0);let m=()=>{let l=i.current?Date.now()-i.current:0,b=0;l>=po?b=2:l>=uo&&(b=1),o(b)};return s.current=window.setInterval(m,400),m(),()=>{s.current!=null&&(clearInterval(s.current),s.current=null)}},[e]),e?a("div",{className:"assistant-busy-bar",role:"status","aria-live":"polite","aria-atomic":"true",children:a("div",{className:"assistant-busy-bar-inner",children:[a("svg",{className:"assistant-busy-bar-spinner",width:"14",height:"14",viewBox:"0 0 50 50","aria-hidden":!0,children:[a("circle",{cx:"25",cy:"25",r:"20",stroke:"var(--primary-green)",strokeWidth:"4",fill:"none",opacity:"0.2"}),a("circle",{cx:"25",cy:"25",r:"20",stroke:"var(--primary-green)",strokeWidth:"4",fill:"none",strokeDasharray:"31.4 94.2",strokeLinecap:"round",children:a("animateTransform",{attributeName:"transform",type:"rotate",from:"0 25 25",to:"360 25 25",dur:"1s",repeatCount:"indefinite"})})]}),a("div",{className:"assistant-busy-bar-text",children:[a("div",{className:"assistant-busy-bar-primary",children:c}),t?a("div",{className:"assistant-busy-bar-tool",children:t}):null,u?a("div",{className:"assistant-busy-bar-tier",children:u}):null,d?a("div",{className:"assistant-busy-bar-tier",children:d}):null]})]})}):null}var Nt=window,Wr="oasis.assistant.onboardingChecklistCollapsed";function go(){try{let e=sessionStorage.getItem(Wr);return e===null?!1:e==="1"}catch{return!1}}function oa(e){try{sessionStorage.setItem(Wr,e?"1":"0")}catch{}}var fo={width:"100%",margin:0,padding:"10px",borderRadius:"12px",background:"var(--surface-default)",border:"1px solid var(--primary-50)",boxSizing:"border-box"};function Ke({done:e}){return a("span",{"aria-hidden":!0,style:{flexShrink:0,width:"16px",height:"16px",borderRadius:"50%",border:e?"none":"2px solid #c5d49a",background:e?"var(--primary-green)":"transparent",color:"#fff",fontSize:"10px",display:"flex",alignItems:"center",justifyContent:"center",fontWeight:700},children:e?"\u2713":""})}var bo="chrome://browser/content/migration/brands/chrome.png",mo="chrome://browser/content/migration/brands/edge.png",ho="chrome://browser/content/migration/brands/safari.png",vo="chrome://browser/content/migration/brands/brave.png";function xo(){return a("span",{className:"onboarding-import-brand-imgs onboarding-import-brand-imgs--header","aria-hidden":"true",children:[a("img",{src:bo,width:16,height:16,alt:"",decoding:"async"}),a("img",{src:mo,width:16,height:16,alt:"",decoding:"async"}),a("img",{src:ho,width:16,height:16,alt:"",decoding:"async"}),a("img",{src:vo,width:16,height:16,alt:"",decoding:"async"})]})}function yo(){return a("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:a("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z",fill:"#e8eedc",stroke:"#6b7c52",strokeWidth:"1.75",strokeLinejoin:"round"})})}function _o(){return a("svg",{className:"onboarding-import-primary-btn-icon",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[a("path",{d:"M12 15V3m0 12l-4-4m4 4 4-4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),a("path",{d:"M5 21h14",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]})}function wo(){return a("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:[a("path",{d:"M9 11l3 3L22 4",stroke:"var(--header-title-color)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),a("path",{d:"M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11",stroke:"var(--header-title-color)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})}function ia({auth:e,view:t,onNavigate:r,onCollapseRequest:n}){let[o,i]=y(null),[s,c]=y(go),u=G(0),d=j(()=>{var v,T,h;let _=(h=(T=(v=Nt.assistantBridge)==null?void 0:v.getOnboardingStatus)==null?void 0:T.call(v))!=null?h:null;i(_)},[]);P(()=>{d();let _=window.setInterval(d,2e3),v=()=>d(),T=()=>d();return window.addEventListener("oasis-auth-update",v),window.addEventListener("oasis-onboarding-update",T),()=>{window.clearInterval(_),window.removeEventListener("oasis-auth-update",v),window.removeEventListener("oasis-onboarding-update",T)}},[d]),P(()=>{n==null||n<1||n!==u.current&&(u.current=n,c(!0),oa(!0))},[n]);let m=(o==null?void 0:o.migrationCompleted)||(o==null?void 0:o.importOptOut)||!1,l=!!e.isAuthenticated,b=(o==null?void 0:o.firstAiTurnComplete)||!1,p=m&&l&&b;if(P(()=>{var _,v;!(o!=null&&o.guidedFlowEnabled)||!p||(v=(_=Nt.assistantBridge)==null?void 0:_.dismissOnboardingChecklist)==null||v.call(_)},[o==null?void 0:o.guidedFlowEnabled,p]),!(o!=null&&o.guidedFlowEnabled)||o!=null&&o.checklistDismissed||p)return null;let f=3,k=(m?1:0)+(l?1:0)+(b?1:0),C=100*k/f,g=()=>{var _,v;(v=(_=Nt.assistantBridge)==null?void 0:_.openImportBrowserData)==null||v.call(_)},S=()=>{c(!1),oa(!1)},N=()=>{c(!0),oa(!0)},M={display:"flex",alignItems:"flex-start",gap:"10px",width:"100%",padding:"10px 8px",margin:0,border:"none",borderRadius:"8px",background:"transparent",cursor:"pointer",textAlign:"left",font:"inherit",color:"#333"},H={...M,cursor:"default",opacity:.72,color:"#9ca3af"};return s?a("div",{className:"assistant-onboarding-dock assistant-onboarding-dock--collapsed",children:a("button",{type:"button",className:"onboarding-checklist-compact",onClick:S,"aria-expanded":"false","aria-controls":"oasis-onboarding-checklist-panel",title:"Open onboarding checklist",children:[a("div",{className:"onboarding-checklist-compact-top",children:[a("span",{className:"onboarding-checklist-compact-icon",children:a(wo,{})}),a("span",{className:"onboarding-checklist-compact-title",children:"Getting started"}),a("span",{className:"onboarding-checklist-compact-count",children:[k,"/",f]})]}),a("div",{className:"onboarding-checklist-compact-bar",children:a("div",{className:"onboarding-checklist-compact-bar-fill",style:{width:`${C}%`}})})]})}):a("div",{id:"oasis-onboarding-checklist-panel",className:"assistant-onboarding-dock",style:fo,children:[a("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"10px",gap:"8px"},children:[a("span",{style:{fontSize:"14px",fontWeight:600,color:"var(--header-title-color)"},children:"Getting started"}),a("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a("span",{style:{fontSize:"12px",color:"#6b7280"},children:[k,"/",f]}),a("button",{type:"button",onClick:N,"aria-expanded":"true",title:"Collapse checklist",style:{border:"none",background:"rgba(122, 146, 0, 0.12)",borderRadius:"8px",width:"32px",height:"28px",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--header-title-color)",flexShrink:0},children:a("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:a("path",{d:"M6 9l6 6 6-6",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]}),a("div",{style:{height:"4px",borderRadius:"4px",background:"#e2e8d0",marginBottom:"12px",overflow:"hidden"},children:a("div",{style:{height:"100%",width:`${C}%`,background:"var(--primary-green)",borderRadius:"4px",transition:"width 0.25s ease"}})}),a("div",{style:{display:"flex",flexDirection:"column",gap:"4px"},children:[a("div",{style:{borderRadius:"8px",border:"1px solid #e2e8d0",background:"#fff",overflow:"hidden"},children:m?a("div",{className:"onboarding-import-step-header onboarding-import-step-header--done",children:[a(Ke,{done:!0}),a("span",{className:"onboarding-import-done-label",children:"Browser data imported"})]}):a(te,{children:[a("div",{className:"onboarding-import-step-header",children:[a(Ke,{done:!1}),a("div",{className:"onboarding-import-card-head",children:[a("span",{className:"onboarding-import-card-from",children:"Import your data from"}),a(xo,{})]})]}),a("div",{className:"onboarding-import-expand",children:[a("span",{className:"assistant-sr-only",children:"Optional import from Chrome, Edge, Safari, or Brave. Runs on this device only; Oasis does not receive your data."}),a("div",{className:"onboarding-import-callout",children:[a("span",{className:"onboarding-import-callout-shield",children:a(yo,{})}),a("div",{className:"onboarding-import-callout-main",children:[a("p",{className:"onboarding-import-callout-text",children:"Import runs in your browser on this device only. Oasis does not receive a copy of your data."}),a("a",{href:"about:preferences#general",className:"onboarding-import-learn-more",onClick:_=>{var v,T;_.preventDefault(),(T=(v=Nt.assistantBridge)==null?void 0:v.openTab)==null||T.call(v,"about:preferences#general")},children:"Learn more about importing"})]})]}),a("div",{className:"onboarding-import-actions",children:a("button",{type:"button",className:"onboarding-import-primary-btn",title:"Open browser import",onClick:_=>{_.stopPropagation(),g()},style:{fontSize:"12px",padding:"6px 12px",borderRadius:"8px",border:"1px solid #c5d49a",background:"#fff",color:"var(--header-title-color)",cursor:"pointer"},children:[a(_o,{}),"Import browser data"]})})]})]})}),l?a("div",{role:"status","aria-label":"Completed: Sign in to Oasis AI",style:H,children:[a(Ke,{done:!0}),a("span",{style:{flex:1,minWidth:0},children:[a("span",{style:{fontSize:"13px",fontWeight:600,display:"block"},children:"Sign in to Oasis AI"}),a("span",{style:{fontSize:"12px",color:"#9ca3af",display:"block",marginTop:"2px"},children:t==="auth"?"Use Google, Apple, Microsoft, or email.":"Open sign-in to create an account or log in."})]})]}):a("button",{type:"button",style:M,onClick:()=>{r.scrollToAuthPanel()},children:[a(Ke,{done:!1}),a("span",{style:{flex:1,minWidth:0},children:[a("span",{style:{fontSize:"13px",fontWeight:600,display:"block"},children:"Sign in to Oasis AI"}),a("span",{style:{fontSize:"12px",color:"#6b7280",display:"block",marginTop:"2px"},children:t==="auth"?"Use Google, Apple, Microsoft, or email.":"Open sign-in to create an account or log in."})]}),a("span",{style:{color:"#9ca3af",fontSize:"18px",lineHeight:1},"aria-hidden":!0,children:"\u203A"})]}),b?a("div",{role:"status","aria-label":"Completed: Run your first AI command",style:H,children:[a(Ke,{done:!0}),a("span",{style:{flex:1,minWidth:0},children:[a("span",{style:{fontSize:"13px",fontWeight:600,display:"block"},children:"Run your first AI command"}),a("span",{style:{fontSize:"12px",color:"#9ca3af",display:"block",marginTop:"2px"},children:e.isAuthenticated?"Ask a question or use voice after you are signed in.":"Use the composer and start chatting to run a command."})]})]}):a("button",{type:"button",style:M,onClick:()=>{if(!e.isAuthenticated){r.scrollToAuthPanel();return}r.snapToComposer()},children:[a(Ke,{done:!1}),a("span",{style:{flex:1,minWidth:0},children:[a("span",{style:{fontSize:"13px",fontWeight:600,display:"block"},children:"Run your first AI command"}),a("span",{style:{fontSize:"12px",color:"#6b7280",display:"block",marginTop:"2px"},children:e.isAuthenticated?"Ask a question or use voice after you are signed in.":"Use the composer and start chatting to run a command."})]}),a("span",{style:{color:"#9ca3af",fontSize:"18px",lineHeight:1},"aria-hidden":!0,children:"\u203A"})]})]})]})}var ko="oasis_assistant_chats";var _e="conversations",Ne="messages";function Ge(e){return`active:${e}`}function Oe(e){return new Promise((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>{var n;return r((n=e.error)!=null?n:new Error("IndexedDB request failed"))}})}function we(e){return new Promise((t,r)=>{e.oncomplete=()=>t(),e.onerror=()=>{var n;return r((n=e.error)!=null?n:new Error("IndexedDB transaction failed"))},e.onabort=()=>{var n;return r((n=e.error)!=null?n:new Error("IndexedDB transaction aborted"))}})}var Mt=null;function ke(){return Mt||(Mt=new Promise((e,t)=>{try{let r=indexedDB.open(ko,1);r.onupgradeneeded=()=>{let n=r.result;if(n.objectStoreNames.contains("kv")||n.createObjectStore("kv",{keyPath:"key"}),!n.objectStoreNames.contains(_e)){let o=n.createObjectStore(_e,{keyPath:"id"});o.createIndex("byUser","userId",{unique:!1}),o.createIndex("byUserUpdated",["userId","updatedAt"],{unique:!1})}n.objectStoreNames.contains(Ne)||n.createObjectStore(Ne,{keyPath:"id"}).createIndex("byConversation","conversationId",{unique:!1})},r.onsuccess=()=>e(r.result),r.onerror=()=>{var n;return t((n=r.error)!=null?n:new Error("IndexedDB open failed"))}}catch(r){t(r)}}),Mt)}async function So(e){let r=(await ke()).transaction("kv","readonly"),n=r.objectStore("kv"),o=await Oe(n.get(e));return await we(r),o==null?void 0:o.value}async function Co(e,t){let n=(await ke()).transaction("kv","readwrite");n.objectStore("kv").put({key:e,value:t}),await we(n)}async function Ao(e){let t=await So(Ge(e));return typeof t=="string"?t:null}async function Lt(e,t){if(t==null){let n=(await ke()).transaction("kv","readwrite");n.objectStore("kv").delete(Ge(e)),await we(n);return}await Co(Ge(e),t)}function sa(e){let t=e.find(n=>n.role==="user"&&n.content.trim());if(!t)return"New chat";let r=t.content.replace(/\s+/g," ").trim();return r.length>48?`${r.slice(0,47)}\u2026`:r}async function Te(e){let r=(await ke()).transaction(_e,"readonly"),n=r.objectStore(_e).index("byUser"),o=await Oe(n.getAll(e));return await we(r),o.sort((i,s)=>s.updatedAt-i.updatedAt),o}async function Pt(e,t="New chat"){let r=await ke(),n=typeof crypto!="undefined"&&crypto.randomUUID?crypto.randomUUID():`conv-${Date.now()}-${Math.random().toString(16).slice(2)}`,o={id:n,userId:e,title:t,updatedAt:Date.now()},i=r.transaction([_e,"kv"],"readwrite");return i.objectStore(_e).put(o),i.objectStore("kv").put({key:Ge(e),value:n}),await we(i),n}async function la(e,t){var s;let n=(await ke()).transaction(_e,"readwrite"),o=n.objectStore(_e),i=await Oe(o.get(e));if(!i){await we(n);return}o.put({...i,...t,updatedAt:(s=t.updatedAt)!=null?s:i.updatedAt}),await we(n)}async function Fr(e,t){let n=(await ke()).transaction([Ne,_e,"kv"],"readwrite"),o=n.objectStore(Ne),i=o.index("byConversation"),s=await Oe(i.getAllKeys(t));for(let u of s)o.delete(u);n.objectStore(_e).delete(t);let c=await Oe(n.objectStore("kv").get(Ge(e)));c&&c.value===t&&n.objectStore("kv").delete(Ge(e)),await we(n)}async function qe(e){let r=(await ke()).transaction(Ne,"readonly"),n=r.objectStore(Ne).index("byConversation"),o=await Oe(n.getAll(e));return await we(r),o.sort((i,s)=>i.sortOrder-s.sortOrder),o}async function ca(e,t){let n=(await ke()).transaction(Ne,"readwrite"),o=n.objectStore(Ne),i=o.index("byConversation"),s=await Oe(i.getAllKeys(e));for(let u of s)o.delete(u);let c=0;for(let u of t)o.put({id:u.id,conversationId:e,role:u.role,content:u.content,sortOrder:c++});await we(n)}function lt(e){return e.map(t=>({id:t.id,role:t.role,content:t.content}))}async function Vr(e){await ke();let t=await Te(e),r=await Ao(e);if(t.length===0)return{activeId:await Pt(e),messages:[]};(!r||!t.some(o=>o.id===r))&&(r=t[0].id,await Lt(e,r));let n=await qe(r);return{activeId:r,messages:lt(n)}}async function jr(e,t,r){let n=await Te(e);if(n.length!==1||n[0].id!==t||(await qe(t)).length>0)return!1;let i=await r();if(i.length===0)return!1;await ca(t,i);let s=sa(i);return await la(t,{title:s,updatedAt:Date.now()}),!0}function Xe(e){let t=[];for(let r=0;r0?e.id:typeof e.email=="string"&&e.email.length>0?`email:${e.email}`:null}var Z=window;function me(){try{if(typeof crypto!="undefined"&&crypto.randomUUID)return crypto.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function Ot(){try{window.dispatchEvent(new CustomEvent("oasis-usage-update"))}catch{}}function Eo(e){if(!e)return"";if(e.includes(" "))return e;let t=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/([A-Z])([A-Z][a-z])/g,"$1 $2");return t.charAt(0).toUpperCase()+t.slice(1)}function Kr(e){return String(e||"")}function Io(e){var t,r;return e.type==="human"||((t=e.id)==null?void 0:t.includes("Human"))||((r=e.constructor)==null?void 0:r.name)==="HumanMessage"}var dt=1,Ye="oasis.assistant.composerInlineChipsSendCount",Je="oasis.assistant.composerInlineChipsRetired",Gr=50;function No(){try{if(localStorage.getItem(Je)==="1")return dt;let e=parseInt(localStorage.getItem(Ye)||"0",10);return Number.isFinite(e)&&e>=0?e:0}catch{return 0}}function qr(){try{if(localStorage.getItem(Je)==="1")return dt;let e=parseInt(localStorage.getItem(Ye)||"0",10),r=(Number.isFinite(e)&&e>=0?e:0)+1;return localStorage.setItem(Ye,String(r)),r>=dt&&localStorage.setItem(Je,"1"),r}catch{return dt}}function Mo(e,t){let r=t.replace(/\s+/g," ").trim();r&&(e.length>0&&e[e.length-1]===r||(e.push(r),e.length>Gr&&e.splice(0,e.length-Gr)))}function Lo(e){return e.map((t,r)=>{let n=Io(t),o=t.content||(t.lc_kwargs?t.lc_kwargs.content:"")||"";return{id:t.id||`hist-${r}-${t.role||"msg"}`,role:n?"user":"ai",content:o}})}function Xr(e){let{auth:t,setPendingConfirmation:r,originalResetAssistantSession:n}=e,[o,i]=y([]),[s,c]=y(""),[u,d]=y(!1),[m,l]=y(!1),[b,p]=y([]),[f,k]=y(!0),[C,g]=y(null),[S,N]=y(No),[M,H]=y(0),[_,v]=y(null),[T,h]=y([]),J=G([]),B=G(null),W=G(null),Q=G(null),ue=G([]),R=G(-1),$=G(""),z=be(()=>t.isAuthenticated?ct(t.user):null,[t.isAuthenticated,t.user]);P(()=>{J.current=o},[o]),P(()=>{B.current=_},[_]),P(()=>{let x=Z.oasisSetRailroadSessionKey;if(typeof x=="function"){if(!t.isAuthenticated||!z||!_){x(null);return}x(`${z}:${_}`)}},[t.isAuthenticated,z,_]);let F=j(async()=>{var L;let x=ct(t.user),A=B.current;if(!x||!A||!t.isAuthenticated)return;let O=J.current;try{await ca(A,O),await la(A,{title:sa(O),updatedAt:Date.now()}),(L=Z.oasisSyncSessionFromPlainTurns)==null||L.call(Z,Xe(O)),h(await Te(x))}catch(q){console.error("oasis chat persist",q)}},[t.isAuthenticated,t.user]);P(()=>{if(!t.isAuthenticated||!z){v(null),B.current=null,h([]),i([]),J.current=[];return}let x=!1;return(async()=>{var A;try{let O=await Vr(z);if(x)return;let L=O.activeId;await jr(z,L,async()=>{let le=Z.getAssistantHistory;if(typeof le!="function")return[];let ce=await Promise.resolve(le());return Array.isArray(ce)?Lo(ce):[]});let q=await qe(L),re=lt(q);if(x)return;B.current=L,v(L),i(re),J.current=re;let Y=await Te(z);if(x)return;h(Y),(A=Z.oasisSyncSessionFromPlainTurns)==null||A.call(Z,Xe(re))}catch(O){console.error("oasis chat init",O)}})(),()=>{x=!0}},[t.isAuthenticated,z,M]),P(()=>{if(!t.isAuthenticated||!z||!_)return;let x=window.setTimeout(()=>{F()},400);return()=>window.clearTimeout(x)},[o,_,z,t.isAuthenticated,F]);let E=j((x,A)=>{i(O=>{let L=O.findIndex(Y=>Y.id===x);if(L===-1)return O;let q=[...O],re=q[L];return q[L]={...re,content:`${re.content}${A}`},q})},[]),I=j(()=>{W.current&&(W.current.pause(),W.current=null),Q.current&&(URL.revokeObjectURL(Q.current),Q.current=null),g(null)},[]),ee=j(async(x,A)=>{let O=Z.textToSpeech;if(typeof O=="function"){I(),g(A);try{let L=x.replace(/<[^>]*>/g,"").replace(/[#*_`~\[\]()>!|]/g,"").replace(/\n{2,}/g,". ").replace(/\n/g," ").trim();if(!L)return;let q=await O(L),re=URL.createObjectURL(q);Q.current=re;let Y=new Audio(re);W.current=Y,Y.onended=()=>{I()},Y.onerror=()=>{I()},await Y.play()}catch(L){console.error("TTS playback error:",L),I()}}},[I]),K=j(async(x,A="text")=>{let O=Z.runAssistantStream;if(typeof O!="function")return i(Y=>[...Y,{id:me(),role:"ai",content:"(runAssistantStream not available)"}]),null;let L=me();i(Y=>[...Y,{id:L,role:"ai",content:""}]);let q=!1;return{fullText:await O(x,Y=>{let le=Kr(Y);le&&(q||(q=!0,l(!0)),E(L,le))},A,L),aiMessageId:L}},[E]),w=j((x,A,O)=>{let L=me(),q=O||$r[x]||Eo(x);return p(re=>[...re,{id:L,name:x,status:"running",messageId:A,label:q}]),L},[]),X=j((x,A)=>{p(O=>O.map(L=>L.id===x?{...L,status:A}:L))},[]),U=be(()=>[...b].reverse().find(x=>x.status==="running"||x.status==="pending")||null,[b]),se=be(()=>t.isAuthenticated&&(o.length===0||S{R.current=-1,c(x)},[]),Re=j(async()=>{i([]),J.current=[],p([]),N(0),v(null),B.current=null,h([]),H(A=>A+1);try{localStorage.removeItem(Ye),localStorage.removeItem(Je)}catch{}typeof n=="function"&&await Promise.resolve(n());let x=Z.setAssistantHistory;typeof x=="function"&&await x([])},[n]),Me=j(async()=>{let x=ct(t.user);if(!x||!t.isAuthenticated)return;I(),p([]),N(0);try{localStorage.removeItem(Ye),localStorage.removeItem(Je)}catch{}await F(),typeof n=="function"&&await Promise.resolve(n());let A=await Pt(x);J.current=[],i([]),B.current=A,v(A),c(""),h(await Te(x))},[t.isAuthenticated,t.user,F,n,I]),Le=j(async x=>{var q;let A=ct(t.user);if(!A||!t.isAuthenticated||x===B.current)return;I(),p([]),await F();let O=await qe(x),L=lt(O);await Lt(A,x),J.current=L,i(L),B.current=x,v(x),(q=Z.oasisSyncSessionFromPlainTurns)==null||q.call(Z,Xe(L)),h(await Te(A))},[t.isAuthenticated,t.user,F,I]),Ee=j(async x=>{var le,ce;let A=ct(t.user);if(!A||!t.isAuthenticated)return;let O=B.current===x;O?(I(),p([])):await F(),await Fr(A,x);let L=await Te(A);if(h(L),!O)return;if(L.length===0){try{localStorage.removeItem(Ye),localStorage.removeItem(Je)}catch{}N(0),typeof n=="function"&&await Promise.resolve(n());let ve=await Pt(A);J.current=[],i([]),B.current=ve,v(ve),c(""),(le=Z.oasisSyncSessionFromPlainTurns)==null||le.call(Z,Xe([])),h(await Te(A));return}let q=L[0].id,re=await qe(q),Y=lt(re);await Lt(A,q),J.current=Y,i(Y),B.current=q,v(q),(ce=Z.oasisSyncSessionFromPlainTurns)==null||ce.call(Z,Xe(Y))},[t.isAuthenticated,t.user,F,n,I]),De=[At,"","Oasis assistant capabilities are not available in this build.","","You can still describe what you wanted in plain English. When something is wrong or missing, use the feedback link below or the thumbs up and thumbs down on assistant replies (training) so we can widen what Oasis supports.","","### Support and feedback","","Kahana lists commands in depth; the feedback form captures suggestions. Thumbs on each reply add training signal so we can expand supported behavior quickly.","",`- [${Tt}](${je})`,`- [${Et}](${$e})`].join(` +`),Be=j(()=>{var q,re,Y,le,ce,ve;if(!t.isAuthenticated){i(de=>[...de,{id:me(),role:"ai",content:"Please sign in to use the assistant."}]);return}I(),N(qr());let x=De;try{let de=(q=Z.getOasisCapabilitiesMarkdown)==null?void 0:q.call(Z);de&&de.replace(/\s+/g,"").length>0&&(x=de)}catch{x=De}(re=Z.oasisPushLocalChatTurn)==null||re.call(Z,st,x);let A=me(),O=me();i(de=>[...de,{id:A,role:"user",content:st},{id:O,role:"ai",content:x}]);let L=(le=(Y=Z.assistantBridge)==null?void 0:Y.getOnboardingStatus)==null?void 0:le.call(Y);L&&!L.firstAiTurnComplete&&((ve=(ce=Z.assistantBridge)==null?void 0:ce.markFirstAiTurnComplete)==null||ve.call(ce)),Ot()},[t.isAuthenticated,I]),ze=j(async(x,A)=>{var re,Y,le,ce,ve,de;let O=(re=A==null?void 0:A.fromVoice)!=null?re:!1,L=x||s;if(!L.trim())return;if(!t.isAuthenticated){i(fe=>[...fe,{id:me(),role:"ai",content:"Please sign in to use the assistant."}]);return}I(),O||(Mo(ue.current,L),R.current=-1,N(qr())),c(""),l(!1),d(!0),p([]);let q=me();i(fe=>[...fe,{id:q,role:"user",content:L}]);try{let fe=await K(L,O?"voice":"text");if(fe){let pt=(le=(Y=Z.assistantBridge)==null?void 0:Y.getOnboardingStatus)==null?void 0:le.call(Y);pt&&!pt.firstAiTurnComplete&&((ve=(ce=Z.assistantBridge)==null?void 0:ce.markFirstAiTurnComplete)==null||ve.call(ce))}O&&f&&((de=fe==null?void 0:fe.fullText)!=null&&de.trim())&&ee(fe.fullText,fe.aiMessageId)}catch(fe){i(pt=>[...pt,{id:me(),role:"ai",content:`Error: ${String(fe)}`}])}finally{l(!1),d(!1),F(),Ot()}},[t.isAuthenticated,F,s,K,ee,I,f]),Rt=j(x=>{var ve;if(x.key==="Enter"&&!x.shiftKey){x.preventDefault(),R.current=-1,ze();return}if(x.key!=="ArrowUp"&&x.key!=="ArrowDown"||x.shiftKey||x.metaKey||x.ctrlKey||x.altKey)return;let A=x.target;if(!A||A.tagName!=="TEXTAREA")return;let O=A.value,L=(ve=A.selectionStart)!=null?ve:0,q=ue.current;if(q.length===0)return;let re=O.indexOf(` +`),Y=re===-1||L<=re;if(x.key==="ArrowUp"){let de=R.current;if(de<0){if(!Y)return;$.current=O,de=0}else{if(de>=q.length-1)return;de+=1}R.current=de;let fe=q[q.length-1-de];x.preventDefault(),c(fe);return}let le=R.current;if(le<0)return;if(x.preventDefault(),le===0){R.current=-1,c($.current);return}let ce=le-1;R.current=ce,c(q[q.length-1-ce])},[ze,c]),Dt=j(async()=>{r(null),I(),l(!1),d(!0),p([]);try{await K("yes","text")}finally{l(!1),d(!1),F(),Ot()}},[F,K,r,I]),D=j(async()=>{r(null),I(),l(!1),d(!0),p([]);try{await K("no","text")}catch{let x=Z.oasisClearPendingConfirmation;typeof x=="function"&&x(),i(A=>[...A,{id:me(),role:"ai",content:"Action cancelled."}])}finally{l(!1),d(!1),F(),Ot()}},[F,K,r,I]),ae=j(()=>{k(x=>(x&&I(),!x))},[I]),ge=j(x=>{let A=me(),O=me();return i(L=>[...L,{id:A,role:"user",content:x},{id:O,role:"ai",content:""}]),O},[]),Se=j((x,A)=>{let O=Kr(A);O&&E(x,O)},[E]),Ie=j((x,A)=>{let O=x.replace(/\s+/g," ").trim(),L=A.replace(/\s+/g," ").trim();!O&&!L||i(q=>[...q,...O?[{id:me(),role:"user",content:O}]:[],...L?[{id:me(),role:"ai",content:L}]:[]])},[]);return{messages:o,setMessages:i,input:s,setInput:c,handleComposerInput:pe,busy:u,responseStreaming:m,toolActions:b,activeToolAction:U,send:ze,insertCapabilitiesOverview:Be,handleKeyDown:Rt,showComposerInlineChips:se,handleConfirmationApprove:Dt,handleConfirmationCancel:D,startToolAction:w,updateToolAction:X,resetAssistantSession:Re,startNewChat:Me,openConversation:Le,deleteChatConversation:Ee,activeChatId:_,chatConversations:T,ttsEnabled:f,toggleTtsEnabled:ae,speakingMsgId:C,speakText:ee,stopSpeaking:I,voiceTurnBeginForChat:ge,voiceStreamChunkForChat:Se,voiceSpokenTurnMirrorForChat:Ie}}var da="oasis-auth-update";var ua="oasis-confirmation-update";var ut=window;function Yr(e){if(!(!e||typeof e=="string"))return typeof e.id=="string"?e.id:void 0}function Po(e){var t,r;if(typeof e=="function")return e;if(e&&typeof e=="object"){let n=e;if(typeof n.unsubscribe=="function")return()=>{n.unsubscribe()};if(typeof((r=(t=n.data)==null?void 0:t.subscription)==null?void 0:r.unsubscribe)=="function"){let o=n.data.subscription.unsubscribe;return()=>{o()}}}}function Jr(e){let{setAuth:t,setPendingConfirmation:r,onAuthenticated:n,onUserChanged:o}=e;P(()=>{var m;let i=()=>{let l=ut.oasisAuthState;!l||l.isAuthenticated===void 0||(t(b=>{let p=b.isAuthenticated===l.isAuthenticated,f=Yr(b.user)===Yr(l.user);return p&&f?b:(f||o(),{isAuthenticated:!!l.isAuthenticated,user:l.user})}),l.isAuthenticated&&n())},s=async()=>{try{let l=ut.oasisAuthState;if(l!=null&&l.isAuthenticated){t({isAuthenticated:!0,user:l.user}),n();return}let b=ut.supabaseAuth;if(!b||!await b.isAuthenticated())return;let f=await b.getCurrentUser();t({isAuthenticated:!0,user:f}),n()}catch{}};s(),window.addEventListener(da,i);let c=l=>{let b=l.detail;r(b)};window.addEventListener(ua,c);let u;if(typeof((m=ut.supabaseAuth)==null?void 0:m.onAuthStateChange)=="function"){let l=ut.supabaseAuth.onAuthStateChange(b=>{t({isAuthenticated:!!b.isAuthenticated,user:b.user}),b.isAuthenticated&&(n(),o())});u=Po(l)}let d=window.setTimeout(()=>{s()},1500);return()=>{window.removeEventListener(da,i),window.removeEventListener(ua,c),window.clearTimeout(d),u==null||u()}},[n,o,t,r])}var he=window;function Zr(e){let{startToolAction:t,updateToolAction:r,resetAssistantSession:n,setPendingConfirmation:o}=e;P(()=>{let i=he.oasisRecordToolActionStart,s=he.oasisRecordToolActionUpdate,c=he.resetAssistantSession,u=he.oasisSetPendingConfirmationRelay;return he.oasisRecordToolActionStart=(d,m,l)=>t(d,m,l),he.oasisRecordToolActionUpdate=(d,m)=>{r(d,m)},he.resetAssistantSession=()=>n(),he.oasisSetPendingConfirmationRelay=d=>{o(d)},()=>{he.oasisRecordToolActionStart=i,he.oasisRecordToolActionUpdate=s,he.resetAssistantSession=c,he.oasisSetPendingConfirmationRelay=u}},[n,o,t,r])}var ne=window,Oo=5e3;function Ro({email:e,onClose:t}){return a("div",{className:"signed-in-banner",children:[a("div",{className:"banner-content",children:[a("span",{className:"banner-label",children:"Signed in as"}),a("span",{className:"banner-email",children:e})]}),a("button",{className:"banner-close",onClick:t,title:"Close",children:a("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[a("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})}function Do(e){return e?typeof e=="string"?e:typeof e.email=="string"?e.email:"":""}var Qr="oasis.voice.echoHintDismissed";function Bo(e,t,r,n){if(r==="echo_guard")return"Ready in a moment\u2026";switch(e){case"idle":return"Voice ready";case"listening":return t?"Hearing you":"Listening";case"transcribing":return"Processing speech";case"thinking":return n?"Assistant is thinking":"Writing in chat";case"speaking":return"Assistant is speaking";default:return""}}function zo(e,t,r){if(t==="echo_guard")return"Letting the room quiet down so your mic is not picking up the assistant.";switch(e){case"idle":return"Tap the microphone below to start";case"listening":return"Pause briefly after you speak, or tap the orb to send now";case"transcribing":return"Tap the orb to cancel if this takes too long";case"thinking":return r?"Tap the orb to cancel if this takes too long":"Watch the chat for the streamed reply; tap the orb to cancel";case"speaking":return"Tap the orb to stop playback";default:return""}}function Ho(e){return e==="listening"?"voice-agent-overlay-phase-you":e==="transcribing"||e==="thinking"||e==="speaking"?"voice-agent-overlay-phase-assistant":"voice-agent-overlay-phase-idle"}function Uo(){try{return localStorage.getItem(Qr)==="1"}catch{return!1}}function Wo({onClose:e}){let[t,r]=y("idle"),[n,o]=y(""),[i,s]=y(""),[c,u]=y(!1),[d,m]=y(null),[l,b]=y("continuous"),[p,f]=y(!0),[k,C]=y(Uo),g=ne.voiceAgent;P(()=>{if(!g)return;b(g.getCaptureMode()),f(g.getVoiceSpokenRepliesEnabled());let W=g.on(Q=>{switch(Q.type){case"state":r(Q.state),Q.state==="idle"&&m(null);break;case"userTranscript":o(Q.text),Q.text.trim()&&s("");break;case"error":s(Q.message);break;case"vad":u(Q.userSpeaking);break;case"listening_phase":m(Q.phase);break;case"turn_done":break;case"assistant_reply_text":case"audio_level":break}});return r(g.getState()),u(g.getUserSpeaking()),()=>{W(),g.stop()}},[g]);let S=()=>{if(!g)return;let W=g.getState();if(W==="transcribing"||W==="thinking"){g.stop();return}if(W==="speaking"){g.stopSpeaking();return}if(W==="listening"){g.finishListening();return}W==="idle"&&(s(""),g.startConversation())},N=()=>{g&&g.stop(),e()},M=t==="listening",H=t==="transcribing"||t==="thinking",_=t==="speaking",v=!k&&M&&d==="capturing",T=W=>{g&&(g.setCaptureMode(W),b(W))},h=W=>{g&&(g.setVoiceSpokenRepliesEnabled(W),f(W))},J=()=>{C(!0);try{localStorage.setItem(Qr,"1")}catch{}};if(!g)return a("div",{className:"voice-agent-overlay voice-agent-overlay-phase-idle",children:[a("button",{className:"voice-agent-close",onClick:e,type:"button",title:"Close","aria-label":"Close voice assistant",children:a("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[a("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}),a("div",{className:"voice-agent-content",children:a("div",{className:"voice-agent-transcript voice-agent-error",children:"Voice assistant is not available in this build."})})]});let B=H?"Cancel":t==="speaking"?"Stop playback":t==="listening"?"Tap to stop listening and send what we heard":"Start voice conversation";return a("div",{className:`voice-agent-overlay ${Ho(t)}`,children:[a("button",{className:"voice-agent-close",onClick:N,title:"Close","aria-label":"Close voice assistant",children:a("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[a("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}),a("div",{className:"voice-agent-content",children:[a(Ha,{agent:g,agentState:t}),M&&a("div",{className:c?"voice-agent-recording-pill voice-agent-recording-pill-active":"voice-agent-recording-pill","aria-live":"polite",children:c?"Picking up speech":"Mic on"}),n&&a("div",{className:"voice-agent-transcript voice-agent-user-text",children:n}),v&&a("div",{className:"voice-agent-echo-hint",role:"status",children:[a("span",{children:"For best results, use headphones or keep speaker volume low to reduce echo."}),a("button",{type:"button",className:"voice-agent-echo-hint-dismiss",onClick:J,children:"Dismiss"})]}),i&&a("div",{className:"voice-agent-error-row",children:[a("div",{className:"voice-agent-transcript voice-agent-error",children:i}),a("button",{type:"button",className:"voice-agent-error-dismiss",onClick:()=>s(""),children:"Dismiss"})]})]}),a("div",{className:"voice-agent-bottom",children:[a("div",{className:"voice-agent-capture-toggle",role:"group","aria-label":"Voice capture mode",children:[a("span",{className:"voice-agent-capture-label",children:"Capture"}),a("button",{type:"button",className:l==="continuous"?"voice-agent-capture-option voice-agent-capture-option-active":"voice-agent-capture-option",onClick:()=>T("continuous"),children:"Continuous"}),a("button",{type:"button",className:l==="precise"?"voice-agent-capture-option voice-agent-capture-option-active":"voice-agent-capture-option",onClick:()=>T("precise"),children:"Precise"})]}),a("div",{className:"voice-agent-capture-toggle",role:"group","aria-label":"Voice reply mode",children:[a("span",{className:"voice-agent-capture-label",children:"Replies"}),a("button",{type:"button",className:p?"voice-agent-capture-option voice-agent-capture-option-active":"voice-agent-capture-option",onClick:()=>h(!0),children:"Spoken"}),a("button",{type:"button",className:p?"voice-agent-capture-option":"voice-agent-capture-option voice-agent-capture-option-active",onClick:()=>h(!1),children:"Chat"})]}),a("div",{className:"voice-agent-status-block",children:[a("div",{className:"voice-agent-status","aria-live":"polite",children:Bo(t,c,d,p)}),a("div",{className:"voice-agent-hint",children:zo(t,d,p)})]}),a("button",{type:"button",className:["voice-agent-orb",M?"voice-agent-orb-listening":"",H?"voice-agent-orb-busy":"",_?"voice-agent-orb-speaking":""].filter(Boolean).join(" "),onPointerDown:S,title:B,"aria-label":B,children:H?a("svg",{className:"voice-agent-orb-icon",width:"32",height:"32",viewBox:"0 0 24 24",fill:"currentColor",children:a("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"})}):_?a("svg",{className:"voice-agent-orb-icon",width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a("rect",{x:"6",y:"4",width:"4",height:"16"}),a("rect",{x:"14",y:"4",width:"4",height:"16"})]}):a("svg",{className:"voice-agent-orb-icon",width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a("path",{d:"M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"}),a("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),a("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),a("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]})})]})]})}function Fo(){var e;try{if((e=ne.oasisAuthState)!=null&&e.isAuthenticated)return"chat"}catch{}return"auth"}function en(){var ee,K;let[e,t]=y({isAuthenticated:!1,user:null}),[r,n]=y(()=>Fo()),o=ht(),[i,s]=y(!0),[c,u]=y(null),[d,m]=y(!1),[l,b]=y(!1),[p,f]=y(0),[k,C]=y(""),[g,S]=y(!1),[N,M]=y(!1),[H,_]=y(0),v=G(ne.resetAssistantSession),T=j(()=>{var w,X;(X=(w=ne.subscriptionService)==null?void 0:w.forceRefresh)==null||X.call(w),n("chat")},[]),h=Xr({auth:e,setPendingConfirmation:u,originalResetAssistantSession:v.current}),J=j(()=>{var w,X;s(!0),h.resetAssistantSession(),(X=(w=ne.subscriptionService)==null?void 0:w.forceRefresh)==null||X.call(w)},[h.resetAssistantSession]);Zr({startToolAction:h.startToolAction,updateToolAction:h.updateToolAction,resetAssistantSession:h.resetAssistantSession,setPendingConfirmation:u}),P(()=>{let w=h.voiceTurnBeginForChat,X=h.voiceStreamChunkForChat,U=h.voiceSpokenTurnMirrorForChat;return ne.oasisVoiceAssistantTurnBegin=w,ne.oasisVoiceAssistantStreamChunk=X,ne.oasisVoiceSpokenTurnMirror=U,()=>{ne.oasisVoiceAssistantTurnBegin===w&&delete ne.oasisVoiceAssistantTurnBegin,ne.oasisVoiceAssistantStreamChunk===X&&delete ne.oasisVoiceAssistantStreamChunk,ne.oasisVoiceSpokenTurnMirror===U&&delete ne.oasisVoiceSpokenTurnMirror}},[h.voiceTurnBeginForChat,h.voiceStreamChunkForChat,h.voiceSpokenTurnMirrorForChat]),Jr({setAuth:t,setPendingConfirmation:u,onAuthenticated:T,onUserChanged:J}),P(()=>{var w,X;try{let U=(X=(w=ne.assistantBridge)==null?void 0:w.getAssistantTheme)==null?void 0:X.call(w);ot(typeof U=="string"?U:"default")}catch{ot("default")}},[]);let B=G(null);P(()=>{let w=B.current,X=e.isAuthenticated;w===!0&&X===!1&&n("auth"),B.current=X},[e.isAuthenticated]);let W=w=>{w.preventDefault(),w.stopPropagation(),nt({type:"oasisOverlayResizeStart",screenX:w.screenX,screenY:w.screenY})},Q=()=>{let w="https://tally.so/r/3jkNN6";if(typeof ne.openWebLinkIn=="function"){ne.openWebLinkIn(w,"tab",{});return}if(window.top&&typeof window.top.openWebLinkIn=="function"){window.top.openWebLinkIn(w,"tab",{});return}window.open(w,"_blank")},ue=j(w=>{Ct()},[]),R=j(()=>{var U;n("chat");let w=null;for(let se=h.messages.length-1;se>=0;se--){let pe=h.messages[se];if(pe.role==="ai"&&((U=pe.content)!=null&&U.trim())){w=pe.id;break}}let X=!!w;ne.mpTrack&&ne.mpTrack("token_usage_go_to_training",{hadTarget:X}),X&&w?(C(w),f(se=>se+1)):(C(""),requestAnimationFrame(()=>{requestAnimationFrame(()=>{var se,pe;(se=document.getElementById("oasis-assistant-composer"))==null||se.scrollIntoView({block:"center",behavior:"smooth"}),(pe=o.current)==null||pe.focus()})}),S(!0),window.setTimeout(()=>S(!1),6e3))},[h.messages]),$=j(()=>{b(!0),ne.mpTrack&&ne.mpTrack("training_gallery_opened",{})},[]),z=w=>{var pe;let U=w.target.closest("a");if(!U||!U.href||U.href.startsWith("javascript:"))return;w.preventDefault();let se=U.href;(pe=ne.assistantBridge)!=null&&pe.openTab?ne.assistantBridge.openTab(se):window.open(se,"_blank")},F=j((w,X)=>{if(!X){h.stopSpeaking();return}h.speakText(X,w)},[h]),E=Do(e.user);P(()=>{if(!e.isAuthenticated||!E||!i)return;let w=window.setTimeout(()=>{s(!1)},Oo);return()=>window.clearTimeout(w)},[e.isAuthenticated,E,i]);let I=be(()=>({goAuth:()=>n("auth"),goChat:()=>n("chat"),focusComposer:()=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>{var w;(w=o.current)==null||w.focus()})})},scrollToAuthPanel:()=>{n("auth"),requestAnimationFrame(()=>{requestAnimationFrame(()=>{var w;(w=document.getElementById("oasis-auth-panel"))==null||w.scrollIntoView({block:"start",behavior:"smooth"})})})},snapToComposer:()=>{n("chat"),requestAnimationFrame(()=>{requestAnimationFrame(()=>{var w,X;(w=document.getElementById("oasis-assistant-composer"))==null||w.scrollIntoView({block:"center",behavior:"smooth"}),(X=o.current)==null||X.focus(),M(!0),window.setTimeout(()=>M(!1),3200)})})}}),[]);return a("div",{className:"assistant-container",children:[d&&a(Wo,{onClose:()=>m(!1)}),l&&a(Hr,{open:l,onClose:()=>b(!1)}),c&&a(Ja,{data:c,onConfirm:()=>{h.handleConfirmationApprove()},onCancel:()=>{h.handleConfirmationCancel()}}),a(Ka,{auth:e,onShowAuth:()=>n("auth"),onOpenTrainingGallery:$,chatHistory:e.isAuthenticated&&r==="chat"?{conversations:h.chatConversations,activeId:h.activeChatId,onSelectConversation:w=>{h.openConversation(w)},onNewChat:()=>{h.startNewChat()},onDeleteConversation:w=>{h.deleteChatConversation(w)}}:null}),a("div",{className:`assistant-main${r==="auth"?" assistant-main--auth":""}${r!=="auth"&&e.isAuthenticated&&h.messages.length===0?" assistant-main--empty-signed-chat":""}`,"aria-busy":r!=="auth"&&h.busy?!0:void 0,children:[r!=="auth"&&a("div",{className:"assistant-onboarding-top",children:a(ia,{auth:e,view:r,onNavigate:I,onCollapseRequest:H})}),a("div",{className:`assistant-scroll${r==="auth"?" assistant-scroll--auth":""}`,children:r==="auth"?a(te,{children:[a(Ya,{onSuccess:()=>n("chat"),onEmailPasswordOpen:()=>_(w=>w+1)}),a(ia,{auth:e,view:r,onNavigate:I,onCollapseRequest:H})]}):a("div",{className:"assistant-chat-stack",children:[e.isAuthenticated&&E&&i&&a(Ro,{email:E,onClose:()=>s(!1)}),a(Ir,{messages:h.messages,isAuthenticated:e.isAuthenticated,busy:h.busy,activeToolLabel:((ee=h.activeToolAction)==null?void 0:ee.label)||null,responseStreaming:h.responseStreaming,onLinkClick:z,speakingMsgId:h.speakingMsgId,onTtsClick:F,onTrainingSubmitted:ue,trainingFocusTick:p,trainingFocusMessageId:k})]})}),r!=="auth"&&a(Ur,{busy:h.busy,activeToolLabel:((K=h.activeToolAction)==null?void 0:K.label)||null,responseStreaming:h.responseStreaming}),r!=="auth"&&a(Br,{input:h.input,busy:h.busy,isAuthenticated:e.isAuthenticated,chatIsEmpty:h.messages.length===0,ttsEnabled:h.ttsEnabled,inputRef:o,showInlineChips:h.showComposerInlineChips,inlineSuggestions:Pr,highlightInlineChips:N,onInlineSuggestionSend:w=>{h.send(w)},onInput:h.handleComposerInput,onKeyDown:h.handleKeyDown,onSend:()=>{h.send()},onResetSession:()=>{h.startNewChat()},onFeedback:Q,onToggleTts:()=>{h.speakingMsgId&&h.stopSpeaking(),h.toggleTtsEnabled()},onOpenVoiceAgent:()=>m(!0),onRequestSignIn:()=>n("auth"),onOpenTraining:R,showTrainLatestComposerHint:g,onDismissTrainLatestHint:()=>S(!1),onInsertCapabilities:()=>{h.insertCapabilitiesOverview()}})]}),a("div",{onPointerDown:W,style:{position:"fixed",bottom:"0",right:"0",width:"20px",height:"20px",cursor:"nwse-resize",zIndex:99999},title:"Resize",children:a("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",style:{position:"absolute",bottom:2,right:2,opacity:.3},children:[a("path",{d:"M14 14L18 18",stroke:"#000",strokeWidth:"2",strokeLinecap:"round"}),a("path",{d:"M10 18L18 10",stroke:"#000",strokeWidth:"2",strokeLinecap:"round"})]})})]})}var tn="assistant-preact-root";function Vo(){let e=document.getElementById(tn);if(!e){e=document.createElement("div"),e.id=tn;let t=document.getElementById("log");t&&t.parentElement?t.parentElement.insertBefore(e,t):document.body.appendChild(e)}return e}var jo=Vo(),an;(an=document.getElementById("assistant-ui-loading"))==null||an.remove();tt(Ae(en,{}),jo);})(); diff --git a/browser/base/content/assistant/embedding-assets/models/Xenova/all-MiniLM-L6-v2/config.json b/browser/base/content/assistant/embedding-assets/models/Xenova/all-MiniLM-L6-v2/config.json new file mode 100644 index 0000000000000..72147e4ff4426 --- /dev/null +++ b/browser/base/content/assistant/embedding-assets/models/Xenova/all-MiniLM-L6-v2/config.json @@ -0,0 +1,25 @@ +{ + "_name_or_path": "sentence-transformers/all-MiniLM-L6-v2", + "architectures": [ + "BertModel" + ], + "attention_probs_dropout_prob": 0.1, + "classifier_dropout": null, + "gradient_checkpointing": false, + "hidden_act": "gelu", + "hidden_dropout_prob": 0.1, + "hidden_size": 384, + "initializer_range": 0.02, + "intermediate_size": 1536, + "layer_norm_eps": 1e-12, + "max_position_embeddings": 512, + "model_type": "bert", + "num_attention_heads": 12, + "num_hidden_layers": 6, + "pad_token_id": 0, + "position_embedding_type": "absolute", + "transformers_version": "4.29.2", + "type_vocab_size": 2, + "use_cache": true, + "vocab_size": 30522 +} diff --git a/browser/base/content/assistant/embedding-assets/models/Xenova/all-MiniLM-L6-v2/onnx/model_quantized.onnx b/browser/base/content/assistant/embedding-assets/models/Xenova/all-MiniLM-L6-v2/onnx/model_quantized.onnx new file mode 100644 index 0000000000000..712e070a96dae Binary files /dev/null and b/browser/base/content/assistant/embedding-assets/models/Xenova/all-MiniLM-L6-v2/onnx/model_quantized.onnx differ diff --git a/browser/base/content/assistant/embedding-assets/models/Xenova/all-MiniLM-L6-v2/special_tokens_map.json b/browser/base/content/assistant/embedding-assets/models/Xenova/all-MiniLM-L6-v2/special_tokens_map.json new file mode 100644 index 0000000000000..a8b3208c2884c --- /dev/null +++ b/browser/base/content/assistant/embedding-assets/models/Xenova/all-MiniLM-L6-v2/special_tokens_map.json @@ -0,0 +1,7 @@ +{ + "cls_token": "[CLS]", + "mask_token": "[MASK]", + "pad_token": "[PAD]", + "sep_token": "[SEP]", + "unk_token": "[UNK]" +} diff --git a/browser/base/content/assistant/embedding-assets/models/Xenova/all-MiniLM-L6-v2/tokenizer.json b/browser/base/content/assistant/embedding-assets/models/Xenova/all-MiniLM-L6-v2/tokenizer.json new file mode 100644 index 0000000000000..c17ed520ed843 --- /dev/null +++ b/browser/base/content/assistant/embedding-assets/models/Xenova/all-MiniLM-L6-v2/tokenizer.json @@ -0,0 +1,30686 @@ +{ + "version": "1.0", + "truncation": { + "direction": "Right", + "max_length": 128, + "strategy": "LongestFirst", + "stride": 0 + }, + "padding": { + "strategy": { + "Fixed": 128 + }, + "direction": "Right", + "pad_to_multiple_of": null, + "pad_id": 0, + "pad_type_id": 0, + "pad_token": "[PAD]" + }, + "added_tokens": [ + { + "id": 0, + "content": "[PAD]", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + { + "id": 100, + "content": "[UNK]", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + { + "id": 101, + "content": "[CLS]", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + { + "id": 102, + "content": "[SEP]", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + }, + { + "id": 103, + "content": "[MASK]", + "single_word": false, + "lstrip": false, + "rstrip": false, + "normalized": false, + "special": true + } + ], + "normalizer": { + "type": "BertNormalizer", + "clean_text": true, + "handle_chinese_chars": true, + "strip_accents": null, + "lowercase": true + }, + "pre_tokenizer": { + "type": "BertPreTokenizer" + }, + "post_processor": { + "type": "TemplateProcessing", + "single": [ + { + "SpecialToken": { + "id": "[CLS]", + "type_id": 0 + } + }, + { + "Sequence": { + "id": "A", + "type_id": 0 + } + }, + { + "SpecialToken": { + "id": "[SEP]", + "type_id": 0 + } + } + ], + "pair": [ + { + "SpecialToken": { + "id": "[CLS]", + "type_id": 0 + } + }, + { + "Sequence": { + "id": "A", + "type_id": 0 + } + }, + { + "SpecialToken": { + "id": "[SEP]", + "type_id": 0 + } + }, + { + "Sequence": { + "id": "B", + "type_id": 1 + } + }, + { + "SpecialToken": { + "id": "[SEP]", + "type_id": 1 + } + } + ], + "special_tokens": { + "[CLS]": { + "id": "[CLS]", + "ids": [ + 101 + ], + "tokens": [ + "[CLS]" + ] + }, + "[SEP]": { + "id": "[SEP]", + "ids": [ + 102 + ], + "tokens": [ + "[SEP]" + ] + } + } + }, + "decoder": { + "type": "WordPiece", + "prefix": "##", + "cleanup": true + }, + "model": { + "type": "WordPiece", + "unk_token": "[UNK]", + "continuing_subword_prefix": "##", + "max_input_chars_per_word": 100, + "vocab": { + "[PAD]": 0, + "[unused0]": 1, + "[unused1]": 2, + "[unused2]": 3, + "[unused3]": 4, + "[unused4]": 5, + "[unused5]": 6, + "[unused6]": 7, + "[unused7]": 8, + "[unused8]": 9, + "[unused9]": 10, + "[unused10]": 11, + "[unused11]": 12, + "[unused12]": 13, + "[unused13]": 14, + "[unused14]": 15, + "[unused15]": 16, + "[unused16]": 17, + "[unused17]": 18, + "[unused18]": 19, + "[unused19]": 20, + "[unused20]": 21, + "[unused21]": 22, + "[unused22]": 23, + "[unused23]": 24, + "[unused24]": 25, + "[unused25]": 26, + "[unused26]": 27, + "[unused27]": 28, + "[unused28]": 29, + "[unused29]": 30, + "[unused30]": 31, + "[unused31]": 32, + "[unused32]": 33, + "[unused33]": 34, + "[unused34]": 35, + "[unused35]": 36, + "[unused36]": 37, + "[unused37]": 38, + "[unused38]": 39, + "[unused39]": 40, + "[unused40]": 41, + "[unused41]": 42, + "[unused42]": 43, + "[unused43]": 44, + "[unused44]": 45, + "[unused45]": 46, + "[unused46]": 47, + "[unused47]": 48, + "[unused48]": 49, + "[unused49]": 50, + "[unused50]": 51, + "[unused51]": 52, + "[unused52]": 53, + "[unused53]": 54, + "[unused54]": 55, + "[unused55]": 56, + "[unused56]": 57, + "[unused57]": 58, + "[unused58]": 59, + "[unused59]": 60, + "[unused60]": 61, + "[unused61]": 62, + "[unused62]": 63, + "[unused63]": 64, + "[unused64]": 65, + "[unused65]": 66, + "[unused66]": 67, + "[unused67]": 68, + "[unused68]": 69, + "[unused69]": 70, + "[unused70]": 71, + "[unused71]": 72, + "[unused72]": 73, + "[unused73]": 74, + "[unused74]": 75, + "[unused75]": 76, + "[unused76]": 77, + "[unused77]": 78, + "[unused78]": 79, + "[unused79]": 80, + "[unused80]": 81, + "[unused81]": 82, + "[unused82]": 83, + "[unused83]": 84, + "[unused84]": 85, + "[unused85]": 86, + "[unused86]": 87, + "[unused87]": 88, + "[unused88]": 89, + "[unused89]": 90, + "[unused90]": 91, + "[unused91]": 92, + "[unused92]": 93, + "[unused93]": 94, + "[unused94]": 95, + "[unused95]": 96, + "[unused96]": 97, + "[unused97]": 98, + "[unused98]": 99, + "[UNK]": 100, + "[CLS]": 101, + "[SEP]": 102, + "[MASK]": 103, + "[unused99]": 104, + "[unused100]": 105, + "[unused101]": 106, + "[unused102]": 107, + "[unused103]": 108, + "[unused104]": 109, + "[unused105]": 110, + "[unused106]": 111, + "[unused107]": 112, + "[unused108]": 113, + "[unused109]": 114, + "[unused110]": 115, + "[unused111]": 116, + "[unused112]": 117, + "[unused113]": 118, + "[unused114]": 119, + "[unused115]": 120, + "[unused116]": 121, + "[unused117]": 122, + "[unused118]": 123, + "[unused119]": 124, + "[unused120]": 125, + "[unused121]": 126, + "[unused122]": 127, + "[unused123]": 128, + "[unused124]": 129, + "[unused125]": 130, + "[unused126]": 131, + "[unused127]": 132, + "[unused128]": 133, + "[unused129]": 134, + "[unused130]": 135, + "[unused131]": 136, + "[unused132]": 137, + "[unused133]": 138, + "[unused134]": 139, + "[unused135]": 140, + "[unused136]": 141, + "[unused137]": 142, + "[unused138]": 143, + "[unused139]": 144, + "[unused140]": 145, + "[unused141]": 146, + "[unused142]": 147, + "[unused143]": 148, + "[unused144]": 149, + "[unused145]": 150, + "[unused146]": 151, + "[unused147]": 152, + "[unused148]": 153, + "[unused149]": 154, + "[unused150]": 155, + "[unused151]": 156, + "[unused152]": 157, + "[unused153]": 158, + "[unused154]": 159, + "[unused155]": 160, + "[unused156]": 161, + "[unused157]": 162, + "[unused158]": 163, + "[unused159]": 164, + "[unused160]": 165, + "[unused161]": 166, + "[unused162]": 167, + "[unused163]": 168, + "[unused164]": 169, + "[unused165]": 170, + "[unused166]": 171, + "[unused167]": 172, + "[unused168]": 173, + "[unused169]": 174, + "[unused170]": 175, + "[unused171]": 176, + "[unused172]": 177, + "[unused173]": 178, + "[unused174]": 179, + "[unused175]": 180, + "[unused176]": 181, + "[unused177]": 182, + "[unused178]": 183, + "[unused179]": 184, + "[unused180]": 185, + "[unused181]": 186, + "[unused182]": 187, + "[unused183]": 188, + "[unused184]": 189, + "[unused185]": 190, + "[unused186]": 191, + "[unused187]": 192, + "[unused188]": 193, + "[unused189]": 194, + "[unused190]": 195, + "[unused191]": 196, + "[unused192]": 197, + "[unused193]": 198, + "[unused194]": 199, + "[unused195]": 200, + "[unused196]": 201, + "[unused197]": 202, + "[unused198]": 203, + "[unused199]": 204, + "[unused200]": 205, + "[unused201]": 206, + "[unused202]": 207, + "[unused203]": 208, + "[unused204]": 209, + "[unused205]": 210, + "[unused206]": 211, + "[unused207]": 212, + "[unused208]": 213, + "[unused209]": 214, + "[unused210]": 215, + "[unused211]": 216, + "[unused212]": 217, + "[unused213]": 218, + "[unused214]": 219, + "[unused215]": 220, + "[unused216]": 221, + "[unused217]": 222, + "[unused218]": 223, + "[unused219]": 224, + "[unused220]": 225, + "[unused221]": 226, + "[unused222]": 227, + "[unused223]": 228, + "[unused224]": 229, + "[unused225]": 230, + "[unused226]": 231, + "[unused227]": 232, + "[unused228]": 233, + "[unused229]": 234, + "[unused230]": 235, + "[unused231]": 236, + "[unused232]": 237, + "[unused233]": 238, + "[unused234]": 239, + "[unused235]": 240, + "[unused236]": 241, + "[unused237]": 242, + "[unused238]": 243, + "[unused239]": 244, + "[unused240]": 245, + "[unused241]": 246, + "[unused242]": 247, + "[unused243]": 248, + "[unused244]": 249, + "[unused245]": 250, + "[unused246]": 251, + "[unused247]": 252, + "[unused248]": 253, + "[unused249]": 254, + "[unused250]": 255, + "[unused251]": 256, + "[unused252]": 257, + "[unused253]": 258, + "[unused254]": 259, + "[unused255]": 260, + "[unused256]": 261, + "[unused257]": 262, + "[unused258]": 263, + "[unused259]": 264, + "[unused260]": 265, + "[unused261]": 266, + "[unused262]": 267, + "[unused263]": 268, + "[unused264]": 269, + "[unused265]": 270, + "[unused266]": 271, + "[unused267]": 272, + "[unused268]": 273, + "[unused269]": 274, + "[unused270]": 275, + "[unused271]": 276, + "[unused272]": 277, + "[unused273]": 278, + "[unused274]": 279, + "[unused275]": 280, + "[unused276]": 281, + "[unused277]": 282, + "[unused278]": 283, + "[unused279]": 284, + "[unused280]": 285, + "[unused281]": 286, + "[unused282]": 287, + "[unused283]": 288, + "[unused284]": 289, + "[unused285]": 290, + "[unused286]": 291, + "[unused287]": 292, + "[unused288]": 293, + "[unused289]": 294, + "[unused290]": 295, + "[unused291]": 296, + "[unused292]": 297, + "[unused293]": 298, + "[unused294]": 299, + "[unused295]": 300, + "[unused296]": 301, + "[unused297]": 302, + "[unused298]": 303, + "[unused299]": 304, + "[unused300]": 305, + "[unused301]": 306, + "[unused302]": 307, + "[unused303]": 308, + "[unused304]": 309, + "[unused305]": 310, + "[unused306]": 311, + "[unused307]": 312, + "[unused308]": 313, + "[unused309]": 314, + "[unused310]": 315, + "[unused311]": 316, + "[unused312]": 317, + "[unused313]": 318, + "[unused314]": 319, + "[unused315]": 320, + "[unused316]": 321, + "[unused317]": 322, + "[unused318]": 323, + "[unused319]": 324, + "[unused320]": 325, + "[unused321]": 326, + "[unused322]": 327, + "[unused323]": 328, + "[unused324]": 329, + "[unused325]": 330, + "[unused326]": 331, + "[unused327]": 332, + "[unused328]": 333, + "[unused329]": 334, + "[unused330]": 335, + "[unused331]": 336, + "[unused332]": 337, + "[unused333]": 338, + "[unused334]": 339, + "[unused335]": 340, + "[unused336]": 341, + "[unused337]": 342, + "[unused338]": 343, + "[unused339]": 344, + "[unused340]": 345, + "[unused341]": 346, + "[unused342]": 347, + "[unused343]": 348, + "[unused344]": 349, + "[unused345]": 350, + "[unused346]": 351, + "[unused347]": 352, + "[unused348]": 353, + "[unused349]": 354, + "[unused350]": 355, + "[unused351]": 356, + "[unused352]": 357, + "[unused353]": 358, + "[unused354]": 359, + "[unused355]": 360, + "[unused356]": 361, + "[unused357]": 362, + "[unused358]": 363, + "[unused359]": 364, + "[unused360]": 365, + "[unused361]": 366, + "[unused362]": 367, + "[unused363]": 368, + "[unused364]": 369, + "[unused365]": 370, + "[unused366]": 371, + "[unused367]": 372, + "[unused368]": 373, + "[unused369]": 374, + "[unused370]": 375, + "[unused371]": 376, + "[unused372]": 377, + "[unused373]": 378, + "[unused374]": 379, + "[unused375]": 380, + "[unused376]": 381, + "[unused377]": 382, + "[unused378]": 383, + "[unused379]": 384, + "[unused380]": 385, + "[unused381]": 386, + "[unused382]": 387, + "[unused383]": 388, + "[unused384]": 389, + "[unused385]": 390, + "[unused386]": 391, + "[unused387]": 392, + "[unused388]": 393, + "[unused389]": 394, + "[unused390]": 395, + "[unused391]": 396, + "[unused392]": 397, + "[unused393]": 398, + "[unused394]": 399, + "[unused395]": 400, + "[unused396]": 401, + "[unused397]": 402, + "[unused398]": 403, + "[unused399]": 404, + "[unused400]": 405, + "[unused401]": 406, + "[unused402]": 407, + "[unused403]": 408, + "[unused404]": 409, + "[unused405]": 410, + "[unused406]": 411, + "[unused407]": 412, + "[unused408]": 413, + "[unused409]": 414, + "[unused410]": 415, + "[unused411]": 416, + "[unused412]": 417, + "[unused413]": 418, + "[unused414]": 419, + "[unused415]": 420, + "[unused416]": 421, + "[unused417]": 422, + "[unused418]": 423, + "[unused419]": 424, + "[unused420]": 425, + "[unused421]": 426, + "[unused422]": 427, + "[unused423]": 428, + "[unused424]": 429, + "[unused425]": 430, + "[unused426]": 431, + "[unused427]": 432, + "[unused428]": 433, + "[unused429]": 434, + "[unused430]": 435, + "[unused431]": 436, + "[unused432]": 437, + "[unused433]": 438, + "[unused434]": 439, + "[unused435]": 440, + "[unused436]": 441, + "[unused437]": 442, + "[unused438]": 443, + "[unused439]": 444, + "[unused440]": 445, + "[unused441]": 446, + "[unused442]": 447, + "[unused443]": 448, + "[unused444]": 449, + "[unused445]": 450, + "[unused446]": 451, + "[unused447]": 452, + "[unused448]": 453, + "[unused449]": 454, + "[unused450]": 455, + "[unused451]": 456, + "[unused452]": 457, + "[unused453]": 458, + "[unused454]": 459, + "[unused455]": 460, + "[unused456]": 461, + "[unused457]": 462, + "[unused458]": 463, + "[unused459]": 464, + "[unused460]": 465, + "[unused461]": 466, + "[unused462]": 467, + "[unused463]": 468, + "[unused464]": 469, + "[unused465]": 470, + "[unused466]": 471, + "[unused467]": 472, + "[unused468]": 473, + "[unused469]": 474, + "[unused470]": 475, + "[unused471]": 476, + "[unused472]": 477, + "[unused473]": 478, + "[unused474]": 479, + "[unused475]": 480, + "[unused476]": 481, + "[unused477]": 482, + "[unused478]": 483, + "[unused479]": 484, + "[unused480]": 485, + "[unused481]": 486, + "[unused482]": 487, + "[unused483]": 488, + "[unused484]": 489, + "[unused485]": 490, + "[unused486]": 491, + "[unused487]": 492, + "[unused488]": 493, + "[unused489]": 494, + "[unused490]": 495, + "[unused491]": 496, + "[unused492]": 497, + "[unused493]": 498, + "[unused494]": 499, + "[unused495]": 500, + "[unused496]": 501, + "[unused497]": 502, + "[unused498]": 503, + "[unused499]": 504, + "[unused500]": 505, + "[unused501]": 506, + "[unused502]": 507, + "[unused503]": 508, + "[unused504]": 509, + "[unused505]": 510, + "[unused506]": 511, + "[unused507]": 512, + "[unused508]": 513, + "[unused509]": 514, + "[unused510]": 515, + "[unused511]": 516, + "[unused512]": 517, + "[unused513]": 518, + "[unused514]": 519, + "[unused515]": 520, + "[unused516]": 521, + "[unused517]": 522, + "[unused518]": 523, + "[unused519]": 524, + "[unused520]": 525, + "[unused521]": 526, + "[unused522]": 527, + "[unused523]": 528, + "[unused524]": 529, + "[unused525]": 530, + "[unused526]": 531, + "[unused527]": 532, + "[unused528]": 533, + "[unused529]": 534, + "[unused530]": 535, + "[unused531]": 536, + "[unused532]": 537, + "[unused533]": 538, + "[unused534]": 539, + "[unused535]": 540, + "[unused536]": 541, + "[unused537]": 542, + "[unused538]": 543, + "[unused539]": 544, + "[unused540]": 545, + "[unused541]": 546, + "[unused542]": 547, + "[unused543]": 548, + "[unused544]": 549, + "[unused545]": 550, + "[unused546]": 551, + "[unused547]": 552, + "[unused548]": 553, + "[unused549]": 554, + "[unused550]": 555, + "[unused551]": 556, + "[unused552]": 557, + "[unused553]": 558, + "[unused554]": 559, + "[unused555]": 560, + "[unused556]": 561, + "[unused557]": 562, + "[unused558]": 563, + "[unused559]": 564, + "[unused560]": 565, + "[unused561]": 566, + "[unused562]": 567, + "[unused563]": 568, + "[unused564]": 569, + "[unused565]": 570, + "[unused566]": 571, + "[unused567]": 572, + "[unused568]": 573, + "[unused569]": 574, + "[unused570]": 575, + "[unused571]": 576, + "[unused572]": 577, + "[unused573]": 578, + "[unused574]": 579, + "[unused575]": 580, + "[unused576]": 581, + "[unused577]": 582, + "[unused578]": 583, + "[unused579]": 584, + "[unused580]": 585, + "[unused581]": 586, + "[unused582]": 587, + "[unused583]": 588, + "[unused584]": 589, + "[unused585]": 590, + "[unused586]": 591, + "[unused587]": 592, + "[unused588]": 593, + "[unused589]": 594, + "[unused590]": 595, + "[unused591]": 596, + "[unused592]": 597, + "[unused593]": 598, + "[unused594]": 599, + "[unused595]": 600, + "[unused596]": 601, + "[unused597]": 602, + "[unused598]": 603, + "[unused599]": 604, + "[unused600]": 605, + "[unused601]": 606, + "[unused602]": 607, + "[unused603]": 608, + "[unused604]": 609, + "[unused605]": 610, + "[unused606]": 611, + "[unused607]": 612, + "[unused608]": 613, + "[unused609]": 614, + "[unused610]": 615, + "[unused611]": 616, + "[unused612]": 617, + "[unused613]": 618, + "[unused614]": 619, + "[unused615]": 620, + "[unused616]": 621, + "[unused617]": 622, + "[unused618]": 623, + "[unused619]": 624, + "[unused620]": 625, + "[unused621]": 626, + "[unused622]": 627, + "[unused623]": 628, + "[unused624]": 629, + "[unused625]": 630, + "[unused626]": 631, + "[unused627]": 632, + "[unused628]": 633, + "[unused629]": 634, + "[unused630]": 635, + "[unused631]": 636, + "[unused632]": 637, + "[unused633]": 638, + "[unused634]": 639, + "[unused635]": 640, + "[unused636]": 641, + "[unused637]": 642, + "[unused638]": 643, + "[unused639]": 644, + "[unused640]": 645, + "[unused641]": 646, + "[unused642]": 647, + "[unused643]": 648, + "[unused644]": 649, + "[unused645]": 650, + "[unused646]": 651, + "[unused647]": 652, + "[unused648]": 653, + "[unused649]": 654, + "[unused650]": 655, + "[unused651]": 656, + "[unused652]": 657, + "[unused653]": 658, + "[unused654]": 659, + "[unused655]": 660, + "[unused656]": 661, + "[unused657]": 662, + "[unused658]": 663, + "[unused659]": 664, + "[unused660]": 665, + "[unused661]": 666, + "[unused662]": 667, + "[unused663]": 668, + "[unused664]": 669, + "[unused665]": 670, + "[unused666]": 671, + "[unused667]": 672, + "[unused668]": 673, + "[unused669]": 674, + "[unused670]": 675, + "[unused671]": 676, + "[unused672]": 677, + "[unused673]": 678, + "[unused674]": 679, + "[unused675]": 680, + "[unused676]": 681, + "[unused677]": 682, + "[unused678]": 683, + "[unused679]": 684, + "[unused680]": 685, + "[unused681]": 686, + "[unused682]": 687, + "[unused683]": 688, + "[unused684]": 689, + "[unused685]": 690, + "[unused686]": 691, + "[unused687]": 692, + "[unused688]": 693, + "[unused689]": 694, + "[unused690]": 695, + "[unused691]": 696, + "[unused692]": 697, + "[unused693]": 698, + "[unused694]": 699, + "[unused695]": 700, + "[unused696]": 701, + "[unused697]": 702, + "[unused698]": 703, + "[unused699]": 704, + "[unused700]": 705, + "[unused701]": 706, + "[unused702]": 707, + "[unused703]": 708, + "[unused704]": 709, + "[unused705]": 710, + "[unused706]": 711, + "[unused707]": 712, + "[unused708]": 713, + "[unused709]": 714, + "[unused710]": 715, + "[unused711]": 716, + "[unused712]": 717, + "[unused713]": 718, + "[unused714]": 719, + "[unused715]": 720, + "[unused716]": 721, + "[unused717]": 722, + "[unused718]": 723, + "[unused719]": 724, + "[unused720]": 725, + "[unused721]": 726, + "[unused722]": 727, + "[unused723]": 728, + "[unused724]": 729, + "[unused725]": 730, + "[unused726]": 731, + "[unused727]": 732, + "[unused728]": 733, + "[unused729]": 734, + "[unused730]": 735, + "[unused731]": 736, + "[unused732]": 737, + "[unused733]": 738, + "[unused734]": 739, + "[unused735]": 740, + "[unused736]": 741, + "[unused737]": 742, + "[unused738]": 743, + "[unused739]": 744, + "[unused740]": 745, + "[unused741]": 746, + "[unused742]": 747, + "[unused743]": 748, + "[unused744]": 749, + "[unused745]": 750, + "[unused746]": 751, + "[unused747]": 752, + "[unused748]": 753, + "[unused749]": 754, + "[unused750]": 755, + "[unused751]": 756, + "[unused752]": 757, + "[unused753]": 758, + "[unused754]": 759, + "[unused755]": 760, + "[unused756]": 761, + "[unused757]": 762, + "[unused758]": 763, + "[unused759]": 764, + "[unused760]": 765, + "[unused761]": 766, + "[unused762]": 767, + "[unused763]": 768, + "[unused764]": 769, + "[unused765]": 770, + "[unused766]": 771, + "[unused767]": 772, + "[unused768]": 773, + "[unused769]": 774, + "[unused770]": 775, + "[unused771]": 776, + "[unused772]": 777, + "[unused773]": 778, + "[unused774]": 779, + "[unused775]": 780, + "[unused776]": 781, + "[unused777]": 782, + "[unused778]": 783, + "[unused779]": 784, + "[unused780]": 785, + "[unused781]": 786, + "[unused782]": 787, + "[unused783]": 788, + "[unused784]": 789, + "[unused785]": 790, + "[unused786]": 791, + "[unused787]": 792, + "[unused788]": 793, + "[unused789]": 794, + "[unused790]": 795, + "[unused791]": 796, + "[unused792]": 797, + "[unused793]": 798, + "[unused794]": 799, + "[unused795]": 800, + "[unused796]": 801, + "[unused797]": 802, + "[unused798]": 803, + "[unused799]": 804, + "[unused800]": 805, + "[unused801]": 806, + "[unused802]": 807, + "[unused803]": 808, + "[unused804]": 809, + "[unused805]": 810, + "[unused806]": 811, + "[unused807]": 812, + "[unused808]": 813, + "[unused809]": 814, + "[unused810]": 815, + "[unused811]": 816, + "[unused812]": 817, + "[unused813]": 818, + "[unused814]": 819, + "[unused815]": 820, + "[unused816]": 821, + "[unused817]": 822, + "[unused818]": 823, + "[unused819]": 824, + "[unused820]": 825, + "[unused821]": 826, + "[unused822]": 827, + "[unused823]": 828, + "[unused824]": 829, + "[unused825]": 830, + "[unused826]": 831, + "[unused827]": 832, + "[unused828]": 833, + "[unused829]": 834, + "[unused830]": 835, + "[unused831]": 836, + "[unused832]": 837, + "[unused833]": 838, + "[unused834]": 839, + "[unused835]": 840, + "[unused836]": 841, + "[unused837]": 842, + "[unused838]": 843, + "[unused839]": 844, + "[unused840]": 845, + "[unused841]": 846, + "[unused842]": 847, + "[unused843]": 848, + "[unused844]": 849, + "[unused845]": 850, + "[unused846]": 851, + "[unused847]": 852, + "[unused848]": 853, + "[unused849]": 854, + "[unused850]": 855, + "[unused851]": 856, + "[unused852]": 857, + "[unused853]": 858, + "[unused854]": 859, + "[unused855]": 860, + "[unused856]": 861, + "[unused857]": 862, + "[unused858]": 863, + "[unused859]": 864, + "[unused860]": 865, + "[unused861]": 866, + "[unused862]": 867, + "[unused863]": 868, + "[unused864]": 869, + "[unused865]": 870, + "[unused866]": 871, + "[unused867]": 872, + "[unused868]": 873, + "[unused869]": 874, + "[unused870]": 875, + "[unused871]": 876, + "[unused872]": 877, + "[unused873]": 878, + "[unused874]": 879, + "[unused875]": 880, + "[unused876]": 881, + "[unused877]": 882, + "[unused878]": 883, + "[unused879]": 884, + "[unused880]": 885, + "[unused881]": 886, + "[unused882]": 887, + "[unused883]": 888, + "[unused884]": 889, + "[unused885]": 890, + "[unused886]": 891, + "[unused887]": 892, + "[unused888]": 893, + "[unused889]": 894, + "[unused890]": 895, + "[unused891]": 896, + "[unused892]": 897, + "[unused893]": 898, + "[unused894]": 899, + "[unused895]": 900, + "[unused896]": 901, + "[unused897]": 902, + "[unused898]": 903, + "[unused899]": 904, + "[unused900]": 905, + "[unused901]": 906, + "[unused902]": 907, + "[unused903]": 908, + "[unused904]": 909, + "[unused905]": 910, + "[unused906]": 911, + "[unused907]": 912, + "[unused908]": 913, + "[unused909]": 914, + "[unused910]": 915, + "[unused911]": 916, + "[unused912]": 917, + "[unused913]": 918, + "[unused914]": 919, + "[unused915]": 920, + "[unused916]": 921, + "[unused917]": 922, + "[unused918]": 923, + "[unused919]": 924, + "[unused920]": 925, + "[unused921]": 926, + "[unused922]": 927, + "[unused923]": 928, + "[unused924]": 929, + "[unused925]": 930, + "[unused926]": 931, + "[unused927]": 932, + "[unused928]": 933, + "[unused929]": 934, + "[unused930]": 935, + "[unused931]": 936, + "[unused932]": 937, + "[unused933]": 938, + "[unused934]": 939, + "[unused935]": 940, + "[unused936]": 941, + "[unused937]": 942, + "[unused938]": 943, + "[unused939]": 944, + "[unused940]": 945, + "[unused941]": 946, + "[unused942]": 947, + "[unused943]": 948, + "[unused944]": 949, + "[unused945]": 950, + "[unused946]": 951, + "[unused947]": 952, + "[unused948]": 953, + "[unused949]": 954, + "[unused950]": 955, + "[unused951]": 956, + "[unused952]": 957, + "[unused953]": 958, + "[unused954]": 959, + "[unused955]": 960, + "[unused956]": 961, + "[unused957]": 962, + "[unused958]": 963, + "[unused959]": 964, + "[unused960]": 965, + "[unused961]": 966, + "[unused962]": 967, + "[unused963]": 968, + "[unused964]": 969, + "[unused965]": 970, + "[unused966]": 971, + "[unused967]": 972, + "[unused968]": 973, + "[unused969]": 974, + "[unused970]": 975, + "[unused971]": 976, + "[unused972]": 977, + "[unused973]": 978, + "[unused974]": 979, + "[unused975]": 980, + "[unused976]": 981, + "[unused977]": 982, + "[unused978]": 983, + "[unused979]": 984, + "[unused980]": 985, + "[unused981]": 986, + "[unused982]": 987, + "[unused983]": 988, + "[unused984]": 989, + "[unused985]": 990, + "[unused986]": 991, + "[unused987]": 992, + "[unused988]": 993, + "[unused989]": 994, + "[unused990]": 995, + "[unused991]": 996, + "[unused992]": 997, + "[unused993]": 998, + "!": 999, + "\"": 1000, + "#": 1001, + "$": 1002, + "%": 1003, + "&": 1004, + "'": 1005, + "(": 1006, + ")": 1007, + "*": 1008, + "+": 1009, + ",": 1010, + "-": 1011, + ".": 1012, + "/": 1013, + "0": 1014, + "1": 1015, + "2": 1016, + "3": 1017, + "4": 1018, + "5": 1019, + "6": 1020, + "7": 1021, + "8": 1022, + "9": 1023, + ":": 1024, + ";": 1025, + "<": 1026, + "=": 1027, + ">": 1028, + "?": 1029, + "@": 1030, + "[": 1031, + "\\": 1032, + "]": 1033, + "^": 1034, + "_": 1035, + "`": 1036, + "a": 1037, + "b": 1038, + "c": 1039, + "d": 1040, + "e": 1041, + "f": 1042, + "g": 1043, + "h": 1044, + "i": 1045, + "j": 1046, + "k": 1047, + "l": 1048, + "m": 1049, + "n": 1050, + "o": 1051, + "p": 1052, + "q": 1053, + "r": 1054, + "s": 1055, + "t": 1056, + "u": 1057, + "v": 1058, + "w": 1059, + "x": 1060, + "y": 1061, + "z": 1062, + "{": 1063, + "|": 1064, + "}": 1065, + "~": 1066, + "¡": 1067, + "¢": 1068, + "£": 1069, + "¤": 1070, + "¥": 1071, + "¦": 1072, + "§": 1073, + "¨": 1074, + "©": 1075, + "ª": 1076, + "«": 1077, + "¬": 1078, + "®": 1079, + "°": 1080, + "±": 1081, + "²": 1082, + "³": 1083, + "´": 1084, + "µ": 1085, + "¶": 1086, + "·": 1087, + "¹": 1088, + "º": 1089, + "»": 1090, + "¼": 1091, + "½": 1092, + "¾": 1093, + "¿": 1094, + "×": 1095, + "ß": 1096, + "æ": 1097, + "ð": 1098, + "÷": 1099, + "ø": 1100, + "þ": 1101, + "đ": 1102, + "ħ": 1103, + "ı": 1104, + "ł": 1105, + "ŋ": 1106, + "œ": 1107, + "ƒ": 1108, + "ɐ": 1109, + "ɑ": 1110, + "ɒ": 1111, + "ɔ": 1112, + "ɕ": 1113, + "ə": 1114, + "ɛ": 1115, + "ɡ": 1116, + "ɣ": 1117, + "ɨ": 1118, + "ɪ": 1119, + "ɫ": 1120, + "ɬ": 1121, + "ɯ": 1122, + "ɲ": 1123, + "ɴ": 1124, + "ɹ": 1125, + "ɾ": 1126, + "ʀ": 1127, + "ʁ": 1128, + "ʂ": 1129, + "ʃ": 1130, + "ʉ": 1131, + "ʊ": 1132, + "ʋ": 1133, + "ʌ": 1134, + "ʎ": 1135, + "ʐ": 1136, + "ʑ": 1137, + "ʒ": 1138, + "ʔ": 1139, + "ʰ": 1140, + "ʲ": 1141, + "ʳ": 1142, + "ʷ": 1143, + "ʸ": 1144, + "ʻ": 1145, + "ʼ": 1146, + "ʾ": 1147, + "ʿ": 1148, + "ˈ": 1149, + "ː": 1150, + "ˡ": 1151, + "ˢ": 1152, + "ˣ": 1153, + "ˤ": 1154, + "α": 1155, + "β": 1156, + "γ": 1157, + "δ": 1158, + "ε": 1159, + "ζ": 1160, + "η": 1161, + "θ": 1162, + "ι": 1163, + "κ": 1164, + "λ": 1165, + "μ": 1166, + "ν": 1167, + "ξ": 1168, + "ο": 1169, + "π": 1170, + "ρ": 1171, + "ς": 1172, + "σ": 1173, + "τ": 1174, + "υ": 1175, + "φ": 1176, + "χ": 1177, + "ψ": 1178, + "ω": 1179, + "а": 1180, + "б": 1181, + "в": 1182, + "г": 1183, + "д": 1184, + "е": 1185, + "ж": 1186, + "з": 1187, + "и": 1188, + "к": 1189, + "л": 1190, + "м": 1191, + "н": 1192, + "о": 1193, + "п": 1194, + "р": 1195, + "с": 1196, + "т": 1197, + "у": 1198, + "ф": 1199, + "х": 1200, + "ц": 1201, + "ч": 1202, + "ш": 1203, + "щ": 1204, + "ъ": 1205, + "ы": 1206, + "ь": 1207, + "э": 1208, + "ю": 1209, + "я": 1210, + "ђ": 1211, + "є": 1212, + "і": 1213, + "ј": 1214, + "љ": 1215, + "њ": 1216, + "ћ": 1217, + "ӏ": 1218, + "ա": 1219, + "բ": 1220, + "գ": 1221, + "դ": 1222, + "ե": 1223, + "թ": 1224, + "ի": 1225, + "լ": 1226, + "կ": 1227, + "հ": 1228, + "մ": 1229, + "յ": 1230, + "ն": 1231, + "ո": 1232, + "պ": 1233, + "ս": 1234, + "վ": 1235, + "տ": 1236, + "ր": 1237, + "ւ": 1238, + "ք": 1239, + "־": 1240, + "א": 1241, + "ב": 1242, + "ג": 1243, + "ד": 1244, + "ה": 1245, + "ו": 1246, + "ז": 1247, + "ח": 1248, + "ט": 1249, + "י": 1250, + "ך": 1251, + "כ": 1252, + "ל": 1253, + "ם": 1254, + "מ": 1255, + "ן": 1256, + "נ": 1257, + "ס": 1258, + "ע": 1259, + "ף": 1260, + "פ": 1261, + "ץ": 1262, + "צ": 1263, + "ק": 1264, + "ר": 1265, + "ש": 1266, + "ת": 1267, + "،": 1268, + "ء": 1269, + "ا": 1270, + "ب": 1271, + "ة": 1272, + "ت": 1273, + "ث": 1274, + "ج": 1275, + "ح": 1276, + "خ": 1277, + "د": 1278, + "ذ": 1279, + "ر": 1280, + "ز": 1281, + "س": 1282, + "ش": 1283, + "ص": 1284, + "ض": 1285, + "ط": 1286, + "ظ": 1287, + "ع": 1288, + "غ": 1289, + "ـ": 1290, + "ف": 1291, + "ق": 1292, + "ك": 1293, + "ل": 1294, + "م": 1295, + "ن": 1296, + "ه": 1297, + "و": 1298, + "ى": 1299, + "ي": 1300, + "ٹ": 1301, + "پ": 1302, + "چ": 1303, + "ک": 1304, + "گ": 1305, + "ں": 1306, + "ھ": 1307, + "ہ": 1308, + "ی": 1309, + "ے": 1310, + "अ": 1311, + "आ": 1312, + "उ": 1313, + "ए": 1314, + "क": 1315, + "ख": 1316, + "ग": 1317, + "च": 1318, + "ज": 1319, + "ट": 1320, + "ड": 1321, + "ण": 1322, + "त": 1323, + "थ": 1324, + "द": 1325, + "ध": 1326, + "न": 1327, + "प": 1328, + "ब": 1329, + "भ": 1330, + "म": 1331, + "य": 1332, + "र": 1333, + "ल": 1334, + "व": 1335, + "श": 1336, + "ष": 1337, + "स": 1338, + "ह": 1339, + "ा": 1340, + "ि": 1341, + "ी": 1342, + "ो": 1343, + "।": 1344, + "॥": 1345, + "ং": 1346, + "অ": 1347, + "আ": 1348, + "ই": 1349, + "উ": 1350, + "এ": 1351, + "ও": 1352, + "ক": 1353, + "খ": 1354, + "গ": 1355, + "চ": 1356, + "ছ": 1357, + "জ": 1358, + "ট": 1359, + "ড": 1360, + "ণ": 1361, + "ত": 1362, + "থ": 1363, + "দ": 1364, + "ধ": 1365, + "ন": 1366, + "প": 1367, + "ব": 1368, + "ভ": 1369, + "ম": 1370, + "য": 1371, + "র": 1372, + "ল": 1373, + "শ": 1374, + "ষ": 1375, + "স": 1376, + "হ": 1377, + "া": 1378, + "ি": 1379, + "ী": 1380, + "ে": 1381, + "க": 1382, + "ச": 1383, + "ட": 1384, + "த": 1385, + "ந": 1386, + "ன": 1387, + "ப": 1388, + "ம": 1389, + "ய": 1390, + "ர": 1391, + "ல": 1392, + "ள": 1393, + "வ": 1394, + "ா": 1395, + "ி": 1396, + "ு": 1397, + "ே": 1398, + "ை": 1399, + "ನ": 1400, + "ರ": 1401, + "ಾ": 1402, + "ක": 1403, + "ය": 1404, + "ර": 1405, + "ල": 1406, + "ව": 1407, + "ා": 1408, + "ก": 1409, + "ง": 1410, + "ต": 1411, + "ท": 1412, + "น": 1413, + "พ": 1414, + "ม": 1415, + "ย": 1416, + "ร": 1417, + "ล": 1418, + "ว": 1419, + "ส": 1420, + "อ": 1421, + "า": 1422, + "เ": 1423, + "་": 1424, + "།": 1425, + "ག": 1426, + "ང": 1427, + "ད": 1428, + "ན": 1429, + "པ": 1430, + "བ": 1431, + "མ": 1432, + "འ": 1433, + "ར": 1434, + "ལ": 1435, + "ས": 1436, + "မ": 1437, + "ა": 1438, + "ბ": 1439, + "გ": 1440, + "დ": 1441, + "ე": 1442, + "ვ": 1443, + "თ": 1444, + "ი": 1445, + "კ": 1446, + "ლ": 1447, + "მ": 1448, + "ნ": 1449, + "ო": 1450, + "რ": 1451, + "ს": 1452, + "ტ": 1453, + "უ": 1454, + "ᄀ": 1455, + "ᄂ": 1456, + "ᄃ": 1457, + "ᄅ": 1458, + "ᄆ": 1459, + "ᄇ": 1460, + "ᄉ": 1461, + "ᄊ": 1462, + "ᄋ": 1463, + "ᄌ": 1464, + "ᄎ": 1465, + "ᄏ": 1466, + "ᄐ": 1467, + "ᄑ": 1468, + "ᄒ": 1469, + "ᅡ": 1470, + "ᅢ": 1471, + "ᅥ": 1472, + "ᅦ": 1473, + "ᅧ": 1474, + "ᅩ": 1475, + "ᅪ": 1476, + "ᅭ": 1477, + "ᅮ": 1478, + "ᅯ": 1479, + "ᅲ": 1480, + "ᅳ": 1481, + "ᅴ": 1482, + "ᅵ": 1483, + "ᆨ": 1484, + "ᆫ": 1485, + "ᆯ": 1486, + "ᆷ": 1487, + "ᆸ": 1488, + "ᆼ": 1489, + "ᴬ": 1490, + "ᴮ": 1491, + "ᴰ": 1492, + "ᴵ": 1493, + "ᴺ": 1494, + "ᵀ": 1495, + "ᵃ": 1496, + "ᵇ": 1497, + "ᵈ": 1498, + "ᵉ": 1499, + "ᵍ": 1500, + "ᵏ": 1501, + "ᵐ": 1502, + "ᵒ": 1503, + "ᵖ": 1504, + "ᵗ": 1505, + "ᵘ": 1506, + "ᵢ": 1507, + "ᵣ": 1508, + "ᵤ": 1509, + "ᵥ": 1510, + "ᶜ": 1511, + "ᶠ": 1512, + "‐": 1513, + "‑": 1514, + "‒": 1515, + "–": 1516, + "—": 1517, + "―": 1518, + "‖": 1519, + "‘": 1520, + "’": 1521, + "‚": 1522, + "“": 1523, + "”": 1524, + "„": 1525, + "†": 1526, + "‡": 1527, + "•": 1528, + "…": 1529, + "‰": 1530, + "′": 1531, + "″": 1532, + "›": 1533, + "‿": 1534, + "⁄": 1535, + "⁰": 1536, + "ⁱ": 1537, + "⁴": 1538, + "⁵": 1539, + "⁶": 1540, + "⁷": 1541, + "⁸": 1542, + "⁹": 1543, + "⁺": 1544, + "⁻": 1545, + "ⁿ": 1546, + "₀": 1547, + "₁": 1548, + "₂": 1549, + "₃": 1550, + "₄": 1551, + "₅": 1552, + "₆": 1553, + "₇": 1554, + "₈": 1555, + "₉": 1556, + "₊": 1557, + "₍": 1558, + "₎": 1559, + "ₐ": 1560, + "ₑ": 1561, + "ₒ": 1562, + "ₓ": 1563, + "ₕ": 1564, + "ₖ": 1565, + "ₗ": 1566, + "ₘ": 1567, + "ₙ": 1568, + "ₚ": 1569, + "ₛ": 1570, + "ₜ": 1571, + "₤": 1572, + "₩": 1573, + "€": 1574, + "₱": 1575, + "₹": 1576, + "ℓ": 1577, + "№": 1578, + "ℝ": 1579, + "™": 1580, + "⅓": 1581, + "⅔": 1582, + "←": 1583, + "↑": 1584, + "→": 1585, + "↓": 1586, + "↔": 1587, + "↦": 1588, + "⇄": 1589, + "⇌": 1590, + "⇒": 1591, + "∂": 1592, + "∅": 1593, + "∆": 1594, + "∇": 1595, + "∈": 1596, + "−": 1597, + "∗": 1598, + "∘": 1599, + "√": 1600, + "∞": 1601, + "∧": 1602, + "∨": 1603, + "∩": 1604, + "∪": 1605, + "≈": 1606, + "≡": 1607, + "≤": 1608, + "≥": 1609, + "⊂": 1610, + "⊆": 1611, + "⊕": 1612, + "⊗": 1613, + "⋅": 1614, + "─": 1615, + "│": 1616, + "■": 1617, + "▪": 1618, + "●": 1619, + "★": 1620, + "☆": 1621, + "☉": 1622, + "♠": 1623, + "♣": 1624, + "♥": 1625, + "♦": 1626, + "♭": 1627, + "♯": 1628, + "⟨": 1629, + "⟩": 1630, + "ⱼ": 1631, + "⺩": 1632, + "⺼": 1633, + "⽥": 1634, + "、": 1635, + "。": 1636, + "〈": 1637, + "〉": 1638, + "《": 1639, + "》": 1640, + "「": 1641, + "」": 1642, + "『": 1643, + "』": 1644, + "〜": 1645, + "あ": 1646, + "い": 1647, + "う": 1648, + "え": 1649, + "お": 1650, + "か": 1651, + "き": 1652, + "く": 1653, + "け": 1654, + "こ": 1655, + "さ": 1656, + "し": 1657, + "す": 1658, + "せ": 1659, + "そ": 1660, + "た": 1661, + "ち": 1662, + "っ": 1663, + "つ": 1664, + "て": 1665, + "と": 1666, + "な": 1667, + "に": 1668, + "ぬ": 1669, + "ね": 1670, + "の": 1671, + "は": 1672, + "ひ": 1673, + "ふ": 1674, + "へ": 1675, + "ほ": 1676, + "ま": 1677, + "み": 1678, + "む": 1679, + "め": 1680, + "も": 1681, + "や": 1682, + "ゆ": 1683, + "よ": 1684, + "ら": 1685, + "り": 1686, + "る": 1687, + "れ": 1688, + "ろ": 1689, + "を": 1690, + "ん": 1691, + "ァ": 1692, + "ア": 1693, + "ィ": 1694, + "イ": 1695, + "ウ": 1696, + "ェ": 1697, + "エ": 1698, + "オ": 1699, + "カ": 1700, + "キ": 1701, + "ク": 1702, + "ケ": 1703, + "コ": 1704, + "サ": 1705, + "シ": 1706, + "ス": 1707, + "セ": 1708, + "タ": 1709, + "チ": 1710, + "ッ": 1711, + "ツ": 1712, + "テ": 1713, + "ト": 1714, + "ナ": 1715, + "ニ": 1716, + "ノ": 1717, + "ハ": 1718, + "ヒ": 1719, + "フ": 1720, + "ヘ": 1721, + "ホ": 1722, + "マ": 1723, + "ミ": 1724, + "ム": 1725, + "メ": 1726, + "モ": 1727, + "ャ": 1728, + "ュ": 1729, + "ョ": 1730, + "ラ": 1731, + "リ": 1732, + "ル": 1733, + "レ": 1734, + "ロ": 1735, + "ワ": 1736, + "ン": 1737, + "・": 1738, + "ー": 1739, + "一": 1740, + "三": 1741, + "上": 1742, + "下": 1743, + "不": 1744, + "世": 1745, + "中": 1746, + "主": 1747, + "久": 1748, + "之": 1749, + "也": 1750, + "事": 1751, + "二": 1752, + "五": 1753, + "井": 1754, + "京": 1755, + "人": 1756, + "亻": 1757, + "仁": 1758, + "介": 1759, + "代": 1760, + "仮": 1761, + "伊": 1762, + "会": 1763, + "佐": 1764, + "侍": 1765, + "保": 1766, + "信": 1767, + "健": 1768, + "元": 1769, + "光": 1770, + "八": 1771, + "公": 1772, + "内": 1773, + "出": 1774, + "分": 1775, + "前": 1776, + "劉": 1777, + "力": 1778, + "加": 1779, + "勝": 1780, + "北": 1781, + "区": 1782, + "十": 1783, + "千": 1784, + "南": 1785, + "博": 1786, + "原": 1787, + "口": 1788, + "古": 1789, + "史": 1790, + "司": 1791, + "合": 1792, + "吉": 1793, + "同": 1794, + "名": 1795, + "和": 1796, + "囗": 1797, + "四": 1798, + "国": 1799, + "國": 1800, + "土": 1801, + "地": 1802, + "坂": 1803, + "城": 1804, + "堂": 1805, + "場": 1806, + "士": 1807, + "夏": 1808, + "外": 1809, + "大": 1810, + "天": 1811, + "太": 1812, + "夫": 1813, + "奈": 1814, + "女": 1815, + "子": 1816, + "学": 1817, + "宀": 1818, + "宇": 1819, + "安": 1820, + "宗": 1821, + "定": 1822, + "宣": 1823, + "宮": 1824, + "家": 1825, + "宿": 1826, + "寺": 1827, + "將": 1828, + "小": 1829, + "尚": 1830, + "山": 1831, + "岡": 1832, + "島": 1833, + "崎": 1834, + "川": 1835, + "州": 1836, + "巿": 1837, + "帝": 1838, + "平": 1839, + "年": 1840, + "幸": 1841, + "广": 1842, + "弘": 1843, + "張": 1844, + "彳": 1845, + "後": 1846, + "御": 1847, + "德": 1848, + "心": 1849, + "忄": 1850, + "志": 1851, + "忠": 1852, + "愛": 1853, + "成": 1854, + "我": 1855, + "戦": 1856, + "戸": 1857, + "手": 1858, + "扌": 1859, + "政": 1860, + "文": 1861, + "新": 1862, + "方": 1863, + "日": 1864, + "明": 1865, + "星": 1866, + "春": 1867, + "昭": 1868, + "智": 1869, + "曲": 1870, + "書": 1871, + "月": 1872, + "有": 1873, + "朝": 1874, + "木": 1875, + "本": 1876, + "李": 1877, + "村": 1878, + "東": 1879, + "松": 1880, + "林": 1881, + "森": 1882, + "楊": 1883, + "樹": 1884, + "橋": 1885, + "歌": 1886, + "止": 1887, + "正": 1888, + "武": 1889, + "比": 1890, + "氏": 1891, + "民": 1892, + "水": 1893, + "氵": 1894, + "氷": 1895, + "永": 1896, + "江": 1897, + "沢": 1898, + "河": 1899, + "治": 1900, + "法": 1901, + "海": 1902, + "清": 1903, + "漢": 1904, + "瀬": 1905, + "火": 1906, + "版": 1907, + "犬": 1908, + "王": 1909, + "生": 1910, + "田": 1911, + "男": 1912, + "疒": 1913, + "発": 1914, + "白": 1915, + "的": 1916, + "皇": 1917, + "目": 1918, + "相": 1919, + "省": 1920, + "真": 1921, + "石": 1922, + "示": 1923, + "社": 1924, + "神": 1925, + "福": 1926, + "禾": 1927, + "秀": 1928, + "秋": 1929, + "空": 1930, + "立": 1931, + "章": 1932, + "竹": 1933, + "糹": 1934, + "美": 1935, + "義": 1936, + "耳": 1937, + "良": 1938, + "艹": 1939, + "花": 1940, + "英": 1941, + "華": 1942, + "葉": 1943, + "藤": 1944, + "行": 1945, + "街": 1946, + "西": 1947, + "見": 1948, + "訁": 1949, + "語": 1950, + "谷": 1951, + "貝": 1952, + "貴": 1953, + "車": 1954, + "軍": 1955, + "辶": 1956, + "道": 1957, + "郎": 1958, + "郡": 1959, + "部": 1960, + "都": 1961, + "里": 1962, + "野": 1963, + "金": 1964, + "鈴": 1965, + "镇": 1966, + "長": 1967, + "門": 1968, + "間": 1969, + "阝": 1970, + "阿": 1971, + "陳": 1972, + "陽": 1973, + "雄": 1974, + "青": 1975, + "面": 1976, + "風": 1977, + "食": 1978, + "香": 1979, + "馬": 1980, + "高": 1981, + "龍": 1982, + "龸": 1983, + "fi": 1984, + "fl": 1985, + "!": 1986, + "(": 1987, + ")": 1988, + ",": 1989, + "-": 1990, + ".": 1991, + "/": 1992, + ":": 1993, + "?": 1994, + "~": 1995, + "the": 1996, + "of": 1997, + "and": 1998, + "in": 1999, + "to": 2000, + "was": 2001, + "he": 2002, + "is": 2003, + "as": 2004, + "for": 2005, + "on": 2006, + "with": 2007, + "that": 2008, + "it": 2009, + "his": 2010, + "by": 2011, + "at": 2012, + "from": 2013, + "her": 2014, + "##s": 2015, + "she": 2016, + "you": 2017, + "had": 2018, + "an": 2019, + "were": 2020, + "but": 2021, + "be": 2022, + "this": 2023, + "are": 2024, + "not": 2025, + "my": 2026, + "they": 2027, + "one": 2028, + "which": 2029, + "or": 2030, + "have": 2031, + "him": 2032, + "me": 2033, + "first": 2034, + "all": 2035, + "also": 2036, + "their": 2037, + "has": 2038, + "up": 2039, + "who": 2040, + "out": 2041, + "been": 2042, + "when": 2043, + "after": 2044, + "there": 2045, + "into": 2046, + "new": 2047, + "two": 2048, + "its": 2049, + "##a": 2050, + "time": 2051, + "would": 2052, + "no": 2053, + "what": 2054, + "about": 2055, + "said": 2056, + "we": 2057, + "over": 2058, + "then": 2059, + "other": 2060, + "so": 2061, + "more": 2062, + "##e": 2063, + "can": 2064, + "if": 2065, + "like": 2066, + "back": 2067, + "them": 2068, + "only": 2069, + "some": 2070, + "could": 2071, + "##i": 2072, + "where": 2073, + "just": 2074, + "##ing": 2075, + "during": 2076, + "before": 2077, + "##n": 2078, + "do": 2079, + "##o": 2080, + "made": 2081, + "school": 2082, + "through": 2083, + "than": 2084, + "now": 2085, + "years": 2086, + "most": 2087, + "world": 2088, + "may": 2089, + "between": 2090, + "down": 2091, + "well": 2092, + "three": 2093, + "##d": 2094, + "year": 2095, + "while": 2096, + "will": 2097, + "##ed": 2098, + "##r": 2099, + "##y": 2100, + "later": 2101, + "##t": 2102, + "city": 2103, + "under": 2104, + "around": 2105, + "did": 2106, + "such": 2107, + "being": 2108, + "used": 2109, + "state": 2110, + "people": 2111, + "part": 2112, + "know": 2113, + "against": 2114, + "your": 2115, + "many": 2116, + "second": 2117, + "university": 2118, + "both": 2119, + "national": 2120, + "##er": 2121, + "these": 2122, + "don": 2123, + "known": 2124, + "off": 2125, + "way": 2126, + "until": 2127, + "re": 2128, + "how": 2129, + "even": 2130, + "get": 2131, + "head": 2132, + "...": 2133, + "didn": 2134, + "##ly": 2135, + "team": 2136, + "american": 2137, + "because": 2138, + "de": 2139, + "##l": 2140, + "born": 2141, + "united": 2142, + "film": 2143, + "since": 2144, + "still": 2145, + "long": 2146, + "work": 2147, + "south": 2148, + "us": 2149, + "became": 2150, + "any": 2151, + "high": 2152, + "again": 2153, + "day": 2154, + "family": 2155, + "see": 2156, + "right": 2157, + "man": 2158, + "eyes": 2159, + "house": 2160, + "season": 2161, + "war": 2162, + "states": 2163, + "including": 2164, + "took": 2165, + "life": 2166, + "north": 2167, + "same": 2168, + "each": 2169, + "called": 2170, + "name": 2171, + "much": 2172, + "place": 2173, + "however": 2174, + "go": 2175, + "four": 2176, + "group": 2177, + "another": 2178, + "found": 2179, + "won": 2180, + "area": 2181, + "here": 2182, + "going": 2183, + "10": 2184, + "away": 2185, + "series": 2186, + "left": 2187, + "home": 2188, + "music": 2189, + "best": 2190, + "make": 2191, + "hand": 2192, + "number": 2193, + "company": 2194, + "several": 2195, + "never": 2196, + "last": 2197, + "john": 2198, + "000": 2199, + "very": 2200, + "album": 2201, + "take": 2202, + "end": 2203, + "good": 2204, + "too": 2205, + "following": 2206, + "released": 2207, + "game": 2208, + "played": 2209, + "little": 2210, + "began": 2211, + "district": 2212, + "##m": 2213, + "old": 2214, + "want": 2215, + "those": 2216, + "side": 2217, + "held": 2218, + "own": 2219, + "early": 2220, + "county": 2221, + "ll": 2222, + "league": 2223, + "use": 2224, + "west": 2225, + "##u": 2226, + "face": 2227, + "think": 2228, + "##es": 2229, + "2010": 2230, + "government": 2231, + "##h": 2232, + "march": 2233, + "came": 2234, + "small": 2235, + "general": 2236, + "town": 2237, + "june": 2238, + "##on": 2239, + "line": 2240, + "based": 2241, + "something": 2242, + "##k": 2243, + "september": 2244, + "thought": 2245, + "looked": 2246, + "along": 2247, + "international": 2248, + "2011": 2249, + "air": 2250, + "july": 2251, + "club": 2252, + "went": 2253, + "january": 2254, + "october": 2255, + "our": 2256, + "august": 2257, + "april": 2258, + "york": 2259, + "12": 2260, + "few": 2261, + "2012": 2262, + "2008": 2263, + "east": 2264, + "show": 2265, + "member": 2266, + "college": 2267, + "2009": 2268, + "father": 2269, + "public": 2270, + "##us": 2271, + "come": 2272, + "men": 2273, + "five": 2274, + "set": 2275, + "station": 2276, + "church": 2277, + "##c": 2278, + "next": 2279, + "former": 2280, + "november": 2281, + "room": 2282, + "party": 2283, + "located": 2284, + "december": 2285, + "2013": 2286, + "age": 2287, + "got": 2288, + "2007": 2289, + "##g": 2290, + "system": 2291, + "let": 2292, + "love": 2293, + "2006": 2294, + "though": 2295, + "every": 2296, + "2014": 2297, + "look": 2298, + "song": 2299, + "water": 2300, + "century": 2301, + "without": 2302, + "body": 2303, + "black": 2304, + "night": 2305, + "within": 2306, + "great": 2307, + "women": 2308, + "single": 2309, + "ve": 2310, + "building": 2311, + "large": 2312, + "population": 2313, + "river": 2314, + "named": 2315, + "band": 2316, + "white": 2317, + "started": 2318, + "##an": 2319, + "once": 2320, + "15": 2321, + "20": 2322, + "should": 2323, + "18": 2324, + "2015": 2325, + "service": 2326, + "top": 2327, + "built": 2328, + "british": 2329, + "open": 2330, + "death": 2331, + "king": 2332, + "moved": 2333, + "local": 2334, + "times": 2335, + "children": 2336, + "february": 2337, + "book": 2338, + "why": 2339, + "11": 2340, + "door": 2341, + "need": 2342, + "president": 2343, + "order": 2344, + "final": 2345, + "road": 2346, + "wasn": 2347, + "although": 2348, + "due": 2349, + "major": 2350, + "died": 2351, + "village": 2352, + "third": 2353, + "knew": 2354, + "2016": 2355, + "asked": 2356, + "turned": 2357, + "st": 2358, + "wanted": 2359, + "say": 2360, + "##p": 2361, + "together": 2362, + "received": 2363, + "main": 2364, + "son": 2365, + "served": 2366, + "different": 2367, + "##en": 2368, + "behind": 2369, + "himself": 2370, + "felt": 2371, + "members": 2372, + "power": 2373, + "football": 2374, + "law": 2375, + "voice": 2376, + "play": 2377, + "##in": 2378, + "near": 2379, + "park": 2380, + "history": 2381, + "30": 2382, + "having": 2383, + "2005": 2384, + "16": 2385, + "##man": 2386, + "saw": 2387, + "mother": 2388, + "##al": 2389, + "army": 2390, + "point": 2391, + "front": 2392, + "help": 2393, + "english": 2394, + "street": 2395, + "art": 2396, + "late": 2397, + "hands": 2398, + "games": 2399, + "award": 2400, + "##ia": 2401, + "young": 2402, + "14": 2403, + "put": 2404, + "published": 2405, + "country": 2406, + "division": 2407, + "across": 2408, + "told": 2409, + "13": 2410, + "often": 2411, + "ever": 2412, + "french": 2413, + "london": 2414, + "center": 2415, + "six": 2416, + "red": 2417, + "2017": 2418, + "led": 2419, + "days": 2420, + "include": 2421, + "light": 2422, + "25": 2423, + "find": 2424, + "tell": 2425, + "among": 2426, + "species": 2427, + "really": 2428, + "according": 2429, + "central": 2430, + "half": 2431, + "2004": 2432, + "form": 2433, + "original": 2434, + "gave": 2435, + "office": 2436, + "making": 2437, + "enough": 2438, + "lost": 2439, + "full": 2440, + "opened": 2441, + "must": 2442, + "included": 2443, + "live": 2444, + "given": 2445, + "german": 2446, + "player": 2447, + "run": 2448, + "business": 2449, + "woman": 2450, + "community": 2451, + "cup": 2452, + "might": 2453, + "million": 2454, + "land": 2455, + "2000": 2456, + "court": 2457, + "development": 2458, + "17": 2459, + "short": 2460, + "round": 2461, + "ii": 2462, + "km": 2463, + "seen": 2464, + "class": 2465, + "story": 2466, + "always": 2467, + "become": 2468, + "sure": 2469, + "research": 2470, + "almost": 2471, + "director": 2472, + "council": 2473, + "la": 2474, + "##2": 2475, + "career": 2476, + "things": 2477, + "using": 2478, + "island": 2479, + "##z": 2480, + "couldn": 2481, + "car": 2482, + "##is": 2483, + "24": 2484, + "close": 2485, + "force": 2486, + "##1": 2487, + "better": 2488, + "free": 2489, + "support": 2490, + "control": 2491, + "field": 2492, + "students": 2493, + "2003": 2494, + "education": 2495, + "married": 2496, + "##b": 2497, + "nothing": 2498, + "worked": 2499, + "others": 2500, + "record": 2501, + "big": 2502, + "inside": 2503, + "level": 2504, + "anything": 2505, + "continued": 2506, + "give": 2507, + "james": 2508, + "##3": 2509, + "military": 2510, + "established": 2511, + "non": 2512, + "returned": 2513, + "feel": 2514, + "does": 2515, + "title": 2516, + "written": 2517, + "thing": 2518, + "feet": 2519, + "william": 2520, + "far": 2521, + "co": 2522, + "association": 2523, + "hard": 2524, + "already": 2525, + "2002": 2526, + "##ra": 2527, + "championship": 2528, + "human": 2529, + "western": 2530, + "100": 2531, + "##na": 2532, + "department": 2533, + "hall": 2534, + "role": 2535, + "various": 2536, + "production": 2537, + "21": 2538, + "19": 2539, + "heart": 2540, + "2001": 2541, + "living": 2542, + "fire": 2543, + "version": 2544, + "##ers": 2545, + "##f": 2546, + "television": 2547, + "royal": 2548, + "##4": 2549, + "produced": 2550, + "working": 2551, + "act": 2552, + "case": 2553, + "society": 2554, + "region": 2555, + "present": 2556, + "radio": 2557, + "period": 2558, + "looking": 2559, + "least": 2560, + "total": 2561, + "keep": 2562, + "england": 2563, + "wife": 2564, + "program": 2565, + "per": 2566, + "brother": 2567, + "mind": 2568, + "special": 2569, + "22": 2570, + "##le": 2571, + "am": 2572, + "works": 2573, + "soon": 2574, + "##6": 2575, + "political": 2576, + "george": 2577, + "services": 2578, + "taken": 2579, + "created": 2580, + "##7": 2581, + "further": 2582, + "able": 2583, + "reached": 2584, + "david": 2585, + "union": 2586, + "joined": 2587, + "upon": 2588, + "done": 2589, + "important": 2590, + "social": 2591, + "information": 2592, + "either": 2593, + "##ic": 2594, + "##x": 2595, + "appeared": 2596, + "position": 2597, + "ground": 2598, + "lead": 2599, + "rock": 2600, + "dark": 2601, + "election": 2602, + "23": 2603, + "board": 2604, + "france": 2605, + "hair": 2606, + "course": 2607, + "arms": 2608, + "site": 2609, + "police": 2610, + "girl": 2611, + "instead": 2612, + "real": 2613, + "sound": 2614, + "##v": 2615, + "words": 2616, + "moment": 2617, + "##te": 2618, + "someone": 2619, + "##8": 2620, + "summer": 2621, + "project": 2622, + "announced": 2623, + "san": 2624, + "less": 2625, + "wrote": 2626, + "past": 2627, + "followed": 2628, + "##5": 2629, + "blue": 2630, + "founded": 2631, + "al": 2632, + "finally": 2633, + "india": 2634, + "taking": 2635, + "records": 2636, + "america": 2637, + "##ne": 2638, + "1999": 2639, + "design": 2640, + "considered": 2641, + "northern": 2642, + "god": 2643, + "stop": 2644, + "battle": 2645, + "toward": 2646, + "european": 2647, + "outside": 2648, + "described": 2649, + "track": 2650, + "today": 2651, + "playing": 2652, + "language": 2653, + "28": 2654, + "call": 2655, + "26": 2656, + "heard": 2657, + "professional": 2658, + "low": 2659, + "australia": 2660, + "miles": 2661, + "california": 2662, + "win": 2663, + "yet": 2664, + "green": 2665, + "##ie": 2666, + "trying": 2667, + "blood": 2668, + "##ton": 2669, + "southern": 2670, + "science": 2671, + "maybe": 2672, + "everything": 2673, + "match": 2674, + "square": 2675, + "27": 2676, + "mouth": 2677, + "video": 2678, + "race": 2679, + "recorded": 2680, + "leave": 2681, + "above": 2682, + "##9": 2683, + "daughter": 2684, + "points": 2685, + "space": 2686, + "1998": 2687, + "museum": 2688, + "change": 2689, + "middle": 2690, + "common": 2691, + "##0": 2692, + "move": 2693, + "tv": 2694, + "post": 2695, + "##ta": 2696, + "lake": 2697, + "seven": 2698, + "tried": 2699, + "elected": 2700, + "closed": 2701, + "ten": 2702, + "paul": 2703, + "minister": 2704, + "##th": 2705, + "months": 2706, + "start": 2707, + "chief": 2708, + "return": 2709, + "canada": 2710, + "person": 2711, + "sea": 2712, + "release": 2713, + "similar": 2714, + "modern": 2715, + "brought": 2716, + "rest": 2717, + "hit": 2718, + "formed": 2719, + "mr": 2720, + "##la": 2721, + "1997": 2722, + "floor": 2723, + "event": 2724, + "doing": 2725, + "thomas": 2726, + "1996": 2727, + "robert": 2728, + "care": 2729, + "killed": 2730, + "training": 2731, + "star": 2732, + "week": 2733, + "needed": 2734, + "turn": 2735, + "finished": 2736, + "railway": 2737, + "rather": 2738, + "news": 2739, + "health": 2740, + "sent": 2741, + "example": 2742, + "ran": 2743, + "term": 2744, + "michael": 2745, + "coming": 2746, + "currently": 2747, + "yes": 2748, + "forces": 2749, + "despite": 2750, + "gold": 2751, + "areas": 2752, + "50": 2753, + "stage": 2754, + "fact": 2755, + "29": 2756, + "dead": 2757, + "says": 2758, + "popular": 2759, + "2018": 2760, + "originally": 2761, + "germany": 2762, + "probably": 2763, + "developed": 2764, + "result": 2765, + "pulled": 2766, + "friend": 2767, + "stood": 2768, + "money": 2769, + "running": 2770, + "mi": 2771, + "signed": 2772, + "word": 2773, + "songs": 2774, + "child": 2775, + "eventually": 2776, + "met": 2777, + "tour": 2778, + "average": 2779, + "teams": 2780, + "minutes": 2781, + "festival": 2782, + "current": 2783, + "deep": 2784, + "kind": 2785, + "1995": 2786, + "decided": 2787, + "usually": 2788, + "eastern": 2789, + "seemed": 2790, + "##ness": 2791, + "episode": 2792, + "bed": 2793, + "added": 2794, + "table": 2795, + "indian": 2796, + "private": 2797, + "charles": 2798, + "route": 2799, + "available": 2800, + "idea": 2801, + "throughout": 2802, + "centre": 2803, + "addition": 2804, + "appointed": 2805, + "style": 2806, + "1994": 2807, + "books": 2808, + "eight": 2809, + "construction": 2810, + "press": 2811, + "mean": 2812, + "wall": 2813, + "friends": 2814, + "remained": 2815, + "schools": 2816, + "study": 2817, + "##ch": 2818, + "##um": 2819, + "institute": 2820, + "oh": 2821, + "chinese": 2822, + "sometimes": 2823, + "events": 2824, + "possible": 2825, + "1992": 2826, + "australian": 2827, + "type": 2828, + "brown": 2829, + "forward": 2830, + "talk": 2831, + "process": 2832, + "food": 2833, + "debut": 2834, + "seat": 2835, + "performance": 2836, + "committee": 2837, + "features": 2838, + "character": 2839, + "arts": 2840, + "herself": 2841, + "else": 2842, + "lot": 2843, + "strong": 2844, + "russian": 2845, + "range": 2846, + "hours": 2847, + "peter": 2848, + "arm": 2849, + "##da": 2850, + "morning": 2851, + "dr": 2852, + "sold": 2853, + "##ry": 2854, + "quickly": 2855, + "directed": 2856, + "1993": 2857, + "guitar": 2858, + "china": 2859, + "##w": 2860, + "31": 2861, + "list": 2862, + "##ma": 2863, + "performed": 2864, + "media": 2865, + "uk": 2866, + "players": 2867, + "smile": 2868, + "##rs": 2869, + "myself": 2870, + "40": 2871, + "placed": 2872, + "coach": 2873, + "province": 2874, + "towards": 2875, + "wouldn": 2876, + "leading": 2877, + "whole": 2878, + "boy": 2879, + "official": 2880, + "designed": 2881, + "grand": 2882, + "census": 2883, + "##el": 2884, + "europe": 2885, + "attack": 2886, + "japanese": 2887, + "henry": 2888, + "1991": 2889, + "##re": 2890, + "##os": 2891, + "cross": 2892, + "getting": 2893, + "alone": 2894, + "action": 2895, + "lower": 2896, + "network": 2897, + "wide": 2898, + "washington": 2899, + "japan": 2900, + "1990": 2901, + "hospital": 2902, + "believe": 2903, + "changed": 2904, + "sister": 2905, + "##ar": 2906, + "hold": 2907, + "gone": 2908, + "sir": 2909, + "hadn": 2910, + "ship": 2911, + "##ka": 2912, + "studies": 2913, + "academy": 2914, + "shot": 2915, + "rights": 2916, + "below": 2917, + "base": 2918, + "bad": 2919, + "involved": 2920, + "kept": 2921, + "largest": 2922, + "##ist": 2923, + "bank": 2924, + "future": 2925, + "especially": 2926, + "beginning": 2927, + "mark": 2928, + "movement": 2929, + "section": 2930, + "female": 2931, + "magazine": 2932, + "plan": 2933, + "professor": 2934, + "lord": 2935, + "longer": 2936, + "##ian": 2937, + "sat": 2938, + "walked": 2939, + "hill": 2940, + "actually": 2941, + "civil": 2942, + "energy": 2943, + "model": 2944, + "families": 2945, + "size": 2946, + "thus": 2947, + "aircraft": 2948, + "completed": 2949, + "includes": 2950, + "data": 2951, + "captain": 2952, + "##or": 2953, + "fight": 2954, + "vocals": 2955, + "featured": 2956, + "richard": 2957, + "bridge": 2958, + "fourth": 2959, + "1989": 2960, + "officer": 2961, + "stone": 2962, + "hear": 2963, + "##ism": 2964, + "means": 2965, + "medical": 2966, + "groups": 2967, + "management": 2968, + "self": 2969, + "lips": 2970, + "competition": 2971, + "entire": 2972, + "lived": 2973, + "technology": 2974, + "leaving": 2975, + "federal": 2976, + "tournament": 2977, + "bit": 2978, + "passed": 2979, + "hot": 2980, + "independent": 2981, + "awards": 2982, + "kingdom": 2983, + "mary": 2984, + "spent": 2985, + "fine": 2986, + "doesn": 2987, + "reported": 2988, + "##ling": 2989, + "jack": 2990, + "fall": 2991, + "raised": 2992, + "itself": 2993, + "stay": 2994, + "true": 2995, + "studio": 2996, + "1988": 2997, + "sports": 2998, + "replaced": 2999, + "paris": 3000, + "systems": 3001, + "saint": 3002, + "leader": 3003, + "theatre": 3004, + "whose": 3005, + "market": 3006, + "capital": 3007, + "parents": 3008, + "spanish": 3009, + "canadian": 3010, + "earth": 3011, + "##ity": 3012, + "cut": 3013, + "degree": 3014, + "writing": 3015, + "bay": 3016, + "christian": 3017, + "awarded": 3018, + "natural": 3019, + "higher": 3020, + "bill": 3021, + "##as": 3022, + "coast": 3023, + "provided": 3024, + "previous": 3025, + "senior": 3026, + "ft": 3027, + "valley": 3028, + "organization": 3029, + "stopped": 3030, + "onto": 3031, + "countries": 3032, + "parts": 3033, + "conference": 3034, + "queen": 3035, + "security": 3036, + "interest": 3037, + "saying": 3038, + "allowed": 3039, + "master": 3040, + "earlier": 3041, + "phone": 3042, + "matter": 3043, + "smith": 3044, + "winning": 3045, + "try": 3046, + "happened": 3047, + "moving": 3048, + "campaign": 3049, + "los": 3050, + "##ley": 3051, + "breath": 3052, + "nearly": 3053, + "mid": 3054, + "1987": 3055, + "certain": 3056, + "girls": 3057, + "date": 3058, + "italian": 3059, + "african": 3060, + "standing": 3061, + "fell": 3062, + "artist": 3063, + "##ted": 3064, + "shows": 3065, + "deal": 3066, + "mine": 3067, + "industry": 3068, + "1986": 3069, + "##ng": 3070, + "everyone": 3071, + "republic": 3072, + "provide": 3073, + "collection": 3074, + "library": 3075, + "student": 3076, + "##ville": 3077, + "primary": 3078, + "owned": 3079, + "older": 3080, + "via": 3081, + "heavy": 3082, + "1st": 3083, + "makes": 3084, + "##able": 3085, + "attention": 3086, + "anyone": 3087, + "africa": 3088, + "##ri": 3089, + "stated": 3090, + "length": 3091, + "ended": 3092, + "fingers": 3093, + "command": 3094, + "staff": 3095, + "skin": 3096, + "foreign": 3097, + "opening": 3098, + "governor": 3099, + "okay": 3100, + "medal": 3101, + "kill": 3102, + "sun": 3103, + "cover": 3104, + "job": 3105, + "1985": 3106, + "introduced": 3107, + "chest": 3108, + "hell": 3109, + "feeling": 3110, + "##ies": 3111, + "success": 3112, + "meet": 3113, + "reason": 3114, + "standard": 3115, + "meeting": 3116, + "novel": 3117, + "1984": 3118, + "trade": 3119, + "source": 3120, + "buildings": 3121, + "##land": 3122, + "rose": 3123, + "guy": 3124, + "goal": 3125, + "##ur": 3126, + "chapter": 3127, + "native": 3128, + "husband": 3129, + "previously": 3130, + "unit": 3131, + "limited": 3132, + "entered": 3133, + "weeks": 3134, + "producer": 3135, + "operations": 3136, + "mountain": 3137, + "takes": 3138, + "covered": 3139, + "forced": 3140, + "related": 3141, + "roman": 3142, + "complete": 3143, + "successful": 3144, + "key": 3145, + "texas": 3146, + "cold": 3147, + "##ya": 3148, + "channel": 3149, + "1980": 3150, + "traditional": 3151, + "films": 3152, + "dance": 3153, + "clear": 3154, + "approximately": 3155, + "500": 3156, + "nine": 3157, + "van": 3158, + "prince": 3159, + "question": 3160, + "active": 3161, + "tracks": 3162, + "ireland": 3163, + "regional": 3164, + "silver": 3165, + "author": 3166, + "personal": 3167, + "sense": 3168, + "operation": 3169, + "##ine": 3170, + "economic": 3171, + "1983": 3172, + "holding": 3173, + "twenty": 3174, + "isbn": 3175, + "additional": 3176, + "speed": 3177, + "hour": 3178, + "edition": 3179, + "regular": 3180, + "historic": 3181, + "places": 3182, + "whom": 3183, + "shook": 3184, + "movie": 3185, + "km²": 3186, + "secretary": 3187, + "prior": 3188, + "report": 3189, + "chicago": 3190, + "read": 3191, + "foundation": 3192, + "view": 3193, + "engine": 3194, + "scored": 3195, + "1982": 3196, + "units": 3197, + "ask": 3198, + "airport": 3199, + "property": 3200, + "ready": 3201, + "immediately": 3202, + "lady": 3203, + "month": 3204, + "listed": 3205, + "contract": 3206, + "##de": 3207, + "manager": 3208, + "themselves": 3209, + "lines": 3210, + "##ki": 3211, + "navy": 3212, + "writer": 3213, + "meant": 3214, + "##ts": 3215, + "runs": 3216, + "##ro": 3217, + "practice": 3218, + "championships": 3219, + "singer": 3220, + "glass": 3221, + "commission": 3222, + "required": 3223, + "forest": 3224, + "starting": 3225, + "culture": 3226, + "generally": 3227, + "giving": 3228, + "access": 3229, + "attended": 3230, + "test": 3231, + "couple": 3232, + "stand": 3233, + "catholic": 3234, + "martin": 3235, + "caught": 3236, + "executive": 3237, + "##less": 3238, + "eye": 3239, + "##ey": 3240, + "thinking": 3241, + "chair": 3242, + "quite": 3243, + "shoulder": 3244, + "1979": 3245, + "hope": 3246, + "decision": 3247, + "plays": 3248, + "defeated": 3249, + "municipality": 3250, + "whether": 3251, + "structure": 3252, + "offered": 3253, + "slowly": 3254, + "pain": 3255, + "ice": 3256, + "direction": 3257, + "##ion": 3258, + "paper": 3259, + "mission": 3260, + "1981": 3261, + "mostly": 3262, + "200": 3263, + "noted": 3264, + "individual": 3265, + "managed": 3266, + "nature": 3267, + "lives": 3268, + "plant": 3269, + "##ha": 3270, + "helped": 3271, + "except": 3272, + "studied": 3273, + "computer": 3274, + "figure": 3275, + "relationship": 3276, + "issue": 3277, + "significant": 3278, + "loss": 3279, + "die": 3280, + "smiled": 3281, + "gun": 3282, + "ago": 3283, + "highest": 3284, + "1972": 3285, + "##am": 3286, + "male": 3287, + "bring": 3288, + "goals": 3289, + "mexico": 3290, + "problem": 3291, + "distance": 3292, + "commercial": 3293, + "completely": 3294, + "location": 3295, + "annual": 3296, + "famous": 3297, + "drive": 3298, + "1976": 3299, + "neck": 3300, + "1978": 3301, + "surface": 3302, + "caused": 3303, + "italy": 3304, + "understand": 3305, + "greek": 3306, + "highway": 3307, + "wrong": 3308, + "hotel": 3309, + "comes": 3310, + "appearance": 3311, + "joseph": 3312, + "double": 3313, + "issues": 3314, + "musical": 3315, + "companies": 3316, + "castle": 3317, + "income": 3318, + "review": 3319, + "assembly": 3320, + "bass": 3321, + "initially": 3322, + "parliament": 3323, + "artists": 3324, + "experience": 3325, + "1974": 3326, + "particular": 3327, + "walk": 3328, + "foot": 3329, + "engineering": 3330, + "talking": 3331, + "window": 3332, + "dropped": 3333, + "##ter": 3334, + "miss": 3335, + "baby": 3336, + "boys": 3337, + "break": 3338, + "1975": 3339, + "stars": 3340, + "edge": 3341, + "remember": 3342, + "policy": 3343, + "carried": 3344, + "train": 3345, + "stadium": 3346, + "bar": 3347, + "sex": 3348, + "angeles": 3349, + "evidence": 3350, + "##ge": 3351, + "becoming": 3352, + "assistant": 3353, + "soviet": 3354, + "1977": 3355, + "upper": 3356, + "step": 3357, + "wing": 3358, + "1970": 3359, + "youth": 3360, + "financial": 3361, + "reach": 3362, + "##ll": 3363, + "actor": 3364, + "numerous": 3365, + "##se": 3366, + "##st": 3367, + "nodded": 3368, + "arrived": 3369, + "##ation": 3370, + "minute": 3371, + "##nt": 3372, + "believed": 3373, + "sorry": 3374, + "complex": 3375, + "beautiful": 3376, + "victory": 3377, + "associated": 3378, + "temple": 3379, + "1968": 3380, + "1973": 3381, + "chance": 3382, + "perhaps": 3383, + "metal": 3384, + "##son": 3385, + "1945": 3386, + "bishop": 3387, + "##et": 3388, + "lee": 3389, + "launched": 3390, + "particularly": 3391, + "tree": 3392, + "le": 3393, + "retired": 3394, + "subject": 3395, + "prize": 3396, + "contains": 3397, + "yeah": 3398, + "theory": 3399, + "empire": 3400, + "##ce": 3401, + "suddenly": 3402, + "waiting": 3403, + "trust": 3404, + "recording": 3405, + "##to": 3406, + "happy": 3407, + "terms": 3408, + "camp": 3409, + "champion": 3410, + "1971": 3411, + "religious": 3412, + "pass": 3413, + "zealand": 3414, + "names": 3415, + "2nd": 3416, + "port": 3417, + "ancient": 3418, + "tom": 3419, + "corner": 3420, + "represented": 3421, + "watch": 3422, + "legal": 3423, + "anti": 3424, + "justice": 3425, + "cause": 3426, + "watched": 3427, + "brothers": 3428, + "45": 3429, + "material": 3430, + "changes": 3431, + "simply": 3432, + "response": 3433, + "louis": 3434, + "fast": 3435, + "##ting": 3436, + "answer": 3437, + "60": 3438, + "historical": 3439, + "1969": 3440, + "stories": 3441, + "straight": 3442, + "create": 3443, + "feature": 3444, + "increased": 3445, + "rate": 3446, + "administration": 3447, + "virginia": 3448, + "el": 3449, + "activities": 3450, + "cultural": 3451, + "overall": 3452, + "winner": 3453, + "programs": 3454, + "basketball": 3455, + "legs": 3456, + "guard": 3457, + "beyond": 3458, + "cast": 3459, + "doctor": 3460, + "mm": 3461, + "flight": 3462, + "results": 3463, + "remains": 3464, + "cost": 3465, + "effect": 3466, + "winter": 3467, + "##ble": 3468, + "larger": 3469, + "islands": 3470, + "problems": 3471, + "chairman": 3472, + "grew": 3473, + "commander": 3474, + "isn": 3475, + "1967": 3476, + "pay": 3477, + "failed": 3478, + "selected": 3479, + "hurt": 3480, + "fort": 3481, + "box": 3482, + "regiment": 3483, + "majority": 3484, + "journal": 3485, + "35": 3486, + "edward": 3487, + "plans": 3488, + "##ke": 3489, + "##ni": 3490, + "shown": 3491, + "pretty": 3492, + "irish": 3493, + "characters": 3494, + "directly": 3495, + "scene": 3496, + "likely": 3497, + "operated": 3498, + "allow": 3499, + "spring": 3500, + "##j": 3501, + "junior": 3502, + "matches": 3503, + "looks": 3504, + "mike": 3505, + "houses": 3506, + "fellow": 3507, + "##tion": 3508, + "beach": 3509, + "marriage": 3510, + "##ham": 3511, + "##ive": 3512, + "rules": 3513, + "oil": 3514, + "65": 3515, + "florida": 3516, + "expected": 3517, + "nearby": 3518, + "congress": 3519, + "sam": 3520, + "peace": 3521, + "recent": 3522, + "iii": 3523, + "wait": 3524, + "subsequently": 3525, + "cell": 3526, + "##do": 3527, + "variety": 3528, + "serving": 3529, + "agreed": 3530, + "please": 3531, + "poor": 3532, + "joe": 3533, + "pacific": 3534, + "attempt": 3535, + "wood": 3536, + "democratic": 3537, + "piece": 3538, + "prime": 3539, + "##ca": 3540, + "rural": 3541, + "mile": 3542, + "touch": 3543, + "appears": 3544, + "township": 3545, + "1964": 3546, + "1966": 3547, + "soldiers": 3548, + "##men": 3549, + "##ized": 3550, + "1965": 3551, + "pennsylvania": 3552, + "closer": 3553, + "fighting": 3554, + "claimed": 3555, + "score": 3556, + "jones": 3557, + "physical": 3558, + "editor": 3559, + "##ous": 3560, + "filled": 3561, + "genus": 3562, + "specific": 3563, + "sitting": 3564, + "super": 3565, + "mom": 3566, + "##va": 3567, + "therefore": 3568, + "supported": 3569, + "status": 3570, + "fear": 3571, + "cases": 3572, + "store": 3573, + "meaning": 3574, + "wales": 3575, + "minor": 3576, + "spain": 3577, + "tower": 3578, + "focus": 3579, + "vice": 3580, + "frank": 3581, + "follow": 3582, + "parish": 3583, + "separate": 3584, + "golden": 3585, + "horse": 3586, + "fifth": 3587, + "remaining": 3588, + "branch": 3589, + "32": 3590, + "presented": 3591, + "stared": 3592, + "##id": 3593, + "uses": 3594, + "secret": 3595, + "forms": 3596, + "##co": 3597, + "baseball": 3598, + "exactly": 3599, + "##ck": 3600, + "choice": 3601, + "note": 3602, + "discovered": 3603, + "travel": 3604, + "composed": 3605, + "truth": 3606, + "russia": 3607, + "ball": 3608, + "color": 3609, + "kiss": 3610, + "dad": 3611, + "wind": 3612, + "continue": 3613, + "ring": 3614, + "referred": 3615, + "numbers": 3616, + "digital": 3617, + "greater": 3618, + "##ns": 3619, + "metres": 3620, + "slightly": 3621, + "direct": 3622, + "increase": 3623, + "1960": 3624, + "responsible": 3625, + "crew": 3626, + "rule": 3627, + "trees": 3628, + "troops": 3629, + "##no": 3630, + "broke": 3631, + "goes": 3632, + "individuals": 3633, + "hundred": 3634, + "weight": 3635, + "creek": 3636, + "sleep": 3637, + "memory": 3638, + "defense": 3639, + "provides": 3640, + "ordered": 3641, + "code": 3642, + "value": 3643, + "jewish": 3644, + "windows": 3645, + "1944": 3646, + "safe": 3647, + "judge": 3648, + "whatever": 3649, + "corps": 3650, + "realized": 3651, + "growing": 3652, + "pre": 3653, + "##ga": 3654, + "cities": 3655, + "alexander": 3656, + "gaze": 3657, + "lies": 3658, + "spread": 3659, + "scott": 3660, + "letter": 3661, + "showed": 3662, + "situation": 3663, + "mayor": 3664, + "transport": 3665, + "watching": 3666, + "workers": 3667, + "extended": 3668, + "##li": 3669, + "expression": 3670, + "normal": 3671, + "##ment": 3672, + "chart": 3673, + "multiple": 3674, + "border": 3675, + "##ba": 3676, + "host": 3677, + "##ner": 3678, + "daily": 3679, + "mrs": 3680, + "walls": 3681, + "piano": 3682, + "##ko": 3683, + "heat": 3684, + "cannot": 3685, + "##ate": 3686, + "earned": 3687, + "products": 3688, + "drama": 3689, + "era": 3690, + "authority": 3691, + "seasons": 3692, + "join": 3693, + "grade": 3694, + "##io": 3695, + "sign": 3696, + "difficult": 3697, + "machine": 3698, + "1963": 3699, + "territory": 3700, + "mainly": 3701, + "##wood": 3702, + "stations": 3703, + "squadron": 3704, + "1962": 3705, + "stepped": 3706, + "iron": 3707, + "19th": 3708, + "##led": 3709, + "serve": 3710, + "appear": 3711, + "sky": 3712, + "speak": 3713, + "broken": 3714, + "charge": 3715, + "knowledge": 3716, + "kilometres": 3717, + "removed": 3718, + "ships": 3719, + "article": 3720, + "campus": 3721, + "simple": 3722, + "##ty": 3723, + "pushed": 3724, + "britain": 3725, + "##ve": 3726, + "leaves": 3727, + "recently": 3728, + "cd": 3729, + "soft": 3730, + "boston": 3731, + "latter": 3732, + "easy": 3733, + "acquired": 3734, + "poland": 3735, + "##sa": 3736, + "quality": 3737, + "officers": 3738, + "presence": 3739, + "planned": 3740, + "nations": 3741, + "mass": 3742, + "broadcast": 3743, + "jean": 3744, + "share": 3745, + "image": 3746, + "influence": 3747, + "wild": 3748, + "offer": 3749, + "emperor": 3750, + "electric": 3751, + "reading": 3752, + "headed": 3753, + "ability": 3754, + "promoted": 3755, + "yellow": 3756, + "ministry": 3757, + "1942": 3758, + "throat": 3759, + "smaller": 3760, + "politician": 3761, + "##by": 3762, + "latin": 3763, + "spoke": 3764, + "cars": 3765, + "williams": 3766, + "males": 3767, + "lack": 3768, + "pop": 3769, + "80": 3770, + "##ier": 3771, + "acting": 3772, + "seeing": 3773, + "consists": 3774, + "##ti": 3775, + "estate": 3776, + "1961": 3777, + "pressure": 3778, + "johnson": 3779, + "newspaper": 3780, + "jr": 3781, + "chris": 3782, + "olympics": 3783, + "online": 3784, + "conditions": 3785, + "beat": 3786, + "elements": 3787, + "walking": 3788, + "vote": 3789, + "##field": 3790, + "needs": 3791, + "carolina": 3792, + "text": 3793, + "featuring": 3794, + "global": 3795, + "block": 3796, + "shirt": 3797, + "levels": 3798, + "francisco": 3799, + "purpose": 3800, + "females": 3801, + "et": 3802, + "dutch": 3803, + "duke": 3804, + "ahead": 3805, + "gas": 3806, + "twice": 3807, + "safety": 3808, + "serious": 3809, + "turning": 3810, + "highly": 3811, + "lieutenant": 3812, + "firm": 3813, + "maria": 3814, + "amount": 3815, + "mixed": 3816, + "daniel": 3817, + "proposed": 3818, + "perfect": 3819, + "agreement": 3820, + "affairs": 3821, + "3rd": 3822, + "seconds": 3823, + "contemporary": 3824, + "paid": 3825, + "1943": 3826, + "prison": 3827, + "save": 3828, + "kitchen": 3829, + "label": 3830, + "administrative": 3831, + "intended": 3832, + "constructed": 3833, + "academic": 3834, + "nice": 3835, + "teacher": 3836, + "races": 3837, + "1956": 3838, + "formerly": 3839, + "corporation": 3840, + "ben": 3841, + "nation": 3842, + "issued": 3843, + "shut": 3844, + "1958": 3845, + "drums": 3846, + "housing": 3847, + "victoria": 3848, + "seems": 3849, + "opera": 3850, + "1959": 3851, + "graduated": 3852, + "function": 3853, + "von": 3854, + "mentioned": 3855, + "picked": 3856, + "build": 3857, + "recognized": 3858, + "shortly": 3859, + "protection": 3860, + "picture": 3861, + "notable": 3862, + "exchange": 3863, + "elections": 3864, + "1980s": 3865, + "loved": 3866, + "percent": 3867, + "racing": 3868, + "fish": 3869, + "elizabeth": 3870, + "garden": 3871, + "volume": 3872, + "hockey": 3873, + "1941": 3874, + "beside": 3875, + "settled": 3876, + "##ford": 3877, + "1940": 3878, + "competed": 3879, + "replied": 3880, + "drew": 3881, + "1948": 3882, + "actress": 3883, + "marine": 3884, + "scotland": 3885, + "steel": 3886, + "glanced": 3887, + "farm": 3888, + "steve": 3889, + "1957": 3890, + "risk": 3891, + "tonight": 3892, + "positive": 3893, + "magic": 3894, + "singles": 3895, + "effects": 3896, + "gray": 3897, + "screen": 3898, + "dog": 3899, + "##ja": 3900, + "residents": 3901, + "bus": 3902, + "sides": 3903, + "none": 3904, + "secondary": 3905, + "literature": 3906, + "polish": 3907, + "destroyed": 3908, + "flying": 3909, + "founder": 3910, + "households": 3911, + "1939": 3912, + "lay": 3913, + "reserve": 3914, + "usa": 3915, + "gallery": 3916, + "##ler": 3917, + "1946": 3918, + "industrial": 3919, + "younger": 3920, + "approach": 3921, + "appearances": 3922, + "urban": 3923, + "ones": 3924, + "1950": 3925, + "finish": 3926, + "avenue": 3927, + "powerful": 3928, + "fully": 3929, + "growth": 3930, + "page": 3931, + "honor": 3932, + "jersey": 3933, + "projects": 3934, + "advanced": 3935, + "revealed": 3936, + "basic": 3937, + "90": 3938, + "infantry": 3939, + "pair": 3940, + "equipment": 3941, + "visit": 3942, + "33": 3943, + "evening": 3944, + "search": 3945, + "grant": 3946, + "effort": 3947, + "solo": 3948, + "treatment": 3949, + "buried": 3950, + "republican": 3951, + "primarily": 3952, + "bottom": 3953, + "owner": 3954, + "1970s": 3955, + "israel": 3956, + "gives": 3957, + "jim": 3958, + "dream": 3959, + "bob": 3960, + "remain": 3961, + "spot": 3962, + "70": 3963, + "notes": 3964, + "produce": 3965, + "champions": 3966, + "contact": 3967, + "ed": 3968, + "soul": 3969, + "accepted": 3970, + "ways": 3971, + "del": 3972, + "##ally": 3973, + "losing": 3974, + "split": 3975, + "price": 3976, + "capacity": 3977, + "basis": 3978, + "trial": 3979, + "questions": 3980, + "##ina": 3981, + "1955": 3982, + "20th": 3983, + "guess": 3984, + "officially": 3985, + "memorial": 3986, + "naval": 3987, + "initial": 3988, + "##ization": 3989, + "whispered": 3990, + "median": 3991, + "engineer": 3992, + "##ful": 3993, + "sydney": 3994, + "##go": 3995, + "columbia": 3996, + "strength": 3997, + "300": 3998, + "1952": 3999, + "tears": 4000, + "senate": 4001, + "00": 4002, + "card": 4003, + "asian": 4004, + "agent": 4005, + "1947": 4006, + "software": 4007, + "44": 4008, + "draw": 4009, + "warm": 4010, + "supposed": 4011, + "com": 4012, + "pro": 4013, + "##il": 4014, + "transferred": 4015, + "leaned": 4016, + "##at": 4017, + "candidate": 4018, + "escape": 4019, + "mountains": 4020, + "asia": 4021, + "potential": 4022, + "activity": 4023, + "entertainment": 4024, + "seem": 4025, + "traffic": 4026, + "jackson": 4027, + "murder": 4028, + "36": 4029, + "slow": 4030, + "product": 4031, + "orchestra": 4032, + "haven": 4033, + "agency": 4034, + "bbc": 4035, + "taught": 4036, + "website": 4037, + "comedy": 4038, + "unable": 4039, + "storm": 4040, + "planning": 4041, + "albums": 4042, + "rugby": 4043, + "environment": 4044, + "scientific": 4045, + "grabbed": 4046, + "protect": 4047, + "##hi": 4048, + "boat": 4049, + "typically": 4050, + "1954": 4051, + "1953": 4052, + "damage": 4053, + "principal": 4054, + "divided": 4055, + "dedicated": 4056, + "mount": 4057, + "ohio": 4058, + "##berg": 4059, + "pick": 4060, + "fought": 4061, + "driver": 4062, + "##der": 4063, + "empty": 4064, + "shoulders": 4065, + "sort": 4066, + "thank": 4067, + "berlin": 4068, + "prominent": 4069, + "account": 4070, + "freedom": 4071, + "necessary": 4072, + "efforts": 4073, + "alex": 4074, + "headquarters": 4075, + "follows": 4076, + "alongside": 4077, + "des": 4078, + "simon": 4079, + "andrew": 4080, + "suggested": 4081, + "operating": 4082, + "learning": 4083, + "steps": 4084, + "1949": 4085, + "sweet": 4086, + "technical": 4087, + "begin": 4088, + "easily": 4089, + "34": 4090, + "teeth": 4091, + "speaking": 4092, + "settlement": 4093, + "scale": 4094, + "##sh": 4095, + "renamed": 4096, + "ray": 4097, + "max": 4098, + "enemy": 4099, + "semi": 4100, + "joint": 4101, + "compared": 4102, + "##rd": 4103, + "scottish": 4104, + "leadership": 4105, + "analysis": 4106, + "offers": 4107, + "georgia": 4108, + "pieces": 4109, + "captured": 4110, + "animal": 4111, + "deputy": 4112, + "guest": 4113, + "organized": 4114, + "##lin": 4115, + "tony": 4116, + "combined": 4117, + "method": 4118, + "challenge": 4119, + "1960s": 4120, + "huge": 4121, + "wants": 4122, + "battalion": 4123, + "sons": 4124, + "rise": 4125, + "crime": 4126, + "types": 4127, + "facilities": 4128, + "telling": 4129, + "path": 4130, + "1951": 4131, + "platform": 4132, + "sit": 4133, + "1990s": 4134, + "##lo": 4135, + "tells": 4136, + "assigned": 4137, + "rich": 4138, + "pull": 4139, + "##ot": 4140, + "commonly": 4141, + "alive": 4142, + "##za": 4143, + "letters": 4144, + "concept": 4145, + "conducted": 4146, + "wearing": 4147, + "happen": 4148, + "bought": 4149, + "becomes": 4150, + "holy": 4151, + "gets": 4152, + "ocean": 4153, + "defeat": 4154, + "languages": 4155, + "purchased": 4156, + "coffee": 4157, + "occurred": 4158, + "titled": 4159, + "##q": 4160, + "declared": 4161, + "applied": 4162, + "sciences": 4163, + "concert": 4164, + "sounds": 4165, + "jazz": 4166, + "brain": 4167, + "##me": 4168, + "painting": 4169, + "fleet": 4170, + "tax": 4171, + "nick": 4172, + "##ius": 4173, + "michigan": 4174, + "count": 4175, + "animals": 4176, + "leaders": 4177, + "episodes": 4178, + "##line": 4179, + "content": 4180, + "##den": 4181, + "birth": 4182, + "##it": 4183, + "clubs": 4184, + "64": 4185, + "palace": 4186, + "critical": 4187, + "refused": 4188, + "fair": 4189, + "leg": 4190, + "laughed": 4191, + "returning": 4192, + "surrounding": 4193, + "participated": 4194, + "formation": 4195, + "lifted": 4196, + "pointed": 4197, + "connected": 4198, + "rome": 4199, + "medicine": 4200, + "laid": 4201, + "taylor": 4202, + "santa": 4203, + "powers": 4204, + "adam": 4205, + "tall": 4206, + "shared": 4207, + "focused": 4208, + "knowing": 4209, + "yards": 4210, + "entrance": 4211, + "falls": 4212, + "##wa": 4213, + "calling": 4214, + "##ad": 4215, + "sources": 4216, + "chosen": 4217, + "beneath": 4218, + "resources": 4219, + "yard": 4220, + "##ite": 4221, + "nominated": 4222, + "silence": 4223, + "zone": 4224, + "defined": 4225, + "##que": 4226, + "gained": 4227, + "thirty": 4228, + "38": 4229, + "bodies": 4230, + "moon": 4231, + "##ard": 4232, + "adopted": 4233, + "christmas": 4234, + "widely": 4235, + "register": 4236, + "apart": 4237, + "iran": 4238, + "premier": 4239, + "serves": 4240, + "du": 4241, + "unknown": 4242, + "parties": 4243, + "##les": 4244, + "generation": 4245, + "##ff": 4246, + "continues": 4247, + "quick": 4248, + "fields": 4249, + "brigade": 4250, + "quiet": 4251, + "teaching": 4252, + "clothes": 4253, + "impact": 4254, + "weapons": 4255, + "partner": 4256, + "flat": 4257, + "theater": 4258, + "supreme": 4259, + "1938": 4260, + "37": 4261, + "relations": 4262, + "##tor": 4263, + "plants": 4264, + "suffered": 4265, + "1936": 4266, + "wilson": 4267, + "kids": 4268, + "begins": 4269, + "##age": 4270, + "1918": 4271, + "seats": 4272, + "armed": 4273, + "internet": 4274, + "models": 4275, + "worth": 4276, + "laws": 4277, + "400": 4278, + "communities": 4279, + "classes": 4280, + "background": 4281, + "knows": 4282, + "thanks": 4283, + "quarter": 4284, + "reaching": 4285, + "humans": 4286, + "carry": 4287, + "killing": 4288, + "format": 4289, + "kong": 4290, + "hong": 4291, + "setting": 4292, + "75": 4293, + "architecture": 4294, + "disease": 4295, + "railroad": 4296, + "inc": 4297, + "possibly": 4298, + "wish": 4299, + "arthur": 4300, + "thoughts": 4301, + "harry": 4302, + "doors": 4303, + "density": 4304, + "##di": 4305, + "crowd": 4306, + "illinois": 4307, + "stomach": 4308, + "tone": 4309, + "unique": 4310, + "reports": 4311, + "anyway": 4312, + "##ir": 4313, + "liberal": 4314, + "der": 4315, + "vehicle": 4316, + "thick": 4317, + "dry": 4318, + "drug": 4319, + "faced": 4320, + "largely": 4321, + "facility": 4322, + "theme": 4323, + "holds": 4324, + "creation": 4325, + "strange": 4326, + "colonel": 4327, + "##mi": 4328, + "revolution": 4329, + "bell": 4330, + "politics": 4331, + "turns": 4332, + "silent": 4333, + "rail": 4334, + "relief": 4335, + "independence": 4336, + "combat": 4337, + "shape": 4338, + "write": 4339, + "determined": 4340, + "sales": 4341, + "learned": 4342, + "4th": 4343, + "finger": 4344, + "oxford": 4345, + "providing": 4346, + "1937": 4347, + "heritage": 4348, + "fiction": 4349, + "situated": 4350, + "designated": 4351, + "allowing": 4352, + "distribution": 4353, + "hosted": 4354, + "##est": 4355, + "sight": 4356, + "interview": 4357, + "estimated": 4358, + "reduced": 4359, + "##ria": 4360, + "toronto": 4361, + "footballer": 4362, + "keeping": 4363, + "guys": 4364, + "damn": 4365, + "claim": 4366, + "motion": 4367, + "sport": 4368, + "sixth": 4369, + "stayed": 4370, + "##ze": 4371, + "en": 4372, + "rear": 4373, + "receive": 4374, + "handed": 4375, + "twelve": 4376, + "dress": 4377, + "audience": 4378, + "granted": 4379, + "brazil": 4380, + "##well": 4381, + "spirit": 4382, + "##ated": 4383, + "noticed": 4384, + "etc": 4385, + "olympic": 4386, + "representative": 4387, + "eric": 4388, + "tight": 4389, + "trouble": 4390, + "reviews": 4391, + "drink": 4392, + "vampire": 4393, + "missing": 4394, + "roles": 4395, + "ranked": 4396, + "newly": 4397, + "household": 4398, + "finals": 4399, + "wave": 4400, + "critics": 4401, + "##ee": 4402, + "phase": 4403, + "massachusetts": 4404, + "pilot": 4405, + "unlike": 4406, + "philadelphia": 4407, + "bright": 4408, + "guns": 4409, + "crown": 4410, + "organizations": 4411, + "roof": 4412, + "42": 4413, + "respectively": 4414, + "clearly": 4415, + "tongue": 4416, + "marked": 4417, + "circle": 4418, + "fox": 4419, + "korea": 4420, + "bronze": 4421, + "brian": 4422, + "expanded": 4423, + "sexual": 4424, + "supply": 4425, + "yourself": 4426, + "inspired": 4427, + "labour": 4428, + "fc": 4429, + "##ah": 4430, + "reference": 4431, + "vision": 4432, + "draft": 4433, + "connection": 4434, + "brand": 4435, + "reasons": 4436, + "1935": 4437, + "classic": 4438, + "driving": 4439, + "trip": 4440, + "jesus": 4441, + "cells": 4442, + "entry": 4443, + "1920": 4444, + "neither": 4445, + "trail": 4446, + "claims": 4447, + "atlantic": 4448, + "orders": 4449, + "labor": 4450, + "nose": 4451, + "afraid": 4452, + "identified": 4453, + "intelligence": 4454, + "calls": 4455, + "cancer": 4456, + "attacked": 4457, + "passing": 4458, + "stephen": 4459, + "positions": 4460, + "imperial": 4461, + "grey": 4462, + "jason": 4463, + "39": 4464, + "sunday": 4465, + "48": 4466, + "swedish": 4467, + "avoid": 4468, + "extra": 4469, + "uncle": 4470, + "message": 4471, + "covers": 4472, + "allows": 4473, + "surprise": 4474, + "materials": 4475, + "fame": 4476, + "hunter": 4477, + "##ji": 4478, + "1930": 4479, + "citizens": 4480, + "figures": 4481, + "davis": 4482, + "environmental": 4483, + "confirmed": 4484, + "shit": 4485, + "titles": 4486, + "di": 4487, + "performing": 4488, + "difference": 4489, + "acts": 4490, + "attacks": 4491, + "##ov": 4492, + "existing": 4493, + "votes": 4494, + "opportunity": 4495, + "nor": 4496, + "shop": 4497, + "entirely": 4498, + "trains": 4499, + "opposite": 4500, + "pakistan": 4501, + "##pa": 4502, + "develop": 4503, + "resulted": 4504, + "representatives": 4505, + "actions": 4506, + "reality": 4507, + "pressed": 4508, + "##ish": 4509, + "barely": 4510, + "wine": 4511, + "conversation": 4512, + "faculty": 4513, + "northwest": 4514, + "ends": 4515, + "documentary": 4516, + "nuclear": 4517, + "stock": 4518, + "grace": 4519, + "sets": 4520, + "eat": 4521, + "alternative": 4522, + "##ps": 4523, + "bag": 4524, + "resulting": 4525, + "creating": 4526, + "surprised": 4527, + "cemetery": 4528, + "1919": 4529, + "drop": 4530, + "finding": 4531, + "sarah": 4532, + "cricket": 4533, + "streets": 4534, + "tradition": 4535, + "ride": 4536, + "1933": 4537, + "exhibition": 4538, + "target": 4539, + "ear": 4540, + "explained": 4541, + "rain": 4542, + "composer": 4543, + "injury": 4544, + "apartment": 4545, + "municipal": 4546, + "educational": 4547, + "occupied": 4548, + "netherlands": 4549, + "clean": 4550, + "billion": 4551, + "constitution": 4552, + "learn": 4553, + "1914": 4554, + "maximum": 4555, + "classical": 4556, + "francis": 4557, + "lose": 4558, + "opposition": 4559, + "jose": 4560, + "ontario": 4561, + "bear": 4562, + "core": 4563, + "hills": 4564, + "rolled": 4565, + "ending": 4566, + "drawn": 4567, + "permanent": 4568, + "fun": 4569, + "##tes": 4570, + "##lla": 4571, + "lewis": 4572, + "sites": 4573, + "chamber": 4574, + "ryan": 4575, + "##way": 4576, + "scoring": 4577, + "height": 4578, + "1934": 4579, + "##house": 4580, + "lyrics": 4581, + "staring": 4582, + "55": 4583, + "officials": 4584, + "1917": 4585, + "snow": 4586, + "oldest": 4587, + "##tic": 4588, + "orange": 4589, + "##ger": 4590, + "qualified": 4591, + "interior": 4592, + "apparently": 4593, + "succeeded": 4594, + "thousand": 4595, + "dinner": 4596, + "lights": 4597, + "existence": 4598, + "fans": 4599, + "heavily": 4600, + "41": 4601, + "greatest": 4602, + "conservative": 4603, + "send": 4604, + "bowl": 4605, + "plus": 4606, + "enter": 4607, + "catch": 4608, + "##un": 4609, + "economy": 4610, + "duty": 4611, + "1929": 4612, + "speech": 4613, + "authorities": 4614, + "princess": 4615, + "performances": 4616, + "versions": 4617, + "shall": 4618, + "graduate": 4619, + "pictures": 4620, + "effective": 4621, + "remembered": 4622, + "poetry": 4623, + "desk": 4624, + "crossed": 4625, + "starring": 4626, + "starts": 4627, + "passenger": 4628, + "sharp": 4629, + "##ant": 4630, + "acres": 4631, + "ass": 4632, + "weather": 4633, + "falling": 4634, + "rank": 4635, + "fund": 4636, + "supporting": 4637, + "check": 4638, + "adult": 4639, + "publishing": 4640, + "heads": 4641, + "cm": 4642, + "southeast": 4643, + "lane": 4644, + "##burg": 4645, + "application": 4646, + "bc": 4647, + "##ura": 4648, + "les": 4649, + "condition": 4650, + "transfer": 4651, + "prevent": 4652, + "display": 4653, + "ex": 4654, + "regions": 4655, + "earl": 4656, + "federation": 4657, + "cool": 4658, + "relatively": 4659, + "answered": 4660, + "besides": 4661, + "1928": 4662, + "obtained": 4663, + "portion": 4664, + "##town": 4665, + "mix": 4666, + "##ding": 4667, + "reaction": 4668, + "liked": 4669, + "dean": 4670, + "express": 4671, + "peak": 4672, + "1932": 4673, + "##tte": 4674, + "counter": 4675, + "religion": 4676, + "chain": 4677, + "rare": 4678, + "miller": 4679, + "convention": 4680, + "aid": 4681, + "lie": 4682, + "vehicles": 4683, + "mobile": 4684, + "perform": 4685, + "squad": 4686, + "wonder": 4687, + "lying": 4688, + "crazy": 4689, + "sword": 4690, + "##ping": 4691, + "attempted": 4692, + "centuries": 4693, + "weren": 4694, + "philosophy": 4695, + "category": 4696, + "##ize": 4697, + "anna": 4698, + "interested": 4699, + "47": 4700, + "sweden": 4701, + "wolf": 4702, + "frequently": 4703, + "abandoned": 4704, + "kg": 4705, + "literary": 4706, + "alliance": 4707, + "task": 4708, + "entitled": 4709, + "##ay": 4710, + "threw": 4711, + "promotion": 4712, + "factory": 4713, + "tiny": 4714, + "soccer": 4715, + "visited": 4716, + "matt": 4717, + "fm": 4718, + "achieved": 4719, + "52": 4720, + "defence": 4721, + "internal": 4722, + "persian": 4723, + "43": 4724, + "methods": 4725, + "##ging": 4726, + "arrested": 4727, + "otherwise": 4728, + "cambridge": 4729, + "programming": 4730, + "villages": 4731, + "elementary": 4732, + "districts": 4733, + "rooms": 4734, + "criminal": 4735, + "conflict": 4736, + "worry": 4737, + "trained": 4738, + "1931": 4739, + "attempts": 4740, + "waited": 4741, + "signal": 4742, + "bird": 4743, + "truck": 4744, + "subsequent": 4745, + "programme": 4746, + "##ol": 4747, + "ad": 4748, + "49": 4749, + "communist": 4750, + "details": 4751, + "faith": 4752, + "sector": 4753, + "patrick": 4754, + "carrying": 4755, + "laugh": 4756, + "##ss": 4757, + "controlled": 4758, + "korean": 4759, + "showing": 4760, + "origin": 4761, + "fuel": 4762, + "evil": 4763, + "1927": 4764, + "##ent": 4765, + "brief": 4766, + "identity": 4767, + "darkness": 4768, + "address": 4769, + "pool": 4770, + "missed": 4771, + "publication": 4772, + "web": 4773, + "planet": 4774, + "ian": 4775, + "anne": 4776, + "wings": 4777, + "invited": 4778, + "##tt": 4779, + "briefly": 4780, + "standards": 4781, + "kissed": 4782, + "##be": 4783, + "ideas": 4784, + "climate": 4785, + "causing": 4786, + "walter": 4787, + "worse": 4788, + "albert": 4789, + "articles": 4790, + "winners": 4791, + "desire": 4792, + "aged": 4793, + "northeast": 4794, + "dangerous": 4795, + "gate": 4796, + "doubt": 4797, + "1922": 4798, + "wooden": 4799, + "multi": 4800, + "##ky": 4801, + "poet": 4802, + "rising": 4803, + "funding": 4804, + "46": 4805, + "communications": 4806, + "communication": 4807, + "violence": 4808, + "copies": 4809, + "prepared": 4810, + "ford": 4811, + "investigation": 4812, + "skills": 4813, + "1924": 4814, + "pulling": 4815, + "electronic": 4816, + "##ak": 4817, + "##ial": 4818, + "##han": 4819, + "containing": 4820, + "ultimately": 4821, + "offices": 4822, + "singing": 4823, + "understanding": 4824, + "restaurant": 4825, + "tomorrow": 4826, + "fashion": 4827, + "christ": 4828, + "ward": 4829, + "da": 4830, + "pope": 4831, + "stands": 4832, + "5th": 4833, + "flow": 4834, + "studios": 4835, + "aired": 4836, + "commissioned": 4837, + "contained": 4838, + "exist": 4839, + "fresh": 4840, + "americans": 4841, + "##per": 4842, + "wrestling": 4843, + "approved": 4844, + "kid": 4845, + "employed": 4846, + "respect": 4847, + "suit": 4848, + "1925": 4849, + "angel": 4850, + "asking": 4851, + "increasing": 4852, + "frame": 4853, + "angry": 4854, + "selling": 4855, + "1950s": 4856, + "thin": 4857, + "finds": 4858, + "##nd": 4859, + "temperature": 4860, + "statement": 4861, + "ali": 4862, + "explain": 4863, + "inhabitants": 4864, + "towns": 4865, + "extensive": 4866, + "narrow": 4867, + "51": 4868, + "jane": 4869, + "flowers": 4870, + "images": 4871, + "promise": 4872, + "somewhere": 4873, + "object": 4874, + "fly": 4875, + "closely": 4876, + "##ls": 4877, + "1912": 4878, + "bureau": 4879, + "cape": 4880, + "1926": 4881, + "weekly": 4882, + "presidential": 4883, + "legislative": 4884, + "1921": 4885, + "##ai": 4886, + "##au": 4887, + "launch": 4888, + "founding": 4889, + "##ny": 4890, + "978": 4891, + "##ring": 4892, + "artillery": 4893, + "strike": 4894, + "un": 4895, + "institutions": 4896, + "roll": 4897, + "writers": 4898, + "landing": 4899, + "chose": 4900, + "kevin": 4901, + "anymore": 4902, + "pp": 4903, + "##ut": 4904, + "attorney": 4905, + "fit": 4906, + "dan": 4907, + "billboard": 4908, + "receiving": 4909, + "agricultural": 4910, + "breaking": 4911, + "sought": 4912, + "dave": 4913, + "admitted": 4914, + "lands": 4915, + "mexican": 4916, + "##bury": 4917, + "charlie": 4918, + "specifically": 4919, + "hole": 4920, + "iv": 4921, + "howard": 4922, + "credit": 4923, + "moscow": 4924, + "roads": 4925, + "accident": 4926, + "1923": 4927, + "proved": 4928, + "wear": 4929, + "struck": 4930, + "hey": 4931, + "guards": 4932, + "stuff": 4933, + "slid": 4934, + "expansion": 4935, + "1915": 4936, + "cat": 4937, + "anthony": 4938, + "##kin": 4939, + "melbourne": 4940, + "opposed": 4941, + "sub": 4942, + "southwest": 4943, + "architect": 4944, + "failure": 4945, + "plane": 4946, + "1916": 4947, + "##ron": 4948, + "map": 4949, + "camera": 4950, + "tank": 4951, + "listen": 4952, + "regarding": 4953, + "wet": 4954, + "introduction": 4955, + "metropolitan": 4956, + "link": 4957, + "ep": 4958, + "fighter": 4959, + "inch": 4960, + "grown": 4961, + "gene": 4962, + "anger": 4963, + "fixed": 4964, + "buy": 4965, + "dvd": 4966, + "khan": 4967, + "domestic": 4968, + "worldwide": 4969, + "chapel": 4970, + "mill": 4971, + "functions": 4972, + "examples": 4973, + "##head": 4974, + "developing": 4975, + "1910": 4976, + "turkey": 4977, + "hits": 4978, + "pocket": 4979, + "antonio": 4980, + "papers": 4981, + "grow": 4982, + "unless": 4983, + "circuit": 4984, + "18th": 4985, + "concerned": 4986, + "attached": 4987, + "journalist": 4988, + "selection": 4989, + "journey": 4990, + "converted": 4991, + "provincial": 4992, + "painted": 4993, + "hearing": 4994, + "aren": 4995, + "bands": 4996, + "negative": 4997, + "aside": 4998, + "wondered": 4999, + "knight": 5000, + "lap": 5001, + "survey": 5002, + "ma": 5003, + "##ow": 5004, + "noise": 5005, + "billy": 5006, + "##ium": 5007, + "shooting": 5008, + "guide": 5009, + "bedroom": 5010, + "priest": 5011, + "resistance": 5012, + "motor": 5013, + "homes": 5014, + "sounded": 5015, + "giant": 5016, + "##mer": 5017, + "150": 5018, + "scenes": 5019, + "equal": 5020, + "comic": 5021, + "patients": 5022, + "hidden": 5023, + "solid": 5024, + "actual": 5025, + "bringing": 5026, + "afternoon": 5027, + "touched": 5028, + "funds": 5029, + "wedding": 5030, + "consisted": 5031, + "marie": 5032, + "canal": 5033, + "sr": 5034, + "kim": 5035, + "treaty": 5036, + "turkish": 5037, + "recognition": 5038, + "residence": 5039, + "cathedral": 5040, + "broad": 5041, + "knees": 5042, + "incident": 5043, + "shaped": 5044, + "fired": 5045, + "norwegian": 5046, + "handle": 5047, + "cheek": 5048, + "contest": 5049, + "represent": 5050, + "##pe": 5051, + "representing": 5052, + "beauty": 5053, + "##sen": 5054, + "birds": 5055, + "advantage": 5056, + "emergency": 5057, + "wrapped": 5058, + "drawing": 5059, + "notice": 5060, + "pink": 5061, + "broadcasting": 5062, + "##ong": 5063, + "somehow": 5064, + "bachelor": 5065, + "seventh": 5066, + "collected": 5067, + "registered": 5068, + "establishment": 5069, + "alan": 5070, + "assumed": 5071, + "chemical": 5072, + "personnel": 5073, + "roger": 5074, + "retirement": 5075, + "jeff": 5076, + "portuguese": 5077, + "wore": 5078, + "tied": 5079, + "device": 5080, + "threat": 5081, + "progress": 5082, + "advance": 5083, + "##ised": 5084, + "banks": 5085, + "hired": 5086, + "manchester": 5087, + "nfl": 5088, + "teachers": 5089, + "structures": 5090, + "forever": 5091, + "##bo": 5092, + "tennis": 5093, + "helping": 5094, + "saturday": 5095, + "sale": 5096, + "applications": 5097, + "junction": 5098, + "hip": 5099, + "incorporated": 5100, + "neighborhood": 5101, + "dressed": 5102, + "ceremony": 5103, + "##ds": 5104, + "influenced": 5105, + "hers": 5106, + "visual": 5107, + "stairs": 5108, + "decades": 5109, + "inner": 5110, + "kansas": 5111, + "hung": 5112, + "hoped": 5113, + "gain": 5114, + "scheduled": 5115, + "downtown": 5116, + "engaged": 5117, + "austria": 5118, + "clock": 5119, + "norway": 5120, + "certainly": 5121, + "pale": 5122, + "protected": 5123, + "1913": 5124, + "victor": 5125, + "employees": 5126, + "plate": 5127, + "putting": 5128, + "surrounded": 5129, + "##ists": 5130, + "finishing": 5131, + "blues": 5132, + "tropical": 5133, + "##ries": 5134, + "minnesota": 5135, + "consider": 5136, + "philippines": 5137, + "accept": 5138, + "54": 5139, + "retrieved": 5140, + "1900": 5141, + "concern": 5142, + "anderson": 5143, + "properties": 5144, + "institution": 5145, + "gordon": 5146, + "successfully": 5147, + "vietnam": 5148, + "##dy": 5149, + "backing": 5150, + "outstanding": 5151, + "muslim": 5152, + "crossing": 5153, + "folk": 5154, + "producing": 5155, + "usual": 5156, + "demand": 5157, + "occurs": 5158, + "observed": 5159, + "lawyer": 5160, + "educated": 5161, + "##ana": 5162, + "kelly": 5163, + "string": 5164, + "pleasure": 5165, + "budget": 5166, + "items": 5167, + "quietly": 5168, + "colorado": 5169, + "philip": 5170, + "typical": 5171, + "##worth": 5172, + "derived": 5173, + "600": 5174, + "survived": 5175, + "asks": 5176, + "mental": 5177, + "##ide": 5178, + "56": 5179, + "jake": 5180, + "jews": 5181, + "distinguished": 5182, + "ltd": 5183, + "1911": 5184, + "sri": 5185, + "extremely": 5186, + "53": 5187, + "athletic": 5188, + "loud": 5189, + "thousands": 5190, + "worried": 5191, + "shadow": 5192, + "transportation": 5193, + "horses": 5194, + "weapon": 5195, + "arena": 5196, + "importance": 5197, + "users": 5198, + "tim": 5199, + "objects": 5200, + "contributed": 5201, + "dragon": 5202, + "douglas": 5203, + "aware": 5204, + "senator": 5205, + "johnny": 5206, + "jordan": 5207, + "sisters": 5208, + "engines": 5209, + "flag": 5210, + "investment": 5211, + "samuel": 5212, + "shock": 5213, + "capable": 5214, + "clark": 5215, + "row": 5216, + "wheel": 5217, + "refers": 5218, + "session": 5219, + "familiar": 5220, + "biggest": 5221, + "wins": 5222, + "hate": 5223, + "maintained": 5224, + "drove": 5225, + "hamilton": 5226, + "request": 5227, + "expressed": 5228, + "injured": 5229, + "underground": 5230, + "churches": 5231, + "walker": 5232, + "wars": 5233, + "tunnel": 5234, + "passes": 5235, + "stupid": 5236, + "agriculture": 5237, + "softly": 5238, + "cabinet": 5239, + "regarded": 5240, + "joining": 5241, + "indiana": 5242, + "##ea": 5243, + "##ms": 5244, + "push": 5245, + "dates": 5246, + "spend": 5247, + "behavior": 5248, + "woods": 5249, + "protein": 5250, + "gently": 5251, + "chase": 5252, + "morgan": 5253, + "mention": 5254, + "burning": 5255, + "wake": 5256, + "combination": 5257, + "occur": 5258, + "mirror": 5259, + "leads": 5260, + "jimmy": 5261, + "indeed": 5262, + "impossible": 5263, + "singapore": 5264, + "paintings": 5265, + "covering": 5266, + "##nes": 5267, + "soldier": 5268, + "locations": 5269, + "attendance": 5270, + "sell": 5271, + "historian": 5272, + "wisconsin": 5273, + "invasion": 5274, + "argued": 5275, + "painter": 5276, + "diego": 5277, + "changing": 5278, + "egypt": 5279, + "##don": 5280, + "experienced": 5281, + "inches": 5282, + "##ku": 5283, + "missouri": 5284, + "vol": 5285, + "grounds": 5286, + "spoken": 5287, + "switzerland": 5288, + "##gan": 5289, + "reform": 5290, + "rolling": 5291, + "ha": 5292, + "forget": 5293, + "massive": 5294, + "resigned": 5295, + "burned": 5296, + "allen": 5297, + "tennessee": 5298, + "locked": 5299, + "values": 5300, + "improved": 5301, + "##mo": 5302, + "wounded": 5303, + "universe": 5304, + "sick": 5305, + "dating": 5306, + "facing": 5307, + "pack": 5308, + "purchase": 5309, + "user": 5310, + "##pur": 5311, + "moments": 5312, + "##ul": 5313, + "merged": 5314, + "anniversary": 5315, + "1908": 5316, + "coal": 5317, + "brick": 5318, + "understood": 5319, + "causes": 5320, + "dynasty": 5321, + "queensland": 5322, + "establish": 5323, + "stores": 5324, + "crisis": 5325, + "promote": 5326, + "hoping": 5327, + "views": 5328, + "cards": 5329, + "referee": 5330, + "extension": 5331, + "##si": 5332, + "raise": 5333, + "arizona": 5334, + "improve": 5335, + "colonial": 5336, + "formal": 5337, + "charged": 5338, + "##rt": 5339, + "palm": 5340, + "lucky": 5341, + "hide": 5342, + "rescue": 5343, + "faces": 5344, + "95": 5345, + "feelings": 5346, + "candidates": 5347, + "juan": 5348, + "##ell": 5349, + "goods": 5350, + "6th": 5351, + "courses": 5352, + "weekend": 5353, + "59": 5354, + "luke": 5355, + "cash": 5356, + "fallen": 5357, + "##om": 5358, + "delivered": 5359, + "affected": 5360, + "installed": 5361, + "carefully": 5362, + "tries": 5363, + "swiss": 5364, + "hollywood": 5365, + "costs": 5366, + "lincoln": 5367, + "responsibility": 5368, + "##he": 5369, + "shore": 5370, + "file": 5371, + "proper": 5372, + "normally": 5373, + "maryland": 5374, + "assistance": 5375, + "jump": 5376, + "constant": 5377, + "offering": 5378, + "friendly": 5379, + "waters": 5380, + "persons": 5381, + "realize": 5382, + "contain": 5383, + "trophy": 5384, + "800": 5385, + "partnership": 5386, + "factor": 5387, + "58": 5388, + "musicians": 5389, + "cry": 5390, + "bound": 5391, + "oregon": 5392, + "indicated": 5393, + "hero": 5394, + "houston": 5395, + "medium": 5396, + "##ure": 5397, + "consisting": 5398, + "somewhat": 5399, + "##ara": 5400, + "57": 5401, + "cycle": 5402, + "##che": 5403, + "beer": 5404, + "moore": 5405, + "frederick": 5406, + "gotten": 5407, + "eleven": 5408, + "worst": 5409, + "weak": 5410, + "approached": 5411, + "arranged": 5412, + "chin": 5413, + "loan": 5414, + "universal": 5415, + "bond": 5416, + "fifteen": 5417, + "pattern": 5418, + "disappeared": 5419, + "##ney": 5420, + "translated": 5421, + "##zed": 5422, + "lip": 5423, + "arab": 5424, + "capture": 5425, + "interests": 5426, + "insurance": 5427, + "##chi": 5428, + "shifted": 5429, + "cave": 5430, + "prix": 5431, + "warning": 5432, + "sections": 5433, + "courts": 5434, + "coat": 5435, + "plot": 5436, + "smell": 5437, + "feed": 5438, + "golf": 5439, + "favorite": 5440, + "maintain": 5441, + "knife": 5442, + "vs": 5443, + "voted": 5444, + "degrees": 5445, + "finance": 5446, + "quebec": 5447, + "opinion": 5448, + "translation": 5449, + "manner": 5450, + "ruled": 5451, + "operate": 5452, + "productions": 5453, + "choose": 5454, + "musician": 5455, + "discovery": 5456, + "confused": 5457, + "tired": 5458, + "separated": 5459, + "stream": 5460, + "techniques": 5461, + "committed": 5462, + "attend": 5463, + "ranking": 5464, + "kings": 5465, + "throw": 5466, + "passengers": 5467, + "measure": 5468, + "horror": 5469, + "fan": 5470, + "mining": 5471, + "sand": 5472, + "danger": 5473, + "salt": 5474, + "calm": 5475, + "decade": 5476, + "dam": 5477, + "require": 5478, + "runner": 5479, + "##ik": 5480, + "rush": 5481, + "associate": 5482, + "greece": 5483, + "##ker": 5484, + "rivers": 5485, + "consecutive": 5486, + "matthew": 5487, + "##ski": 5488, + "sighed": 5489, + "sq": 5490, + "documents": 5491, + "steam": 5492, + "edited": 5493, + "closing": 5494, + "tie": 5495, + "accused": 5496, + "1905": 5497, + "##ini": 5498, + "islamic": 5499, + "distributed": 5500, + "directors": 5501, + "organisation": 5502, + "bruce": 5503, + "7th": 5504, + "breathing": 5505, + "mad": 5506, + "lit": 5507, + "arrival": 5508, + "concrete": 5509, + "taste": 5510, + "08": 5511, + "composition": 5512, + "shaking": 5513, + "faster": 5514, + "amateur": 5515, + "adjacent": 5516, + "stating": 5517, + "1906": 5518, + "twin": 5519, + "flew": 5520, + "##ran": 5521, + "tokyo": 5522, + "publications": 5523, + "##tone": 5524, + "obviously": 5525, + "ridge": 5526, + "storage": 5527, + "1907": 5528, + "carl": 5529, + "pages": 5530, + "concluded": 5531, + "desert": 5532, + "driven": 5533, + "universities": 5534, + "ages": 5535, + "terminal": 5536, + "sequence": 5537, + "borough": 5538, + "250": 5539, + "constituency": 5540, + "creative": 5541, + "cousin": 5542, + "economics": 5543, + "dreams": 5544, + "margaret": 5545, + "notably": 5546, + "reduce": 5547, + "montreal": 5548, + "mode": 5549, + "17th": 5550, + "ears": 5551, + "saved": 5552, + "jan": 5553, + "vocal": 5554, + "##ica": 5555, + "1909": 5556, + "andy": 5557, + "##jo": 5558, + "riding": 5559, + "roughly": 5560, + "threatened": 5561, + "##ise": 5562, + "meters": 5563, + "meanwhile": 5564, + "landed": 5565, + "compete": 5566, + "repeated": 5567, + "grass": 5568, + "czech": 5569, + "regularly": 5570, + "charges": 5571, + "tea": 5572, + "sudden": 5573, + "appeal": 5574, + "##ung": 5575, + "solution": 5576, + "describes": 5577, + "pierre": 5578, + "classification": 5579, + "glad": 5580, + "parking": 5581, + "##ning": 5582, + "belt": 5583, + "physics": 5584, + "99": 5585, + "rachel": 5586, + "add": 5587, + "hungarian": 5588, + "participate": 5589, + "expedition": 5590, + "damaged": 5591, + "gift": 5592, + "childhood": 5593, + "85": 5594, + "fifty": 5595, + "##red": 5596, + "mathematics": 5597, + "jumped": 5598, + "letting": 5599, + "defensive": 5600, + "mph": 5601, + "##ux": 5602, + "##gh": 5603, + "testing": 5604, + "##hip": 5605, + "hundreds": 5606, + "shoot": 5607, + "owners": 5608, + "matters": 5609, + "smoke": 5610, + "israeli": 5611, + "kentucky": 5612, + "dancing": 5613, + "mounted": 5614, + "grandfather": 5615, + "emma": 5616, + "designs": 5617, + "profit": 5618, + "argentina": 5619, + "##gs": 5620, + "truly": 5621, + "li": 5622, + "lawrence": 5623, + "cole": 5624, + "begun": 5625, + "detroit": 5626, + "willing": 5627, + "branches": 5628, + "smiling": 5629, + "decide": 5630, + "miami": 5631, + "enjoyed": 5632, + "recordings": 5633, + "##dale": 5634, + "poverty": 5635, + "ethnic": 5636, + "gay": 5637, + "##bi": 5638, + "gary": 5639, + "arabic": 5640, + "09": 5641, + "accompanied": 5642, + "##one": 5643, + "##ons": 5644, + "fishing": 5645, + "determine": 5646, + "residential": 5647, + "acid": 5648, + "##ary": 5649, + "alice": 5650, + "returns": 5651, + "starred": 5652, + "mail": 5653, + "##ang": 5654, + "jonathan": 5655, + "strategy": 5656, + "##ue": 5657, + "net": 5658, + "forty": 5659, + "cook": 5660, + "businesses": 5661, + "equivalent": 5662, + "commonwealth": 5663, + "distinct": 5664, + "ill": 5665, + "##cy": 5666, + "seriously": 5667, + "##ors": 5668, + "##ped": 5669, + "shift": 5670, + "harris": 5671, + "replace": 5672, + "rio": 5673, + "imagine": 5674, + "formula": 5675, + "ensure": 5676, + "##ber": 5677, + "additionally": 5678, + "scheme": 5679, + "conservation": 5680, + "occasionally": 5681, + "purposes": 5682, + "feels": 5683, + "favor": 5684, + "##and": 5685, + "##ore": 5686, + "1930s": 5687, + "contrast": 5688, + "hanging": 5689, + "hunt": 5690, + "movies": 5691, + "1904": 5692, + "instruments": 5693, + "victims": 5694, + "danish": 5695, + "christopher": 5696, + "busy": 5697, + "demon": 5698, + "sugar": 5699, + "earliest": 5700, + "colony": 5701, + "studying": 5702, + "balance": 5703, + "duties": 5704, + "##ks": 5705, + "belgium": 5706, + "slipped": 5707, + "carter": 5708, + "05": 5709, + "visible": 5710, + "stages": 5711, + "iraq": 5712, + "fifa": 5713, + "##im": 5714, + "commune": 5715, + "forming": 5716, + "zero": 5717, + "07": 5718, + "continuing": 5719, + "talked": 5720, + "counties": 5721, + "legend": 5722, + "bathroom": 5723, + "option": 5724, + "tail": 5725, + "clay": 5726, + "daughters": 5727, + "afterwards": 5728, + "severe": 5729, + "jaw": 5730, + "visitors": 5731, + "##ded": 5732, + "devices": 5733, + "aviation": 5734, + "russell": 5735, + "kate": 5736, + "##vi": 5737, + "entering": 5738, + "subjects": 5739, + "##ino": 5740, + "temporary": 5741, + "swimming": 5742, + "forth": 5743, + "smooth": 5744, + "ghost": 5745, + "audio": 5746, + "bush": 5747, + "operates": 5748, + "rocks": 5749, + "movements": 5750, + "signs": 5751, + "eddie": 5752, + "##tz": 5753, + "ann": 5754, + "voices": 5755, + "honorary": 5756, + "06": 5757, + "memories": 5758, + "dallas": 5759, + "pure": 5760, + "measures": 5761, + "racial": 5762, + "promised": 5763, + "66": 5764, + "harvard": 5765, + "ceo": 5766, + "16th": 5767, + "parliamentary": 5768, + "indicate": 5769, + "benefit": 5770, + "flesh": 5771, + "dublin": 5772, + "louisiana": 5773, + "1902": 5774, + "1901": 5775, + "patient": 5776, + "sleeping": 5777, + "1903": 5778, + "membership": 5779, + "coastal": 5780, + "medieval": 5781, + "wanting": 5782, + "element": 5783, + "scholars": 5784, + "rice": 5785, + "62": 5786, + "limit": 5787, + "survive": 5788, + "makeup": 5789, + "rating": 5790, + "definitely": 5791, + "collaboration": 5792, + "obvious": 5793, + "##tan": 5794, + "boss": 5795, + "ms": 5796, + "baron": 5797, + "birthday": 5798, + "linked": 5799, + "soil": 5800, + "diocese": 5801, + "##lan": 5802, + "ncaa": 5803, + "##mann": 5804, + "offensive": 5805, + "shell": 5806, + "shouldn": 5807, + "waist": 5808, + "##tus": 5809, + "plain": 5810, + "ross": 5811, + "organ": 5812, + "resolution": 5813, + "manufacturing": 5814, + "adding": 5815, + "relative": 5816, + "kennedy": 5817, + "98": 5818, + "whilst": 5819, + "moth": 5820, + "marketing": 5821, + "gardens": 5822, + "crash": 5823, + "72": 5824, + "heading": 5825, + "partners": 5826, + "credited": 5827, + "carlos": 5828, + "moves": 5829, + "cable": 5830, + "##zi": 5831, + "marshall": 5832, + "##out": 5833, + "depending": 5834, + "bottle": 5835, + "represents": 5836, + "rejected": 5837, + "responded": 5838, + "existed": 5839, + "04": 5840, + "jobs": 5841, + "denmark": 5842, + "lock": 5843, + "##ating": 5844, + "treated": 5845, + "graham": 5846, + "routes": 5847, + "talent": 5848, + "commissioner": 5849, + "drugs": 5850, + "secure": 5851, + "tests": 5852, + "reign": 5853, + "restored": 5854, + "photography": 5855, + "##gi": 5856, + "contributions": 5857, + "oklahoma": 5858, + "designer": 5859, + "disc": 5860, + "grin": 5861, + "seattle": 5862, + "robin": 5863, + "paused": 5864, + "atlanta": 5865, + "unusual": 5866, + "##gate": 5867, + "praised": 5868, + "las": 5869, + "laughing": 5870, + "satellite": 5871, + "hungary": 5872, + "visiting": 5873, + "##sky": 5874, + "interesting": 5875, + "factors": 5876, + "deck": 5877, + "poems": 5878, + "norman": 5879, + "##water": 5880, + "stuck": 5881, + "speaker": 5882, + "rifle": 5883, + "domain": 5884, + "premiered": 5885, + "##her": 5886, + "dc": 5887, + "comics": 5888, + "actors": 5889, + "01": 5890, + "reputation": 5891, + "eliminated": 5892, + "8th": 5893, + "ceiling": 5894, + "prisoners": 5895, + "script": 5896, + "##nce": 5897, + "leather": 5898, + "austin": 5899, + "mississippi": 5900, + "rapidly": 5901, + "admiral": 5902, + "parallel": 5903, + "charlotte": 5904, + "guilty": 5905, + "tools": 5906, + "gender": 5907, + "divisions": 5908, + "fruit": 5909, + "##bs": 5910, + "laboratory": 5911, + "nelson": 5912, + "fantasy": 5913, + "marry": 5914, + "rapid": 5915, + "aunt": 5916, + "tribe": 5917, + "requirements": 5918, + "aspects": 5919, + "suicide": 5920, + "amongst": 5921, + "adams": 5922, + "bone": 5923, + "ukraine": 5924, + "abc": 5925, + "kick": 5926, + "sees": 5927, + "edinburgh": 5928, + "clothing": 5929, + "column": 5930, + "rough": 5931, + "gods": 5932, + "hunting": 5933, + "broadway": 5934, + "gathered": 5935, + "concerns": 5936, + "##ek": 5937, + "spending": 5938, + "ty": 5939, + "12th": 5940, + "snapped": 5941, + "requires": 5942, + "solar": 5943, + "bones": 5944, + "cavalry": 5945, + "##tta": 5946, + "iowa": 5947, + "drinking": 5948, + "waste": 5949, + "index": 5950, + "franklin": 5951, + "charity": 5952, + "thompson": 5953, + "stewart": 5954, + "tip": 5955, + "flash": 5956, + "landscape": 5957, + "friday": 5958, + "enjoy": 5959, + "singh": 5960, + "poem": 5961, + "listening": 5962, + "##back": 5963, + "eighth": 5964, + "fred": 5965, + "differences": 5966, + "adapted": 5967, + "bomb": 5968, + "ukrainian": 5969, + "surgery": 5970, + "corporate": 5971, + "masters": 5972, + "anywhere": 5973, + "##more": 5974, + "waves": 5975, + "odd": 5976, + "sean": 5977, + "portugal": 5978, + "orleans": 5979, + "dick": 5980, + "debate": 5981, + "kent": 5982, + "eating": 5983, + "puerto": 5984, + "cleared": 5985, + "96": 5986, + "expect": 5987, + "cinema": 5988, + "97": 5989, + "guitarist": 5990, + "blocks": 5991, + "electrical": 5992, + "agree": 5993, + "involving": 5994, + "depth": 5995, + "dying": 5996, + "panel": 5997, + "struggle": 5998, + "##ged": 5999, + "peninsula": 6000, + "adults": 6001, + "novels": 6002, + "emerged": 6003, + "vienna": 6004, + "metro": 6005, + "debuted": 6006, + "shoes": 6007, + "tamil": 6008, + "songwriter": 6009, + "meets": 6010, + "prove": 6011, + "beating": 6012, + "instance": 6013, + "heaven": 6014, + "scared": 6015, + "sending": 6016, + "marks": 6017, + "artistic": 6018, + "passage": 6019, + "superior": 6020, + "03": 6021, + "significantly": 6022, + "shopping": 6023, + "##tive": 6024, + "retained": 6025, + "##izing": 6026, + "malaysia": 6027, + "technique": 6028, + "cheeks": 6029, + "##ola": 6030, + "warren": 6031, + "maintenance": 6032, + "destroy": 6033, + "extreme": 6034, + "allied": 6035, + "120": 6036, + "appearing": 6037, + "##yn": 6038, + "fill": 6039, + "advice": 6040, + "alabama": 6041, + "qualifying": 6042, + "policies": 6043, + "cleveland": 6044, + "hat": 6045, + "battery": 6046, + "smart": 6047, + "authors": 6048, + "10th": 6049, + "soundtrack": 6050, + "acted": 6051, + "dated": 6052, + "lb": 6053, + "glance": 6054, + "equipped": 6055, + "coalition": 6056, + "funny": 6057, + "outer": 6058, + "ambassador": 6059, + "roy": 6060, + "possibility": 6061, + "couples": 6062, + "campbell": 6063, + "dna": 6064, + "loose": 6065, + "ethan": 6066, + "supplies": 6067, + "1898": 6068, + "gonna": 6069, + "88": 6070, + "monster": 6071, + "##res": 6072, + "shake": 6073, + "agents": 6074, + "frequency": 6075, + "springs": 6076, + "dogs": 6077, + "practices": 6078, + "61": 6079, + "gang": 6080, + "plastic": 6081, + "easier": 6082, + "suggests": 6083, + "gulf": 6084, + "blade": 6085, + "exposed": 6086, + "colors": 6087, + "industries": 6088, + "markets": 6089, + "pan": 6090, + "nervous": 6091, + "electoral": 6092, + "charts": 6093, + "legislation": 6094, + "ownership": 6095, + "##idae": 6096, + "mac": 6097, + "appointment": 6098, + "shield": 6099, + "copy": 6100, + "assault": 6101, + "socialist": 6102, + "abbey": 6103, + "monument": 6104, + "license": 6105, + "throne": 6106, + "employment": 6107, + "jay": 6108, + "93": 6109, + "replacement": 6110, + "charter": 6111, + "cloud": 6112, + "powered": 6113, + "suffering": 6114, + "accounts": 6115, + "oak": 6116, + "connecticut": 6117, + "strongly": 6118, + "wright": 6119, + "colour": 6120, + "crystal": 6121, + "13th": 6122, + "context": 6123, + "welsh": 6124, + "networks": 6125, + "voiced": 6126, + "gabriel": 6127, + "jerry": 6128, + "##cing": 6129, + "forehead": 6130, + "mp": 6131, + "##ens": 6132, + "manage": 6133, + "schedule": 6134, + "totally": 6135, + "remix": 6136, + "##ii": 6137, + "forests": 6138, + "occupation": 6139, + "print": 6140, + "nicholas": 6141, + "brazilian": 6142, + "strategic": 6143, + "vampires": 6144, + "engineers": 6145, + "76": 6146, + "roots": 6147, + "seek": 6148, + "correct": 6149, + "instrumental": 6150, + "und": 6151, + "alfred": 6152, + "backed": 6153, + "hop": 6154, + "##des": 6155, + "stanley": 6156, + "robinson": 6157, + "traveled": 6158, + "wayne": 6159, + "welcome": 6160, + "austrian": 6161, + "achieve": 6162, + "67": 6163, + "exit": 6164, + "rates": 6165, + "1899": 6166, + "strip": 6167, + "whereas": 6168, + "##cs": 6169, + "sing": 6170, + "deeply": 6171, + "adventure": 6172, + "bobby": 6173, + "rick": 6174, + "jamie": 6175, + "careful": 6176, + "components": 6177, + "cap": 6178, + "useful": 6179, + "personality": 6180, + "knee": 6181, + "##shi": 6182, + "pushing": 6183, + "hosts": 6184, + "02": 6185, + "protest": 6186, + "ca": 6187, + "ottoman": 6188, + "symphony": 6189, + "##sis": 6190, + "63": 6191, + "boundary": 6192, + "1890": 6193, + "processes": 6194, + "considering": 6195, + "considerable": 6196, + "tons": 6197, + "##work": 6198, + "##ft": 6199, + "##nia": 6200, + "cooper": 6201, + "trading": 6202, + "dear": 6203, + "conduct": 6204, + "91": 6205, + "illegal": 6206, + "apple": 6207, + "revolutionary": 6208, + "holiday": 6209, + "definition": 6210, + "harder": 6211, + "##van": 6212, + "jacob": 6213, + "circumstances": 6214, + "destruction": 6215, + "##lle": 6216, + "popularity": 6217, + "grip": 6218, + "classified": 6219, + "liverpool": 6220, + "donald": 6221, + "baltimore": 6222, + "flows": 6223, + "seeking": 6224, + "honour": 6225, + "approval": 6226, + "92": 6227, + "mechanical": 6228, + "till": 6229, + "happening": 6230, + "statue": 6231, + "critic": 6232, + "increasingly": 6233, + "immediate": 6234, + "describe": 6235, + "commerce": 6236, + "stare": 6237, + "##ster": 6238, + "indonesia": 6239, + "meat": 6240, + "rounds": 6241, + "boats": 6242, + "baker": 6243, + "orthodox": 6244, + "depression": 6245, + "formally": 6246, + "worn": 6247, + "naked": 6248, + "claire": 6249, + "muttered": 6250, + "sentence": 6251, + "11th": 6252, + "emily": 6253, + "document": 6254, + "77": 6255, + "criticism": 6256, + "wished": 6257, + "vessel": 6258, + "spiritual": 6259, + "bent": 6260, + "virgin": 6261, + "parker": 6262, + "minimum": 6263, + "murray": 6264, + "lunch": 6265, + "danny": 6266, + "printed": 6267, + "compilation": 6268, + "keyboards": 6269, + "false": 6270, + "blow": 6271, + "belonged": 6272, + "68": 6273, + "raising": 6274, + "78": 6275, + "cutting": 6276, + "##board": 6277, + "pittsburgh": 6278, + "##up": 6279, + "9th": 6280, + "shadows": 6281, + "81": 6282, + "hated": 6283, + "indigenous": 6284, + "jon": 6285, + "15th": 6286, + "barry": 6287, + "scholar": 6288, + "ah": 6289, + "##zer": 6290, + "oliver": 6291, + "##gy": 6292, + "stick": 6293, + "susan": 6294, + "meetings": 6295, + "attracted": 6296, + "spell": 6297, + "romantic": 6298, + "##ver": 6299, + "ye": 6300, + "1895": 6301, + "photo": 6302, + "demanded": 6303, + "customers": 6304, + "##ac": 6305, + "1896": 6306, + "logan": 6307, + "revival": 6308, + "keys": 6309, + "modified": 6310, + "commanded": 6311, + "jeans": 6312, + "##ious": 6313, + "upset": 6314, + "raw": 6315, + "phil": 6316, + "detective": 6317, + "hiding": 6318, + "resident": 6319, + "vincent": 6320, + "##bly": 6321, + "experiences": 6322, + "diamond": 6323, + "defeating": 6324, + "coverage": 6325, + "lucas": 6326, + "external": 6327, + "parks": 6328, + "franchise": 6329, + "helen": 6330, + "bible": 6331, + "successor": 6332, + "percussion": 6333, + "celebrated": 6334, + "il": 6335, + "lift": 6336, + "profile": 6337, + "clan": 6338, + "romania": 6339, + "##ied": 6340, + "mills": 6341, + "##su": 6342, + "nobody": 6343, + "achievement": 6344, + "shrugged": 6345, + "fault": 6346, + "1897": 6347, + "rhythm": 6348, + "initiative": 6349, + "breakfast": 6350, + "carbon": 6351, + "700": 6352, + "69": 6353, + "lasted": 6354, + "violent": 6355, + "74": 6356, + "wound": 6357, + "ken": 6358, + "killer": 6359, + "gradually": 6360, + "filmed": 6361, + "°c": 6362, + "dollars": 6363, + "processing": 6364, + "94": 6365, + "remove": 6366, + "criticized": 6367, + "guests": 6368, + "sang": 6369, + "chemistry": 6370, + "##vin": 6371, + "legislature": 6372, + "disney": 6373, + "##bridge": 6374, + "uniform": 6375, + "escaped": 6376, + "integrated": 6377, + "proposal": 6378, + "purple": 6379, + "denied": 6380, + "liquid": 6381, + "karl": 6382, + "influential": 6383, + "morris": 6384, + "nights": 6385, + "stones": 6386, + "intense": 6387, + "experimental": 6388, + "twisted": 6389, + "71": 6390, + "84": 6391, + "##ld": 6392, + "pace": 6393, + "nazi": 6394, + "mitchell": 6395, + "ny": 6396, + "blind": 6397, + "reporter": 6398, + "newspapers": 6399, + "14th": 6400, + "centers": 6401, + "burn": 6402, + "basin": 6403, + "forgotten": 6404, + "surviving": 6405, + "filed": 6406, + "collections": 6407, + "monastery": 6408, + "losses": 6409, + "manual": 6410, + "couch": 6411, + "description": 6412, + "appropriate": 6413, + "merely": 6414, + "tag": 6415, + "missions": 6416, + "sebastian": 6417, + "restoration": 6418, + "replacing": 6419, + "triple": 6420, + "73": 6421, + "elder": 6422, + "julia": 6423, + "warriors": 6424, + "benjamin": 6425, + "julian": 6426, + "convinced": 6427, + "stronger": 6428, + "amazing": 6429, + "declined": 6430, + "versus": 6431, + "merchant": 6432, + "happens": 6433, + "output": 6434, + "finland": 6435, + "bare": 6436, + "barbara": 6437, + "absence": 6438, + "ignored": 6439, + "dawn": 6440, + "injuries": 6441, + "##port": 6442, + "producers": 6443, + "##ram": 6444, + "82": 6445, + "luis": 6446, + "##ities": 6447, + "kw": 6448, + "admit": 6449, + "expensive": 6450, + "electricity": 6451, + "nba": 6452, + "exception": 6453, + "symbol": 6454, + "##ving": 6455, + "ladies": 6456, + "shower": 6457, + "sheriff": 6458, + "characteristics": 6459, + "##je": 6460, + "aimed": 6461, + "button": 6462, + "ratio": 6463, + "effectively": 6464, + "summit": 6465, + "angle": 6466, + "jury": 6467, + "bears": 6468, + "foster": 6469, + "vessels": 6470, + "pants": 6471, + "executed": 6472, + "evans": 6473, + "dozen": 6474, + "advertising": 6475, + "kicked": 6476, + "patrol": 6477, + "1889": 6478, + "competitions": 6479, + "lifetime": 6480, + "principles": 6481, + "athletics": 6482, + "##logy": 6483, + "birmingham": 6484, + "sponsored": 6485, + "89": 6486, + "rob": 6487, + "nomination": 6488, + "1893": 6489, + "acoustic": 6490, + "##sm": 6491, + "creature": 6492, + "longest": 6493, + "##tra": 6494, + "credits": 6495, + "harbor": 6496, + "dust": 6497, + "josh": 6498, + "##so": 6499, + "territories": 6500, + "milk": 6501, + "infrastructure": 6502, + "completion": 6503, + "thailand": 6504, + "indians": 6505, + "leon": 6506, + "archbishop": 6507, + "##sy": 6508, + "assist": 6509, + "pitch": 6510, + "blake": 6511, + "arrangement": 6512, + "girlfriend": 6513, + "serbian": 6514, + "operational": 6515, + "hence": 6516, + "sad": 6517, + "scent": 6518, + "fur": 6519, + "dj": 6520, + "sessions": 6521, + "hp": 6522, + "refer": 6523, + "rarely": 6524, + "##ora": 6525, + "exists": 6526, + "1892": 6527, + "##ten": 6528, + "scientists": 6529, + "dirty": 6530, + "penalty": 6531, + "burst": 6532, + "portrait": 6533, + "seed": 6534, + "79": 6535, + "pole": 6536, + "limits": 6537, + "rival": 6538, + "1894": 6539, + "stable": 6540, + "alpha": 6541, + "grave": 6542, + "constitutional": 6543, + "alcohol": 6544, + "arrest": 6545, + "flower": 6546, + "mystery": 6547, + "devil": 6548, + "architectural": 6549, + "relationships": 6550, + "greatly": 6551, + "habitat": 6552, + "##istic": 6553, + "larry": 6554, + "progressive": 6555, + "remote": 6556, + "cotton": 6557, + "##ics": 6558, + "##ok": 6559, + "preserved": 6560, + "reaches": 6561, + "##ming": 6562, + "cited": 6563, + "86": 6564, + "vast": 6565, + "scholarship": 6566, + "decisions": 6567, + "cbs": 6568, + "joy": 6569, + "teach": 6570, + "1885": 6571, + "editions": 6572, + "knocked": 6573, + "eve": 6574, + "searching": 6575, + "partly": 6576, + "participation": 6577, + "gap": 6578, + "animated": 6579, + "fate": 6580, + "excellent": 6581, + "##ett": 6582, + "na": 6583, + "87": 6584, + "alternate": 6585, + "saints": 6586, + "youngest": 6587, + "##ily": 6588, + "climbed": 6589, + "##ita": 6590, + "##tors": 6591, + "suggest": 6592, + "##ct": 6593, + "discussion": 6594, + "staying": 6595, + "choir": 6596, + "lakes": 6597, + "jacket": 6598, + "revenue": 6599, + "nevertheless": 6600, + "peaked": 6601, + "instrument": 6602, + "wondering": 6603, + "annually": 6604, + "managing": 6605, + "neil": 6606, + "1891": 6607, + "signing": 6608, + "terry": 6609, + "##ice": 6610, + "apply": 6611, + "clinical": 6612, + "brooklyn": 6613, + "aim": 6614, + "catherine": 6615, + "fuck": 6616, + "farmers": 6617, + "figured": 6618, + "ninth": 6619, + "pride": 6620, + "hugh": 6621, + "evolution": 6622, + "ordinary": 6623, + "involvement": 6624, + "comfortable": 6625, + "shouted": 6626, + "tech": 6627, + "encouraged": 6628, + "taiwan": 6629, + "representation": 6630, + "sharing": 6631, + "##lia": 6632, + "##em": 6633, + "panic": 6634, + "exact": 6635, + "cargo": 6636, + "competing": 6637, + "fat": 6638, + "cried": 6639, + "83": 6640, + "1920s": 6641, + "occasions": 6642, + "pa": 6643, + "cabin": 6644, + "borders": 6645, + "utah": 6646, + "marcus": 6647, + "##isation": 6648, + "badly": 6649, + "muscles": 6650, + "##ance": 6651, + "victorian": 6652, + "transition": 6653, + "warner": 6654, + "bet": 6655, + "permission": 6656, + "##rin": 6657, + "slave": 6658, + "terrible": 6659, + "similarly": 6660, + "shares": 6661, + "seth": 6662, + "uefa": 6663, + "possession": 6664, + "medals": 6665, + "benefits": 6666, + "colleges": 6667, + "lowered": 6668, + "perfectly": 6669, + "mall": 6670, + "transit": 6671, + "##ye": 6672, + "##kar": 6673, + "publisher": 6674, + "##ened": 6675, + "harrison": 6676, + "deaths": 6677, + "elevation": 6678, + "##ae": 6679, + "asleep": 6680, + "machines": 6681, + "sigh": 6682, + "ash": 6683, + "hardly": 6684, + "argument": 6685, + "occasion": 6686, + "parent": 6687, + "leo": 6688, + "decline": 6689, + "1888": 6690, + "contribution": 6691, + "##ua": 6692, + "concentration": 6693, + "1000": 6694, + "opportunities": 6695, + "hispanic": 6696, + "guardian": 6697, + "extent": 6698, + "emotions": 6699, + "hips": 6700, + "mason": 6701, + "volumes": 6702, + "bloody": 6703, + "controversy": 6704, + "diameter": 6705, + "steady": 6706, + "mistake": 6707, + "phoenix": 6708, + "identify": 6709, + "violin": 6710, + "##sk": 6711, + "departure": 6712, + "richmond": 6713, + "spin": 6714, + "funeral": 6715, + "enemies": 6716, + "1864": 6717, + "gear": 6718, + "literally": 6719, + "connor": 6720, + "random": 6721, + "sergeant": 6722, + "grab": 6723, + "confusion": 6724, + "1865": 6725, + "transmission": 6726, + "informed": 6727, + "op": 6728, + "leaning": 6729, + "sacred": 6730, + "suspended": 6731, + "thinks": 6732, + "gates": 6733, + "portland": 6734, + "luck": 6735, + "agencies": 6736, + "yours": 6737, + "hull": 6738, + "expert": 6739, + "muscle": 6740, + "layer": 6741, + "practical": 6742, + "sculpture": 6743, + "jerusalem": 6744, + "latest": 6745, + "lloyd": 6746, + "statistics": 6747, + "deeper": 6748, + "recommended": 6749, + "warrior": 6750, + "arkansas": 6751, + "mess": 6752, + "supports": 6753, + "greg": 6754, + "eagle": 6755, + "1880": 6756, + "recovered": 6757, + "rated": 6758, + "concerts": 6759, + "rushed": 6760, + "##ano": 6761, + "stops": 6762, + "eggs": 6763, + "files": 6764, + "premiere": 6765, + "keith": 6766, + "##vo": 6767, + "delhi": 6768, + "turner": 6769, + "pit": 6770, + "affair": 6771, + "belief": 6772, + "paint": 6773, + "##zing": 6774, + "mate": 6775, + "##ach": 6776, + "##ev": 6777, + "victim": 6778, + "##ology": 6779, + "withdrew": 6780, + "bonus": 6781, + "styles": 6782, + "fled": 6783, + "##ud": 6784, + "glasgow": 6785, + "technologies": 6786, + "funded": 6787, + "nbc": 6788, + "adaptation": 6789, + "##ata": 6790, + "portrayed": 6791, + "cooperation": 6792, + "supporters": 6793, + "judges": 6794, + "bernard": 6795, + "justin": 6796, + "hallway": 6797, + "ralph": 6798, + "##ick": 6799, + "graduating": 6800, + "controversial": 6801, + "distant": 6802, + "continental": 6803, + "spider": 6804, + "bite": 6805, + "##ho": 6806, + "recognize": 6807, + "intention": 6808, + "mixing": 6809, + "##ese": 6810, + "egyptian": 6811, + "bow": 6812, + "tourism": 6813, + "suppose": 6814, + "claiming": 6815, + "tiger": 6816, + "dominated": 6817, + "participants": 6818, + "vi": 6819, + "##ru": 6820, + "nurse": 6821, + "partially": 6822, + "tape": 6823, + "##rum": 6824, + "psychology": 6825, + "##rn": 6826, + "essential": 6827, + "touring": 6828, + "duo": 6829, + "voting": 6830, + "civilian": 6831, + "emotional": 6832, + "channels": 6833, + "##king": 6834, + "apparent": 6835, + "hebrew": 6836, + "1887": 6837, + "tommy": 6838, + "carrier": 6839, + "intersection": 6840, + "beast": 6841, + "hudson": 6842, + "##gar": 6843, + "##zo": 6844, + "lab": 6845, + "nova": 6846, + "bench": 6847, + "discuss": 6848, + "costa": 6849, + "##ered": 6850, + "detailed": 6851, + "behalf": 6852, + "drivers": 6853, + "unfortunately": 6854, + "obtain": 6855, + "##lis": 6856, + "rocky": 6857, + "##dae": 6858, + "siege": 6859, + "friendship": 6860, + "honey": 6861, + "##rian": 6862, + "1861": 6863, + "amy": 6864, + "hang": 6865, + "posted": 6866, + "governments": 6867, + "collins": 6868, + "respond": 6869, + "wildlife": 6870, + "preferred": 6871, + "operator": 6872, + "##po": 6873, + "laura": 6874, + "pregnant": 6875, + "videos": 6876, + "dennis": 6877, + "suspected": 6878, + "boots": 6879, + "instantly": 6880, + "weird": 6881, + "automatic": 6882, + "businessman": 6883, + "alleged": 6884, + "placing": 6885, + "throwing": 6886, + "ph": 6887, + "mood": 6888, + "1862": 6889, + "perry": 6890, + "venue": 6891, + "jet": 6892, + "remainder": 6893, + "##lli": 6894, + "##ci": 6895, + "passion": 6896, + "biological": 6897, + "boyfriend": 6898, + "1863": 6899, + "dirt": 6900, + "buffalo": 6901, + "ron": 6902, + "segment": 6903, + "fa": 6904, + "abuse": 6905, + "##era": 6906, + "genre": 6907, + "thrown": 6908, + "stroke": 6909, + "colored": 6910, + "stress": 6911, + "exercise": 6912, + "displayed": 6913, + "##gen": 6914, + "struggled": 6915, + "##tti": 6916, + "abroad": 6917, + "dramatic": 6918, + "wonderful": 6919, + "thereafter": 6920, + "madrid": 6921, + "component": 6922, + "widespread": 6923, + "##sed": 6924, + "tale": 6925, + "citizen": 6926, + "todd": 6927, + "monday": 6928, + "1886": 6929, + "vancouver": 6930, + "overseas": 6931, + "forcing": 6932, + "crying": 6933, + "descent": 6934, + "##ris": 6935, + "discussed": 6936, + "substantial": 6937, + "ranks": 6938, + "regime": 6939, + "1870": 6940, + "provinces": 6941, + "switch": 6942, + "drum": 6943, + "zane": 6944, + "ted": 6945, + "tribes": 6946, + "proof": 6947, + "lp": 6948, + "cream": 6949, + "researchers": 6950, + "volunteer": 6951, + "manor": 6952, + "silk": 6953, + "milan": 6954, + "donated": 6955, + "allies": 6956, + "venture": 6957, + "principle": 6958, + "delivery": 6959, + "enterprise": 6960, + "##ves": 6961, + "##ans": 6962, + "bars": 6963, + "traditionally": 6964, + "witch": 6965, + "reminded": 6966, + "copper": 6967, + "##uk": 6968, + "pete": 6969, + "inter": 6970, + "links": 6971, + "colin": 6972, + "grinned": 6973, + "elsewhere": 6974, + "competitive": 6975, + "frequent": 6976, + "##oy": 6977, + "scream": 6978, + "##hu": 6979, + "tension": 6980, + "texts": 6981, + "submarine": 6982, + "finnish": 6983, + "defending": 6984, + "defend": 6985, + "pat": 6986, + "detail": 6987, + "1884": 6988, + "affiliated": 6989, + "stuart": 6990, + "themes": 6991, + "villa": 6992, + "periods": 6993, + "tool": 6994, + "belgian": 6995, + "ruling": 6996, + "crimes": 6997, + "answers": 6998, + "folded": 6999, + "licensed": 7000, + "resort": 7001, + "demolished": 7002, + "hans": 7003, + "lucy": 7004, + "1881": 7005, + "lion": 7006, + "traded": 7007, + "photographs": 7008, + "writes": 7009, + "craig": 7010, + "##fa": 7011, + "trials": 7012, + "generated": 7013, + "beth": 7014, + "noble": 7015, + "debt": 7016, + "percentage": 7017, + "yorkshire": 7018, + "erected": 7019, + "ss": 7020, + "viewed": 7021, + "grades": 7022, + "confidence": 7023, + "ceased": 7024, + "islam": 7025, + "telephone": 7026, + "retail": 7027, + "##ible": 7028, + "chile": 7029, + "m²": 7030, + "roberts": 7031, + "sixteen": 7032, + "##ich": 7033, + "commented": 7034, + "hampshire": 7035, + "innocent": 7036, + "dual": 7037, + "pounds": 7038, + "checked": 7039, + "regulations": 7040, + "afghanistan": 7041, + "sung": 7042, + "rico": 7043, + "liberty": 7044, + "assets": 7045, + "bigger": 7046, + "options": 7047, + "angels": 7048, + "relegated": 7049, + "tribute": 7050, + "wells": 7051, + "attending": 7052, + "leaf": 7053, + "##yan": 7054, + "butler": 7055, + "romanian": 7056, + "forum": 7057, + "monthly": 7058, + "lisa": 7059, + "patterns": 7060, + "gmina": 7061, + "##tory": 7062, + "madison": 7063, + "hurricane": 7064, + "rev": 7065, + "##ians": 7066, + "bristol": 7067, + "##ula": 7068, + "elite": 7069, + "valuable": 7070, + "disaster": 7071, + "democracy": 7072, + "awareness": 7073, + "germans": 7074, + "freyja": 7075, + "##ins": 7076, + "loop": 7077, + "absolutely": 7078, + "paying": 7079, + "populations": 7080, + "maine": 7081, + "sole": 7082, + "prayer": 7083, + "spencer": 7084, + "releases": 7085, + "doorway": 7086, + "bull": 7087, + "##ani": 7088, + "lover": 7089, + "midnight": 7090, + "conclusion": 7091, + "##sson": 7092, + "thirteen": 7093, + "lily": 7094, + "mediterranean": 7095, + "##lt": 7096, + "nhl": 7097, + "proud": 7098, + "sample": 7099, + "##hill": 7100, + "drummer": 7101, + "guinea": 7102, + "##ova": 7103, + "murphy": 7104, + "climb": 7105, + "##ston": 7106, + "instant": 7107, + "attributed": 7108, + "horn": 7109, + "ain": 7110, + "railways": 7111, + "steven": 7112, + "##ao": 7113, + "autumn": 7114, + "ferry": 7115, + "opponent": 7116, + "root": 7117, + "traveling": 7118, + "secured": 7119, + "corridor": 7120, + "stretched": 7121, + "tales": 7122, + "sheet": 7123, + "trinity": 7124, + "cattle": 7125, + "helps": 7126, + "indicates": 7127, + "manhattan": 7128, + "murdered": 7129, + "fitted": 7130, + "1882": 7131, + "gentle": 7132, + "grandmother": 7133, + "mines": 7134, + "shocked": 7135, + "vegas": 7136, + "produces": 7137, + "##light": 7138, + "caribbean": 7139, + "##ou": 7140, + "belong": 7141, + "continuous": 7142, + "desperate": 7143, + "drunk": 7144, + "historically": 7145, + "trio": 7146, + "waved": 7147, + "raf": 7148, + "dealing": 7149, + "nathan": 7150, + "bat": 7151, + "murmured": 7152, + "interrupted": 7153, + "residing": 7154, + "scientist": 7155, + "pioneer": 7156, + "harold": 7157, + "aaron": 7158, + "##net": 7159, + "delta": 7160, + "attempting": 7161, + "minority": 7162, + "mini": 7163, + "believes": 7164, + "chorus": 7165, + "tend": 7166, + "lots": 7167, + "eyed": 7168, + "indoor": 7169, + "load": 7170, + "shots": 7171, + "updated": 7172, + "jail": 7173, + "##llo": 7174, + "concerning": 7175, + "connecting": 7176, + "wealth": 7177, + "##ved": 7178, + "slaves": 7179, + "arrive": 7180, + "rangers": 7181, + "sufficient": 7182, + "rebuilt": 7183, + "##wick": 7184, + "cardinal": 7185, + "flood": 7186, + "muhammad": 7187, + "whenever": 7188, + "relation": 7189, + "runners": 7190, + "moral": 7191, + "repair": 7192, + "viewers": 7193, + "arriving": 7194, + "revenge": 7195, + "punk": 7196, + "assisted": 7197, + "bath": 7198, + "fairly": 7199, + "breathe": 7200, + "lists": 7201, + "innings": 7202, + "illustrated": 7203, + "whisper": 7204, + "nearest": 7205, + "voters": 7206, + "clinton": 7207, + "ties": 7208, + "ultimate": 7209, + "screamed": 7210, + "beijing": 7211, + "lions": 7212, + "andre": 7213, + "fictional": 7214, + "gathering": 7215, + "comfort": 7216, + "radar": 7217, + "suitable": 7218, + "dismissed": 7219, + "hms": 7220, + "ban": 7221, + "pine": 7222, + "wrist": 7223, + "atmosphere": 7224, + "voivodeship": 7225, + "bid": 7226, + "timber": 7227, + "##ned": 7228, + "##nan": 7229, + "giants": 7230, + "##ane": 7231, + "cameron": 7232, + "recovery": 7233, + "uss": 7234, + "identical": 7235, + "categories": 7236, + "switched": 7237, + "serbia": 7238, + "laughter": 7239, + "noah": 7240, + "ensemble": 7241, + "therapy": 7242, + "peoples": 7243, + "touching": 7244, + "##off": 7245, + "locally": 7246, + "pearl": 7247, + "platforms": 7248, + "everywhere": 7249, + "ballet": 7250, + "tables": 7251, + "lanka": 7252, + "herbert": 7253, + "outdoor": 7254, + "toured": 7255, + "derek": 7256, + "1883": 7257, + "spaces": 7258, + "contested": 7259, + "swept": 7260, + "1878": 7261, + "exclusive": 7262, + "slight": 7263, + "connections": 7264, + "##dra": 7265, + "winds": 7266, + "prisoner": 7267, + "collective": 7268, + "bangladesh": 7269, + "tube": 7270, + "publicly": 7271, + "wealthy": 7272, + "thai": 7273, + "##ys": 7274, + "isolated": 7275, + "select": 7276, + "##ric": 7277, + "insisted": 7278, + "pen": 7279, + "fortune": 7280, + "ticket": 7281, + "spotted": 7282, + "reportedly": 7283, + "animation": 7284, + "enforcement": 7285, + "tanks": 7286, + "110": 7287, + "decides": 7288, + "wider": 7289, + "lowest": 7290, + "owen": 7291, + "##time": 7292, + "nod": 7293, + "hitting": 7294, + "##hn": 7295, + "gregory": 7296, + "furthermore": 7297, + "magazines": 7298, + "fighters": 7299, + "solutions": 7300, + "##ery": 7301, + "pointing": 7302, + "requested": 7303, + "peru": 7304, + "reed": 7305, + "chancellor": 7306, + "knights": 7307, + "mask": 7308, + "worker": 7309, + "eldest": 7310, + "flames": 7311, + "reduction": 7312, + "1860": 7313, + "volunteers": 7314, + "##tis": 7315, + "reporting": 7316, + "##hl": 7317, + "wire": 7318, + "advisory": 7319, + "endemic": 7320, + "origins": 7321, + "settlers": 7322, + "pursue": 7323, + "knock": 7324, + "consumer": 7325, + "1876": 7326, + "eu": 7327, + "compound": 7328, + "creatures": 7329, + "mansion": 7330, + "sentenced": 7331, + "ivan": 7332, + "deployed": 7333, + "guitars": 7334, + "frowned": 7335, + "involves": 7336, + "mechanism": 7337, + "kilometers": 7338, + "perspective": 7339, + "shops": 7340, + "maps": 7341, + "terminus": 7342, + "duncan": 7343, + "alien": 7344, + "fist": 7345, + "bridges": 7346, + "##pers": 7347, + "heroes": 7348, + "fed": 7349, + "derby": 7350, + "swallowed": 7351, + "##ros": 7352, + "patent": 7353, + "sara": 7354, + "illness": 7355, + "characterized": 7356, + "adventures": 7357, + "slide": 7358, + "hawaii": 7359, + "jurisdiction": 7360, + "##op": 7361, + "organised": 7362, + "##side": 7363, + "adelaide": 7364, + "walks": 7365, + "biology": 7366, + "se": 7367, + "##ties": 7368, + "rogers": 7369, + "swing": 7370, + "tightly": 7371, + "boundaries": 7372, + "##rie": 7373, + "prepare": 7374, + "implementation": 7375, + "stolen": 7376, + "##sha": 7377, + "certified": 7378, + "colombia": 7379, + "edwards": 7380, + "garage": 7381, + "##mm": 7382, + "recalled": 7383, + "##ball": 7384, + "rage": 7385, + "harm": 7386, + "nigeria": 7387, + "breast": 7388, + "##ren": 7389, + "furniture": 7390, + "pupils": 7391, + "settle": 7392, + "##lus": 7393, + "cuba": 7394, + "balls": 7395, + "client": 7396, + "alaska": 7397, + "21st": 7398, + "linear": 7399, + "thrust": 7400, + "celebration": 7401, + "latino": 7402, + "genetic": 7403, + "terror": 7404, + "##cia": 7405, + "##ening": 7406, + "lightning": 7407, + "fee": 7408, + "witness": 7409, + "lodge": 7410, + "establishing": 7411, + "skull": 7412, + "##ique": 7413, + "earning": 7414, + "hood": 7415, + "##ei": 7416, + "rebellion": 7417, + "wang": 7418, + "sporting": 7419, + "warned": 7420, + "missile": 7421, + "devoted": 7422, + "activist": 7423, + "porch": 7424, + "worship": 7425, + "fourteen": 7426, + "package": 7427, + "1871": 7428, + "decorated": 7429, + "##shire": 7430, + "housed": 7431, + "##ock": 7432, + "chess": 7433, + "sailed": 7434, + "doctors": 7435, + "oscar": 7436, + "joan": 7437, + "treat": 7438, + "garcia": 7439, + "harbour": 7440, + "jeremy": 7441, + "##ire": 7442, + "traditions": 7443, + "dominant": 7444, + "jacques": 7445, + "##gon": 7446, + "##wan": 7447, + "relocated": 7448, + "1879": 7449, + "amendment": 7450, + "sized": 7451, + "companion": 7452, + "simultaneously": 7453, + "volleyball": 7454, + "spun": 7455, + "acre": 7456, + "increases": 7457, + "stopping": 7458, + "loves": 7459, + "belongs": 7460, + "affect": 7461, + "drafted": 7462, + "tossed": 7463, + "scout": 7464, + "battles": 7465, + "1875": 7466, + "filming": 7467, + "shoved": 7468, + "munich": 7469, + "tenure": 7470, + "vertical": 7471, + "romance": 7472, + "pc": 7473, + "##cher": 7474, + "argue": 7475, + "##ical": 7476, + "craft": 7477, + "ranging": 7478, + "www": 7479, + "opens": 7480, + "honest": 7481, + "tyler": 7482, + "yesterday": 7483, + "virtual": 7484, + "##let": 7485, + "muslims": 7486, + "reveal": 7487, + "snake": 7488, + "immigrants": 7489, + "radical": 7490, + "screaming": 7491, + "speakers": 7492, + "firing": 7493, + "saving": 7494, + "belonging": 7495, + "ease": 7496, + "lighting": 7497, + "prefecture": 7498, + "blame": 7499, + "farmer": 7500, + "hungry": 7501, + "grows": 7502, + "rubbed": 7503, + "beam": 7504, + "sur": 7505, + "subsidiary": 7506, + "##cha": 7507, + "armenian": 7508, + "sao": 7509, + "dropping": 7510, + "conventional": 7511, + "##fer": 7512, + "microsoft": 7513, + "reply": 7514, + "qualify": 7515, + "spots": 7516, + "1867": 7517, + "sweat": 7518, + "festivals": 7519, + "##ken": 7520, + "immigration": 7521, + "physician": 7522, + "discover": 7523, + "exposure": 7524, + "sandy": 7525, + "explanation": 7526, + "isaac": 7527, + "implemented": 7528, + "##fish": 7529, + "hart": 7530, + "initiated": 7531, + "connect": 7532, + "stakes": 7533, + "presents": 7534, + "heights": 7535, + "householder": 7536, + "pleased": 7537, + "tourist": 7538, + "regardless": 7539, + "slip": 7540, + "closest": 7541, + "##ction": 7542, + "surely": 7543, + "sultan": 7544, + "brings": 7545, + "riley": 7546, + "preparation": 7547, + "aboard": 7548, + "slammed": 7549, + "baptist": 7550, + "experiment": 7551, + "ongoing": 7552, + "interstate": 7553, + "organic": 7554, + "playoffs": 7555, + "##ika": 7556, + "1877": 7557, + "130": 7558, + "##tar": 7559, + "hindu": 7560, + "error": 7561, + "tours": 7562, + "tier": 7563, + "plenty": 7564, + "arrangements": 7565, + "talks": 7566, + "trapped": 7567, + "excited": 7568, + "sank": 7569, + "ho": 7570, + "athens": 7571, + "1872": 7572, + "denver": 7573, + "welfare": 7574, + "suburb": 7575, + "athletes": 7576, + "trick": 7577, + "diverse": 7578, + "belly": 7579, + "exclusively": 7580, + "yelled": 7581, + "1868": 7582, + "##med": 7583, + "conversion": 7584, + "##ette": 7585, + "1874": 7586, + "internationally": 7587, + "computers": 7588, + "conductor": 7589, + "abilities": 7590, + "sensitive": 7591, + "hello": 7592, + "dispute": 7593, + "measured": 7594, + "globe": 7595, + "rocket": 7596, + "prices": 7597, + "amsterdam": 7598, + "flights": 7599, + "tigers": 7600, + "inn": 7601, + "municipalities": 7602, + "emotion": 7603, + "references": 7604, + "3d": 7605, + "##mus": 7606, + "explains": 7607, + "airlines": 7608, + "manufactured": 7609, + "pm": 7610, + "archaeological": 7611, + "1873": 7612, + "interpretation": 7613, + "devon": 7614, + "comment": 7615, + "##ites": 7616, + "settlements": 7617, + "kissing": 7618, + "absolute": 7619, + "improvement": 7620, + "suite": 7621, + "impressed": 7622, + "barcelona": 7623, + "sullivan": 7624, + "jefferson": 7625, + "towers": 7626, + "jesse": 7627, + "julie": 7628, + "##tin": 7629, + "##lu": 7630, + "grandson": 7631, + "hi": 7632, + "gauge": 7633, + "regard": 7634, + "rings": 7635, + "interviews": 7636, + "trace": 7637, + "raymond": 7638, + "thumb": 7639, + "departments": 7640, + "burns": 7641, + "serial": 7642, + "bulgarian": 7643, + "scores": 7644, + "demonstrated": 7645, + "##ix": 7646, + "1866": 7647, + "kyle": 7648, + "alberta": 7649, + "underneath": 7650, + "romanized": 7651, + "##ward": 7652, + "relieved": 7653, + "acquisition": 7654, + "phrase": 7655, + "cliff": 7656, + "reveals": 7657, + "han": 7658, + "cuts": 7659, + "merger": 7660, + "custom": 7661, + "##dar": 7662, + "nee": 7663, + "gilbert": 7664, + "graduation": 7665, + "##nts": 7666, + "assessment": 7667, + "cafe": 7668, + "difficulty": 7669, + "demands": 7670, + "swung": 7671, + "democrat": 7672, + "jennifer": 7673, + "commons": 7674, + "1940s": 7675, + "grove": 7676, + "##yo": 7677, + "completing": 7678, + "focuses": 7679, + "sum": 7680, + "substitute": 7681, + "bearing": 7682, + "stretch": 7683, + "reception": 7684, + "##py": 7685, + "reflected": 7686, + "essentially": 7687, + "destination": 7688, + "pairs": 7689, + "##ched": 7690, + "survival": 7691, + "resource": 7692, + "##bach": 7693, + "promoting": 7694, + "doubles": 7695, + "messages": 7696, + "tear": 7697, + "##down": 7698, + "##fully": 7699, + "parade": 7700, + "florence": 7701, + "harvey": 7702, + "incumbent": 7703, + "partial": 7704, + "framework": 7705, + "900": 7706, + "pedro": 7707, + "frozen": 7708, + "procedure": 7709, + "olivia": 7710, + "controls": 7711, + "##mic": 7712, + "shelter": 7713, + "personally": 7714, + "temperatures": 7715, + "##od": 7716, + "brisbane": 7717, + "tested": 7718, + "sits": 7719, + "marble": 7720, + "comprehensive": 7721, + "oxygen": 7722, + "leonard": 7723, + "##kov": 7724, + "inaugural": 7725, + "iranian": 7726, + "referring": 7727, + "quarters": 7728, + "attitude": 7729, + "##ivity": 7730, + "mainstream": 7731, + "lined": 7732, + "mars": 7733, + "dakota": 7734, + "norfolk": 7735, + "unsuccessful": 7736, + "##°": 7737, + "explosion": 7738, + "helicopter": 7739, + "congressional": 7740, + "##sing": 7741, + "inspector": 7742, + "bitch": 7743, + "seal": 7744, + "departed": 7745, + "divine": 7746, + "##ters": 7747, + "coaching": 7748, + "examination": 7749, + "punishment": 7750, + "manufacturer": 7751, + "sink": 7752, + "columns": 7753, + "unincorporated": 7754, + "signals": 7755, + "nevada": 7756, + "squeezed": 7757, + "dylan": 7758, + "dining": 7759, + "photos": 7760, + "martial": 7761, + "manuel": 7762, + "eighteen": 7763, + "elevator": 7764, + "brushed": 7765, + "plates": 7766, + "ministers": 7767, + "ivy": 7768, + "congregation": 7769, + "##len": 7770, + "slept": 7771, + "specialized": 7772, + "taxes": 7773, + "curve": 7774, + "restricted": 7775, + "negotiations": 7776, + "likes": 7777, + "statistical": 7778, + "arnold": 7779, + "inspiration": 7780, + "execution": 7781, + "bold": 7782, + "intermediate": 7783, + "significance": 7784, + "margin": 7785, + "ruler": 7786, + "wheels": 7787, + "gothic": 7788, + "intellectual": 7789, + "dependent": 7790, + "listened": 7791, + "eligible": 7792, + "buses": 7793, + "widow": 7794, + "syria": 7795, + "earn": 7796, + "cincinnati": 7797, + "collapsed": 7798, + "recipient": 7799, + "secrets": 7800, + "accessible": 7801, + "philippine": 7802, + "maritime": 7803, + "goddess": 7804, + "clerk": 7805, + "surrender": 7806, + "breaks": 7807, + "playoff": 7808, + "database": 7809, + "##ified": 7810, + "##lon": 7811, + "ideal": 7812, + "beetle": 7813, + "aspect": 7814, + "soap": 7815, + "regulation": 7816, + "strings": 7817, + "expand": 7818, + "anglo": 7819, + "shorter": 7820, + "crosses": 7821, + "retreat": 7822, + "tough": 7823, + "coins": 7824, + "wallace": 7825, + "directions": 7826, + "pressing": 7827, + "##oon": 7828, + "shipping": 7829, + "locomotives": 7830, + "comparison": 7831, + "topics": 7832, + "nephew": 7833, + "##mes": 7834, + "distinction": 7835, + "honors": 7836, + "travelled": 7837, + "sierra": 7838, + "ibn": 7839, + "##over": 7840, + "fortress": 7841, + "sa": 7842, + "recognised": 7843, + "carved": 7844, + "1869": 7845, + "clients": 7846, + "##dan": 7847, + "intent": 7848, + "##mar": 7849, + "coaches": 7850, + "describing": 7851, + "bread": 7852, + "##ington": 7853, + "beaten": 7854, + "northwestern": 7855, + "##ona": 7856, + "merit": 7857, + "youtube": 7858, + "collapse": 7859, + "challenges": 7860, + "em": 7861, + "historians": 7862, + "objective": 7863, + "submitted": 7864, + "virus": 7865, + "attacking": 7866, + "drake": 7867, + "assume": 7868, + "##ere": 7869, + "diseases": 7870, + "marc": 7871, + "stem": 7872, + "leeds": 7873, + "##cus": 7874, + "##ab": 7875, + "farming": 7876, + "glasses": 7877, + "##lock": 7878, + "visits": 7879, + "nowhere": 7880, + "fellowship": 7881, + "relevant": 7882, + "carries": 7883, + "restaurants": 7884, + "experiments": 7885, + "101": 7886, + "constantly": 7887, + "bases": 7888, + "targets": 7889, + "shah": 7890, + "tenth": 7891, + "opponents": 7892, + "verse": 7893, + "territorial": 7894, + "##ira": 7895, + "writings": 7896, + "corruption": 7897, + "##hs": 7898, + "instruction": 7899, + "inherited": 7900, + "reverse": 7901, + "emphasis": 7902, + "##vic": 7903, + "employee": 7904, + "arch": 7905, + "keeps": 7906, + "rabbi": 7907, + "watson": 7908, + "payment": 7909, + "uh": 7910, + "##ala": 7911, + "nancy": 7912, + "##tre": 7913, + "venice": 7914, + "fastest": 7915, + "sexy": 7916, + "banned": 7917, + "adrian": 7918, + "properly": 7919, + "ruth": 7920, + "touchdown": 7921, + "dollar": 7922, + "boards": 7923, + "metre": 7924, + "circles": 7925, + "edges": 7926, + "favour": 7927, + "comments": 7928, + "ok": 7929, + "travels": 7930, + "liberation": 7931, + "scattered": 7932, + "firmly": 7933, + "##ular": 7934, + "holland": 7935, + "permitted": 7936, + "diesel": 7937, + "kenya": 7938, + "den": 7939, + "originated": 7940, + "##ral": 7941, + "demons": 7942, + "resumed": 7943, + "dragged": 7944, + "rider": 7945, + "##rus": 7946, + "servant": 7947, + "blinked": 7948, + "extend": 7949, + "torn": 7950, + "##ias": 7951, + "##sey": 7952, + "input": 7953, + "meal": 7954, + "everybody": 7955, + "cylinder": 7956, + "kinds": 7957, + "camps": 7958, + "##fe": 7959, + "bullet": 7960, + "logic": 7961, + "##wn": 7962, + "croatian": 7963, + "evolved": 7964, + "healthy": 7965, + "fool": 7966, + "chocolate": 7967, + "wise": 7968, + "preserve": 7969, + "pradesh": 7970, + "##ess": 7971, + "respective": 7972, + "1850": 7973, + "##ew": 7974, + "chicken": 7975, + "artificial": 7976, + "gross": 7977, + "corresponding": 7978, + "convicted": 7979, + "cage": 7980, + "caroline": 7981, + "dialogue": 7982, + "##dor": 7983, + "narrative": 7984, + "stranger": 7985, + "mario": 7986, + "br": 7987, + "christianity": 7988, + "failing": 7989, + "trent": 7990, + "commanding": 7991, + "buddhist": 7992, + "1848": 7993, + "maurice": 7994, + "focusing": 7995, + "yale": 7996, + "bike": 7997, + "altitude": 7998, + "##ering": 7999, + "mouse": 8000, + "revised": 8001, + "##sley": 8002, + "veteran": 8003, + "##ig": 8004, + "pulls": 8005, + "theology": 8006, + "crashed": 8007, + "campaigns": 8008, + "legion": 8009, + "##ability": 8010, + "drag": 8011, + "excellence": 8012, + "customer": 8013, + "cancelled": 8014, + "intensity": 8015, + "excuse": 8016, + "##lar": 8017, + "liga": 8018, + "participating": 8019, + "contributing": 8020, + "printing": 8021, + "##burn": 8022, + "variable": 8023, + "##rk": 8024, + "curious": 8025, + "bin": 8026, + "legacy": 8027, + "renaissance": 8028, + "##my": 8029, + "symptoms": 8030, + "binding": 8031, + "vocalist": 8032, + "dancer": 8033, + "##nie": 8034, + "grammar": 8035, + "gospel": 8036, + "democrats": 8037, + "ya": 8038, + "enters": 8039, + "sc": 8040, + "diplomatic": 8041, + "hitler": 8042, + "##ser": 8043, + "clouds": 8044, + "mathematical": 8045, + "quit": 8046, + "defended": 8047, + "oriented": 8048, + "##heim": 8049, + "fundamental": 8050, + "hardware": 8051, + "impressive": 8052, + "equally": 8053, + "convince": 8054, + "confederate": 8055, + "guilt": 8056, + "chuck": 8057, + "sliding": 8058, + "##ware": 8059, + "magnetic": 8060, + "narrowed": 8061, + "petersburg": 8062, + "bulgaria": 8063, + "otto": 8064, + "phd": 8065, + "skill": 8066, + "##ama": 8067, + "reader": 8068, + "hopes": 8069, + "pitcher": 8070, + "reservoir": 8071, + "hearts": 8072, + "automatically": 8073, + "expecting": 8074, + "mysterious": 8075, + "bennett": 8076, + "extensively": 8077, + "imagined": 8078, + "seeds": 8079, + "monitor": 8080, + "fix": 8081, + "##ative": 8082, + "journalism": 8083, + "struggling": 8084, + "signature": 8085, + "ranch": 8086, + "encounter": 8087, + "photographer": 8088, + "observation": 8089, + "protests": 8090, + "##pin": 8091, + "influences": 8092, + "##hr": 8093, + "calendar": 8094, + "##all": 8095, + "cruz": 8096, + "croatia": 8097, + "locomotive": 8098, + "hughes": 8099, + "naturally": 8100, + "shakespeare": 8101, + "basement": 8102, + "hook": 8103, + "uncredited": 8104, + "faded": 8105, + "theories": 8106, + "approaches": 8107, + "dare": 8108, + "phillips": 8109, + "filling": 8110, + "fury": 8111, + "obama": 8112, + "##ain": 8113, + "efficient": 8114, + "arc": 8115, + "deliver": 8116, + "min": 8117, + "raid": 8118, + "breeding": 8119, + "inducted": 8120, + "leagues": 8121, + "efficiency": 8122, + "axis": 8123, + "montana": 8124, + "eagles": 8125, + "##ked": 8126, + "supplied": 8127, + "instructions": 8128, + "karen": 8129, + "picking": 8130, + "indicating": 8131, + "trap": 8132, + "anchor": 8133, + "practically": 8134, + "christians": 8135, + "tomb": 8136, + "vary": 8137, + "occasional": 8138, + "electronics": 8139, + "lords": 8140, + "readers": 8141, + "newcastle": 8142, + "faint": 8143, + "innovation": 8144, + "collect": 8145, + "situations": 8146, + "engagement": 8147, + "160": 8148, + "claude": 8149, + "mixture": 8150, + "##feld": 8151, + "peer": 8152, + "tissue": 8153, + "logo": 8154, + "lean": 8155, + "##ration": 8156, + "°f": 8157, + "floors": 8158, + "##ven": 8159, + "architects": 8160, + "reducing": 8161, + "##our": 8162, + "##ments": 8163, + "rope": 8164, + "1859": 8165, + "ottawa": 8166, + "##har": 8167, + "samples": 8168, + "banking": 8169, + "declaration": 8170, + "proteins": 8171, + "resignation": 8172, + "francois": 8173, + "saudi": 8174, + "advocate": 8175, + "exhibited": 8176, + "armor": 8177, + "twins": 8178, + "divorce": 8179, + "##ras": 8180, + "abraham": 8181, + "reviewed": 8182, + "jo": 8183, + "temporarily": 8184, + "matrix": 8185, + "physically": 8186, + "pulse": 8187, + "curled": 8188, + "##ena": 8189, + "difficulties": 8190, + "bengal": 8191, + "usage": 8192, + "##ban": 8193, + "annie": 8194, + "riders": 8195, + "certificate": 8196, + "##pi": 8197, + "holes": 8198, + "warsaw": 8199, + "distinctive": 8200, + "jessica": 8201, + "##mon": 8202, + "mutual": 8203, + "1857": 8204, + "customs": 8205, + "circular": 8206, + "eugene": 8207, + "removal": 8208, + "loaded": 8209, + "mere": 8210, + "vulnerable": 8211, + "depicted": 8212, + "generations": 8213, + "dame": 8214, + "heir": 8215, + "enormous": 8216, + "lightly": 8217, + "climbing": 8218, + "pitched": 8219, + "lessons": 8220, + "pilots": 8221, + "nepal": 8222, + "ram": 8223, + "google": 8224, + "preparing": 8225, + "brad": 8226, + "louise": 8227, + "renowned": 8228, + "##₂": 8229, + "liam": 8230, + "##ably": 8231, + "plaza": 8232, + "shaw": 8233, + "sophie": 8234, + "brilliant": 8235, + "bills": 8236, + "##bar": 8237, + "##nik": 8238, + "fucking": 8239, + "mainland": 8240, + "server": 8241, + "pleasant": 8242, + "seized": 8243, + "veterans": 8244, + "jerked": 8245, + "fail": 8246, + "beta": 8247, + "brush": 8248, + "radiation": 8249, + "stored": 8250, + "warmth": 8251, + "southeastern": 8252, + "nate": 8253, + "sin": 8254, + "raced": 8255, + "berkeley": 8256, + "joke": 8257, + "athlete": 8258, + "designation": 8259, + "trunk": 8260, + "##low": 8261, + "roland": 8262, + "qualification": 8263, + "archives": 8264, + "heels": 8265, + "artwork": 8266, + "receives": 8267, + "judicial": 8268, + "reserves": 8269, + "##bed": 8270, + "woke": 8271, + "installation": 8272, + "abu": 8273, + "floating": 8274, + "fake": 8275, + "lesser": 8276, + "excitement": 8277, + "interface": 8278, + "concentrated": 8279, + "addressed": 8280, + "characteristic": 8281, + "amanda": 8282, + "saxophone": 8283, + "monk": 8284, + "auto": 8285, + "##bus": 8286, + "releasing": 8287, + "egg": 8288, + "dies": 8289, + "interaction": 8290, + "defender": 8291, + "ce": 8292, + "outbreak": 8293, + "glory": 8294, + "loving": 8295, + "##bert": 8296, + "sequel": 8297, + "consciousness": 8298, + "http": 8299, + "awake": 8300, + "ski": 8301, + "enrolled": 8302, + "##ress": 8303, + "handling": 8304, + "rookie": 8305, + "brow": 8306, + "somebody": 8307, + "biography": 8308, + "warfare": 8309, + "amounts": 8310, + "contracts": 8311, + "presentation": 8312, + "fabric": 8313, + "dissolved": 8314, + "challenged": 8315, + "meter": 8316, + "psychological": 8317, + "lt": 8318, + "elevated": 8319, + "rally": 8320, + "accurate": 8321, + "##tha": 8322, + "hospitals": 8323, + "undergraduate": 8324, + "specialist": 8325, + "venezuela": 8326, + "exhibit": 8327, + "shed": 8328, + "nursing": 8329, + "protestant": 8330, + "fluid": 8331, + "structural": 8332, + "footage": 8333, + "jared": 8334, + "consistent": 8335, + "prey": 8336, + "##ska": 8337, + "succession": 8338, + "reflect": 8339, + "exile": 8340, + "lebanon": 8341, + "wiped": 8342, + "suspect": 8343, + "shanghai": 8344, + "resting": 8345, + "integration": 8346, + "preservation": 8347, + "marvel": 8348, + "variant": 8349, + "pirates": 8350, + "sheep": 8351, + "rounded": 8352, + "capita": 8353, + "sailing": 8354, + "colonies": 8355, + "manuscript": 8356, + "deemed": 8357, + "variations": 8358, + "clarke": 8359, + "functional": 8360, + "emerging": 8361, + "boxing": 8362, + "relaxed": 8363, + "curse": 8364, + "azerbaijan": 8365, + "heavyweight": 8366, + "nickname": 8367, + "editorial": 8368, + "rang": 8369, + "grid": 8370, + "tightened": 8371, + "earthquake": 8372, + "flashed": 8373, + "miguel": 8374, + "rushing": 8375, + "##ches": 8376, + "improvements": 8377, + "boxes": 8378, + "brooks": 8379, + "180": 8380, + "consumption": 8381, + "molecular": 8382, + "felix": 8383, + "societies": 8384, + "repeatedly": 8385, + "variation": 8386, + "aids": 8387, + "civic": 8388, + "graphics": 8389, + "professionals": 8390, + "realm": 8391, + "autonomous": 8392, + "receiver": 8393, + "delayed": 8394, + "workshop": 8395, + "militia": 8396, + "chairs": 8397, + "trump": 8398, + "canyon": 8399, + "##point": 8400, + "harsh": 8401, + "extending": 8402, + "lovely": 8403, + "happiness": 8404, + "##jan": 8405, + "stake": 8406, + "eyebrows": 8407, + "embassy": 8408, + "wellington": 8409, + "hannah": 8410, + "##ella": 8411, + "sony": 8412, + "corners": 8413, + "bishops": 8414, + "swear": 8415, + "cloth": 8416, + "contents": 8417, + "xi": 8418, + "namely": 8419, + "commenced": 8420, + "1854": 8421, + "stanford": 8422, + "nashville": 8423, + "courage": 8424, + "graphic": 8425, + "commitment": 8426, + "garrison": 8427, + "##bin": 8428, + "hamlet": 8429, + "clearing": 8430, + "rebels": 8431, + "attraction": 8432, + "literacy": 8433, + "cooking": 8434, + "ruins": 8435, + "temples": 8436, + "jenny": 8437, + "humanity": 8438, + "celebrate": 8439, + "hasn": 8440, + "freight": 8441, + "sixty": 8442, + "rebel": 8443, + "bastard": 8444, + "##art": 8445, + "newton": 8446, + "##ada": 8447, + "deer": 8448, + "##ges": 8449, + "##ching": 8450, + "smiles": 8451, + "delaware": 8452, + "singers": 8453, + "##ets": 8454, + "approaching": 8455, + "assists": 8456, + "flame": 8457, + "##ph": 8458, + "boulevard": 8459, + "barrel": 8460, + "planted": 8461, + "##ome": 8462, + "pursuit": 8463, + "##sia": 8464, + "consequences": 8465, + "posts": 8466, + "shallow": 8467, + "invitation": 8468, + "rode": 8469, + "depot": 8470, + "ernest": 8471, + "kane": 8472, + "rod": 8473, + "concepts": 8474, + "preston": 8475, + "topic": 8476, + "chambers": 8477, + "striking": 8478, + "blast": 8479, + "arrives": 8480, + "descendants": 8481, + "montgomery": 8482, + "ranges": 8483, + "worlds": 8484, + "##lay": 8485, + "##ari": 8486, + "span": 8487, + "chaos": 8488, + "praise": 8489, + "##ag": 8490, + "fewer": 8491, + "1855": 8492, + "sanctuary": 8493, + "mud": 8494, + "fbi": 8495, + "##ions": 8496, + "programmes": 8497, + "maintaining": 8498, + "unity": 8499, + "harper": 8500, + "bore": 8501, + "handsome": 8502, + "closure": 8503, + "tournaments": 8504, + "thunder": 8505, + "nebraska": 8506, + "linda": 8507, + "facade": 8508, + "puts": 8509, + "satisfied": 8510, + "argentine": 8511, + "dale": 8512, + "cork": 8513, + "dome": 8514, + "panama": 8515, + "##yl": 8516, + "1858": 8517, + "tasks": 8518, + "experts": 8519, + "##ates": 8520, + "feeding": 8521, + "equation": 8522, + "##las": 8523, + "##ida": 8524, + "##tu": 8525, + "engage": 8526, + "bryan": 8527, + "##ax": 8528, + "um": 8529, + "quartet": 8530, + "melody": 8531, + "disbanded": 8532, + "sheffield": 8533, + "blocked": 8534, + "gasped": 8535, + "delay": 8536, + "kisses": 8537, + "maggie": 8538, + "connects": 8539, + "##non": 8540, + "sts": 8541, + "poured": 8542, + "creator": 8543, + "publishers": 8544, + "##we": 8545, + "guided": 8546, + "ellis": 8547, + "extinct": 8548, + "hug": 8549, + "gaining": 8550, + "##ord": 8551, + "complicated": 8552, + "##bility": 8553, + "poll": 8554, + "clenched": 8555, + "investigate": 8556, + "##use": 8557, + "thereby": 8558, + "quantum": 8559, + "spine": 8560, + "cdp": 8561, + "humor": 8562, + "kills": 8563, + "administered": 8564, + "semifinals": 8565, + "##du": 8566, + "encountered": 8567, + "ignore": 8568, + "##bu": 8569, + "commentary": 8570, + "##maker": 8571, + "bother": 8572, + "roosevelt": 8573, + "140": 8574, + "plains": 8575, + "halfway": 8576, + "flowing": 8577, + "cultures": 8578, + "crack": 8579, + "imprisoned": 8580, + "neighboring": 8581, + "airline": 8582, + "##ses": 8583, + "##view": 8584, + "##mate": 8585, + "##ec": 8586, + "gather": 8587, + "wolves": 8588, + "marathon": 8589, + "transformed": 8590, + "##ill": 8591, + "cruise": 8592, + "organisations": 8593, + "carol": 8594, + "punch": 8595, + "exhibitions": 8596, + "numbered": 8597, + "alarm": 8598, + "ratings": 8599, + "daddy": 8600, + "silently": 8601, + "##stein": 8602, + "queens": 8603, + "colours": 8604, + "impression": 8605, + "guidance": 8606, + "liu": 8607, + "tactical": 8608, + "##rat": 8609, + "marshal": 8610, + "della": 8611, + "arrow": 8612, + "##ings": 8613, + "rested": 8614, + "feared": 8615, + "tender": 8616, + "owns": 8617, + "bitter": 8618, + "advisor": 8619, + "escort": 8620, + "##ides": 8621, + "spare": 8622, + "farms": 8623, + "grants": 8624, + "##ene": 8625, + "dragons": 8626, + "encourage": 8627, + "colleagues": 8628, + "cameras": 8629, + "##und": 8630, + "sucked": 8631, + "pile": 8632, + "spirits": 8633, + "prague": 8634, + "statements": 8635, + "suspension": 8636, + "landmark": 8637, + "fence": 8638, + "torture": 8639, + "recreation": 8640, + "bags": 8641, + "permanently": 8642, + "survivors": 8643, + "pond": 8644, + "spy": 8645, + "predecessor": 8646, + "bombing": 8647, + "coup": 8648, + "##og": 8649, + "protecting": 8650, + "transformation": 8651, + "glow": 8652, + "##lands": 8653, + "##book": 8654, + "dug": 8655, + "priests": 8656, + "andrea": 8657, + "feat": 8658, + "barn": 8659, + "jumping": 8660, + "##chen": 8661, + "##ologist": 8662, + "##con": 8663, + "casualties": 8664, + "stern": 8665, + "auckland": 8666, + "pipe": 8667, + "serie": 8668, + "revealing": 8669, + "ba": 8670, + "##bel": 8671, + "trevor": 8672, + "mercy": 8673, + "spectrum": 8674, + "yang": 8675, + "consist": 8676, + "governing": 8677, + "collaborated": 8678, + "possessed": 8679, + "epic": 8680, + "comprises": 8681, + "blew": 8682, + "shane": 8683, + "##ack": 8684, + "lopez": 8685, + "honored": 8686, + "magical": 8687, + "sacrifice": 8688, + "judgment": 8689, + "perceived": 8690, + "hammer": 8691, + "mtv": 8692, + "baronet": 8693, + "tune": 8694, + "das": 8695, + "missionary": 8696, + "sheets": 8697, + "350": 8698, + "neutral": 8699, + "oral": 8700, + "threatening": 8701, + "attractive": 8702, + "shade": 8703, + "aims": 8704, + "seminary": 8705, + "##master": 8706, + "estates": 8707, + "1856": 8708, + "michel": 8709, + "wounds": 8710, + "refugees": 8711, + "manufacturers": 8712, + "##nic": 8713, + "mercury": 8714, + "syndrome": 8715, + "porter": 8716, + "##iya": 8717, + "##din": 8718, + "hamburg": 8719, + "identification": 8720, + "upstairs": 8721, + "purse": 8722, + "widened": 8723, + "pause": 8724, + "cared": 8725, + "breathed": 8726, + "affiliate": 8727, + "santiago": 8728, + "prevented": 8729, + "celtic": 8730, + "fisher": 8731, + "125": 8732, + "recruited": 8733, + "byzantine": 8734, + "reconstruction": 8735, + "farther": 8736, + "##mp": 8737, + "diet": 8738, + "sake": 8739, + "au": 8740, + "spite": 8741, + "sensation": 8742, + "##ert": 8743, + "blank": 8744, + "separation": 8745, + "105": 8746, + "##hon": 8747, + "vladimir": 8748, + "armies": 8749, + "anime": 8750, + "##lie": 8751, + "accommodate": 8752, + "orbit": 8753, + "cult": 8754, + "sofia": 8755, + "archive": 8756, + "##ify": 8757, + "##box": 8758, + "founders": 8759, + "sustained": 8760, + "disorder": 8761, + "honours": 8762, + "northeastern": 8763, + "mia": 8764, + "crops": 8765, + "violet": 8766, + "threats": 8767, + "blanket": 8768, + "fires": 8769, + "canton": 8770, + "followers": 8771, + "southwestern": 8772, + "prototype": 8773, + "voyage": 8774, + "assignment": 8775, + "altered": 8776, + "moderate": 8777, + "protocol": 8778, + "pistol": 8779, + "##eo": 8780, + "questioned": 8781, + "brass": 8782, + "lifting": 8783, + "1852": 8784, + "math": 8785, + "authored": 8786, + "##ual": 8787, + "doug": 8788, + "dimensional": 8789, + "dynamic": 8790, + "##san": 8791, + "1851": 8792, + "pronounced": 8793, + "grateful": 8794, + "quest": 8795, + "uncomfortable": 8796, + "boom": 8797, + "presidency": 8798, + "stevens": 8799, + "relating": 8800, + "politicians": 8801, + "chen": 8802, + "barrier": 8803, + "quinn": 8804, + "diana": 8805, + "mosque": 8806, + "tribal": 8807, + "cheese": 8808, + "palmer": 8809, + "portions": 8810, + "sometime": 8811, + "chester": 8812, + "treasure": 8813, + "wu": 8814, + "bend": 8815, + "download": 8816, + "millions": 8817, + "reforms": 8818, + "registration": 8819, + "##osa": 8820, + "consequently": 8821, + "monitoring": 8822, + "ate": 8823, + "preliminary": 8824, + "brandon": 8825, + "invented": 8826, + "ps": 8827, + "eaten": 8828, + "exterior": 8829, + "intervention": 8830, + "ports": 8831, + "documented": 8832, + "log": 8833, + "displays": 8834, + "lecture": 8835, + "sally": 8836, + "favourite": 8837, + "##itz": 8838, + "vermont": 8839, + "lo": 8840, + "invisible": 8841, + "isle": 8842, + "breed": 8843, + "##ator": 8844, + "journalists": 8845, + "relay": 8846, + "speaks": 8847, + "backward": 8848, + "explore": 8849, + "midfielder": 8850, + "actively": 8851, + "stefan": 8852, + "procedures": 8853, + "cannon": 8854, + "blond": 8855, + "kenneth": 8856, + "centered": 8857, + "servants": 8858, + "chains": 8859, + "libraries": 8860, + "malcolm": 8861, + "essex": 8862, + "henri": 8863, + "slavery": 8864, + "##hal": 8865, + "facts": 8866, + "fairy": 8867, + "coached": 8868, + "cassie": 8869, + "cats": 8870, + "washed": 8871, + "cop": 8872, + "##fi": 8873, + "announcement": 8874, + "item": 8875, + "2000s": 8876, + "vinyl": 8877, + "activated": 8878, + "marco": 8879, + "frontier": 8880, + "growled": 8881, + "curriculum": 8882, + "##das": 8883, + "loyal": 8884, + "accomplished": 8885, + "leslie": 8886, + "ritual": 8887, + "kenny": 8888, + "##00": 8889, + "vii": 8890, + "napoleon": 8891, + "hollow": 8892, + "hybrid": 8893, + "jungle": 8894, + "stationed": 8895, + "friedrich": 8896, + "counted": 8897, + "##ulated": 8898, + "platinum": 8899, + "theatrical": 8900, + "seated": 8901, + "col": 8902, + "rubber": 8903, + "glen": 8904, + "1840": 8905, + "diversity": 8906, + "healing": 8907, + "extends": 8908, + "id": 8909, + "provisions": 8910, + "administrator": 8911, + "columbus": 8912, + "##oe": 8913, + "tributary": 8914, + "te": 8915, + "assured": 8916, + "org": 8917, + "##uous": 8918, + "prestigious": 8919, + "examined": 8920, + "lectures": 8921, + "grammy": 8922, + "ronald": 8923, + "associations": 8924, + "bailey": 8925, + "allan": 8926, + "essays": 8927, + "flute": 8928, + "believing": 8929, + "consultant": 8930, + "proceedings": 8931, + "travelling": 8932, + "1853": 8933, + "kit": 8934, + "kerala": 8935, + "yugoslavia": 8936, + "buddy": 8937, + "methodist": 8938, + "##ith": 8939, + "burial": 8940, + "centres": 8941, + "batman": 8942, + "##nda": 8943, + "discontinued": 8944, + "bo": 8945, + "dock": 8946, + "stockholm": 8947, + "lungs": 8948, + "severely": 8949, + "##nk": 8950, + "citing": 8951, + "manga": 8952, + "##ugh": 8953, + "steal": 8954, + "mumbai": 8955, + "iraqi": 8956, + "robot": 8957, + "celebrity": 8958, + "bride": 8959, + "broadcasts": 8960, + "abolished": 8961, + "pot": 8962, + "joel": 8963, + "overhead": 8964, + "franz": 8965, + "packed": 8966, + "reconnaissance": 8967, + "johann": 8968, + "acknowledged": 8969, + "introduce": 8970, + "handled": 8971, + "doctorate": 8972, + "developments": 8973, + "drinks": 8974, + "alley": 8975, + "palestine": 8976, + "##nis": 8977, + "##aki": 8978, + "proceeded": 8979, + "recover": 8980, + "bradley": 8981, + "grain": 8982, + "patch": 8983, + "afford": 8984, + "infection": 8985, + "nationalist": 8986, + "legendary": 8987, + "##ath": 8988, + "interchange": 8989, + "virtually": 8990, + "gen": 8991, + "gravity": 8992, + "exploration": 8993, + "amber": 8994, + "vital": 8995, + "wishes": 8996, + "powell": 8997, + "doctrine": 8998, + "elbow": 8999, + "screenplay": 9000, + "##bird": 9001, + "contribute": 9002, + "indonesian": 9003, + "pet": 9004, + "creates": 9005, + "##com": 9006, + "enzyme": 9007, + "kylie": 9008, + "discipline": 9009, + "drops": 9010, + "manila": 9011, + "hunger": 9012, + "##ien": 9013, + "layers": 9014, + "suffer": 9015, + "fever": 9016, + "bits": 9017, + "monica": 9018, + "keyboard": 9019, + "manages": 9020, + "##hood": 9021, + "searched": 9022, + "appeals": 9023, + "##bad": 9024, + "testament": 9025, + "grande": 9026, + "reid": 9027, + "##war": 9028, + "beliefs": 9029, + "congo": 9030, + "##ification": 9031, + "##dia": 9032, + "si": 9033, + "requiring": 9034, + "##via": 9035, + "casey": 9036, + "1849": 9037, + "regret": 9038, + "streak": 9039, + "rape": 9040, + "depends": 9041, + "syrian": 9042, + "sprint": 9043, + "pound": 9044, + "tourists": 9045, + "upcoming": 9046, + "pub": 9047, + "##xi": 9048, + "tense": 9049, + "##els": 9050, + "practiced": 9051, + "echo": 9052, + "nationwide": 9053, + "guild": 9054, + "motorcycle": 9055, + "liz": 9056, + "##zar": 9057, + "chiefs": 9058, + "desired": 9059, + "elena": 9060, + "bye": 9061, + "precious": 9062, + "absorbed": 9063, + "relatives": 9064, + "booth": 9065, + "pianist": 9066, + "##mal": 9067, + "citizenship": 9068, + "exhausted": 9069, + "wilhelm": 9070, + "##ceae": 9071, + "##hed": 9072, + "noting": 9073, + "quarterback": 9074, + "urge": 9075, + "hectares": 9076, + "##gue": 9077, + "ace": 9078, + "holly": 9079, + "##tal": 9080, + "blonde": 9081, + "davies": 9082, + "parked": 9083, + "sustainable": 9084, + "stepping": 9085, + "twentieth": 9086, + "airfield": 9087, + "galaxy": 9088, + "nest": 9089, + "chip": 9090, + "##nell": 9091, + "tan": 9092, + "shaft": 9093, + "paulo": 9094, + "requirement": 9095, + "##zy": 9096, + "paradise": 9097, + "tobacco": 9098, + "trans": 9099, + "renewed": 9100, + "vietnamese": 9101, + "##cker": 9102, + "##ju": 9103, + "suggesting": 9104, + "catching": 9105, + "holmes": 9106, + "enjoying": 9107, + "md": 9108, + "trips": 9109, + "colt": 9110, + "holder": 9111, + "butterfly": 9112, + "nerve": 9113, + "reformed": 9114, + "cherry": 9115, + "bowling": 9116, + "trailer": 9117, + "carriage": 9118, + "goodbye": 9119, + "appreciate": 9120, + "toy": 9121, + "joshua": 9122, + "interactive": 9123, + "enabled": 9124, + "involve": 9125, + "##kan": 9126, + "collar": 9127, + "determination": 9128, + "bunch": 9129, + "facebook": 9130, + "recall": 9131, + "shorts": 9132, + "superintendent": 9133, + "episcopal": 9134, + "frustration": 9135, + "giovanni": 9136, + "nineteenth": 9137, + "laser": 9138, + "privately": 9139, + "array": 9140, + "circulation": 9141, + "##ovic": 9142, + "armstrong": 9143, + "deals": 9144, + "painful": 9145, + "permit": 9146, + "discrimination": 9147, + "##wi": 9148, + "aires": 9149, + "retiring": 9150, + "cottage": 9151, + "ni": 9152, + "##sta": 9153, + "horizon": 9154, + "ellen": 9155, + "jamaica": 9156, + "ripped": 9157, + "fernando": 9158, + "chapters": 9159, + "playstation": 9160, + "patron": 9161, + "lecturer": 9162, + "navigation": 9163, + "behaviour": 9164, + "genes": 9165, + "georgian": 9166, + "export": 9167, + "solomon": 9168, + "rivals": 9169, + "swift": 9170, + "seventeen": 9171, + "rodriguez": 9172, + "princeton": 9173, + "independently": 9174, + "sox": 9175, + "1847": 9176, + "arguing": 9177, + "entity": 9178, + "casting": 9179, + "hank": 9180, + "criteria": 9181, + "oakland": 9182, + "geographic": 9183, + "milwaukee": 9184, + "reflection": 9185, + "expanding": 9186, + "conquest": 9187, + "dubbed": 9188, + "##tv": 9189, + "halt": 9190, + "brave": 9191, + "brunswick": 9192, + "doi": 9193, + "arched": 9194, + "curtis": 9195, + "divorced": 9196, + "predominantly": 9197, + "somerset": 9198, + "streams": 9199, + "ugly": 9200, + "zoo": 9201, + "horrible": 9202, + "curved": 9203, + "buenos": 9204, + "fierce": 9205, + "dictionary": 9206, + "vector": 9207, + "theological": 9208, + "unions": 9209, + "handful": 9210, + "stability": 9211, + "chan": 9212, + "punjab": 9213, + "segments": 9214, + "##lly": 9215, + "altar": 9216, + "ignoring": 9217, + "gesture": 9218, + "monsters": 9219, + "pastor": 9220, + "##stone": 9221, + "thighs": 9222, + "unexpected": 9223, + "operators": 9224, + "abruptly": 9225, + "coin": 9226, + "compiled": 9227, + "associates": 9228, + "improving": 9229, + "migration": 9230, + "pin": 9231, + "##ose": 9232, + "compact": 9233, + "collegiate": 9234, + "reserved": 9235, + "##urs": 9236, + "quarterfinals": 9237, + "roster": 9238, + "restore": 9239, + "assembled": 9240, + "hurry": 9241, + "oval": 9242, + "##cies": 9243, + "1846": 9244, + "flags": 9245, + "martha": 9246, + "##del": 9247, + "victories": 9248, + "sharply": 9249, + "##rated": 9250, + "argues": 9251, + "deadly": 9252, + "neo": 9253, + "drawings": 9254, + "symbols": 9255, + "performer": 9256, + "##iel": 9257, + "griffin": 9258, + "restrictions": 9259, + "editing": 9260, + "andrews": 9261, + "java": 9262, + "journals": 9263, + "arabia": 9264, + "compositions": 9265, + "dee": 9266, + "pierce": 9267, + "removing": 9268, + "hindi": 9269, + "casino": 9270, + "runway": 9271, + "civilians": 9272, + "minds": 9273, + "nasa": 9274, + "hotels": 9275, + "##zation": 9276, + "refuge": 9277, + "rent": 9278, + "retain": 9279, + "potentially": 9280, + "conferences": 9281, + "suburban": 9282, + "conducting": 9283, + "##tto": 9284, + "##tions": 9285, + "##tle": 9286, + "descended": 9287, + "massacre": 9288, + "##cal": 9289, + "ammunition": 9290, + "terrain": 9291, + "fork": 9292, + "souls": 9293, + "counts": 9294, + "chelsea": 9295, + "durham": 9296, + "drives": 9297, + "cab": 9298, + "##bank": 9299, + "perth": 9300, + "realizing": 9301, + "palestinian": 9302, + "finn": 9303, + "simpson": 9304, + "##dal": 9305, + "betty": 9306, + "##ule": 9307, + "moreover": 9308, + "particles": 9309, + "cardinals": 9310, + "tent": 9311, + "evaluation": 9312, + "extraordinary": 9313, + "##oid": 9314, + "inscription": 9315, + "##works": 9316, + "wednesday": 9317, + "chloe": 9318, + "maintains": 9319, + "panels": 9320, + "ashley": 9321, + "trucks": 9322, + "##nation": 9323, + "cluster": 9324, + "sunlight": 9325, + "strikes": 9326, + "zhang": 9327, + "##wing": 9328, + "dialect": 9329, + "canon": 9330, + "##ap": 9331, + "tucked": 9332, + "##ws": 9333, + "collecting": 9334, + "##mas": 9335, + "##can": 9336, + "##sville": 9337, + "maker": 9338, + "quoted": 9339, + "evan": 9340, + "franco": 9341, + "aria": 9342, + "buying": 9343, + "cleaning": 9344, + "eva": 9345, + "closet": 9346, + "provision": 9347, + "apollo": 9348, + "clinic": 9349, + "rat": 9350, + "##ez": 9351, + "necessarily": 9352, + "ac": 9353, + "##gle": 9354, + "##ising": 9355, + "venues": 9356, + "flipped": 9357, + "cent": 9358, + "spreading": 9359, + "trustees": 9360, + "checking": 9361, + "authorized": 9362, + "##sco": 9363, + "disappointed": 9364, + "##ado": 9365, + "notion": 9366, + "duration": 9367, + "trumpet": 9368, + "hesitated": 9369, + "topped": 9370, + "brussels": 9371, + "rolls": 9372, + "theoretical": 9373, + "hint": 9374, + "define": 9375, + "aggressive": 9376, + "repeat": 9377, + "wash": 9378, + "peaceful": 9379, + "optical": 9380, + "width": 9381, + "allegedly": 9382, + "mcdonald": 9383, + "strict": 9384, + "copyright": 9385, + "##illa": 9386, + "investors": 9387, + "mar": 9388, + "jam": 9389, + "witnesses": 9390, + "sounding": 9391, + "miranda": 9392, + "michelle": 9393, + "privacy": 9394, + "hugo": 9395, + "harmony": 9396, + "##pp": 9397, + "valid": 9398, + "lynn": 9399, + "glared": 9400, + "nina": 9401, + "102": 9402, + "headquartered": 9403, + "diving": 9404, + "boarding": 9405, + "gibson": 9406, + "##ncy": 9407, + "albanian": 9408, + "marsh": 9409, + "routine": 9410, + "dealt": 9411, + "enhanced": 9412, + "er": 9413, + "intelligent": 9414, + "substance": 9415, + "targeted": 9416, + "enlisted": 9417, + "discovers": 9418, + "spinning": 9419, + "observations": 9420, + "pissed": 9421, + "smoking": 9422, + "rebecca": 9423, + "capitol": 9424, + "visa": 9425, + "varied": 9426, + "costume": 9427, + "seemingly": 9428, + "indies": 9429, + "compensation": 9430, + "surgeon": 9431, + "thursday": 9432, + "arsenal": 9433, + "westminster": 9434, + "suburbs": 9435, + "rid": 9436, + "anglican": 9437, + "##ridge": 9438, + "knots": 9439, + "foods": 9440, + "alumni": 9441, + "lighter": 9442, + "fraser": 9443, + "whoever": 9444, + "portal": 9445, + "scandal": 9446, + "##ray": 9447, + "gavin": 9448, + "advised": 9449, + "instructor": 9450, + "flooding": 9451, + "terrorist": 9452, + "##ale": 9453, + "teenage": 9454, + "interim": 9455, + "senses": 9456, + "duck": 9457, + "teen": 9458, + "thesis": 9459, + "abby": 9460, + "eager": 9461, + "overcome": 9462, + "##ile": 9463, + "newport": 9464, + "glenn": 9465, + "rises": 9466, + "shame": 9467, + "##cc": 9468, + "prompted": 9469, + "priority": 9470, + "forgot": 9471, + "bomber": 9472, + "nicolas": 9473, + "protective": 9474, + "360": 9475, + "cartoon": 9476, + "katherine": 9477, + "breeze": 9478, + "lonely": 9479, + "trusted": 9480, + "henderson": 9481, + "richardson": 9482, + "relax": 9483, + "banner": 9484, + "candy": 9485, + "palms": 9486, + "remarkable": 9487, + "##rio": 9488, + "legends": 9489, + "cricketer": 9490, + "essay": 9491, + "ordained": 9492, + "edmund": 9493, + "rifles": 9494, + "trigger": 9495, + "##uri": 9496, + "##away": 9497, + "sail": 9498, + "alert": 9499, + "1830": 9500, + "audiences": 9501, + "penn": 9502, + "sussex": 9503, + "siblings": 9504, + "pursued": 9505, + "indianapolis": 9506, + "resist": 9507, + "rosa": 9508, + "consequence": 9509, + "succeed": 9510, + "avoided": 9511, + "1845": 9512, + "##ulation": 9513, + "inland": 9514, + "##tie": 9515, + "##nna": 9516, + "counsel": 9517, + "profession": 9518, + "chronicle": 9519, + "hurried": 9520, + "##una": 9521, + "eyebrow": 9522, + "eventual": 9523, + "bleeding": 9524, + "innovative": 9525, + "cure": 9526, + "##dom": 9527, + "committees": 9528, + "accounting": 9529, + "con": 9530, + "scope": 9531, + "hardy": 9532, + "heather": 9533, + "tenor": 9534, + "gut": 9535, + "herald": 9536, + "codes": 9537, + "tore": 9538, + "scales": 9539, + "wagon": 9540, + "##oo": 9541, + "luxury": 9542, + "tin": 9543, + "prefer": 9544, + "fountain": 9545, + "triangle": 9546, + "bonds": 9547, + "darling": 9548, + "convoy": 9549, + "dried": 9550, + "traced": 9551, + "beings": 9552, + "troy": 9553, + "accidentally": 9554, + "slam": 9555, + "findings": 9556, + "smelled": 9557, + "joey": 9558, + "lawyers": 9559, + "outcome": 9560, + "steep": 9561, + "bosnia": 9562, + "configuration": 9563, + "shifting": 9564, + "toll": 9565, + "brook": 9566, + "performers": 9567, + "lobby": 9568, + "philosophical": 9569, + "construct": 9570, + "shrine": 9571, + "aggregate": 9572, + "boot": 9573, + "cox": 9574, + "phenomenon": 9575, + "savage": 9576, + "insane": 9577, + "solely": 9578, + "reynolds": 9579, + "lifestyle": 9580, + "##ima": 9581, + "nationally": 9582, + "holdings": 9583, + "consideration": 9584, + "enable": 9585, + "edgar": 9586, + "mo": 9587, + "mama": 9588, + "##tein": 9589, + "fights": 9590, + "relegation": 9591, + "chances": 9592, + "atomic": 9593, + "hub": 9594, + "conjunction": 9595, + "awkward": 9596, + "reactions": 9597, + "currency": 9598, + "finale": 9599, + "kumar": 9600, + "underwent": 9601, + "steering": 9602, + "elaborate": 9603, + "gifts": 9604, + "comprising": 9605, + "melissa": 9606, + "veins": 9607, + "reasonable": 9608, + "sunshine": 9609, + "chi": 9610, + "solve": 9611, + "trails": 9612, + "inhabited": 9613, + "elimination": 9614, + "ethics": 9615, + "huh": 9616, + "ana": 9617, + "molly": 9618, + "consent": 9619, + "apartments": 9620, + "layout": 9621, + "marines": 9622, + "##ces": 9623, + "hunters": 9624, + "bulk": 9625, + "##oma": 9626, + "hometown": 9627, + "##wall": 9628, + "##mont": 9629, + "cracked": 9630, + "reads": 9631, + "neighbouring": 9632, + "withdrawn": 9633, + "admission": 9634, + "wingspan": 9635, + "damned": 9636, + "anthology": 9637, + "lancashire": 9638, + "brands": 9639, + "batting": 9640, + "forgive": 9641, + "cuban": 9642, + "awful": 9643, + "##lyn": 9644, + "104": 9645, + "dimensions": 9646, + "imagination": 9647, + "##ade": 9648, + "dante": 9649, + "##ship": 9650, + "tracking": 9651, + "desperately": 9652, + "goalkeeper": 9653, + "##yne": 9654, + "groaned": 9655, + "workshops": 9656, + "confident": 9657, + "burton": 9658, + "gerald": 9659, + "milton": 9660, + "circus": 9661, + "uncertain": 9662, + "slope": 9663, + "copenhagen": 9664, + "sophia": 9665, + "fog": 9666, + "philosopher": 9667, + "portraits": 9668, + "accent": 9669, + "cycling": 9670, + "varying": 9671, + "gripped": 9672, + "larvae": 9673, + "garrett": 9674, + "specified": 9675, + "scotia": 9676, + "mature": 9677, + "luther": 9678, + "kurt": 9679, + "rap": 9680, + "##kes": 9681, + "aerial": 9682, + "750": 9683, + "ferdinand": 9684, + "heated": 9685, + "es": 9686, + "transported": 9687, + "##shan": 9688, + "safely": 9689, + "nonetheless": 9690, + "##orn": 9691, + "##gal": 9692, + "motors": 9693, + "demanding": 9694, + "##sburg": 9695, + "startled": 9696, + "##brook": 9697, + "ally": 9698, + "generate": 9699, + "caps": 9700, + "ghana": 9701, + "stained": 9702, + "demo": 9703, + "mentions": 9704, + "beds": 9705, + "ap": 9706, + "afterward": 9707, + "diary": 9708, + "##bling": 9709, + "utility": 9710, + "##iro": 9711, + "richards": 9712, + "1837": 9713, + "conspiracy": 9714, + "conscious": 9715, + "shining": 9716, + "footsteps": 9717, + "observer": 9718, + "cyprus": 9719, + "urged": 9720, + "loyalty": 9721, + "developer": 9722, + "probability": 9723, + "olive": 9724, + "upgraded": 9725, + "gym": 9726, + "miracle": 9727, + "insects": 9728, + "graves": 9729, + "1844": 9730, + "ourselves": 9731, + "hydrogen": 9732, + "amazon": 9733, + "katie": 9734, + "tickets": 9735, + "poets": 9736, + "##pm": 9737, + "planes": 9738, + "##pan": 9739, + "prevention": 9740, + "witnessed": 9741, + "dense": 9742, + "jin": 9743, + "randy": 9744, + "tang": 9745, + "warehouse": 9746, + "monroe": 9747, + "bang": 9748, + "archived": 9749, + "elderly": 9750, + "investigations": 9751, + "alec": 9752, + "granite": 9753, + "mineral": 9754, + "conflicts": 9755, + "controlling": 9756, + "aboriginal": 9757, + "carlo": 9758, + "##zu": 9759, + "mechanics": 9760, + "stan": 9761, + "stark": 9762, + "rhode": 9763, + "skirt": 9764, + "est": 9765, + "##berry": 9766, + "bombs": 9767, + "respected": 9768, + "##horn": 9769, + "imposed": 9770, + "limestone": 9771, + "deny": 9772, + "nominee": 9773, + "memphis": 9774, + "grabbing": 9775, + "disabled": 9776, + "##als": 9777, + "amusement": 9778, + "aa": 9779, + "frankfurt": 9780, + "corn": 9781, + "referendum": 9782, + "varies": 9783, + "slowed": 9784, + "disk": 9785, + "firms": 9786, + "unconscious": 9787, + "incredible": 9788, + "clue": 9789, + "sue": 9790, + "##zhou": 9791, + "twist": 9792, + "##cio": 9793, + "joins": 9794, + "idaho": 9795, + "chad": 9796, + "developers": 9797, + "computing": 9798, + "destroyer": 9799, + "103": 9800, + "mortal": 9801, + "tucker": 9802, + "kingston": 9803, + "choices": 9804, + "yu": 9805, + "carson": 9806, + "1800": 9807, + "os": 9808, + "whitney": 9809, + "geneva": 9810, + "pretend": 9811, + "dimension": 9812, + "staged": 9813, + "plateau": 9814, + "maya": 9815, + "##une": 9816, + "freestyle": 9817, + "##bc": 9818, + "rovers": 9819, + "hiv": 9820, + "##ids": 9821, + "tristan": 9822, + "classroom": 9823, + "prospect": 9824, + "##hus": 9825, + "honestly": 9826, + "diploma": 9827, + "lied": 9828, + "thermal": 9829, + "auxiliary": 9830, + "feast": 9831, + "unlikely": 9832, + "iata": 9833, + "##tel": 9834, + "morocco": 9835, + "pounding": 9836, + "treasury": 9837, + "lithuania": 9838, + "considerably": 9839, + "1841": 9840, + "dish": 9841, + "1812": 9842, + "geological": 9843, + "matching": 9844, + "stumbled": 9845, + "destroying": 9846, + "marched": 9847, + "brien": 9848, + "advances": 9849, + "cake": 9850, + "nicole": 9851, + "belle": 9852, + "settling": 9853, + "measuring": 9854, + "directing": 9855, + "##mie": 9856, + "tuesday": 9857, + "bassist": 9858, + "capabilities": 9859, + "stunned": 9860, + "fraud": 9861, + "torpedo": 9862, + "##list": 9863, + "##phone": 9864, + "anton": 9865, + "wisdom": 9866, + "surveillance": 9867, + "ruined": 9868, + "##ulate": 9869, + "lawsuit": 9870, + "healthcare": 9871, + "theorem": 9872, + "halls": 9873, + "trend": 9874, + "aka": 9875, + "horizontal": 9876, + "dozens": 9877, + "acquire": 9878, + "lasting": 9879, + "swim": 9880, + "hawk": 9881, + "gorgeous": 9882, + "fees": 9883, + "vicinity": 9884, + "decrease": 9885, + "adoption": 9886, + "tactics": 9887, + "##ography": 9888, + "pakistani": 9889, + "##ole": 9890, + "draws": 9891, + "##hall": 9892, + "willie": 9893, + "burke": 9894, + "heath": 9895, + "algorithm": 9896, + "integral": 9897, + "powder": 9898, + "elliott": 9899, + "brigadier": 9900, + "jackie": 9901, + "tate": 9902, + "varieties": 9903, + "darker": 9904, + "##cho": 9905, + "lately": 9906, + "cigarette": 9907, + "specimens": 9908, + "adds": 9909, + "##ree": 9910, + "##ensis": 9911, + "##inger": 9912, + "exploded": 9913, + "finalist": 9914, + "cia": 9915, + "murders": 9916, + "wilderness": 9917, + "arguments": 9918, + "nicknamed": 9919, + "acceptance": 9920, + "onwards": 9921, + "manufacture": 9922, + "robertson": 9923, + "jets": 9924, + "tampa": 9925, + "enterprises": 9926, + "blog": 9927, + "loudly": 9928, + "composers": 9929, + "nominations": 9930, + "1838": 9931, + "ai": 9932, + "malta": 9933, + "inquiry": 9934, + "automobile": 9935, + "hosting": 9936, + "viii": 9937, + "rays": 9938, + "tilted": 9939, + "grief": 9940, + "museums": 9941, + "strategies": 9942, + "furious": 9943, + "euro": 9944, + "equality": 9945, + "cohen": 9946, + "poison": 9947, + "surrey": 9948, + "wireless": 9949, + "governed": 9950, + "ridiculous": 9951, + "moses": 9952, + "##esh": 9953, + "##room": 9954, + "vanished": 9955, + "##ito": 9956, + "barnes": 9957, + "attract": 9958, + "morrison": 9959, + "istanbul": 9960, + "##iness": 9961, + "absent": 9962, + "rotation": 9963, + "petition": 9964, + "janet": 9965, + "##logical": 9966, + "satisfaction": 9967, + "custody": 9968, + "deliberately": 9969, + "observatory": 9970, + "comedian": 9971, + "surfaces": 9972, + "pinyin": 9973, + "novelist": 9974, + "strictly": 9975, + "canterbury": 9976, + "oslo": 9977, + "monks": 9978, + "embrace": 9979, + "ibm": 9980, + "jealous": 9981, + "photograph": 9982, + "continent": 9983, + "dorothy": 9984, + "marina": 9985, + "doc": 9986, + "excess": 9987, + "holden": 9988, + "allegations": 9989, + "explaining": 9990, + "stack": 9991, + "avoiding": 9992, + "lance": 9993, + "storyline": 9994, + "majesty": 9995, + "poorly": 9996, + "spike": 9997, + "dos": 9998, + "bradford": 9999, + "raven": 10000, + "travis": 10001, + "classics": 10002, + "proven": 10003, + "voltage": 10004, + "pillow": 10005, + "fists": 10006, + "butt": 10007, + "1842": 10008, + "interpreted": 10009, + "##car": 10010, + "1839": 10011, + "gage": 10012, + "telegraph": 10013, + "lens": 10014, + "promising": 10015, + "expelled": 10016, + "casual": 10017, + "collector": 10018, + "zones": 10019, + "##min": 10020, + "silly": 10021, + "nintendo": 10022, + "##kh": 10023, + "##bra": 10024, + "downstairs": 10025, + "chef": 10026, + "suspicious": 10027, + "afl": 10028, + "flies": 10029, + "vacant": 10030, + "uganda": 10031, + "pregnancy": 10032, + "condemned": 10033, + "lutheran": 10034, + "estimates": 10035, + "cheap": 10036, + "decree": 10037, + "saxon": 10038, + "proximity": 10039, + "stripped": 10040, + "idiot": 10041, + "deposits": 10042, + "contrary": 10043, + "presenter": 10044, + "magnus": 10045, + "glacier": 10046, + "im": 10047, + "offense": 10048, + "edwin": 10049, + "##ori": 10050, + "upright": 10051, + "##long": 10052, + "bolt": 10053, + "##ois": 10054, + "toss": 10055, + "geographical": 10056, + "##izes": 10057, + "environments": 10058, + "delicate": 10059, + "marking": 10060, + "abstract": 10061, + "xavier": 10062, + "nails": 10063, + "windsor": 10064, + "plantation": 10065, + "occurring": 10066, + "equity": 10067, + "saskatchewan": 10068, + "fears": 10069, + "drifted": 10070, + "sequences": 10071, + "vegetation": 10072, + "revolt": 10073, + "##stic": 10074, + "1843": 10075, + "sooner": 10076, + "fusion": 10077, + "opposing": 10078, + "nato": 10079, + "skating": 10080, + "1836": 10081, + "secretly": 10082, + "ruin": 10083, + "lease": 10084, + "##oc": 10085, + "edit": 10086, + "##nne": 10087, + "flora": 10088, + "anxiety": 10089, + "ruby": 10090, + "##ological": 10091, + "##mia": 10092, + "tel": 10093, + "bout": 10094, + "taxi": 10095, + "emmy": 10096, + "frost": 10097, + "rainbow": 10098, + "compounds": 10099, + "foundations": 10100, + "rainfall": 10101, + "assassination": 10102, + "nightmare": 10103, + "dominican": 10104, + "##win": 10105, + "achievements": 10106, + "deserve": 10107, + "orlando": 10108, + "intact": 10109, + "armenia": 10110, + "##nte": 10111, + "calgary": 10112, + "valentine": 10113, + "106": 10114, + "marion": 10115, + "proclaimed": 10116, + "theodore": 10117, + "bells": 10118, + "courtyard": 10119, + "thigh": 10120, + "gonzalez": 10121, + "console": 10122, + "troop": 10123, + "minimal": 10124, + "monte": 10125, + "everyday": 10126, + "##ence": 10127, + "##if": 10128, + "supporter": 10129, + "terrorism": 10130, + "buck": 10131, + "openly": 10132, + "presbyterian": 10133, + "activists": 10134, + "carpet": 10135, + "##iers": 10136, + "rubbing": 10137, + "uprising": 10138, + "##yi": 10139, + "cute": 10140, + "conceived": 10141, + "legally": 10142, + "##cht": 10143, + "millennium": 10144, + "cello": 10145, + "velocity": 10146, + "ji": 10147, + "rescued": 10148, + "cardiff": 10149, + "1835": 10150, + "rex": 10151, + "concentrate": 10152, + "senators": 10153, + "beard": 10154, + "rendered": 10155, + "glowing": 10156, + "battalions": 10157, + "scouts": 10158, + "competitors": 10159, + "sculptor": 10160, + "catalogue": 10161, + "arctic": 10162, + "ion": 10163, + "raja": 10164, + "bicycle": 10165, + "wow": 10166, + "glancing": 10167, + "lawn": 10168, + "##woman": 10169, + "gentleman": 10170, + "lighthouse": 10171, + "publish": 10172, + "predicted": 10173, + "calculated": 10174, + "##val": 10175, + "variants": 10176, + "##gne": 10177, + "strain": 10178, + "##ui": 10179, + "winston": 10180, + "deceased": 10181, + "##nus": 10182, + "touchdowns": 10183, + "brady": 10184, + "caleb": 10185, + "sinking": 10186, + "echoed": 10187, + "crush": 10188, + "hon": 10189, + "blessed": 10190, + "protagonist": 10191, + "hayes": 10192, + "endangered": 10193, + "magnitude": 10194, + "editors": 10195, + "##tine": 10196, + "estimate": 10197, + "responsibilities": 10198, + "##mel": 10199, + "backup": 10200, + "laying": 10201, + "consumed": 10202, + "sealed": 10203, + "zurich": 10204, + "lovers": 10205, + "frustrated": 10206, + "##eau": 10207, + "ahmed": 10208, + "kicking": 10209, + "mit": 10210, + "treasurer": 10211, + "1832": 10212, + "biblical": 10213, + "refuse": 10214, + "terrified": 10215, + "pump": 10216, + "agrees": 10217, + "genuine": 10218, + "imprisonment": 10219, + "refuses": 10220, + "plymouth": 10221, + "##hen": 10222, + "lou": 10223, + "##nen": 10224, + "tara": 10225, + "trembling": 10226, + "antarctic": 10227, + "ton": 10228, + "learns": 10229, + "##tas": 10230, + "crap": 10231, + "crucial": 10232, + "faction": 10233, + "atop": 10234, + "##borough": 10235, + "wrap": 10236, + "lancaster": 10237, + "odds": 10238, + "hopkins": 10239, + "erik": 10240, + "lyon": 10241, + "##eon": 10242, + "bros": 10243, + "##ode": 10244, + "snap": 10245, + "locality": 10246, + "tips": 10247, + "empress": 10248, + "crowned": 10249, + "cal": 10250, + "acclaimed": 10251, + "chuckled": 10252, + "##ory": 10253, + "clara": 10254, + "sends": 10255, + "mild": 10256, + "towel": 10257, + "##fl": 10258, + "##day": 10259, + "##а": 10260, + "wishing": 10261, + "assuming": 10262, + "interviewed": 10263, + "##bal": 10264, + "##die": 10265, + "interactions": 10266, + "eden": 10267, + "cups": 10268, + "helena": 10269, + "##lf": 10270, + "indie": 10271, + "beck": 10272, + "##fire": 10273, + "batteries": 10274, + "filipino": 10275, + "wizard": 10276, + "parted": 10277, + "##lam": 10278, + "traces": 10279, + "##born": 10280, + "rows": 10281, + "idol": 10282, + "albany": 10283, + "delegates": 10284, + "##ees": 10285, + "##sar": 10286, + "discussions": 10287, + "##ex": 10288, + "notre": 10289, + "instructed": 10290, + "belgrade": 10291, + "highways": 10292, + "suggestion": 10293, + "lauren": 10294, + "possess": 10295, + "orientation": 10296, + "alexandria": 10297, + "abdul": 10298, + "beats": 10299, + "salary": 10300, + "reunion": 10301, + "ludwig": 10302, + "alright": 10303, + "wagner": 10304, + "intimate": 10305, + "pockets": 10306, + "slovenia": 10307, + "hugged": 10308, + "brighton": 10309, + "merchants": 10310, + "cruel": 10311, + "stole": 10312, + "trek": 10313, + "slopes": 10314, + "repairs": 10315, + "enrollment": 10316, + "politically": 10317, + "underlying": 10318, + "promotional": 10319, + "counting": 10320, + "boeing": 10321, + "##bb": 10322, + "isabella": 10323, + "naming": 10324, + "##и": 10325, + "keen": 10326, + "bacteria": 10327, + "listing": 10328, + "separately": 10329, + "belfast": 10330, + "ussr": 10331, + "450": 10332, + "lithuanian": 10333, + "anybody": 10334, + "ribs": 10335, + "sphere": 10336, + "martinez": 10337, + "cock": 10338, + "embarrassed": 10339, + "proposals": 10340, + "fragments": 10341, + "nationals": 10342, + "##fs": 10343, + "##wski": 10344, + "premises": 10345, + "fin": 10346, + "1500": 10347, + "alpine": 10348, + "matched": 10349, + "freely": 10350, + "bounded": 10351, + "jace": 10352, + "sleeve": 10353, + "##af": 10354, + "gaming": 10355, + "pier": 10356, + "populated": 10357, + "evident": 10358, + "##like": 10359, + "frances": 10360, + "flooded": 10361, + "##dle": 10362, + "frightened": 10363, + "pour": 10364, + "trainer": 10365, + "framed": 10366, + "visitor": 10367, + "challenging": 10368, + "pig": 10369, + "wickets": 10370, + "##fold": 10371, + "infected": 10372, + "email": 10373, + "##pes": 10374, + "arose": 10375, + "##aw": 10376, + "reward": 10377, + "ecuador": 10378, + "oblast": 10379, + "vale": 10380, + "ch": 10381, + "shuttle": 10382, + "##usa": 10383, + "bach": 10384, + "rankings": 10385, + "forbidden": 10386, + "cornwall": 10387, + "accordance": 10388, + "salem": 10389, + "consumers": 10390, + "bruno": 10391, + "fantastic": 10392, + "toes": 10393, + "machinery": 10394, + "resolved": 10395, + "julius": 10396, + "remembering": 10397, + "propaganda": 10398, + "iceland": 10399, + "bombardment": 10400, + "tide": 10401, + "contacts": 10402, + "wives": 10403, + "##rah": 10404, + "concerto": 10405, + "macdonald": 10406, + "albania": 10407, + "implement": 10408, + "daisy": 10409, + "tapped": 10410, + "sudan": 10411, + "helmet": 10412, + "angela": 10413, + "mistress": 10414, + "##lic": 10415, + "crop": 10416, + "sunk": 10417, + "finest": 10418, + "##craft": 10419, + "hostile": 10420, + "##ute": 10421, + "##tsu": 10422, + "boxer": 10423, + "fr": 10424, + "paths": 10425, + "adjusted": 10426, + "habit": 10427, + "ballot": 10428, + "supervision": 10429, + "soprano": 10430, + "##zen": 10431, + "bullets": 10432, + "wicked": 10433, + "sunset": 10434, + "regiments": 10435, + "disappear": 10436, + "lamp": 10437, + "performs": 10438, + "app": 10439, + "##gia": 10440, + "##oa": 10441, + "rabbit": 10442, + "digging": 10443, + "incidents": 10444, + "entries": 10445, + "##cion": 10446, + "dishes": 10447, + "##oi": 10448, + "introducing": 10449, + "##ati": 10450, + "##fied": 10451, + "freshman": 10452, + "slot": 10453, + "jill": 10454, + "tackles": 10455, + "baroque": 10456, + "backs": 10457, + "##iest": 10458, + "lone": 10459, + "sponsor": 10460, + "destiny": 10461, + "altogether": 10462, + "convert": 10463, + "##aro": 10464, + "consensus": 10465, + "shapes": 10466, + "demonstration": 10467, + "basically": 10468, + "feminist": 10469, + "auction": 10470, + "artifacts": 10471, + "##bing": 10472, + "strongest": 10473, + "twitter": 10474, + "halifax": 10475, + "2019": 10476, + "allmusic": 10477, + "mighty": 10478, + "smallest": 10479, + "precise": 10480, + "alexandra": 10481, + "viola": 10482, + "##los": 10483, + "##ille": 10484, + "manuscripts": 10485, + "##illo": 10486, + "dancers": 10487, + "ari": 10488, + "managers": 10489, + "monuments": 10490, + "blades": 10491, + "barracks": 10492, + "springfield": 10493, + "maiden": 10494, + "consolidated": 10495, + "electron": 10496, + "##end": 10497, + "berry": 10498, + "airing": 10499, + "wheat": 10500, + "nobel": 10501, + "inclusion": 10502, + "blair": 10503, + "payments": 10504, + "geography": 10505, + "bee": 10506, + "cc": 10507, + "eleanor": 10508, + "react": 10509, + "##hurst": 10510, + "afc": 10511, + "manitoba": 10512, + "##yu": 10513, + "su": 10514, + "lineup": 10515, + "fitness": 10516, + "recreational": 10517, + "investments": 10518, + "airborne": 10519, + "disappointment": 10520, + "##dis": 10521, + "edmonton": 10522, + "viewing": 10523, + "##row": 10524, + "renovation": 10525, + "##cast": 10526, + "infant": 10527, + "bankruptcy": 10528, + "roses": 10529, + "aftermath": 10530, + "pavilion": 10531, + "##yer": 10532, + "carpenter": 10533, + "withdrawal": 10534, + "ladder": 10535, + "##hy": 10536, + "discussing": 10537, + "popped": 10538, + "reliable": 10539, + "agreements": 10540, + "rochester": 10541, + "##abad": 10542, + "curves": 10543, + "bombers": 10544, + "220": 10545, + "rao": 10546, + "reverend": 10547, + "decreased": 10548, + "choosing": 10549, + "107": 10550, + "stiff": 10551, + "consulting": 10552, + "naples": 10553, + "crawford": 10554, + "tracy": 10555, + "ka": 10556, + "ribbon": 10557, + "cops": 10558, + "##lee": 10559, + "crushed": 10560, + "deciding": 10561, + "unified": 10562, + "teenager": 10563, + "accepting": 10564, + "flagship": 10565, + "explorer": 10566, + "poles": 10567, + "sanchez": 10568, + "inspection": 10569, + "revived": 10570, + "skilled": 10571, + "induced": 10572, + "exchanged": 10573, + "flee": 10574, + "locals": 10575, + "tragedy": 10576, + "swallow": 10577, + "loading": 10578, + "hanna": 10579, + "demonstrate": 10580, + "##ela": 10581, + "salvador": 10582, + "flown": 10583, + "contestants": 10584, + "civilization": 10585, + "##ines": 10586, + "wanna": 10587, + "rhodes": 10588, + "fletcher": 10589, + "hector": 10590, + "knocking": 10591, + "considers": 10592, + "##ough": 10593, + "nash": 10594, + "mechanisms": 10595, + "sensed": 10596, + "mentally": 10597, + "walt": 10598, + "unclear": 10599, + "##eus": 10600, + "renovated": 10601, + "madame": 10602, + "##cks": 10603, + "crews": 10604, + "governmental": 10605, + "##hin": 10606, + "undertaken": 10607, + "monkey": 10608, + "##ben": 10609, + "##ato": 10610, + "fatal": 10611, + "armored": 10612, + "copa": 10613, + "caves": 10614, + "governance": 10615, + "grasp": 10616, + "perception": 10617, + "certification": 10618, + "froze": 10619, + "damp": 10620, + "tugged": 10621, + "wyoming": 10622, + "##rg": 10623, + "##ero": 10624, + "newman": 10625, + "##lor": 10626, + "nerves": 10627, + "curiosity": 10628, + "graph": 10629, + "115": 10630, + "##ami": 10631, + "withdraw": 10632, + "tunnels": 10633, + "dull": 10634, + "meredith": 10635, + "moss": 10636, + "exhibits": 10637, + "neighbors": 10638, + "communicate": 10639, + "accuracy": 10640, + "explored": 10641, + "raiders": 10642, + "republicans": 10643, + "secular": 10644, + "kat": 10645, + "superman": 10646, + "penny": 10647, + "criticised": 10648, + "##tch": 10649, + "freed": 10650, + "update": 10651, + "conviction": 10652, + "wade": 10653, + "ham": 10654, + "likewise": 10655, + "delegation": 10656, + "gotta": 10657, + "doll": 10658, + "promises": 10659, + "technological": 10660, + "myth": 10661, + "nationality": 10662, + "resolve": 10663, + "convent": 10664, + "##mark": 10665, + "sharon": 10666, + "dig": 10667, + "sip": 10668, + "coordinator": 10669, + "entrepreneur": 10670, + "fold": 10671, + "##dine": 10672, + "capability": 10673, + "councillor": 10674, + "synonym": 10675, + "blown": 10676, + "swan": 10677, + "cursed": 10678, + "1815": 10679, + "jonas": 10680, + "haired": 10681, + "sofa": 10682, + "canvas": 10683, + "keeper": 10684, + "rivalry": 10685, + "##hart": 10686, + "rapper": 10687, + "speedway": 10688, + "swords": 10689, + "postal": 10690, + "maxwell": 10691, + "estonia": 10692, + "potter": 10693, + "recurring": 10694, + "##nn": 10695, + "##ave": 10696, + "errors": 10697, + "##oni": 10698, + "cognitive": 10699, + "1834": 10700, + "##²": 10701, + "claws": 10702, + "nadu": 10703, + "roberto": 10704, + "bce": 10705, + "wrestler": 10706, + "ellie": 10707, + "##ations": 10708, + "infinite": 10709, + "ink": 10710, + "##tia": 10711, + "presumably": 10712, + "finite": 10713, + "staircase": 10714, + "108": 10715, + "noel": 10716, + "patricia": 10717, + "nacional": 10718, + "##cation": 10719, + "chill": 10720, + "eternal": 10721, + "tu": 10722, + "preventing": 10723, + "prussia": 10724, + "fossil": 10725, + "limbs": 10726, + "##logist": 10727, + "ernst": 10728, + "frog": 10729, + "perez": 10730, + "rene": 10731, + "##ace": 10732, + "pizza": 10733, + "prussian": 10734, + "##ios": 10735, + "##vy": 10736, + "molecules": 10737, + "regulatory": 10738, + "answering": 10739, + "opinions": 10740, + "sworn": 10741, + "lengths": 10742, + "supposedly": 10743, + "hypothesis": 10744, + "upward": 10745, + "habitats": 10746, + "seating": 10747, + "ancestors": 10748, + "drank": 10749, + "yield": 10750, + "hd": 10751, + "synthesis": 10752, + "researcher": 10753, + "modest": 10754, + "##var": 10755, + "mothers": 10756, + "peered": 10757, + "voluntary": 10758, + "homeland": 10759, + "##the": 10760, + "acclaim": 10761, + "##igan": 10762, + "static": 10763, + "valve": 10764, + "luxembourg": 10765, + "alto": 10766, + "carroll": 10767, + "fe": 10768, + "receptor": 10769, + "norton": 10770, + "ambulance": 10771, + "##tian": 10772, + "johnston": 10773, + "catholics": 10774, + "depicting": 10775, + "jointly": 10776, + "elephant": 10777, + "gloria": 10778, + "mentor": 10779, + "badge": 10780, + "ahmad": 10781, + "distinguish": 10782, + "remarked": 10783, + "councils": 10784, + "precisely": 10785, + "allison": 10786, + "advancing": 10787, + "detection": 10788, + "crowded": 10789, + "##10": 10790, + "cooperative": 10791, + "ankle": 10792, + "mercedes": 10793, + "dagger": 10794, + "surrendered": 10795, + "pollution": 10796, + "commit": 10797, + "subway": 10798, + "jeffrey": 10799, + "lesson": 10800, + "sculptures": 10801, + "provider": 10802, + "##fication": 10803, + "membrane": 10804, + "timothy": 10805, + "rectangular": 10806, + "fiscal": 10807, + "heating": 10808, + "teammate": 10809, + "basket": 10810, + "particle": 10811, + "anonymous": 10812, + "deployment": 10813, + "##ple": 10814, + "missiles": 10815, + "courthouse": 10816, + "proportion": 10817, + "shoe": 10818, + "sec": 10819, + "##ller": 10820, + "complaints": 10821, + "forbes": 10822, + "blacks": 10823, + "abandon": 10824, + "remind": 10825, + "sizes": 10826, + "overwhelming": 10827, + "autobiography": 10828, + "natalie": 10829, + "##awa": 10830, + "risks": 10831, + "contestant": 10832, + "countryside": 10833, + "babies": 10834, + "scorer": 10835, + "invaded": 10836, + "enclosed": 10837, + "proceed": 10838, + "hurling": 10839, + "disorders": 10840, + "##cu": 10841, + "reflecting": 10842, + "continuously": 10843, + "cruiser": 10844, + "graduates": 10845, + "freeway": 10846, + "investigated": 10847, + "ore": 10848, + "deserved": 10849, + "maid": 10850, + "blocking": 10851, + "phillip": 10852, + "jorge": 10853, + "shakes": 10854, + "dove": 10855, + "mann": 10856, + "variables": 10857, + "lacked": 10858, + "burden": 10859, + "accompanying": 10860, + "que": 10861, + "consistently": 10862, + "organizing": 10863, + "provisional": 10864, + "complained": 10865, + "endless": 10866, + "##rm": 10867, + "tubes": 10868, + "juice": 10869, + "georges": 10870, + "krishna": 10871, + "mick": 10872, + "labels": 10873, + "thriller": 10874, + "##uch": 10875, + "laps": 10876, + "arcade": 10877, + "sage": 10878, + "snail": 10879, + "##table": 10880, + "shannon": 10881, + "fi": 10882, + "laurence": 10883, + "seoul": 10884, + "vacation": 10885, + "presenting": 10886, + "hire": 10887, + "churchill": 10888, + "surprisingly": 10889, + "prohibited": 10890, + "savannah": 10891, + "technically": 10892, + "##oli": 10893, + "170": 10894, + "##lessly": 10895, + "testimony": 10896, + "suited": 10897, + "speeds": 10898, + "toys": 10899, + "romans": 10900, + "mlb": 10901, + "flowering": 10902, + "measurement": 10903, + "talented": 10904, + "kay": 10905, + "settings": 10906, + "charleston": 10907, + "expectations": 10908, + "shattered": 10909, + "achieving": 10910, + "triumph": 10911, + "ceremonies": 10912, + "portsmouth": 10913, + "lanes": 10914, + "mandatory": 10915, + "loser": 10916, + "stretching": 10917, + "cologne": 10918, + "realizes": 10919, + "seventy": 10920, + "cornell": 10921, + "careers": 10922, + "webb": 10923, + "##ulating": 10924, + "americas": 10925, + "budapest": 10926, + "ava": 10927, + "suspicion": 10928, + "##ison": 10929, + "yo": 10930, + "conrad": 10931, + "##hai": 10932, + "sterling": 10933, + "jessie": 10934, + "rector": 10935, + "##az": 10936, + "1831": 10937, + "transform": 10938, + "organize": 10939, + "loans": 10940, + "christine": 10941, + "volcanic": 10942, + "warrant": 10943, + "slender": 10944, + "summers": 10945, + "subfamily": 10946, + "newer": 10947, + "danced": 10948, + "dynamics": 10949, + "rhine": 10950, + "proceeds": 10951, + "heinrich": 10952, + "gastropod": 10953, + "commands": 10954, + "sings": 10955, + "facilitate": 10956, + "easter": 10957, + "ra": 10958, + "positioned": 10959, + "responses": 10960, + "expense": 10961, + "fruits": 10962, + "yanked": 10963, + "imported": 10964, + "25th": 10965, + "velvet": 10966, + "vic": 10967, + "primitive": 10968, + "tribune": 10969, + "baldwin": 10970, + "neighbourhood": 10971, + "donna": 10972, + "rip": 10973, + "hay": 10974, + "pr": 10975, + "##uro": 10976, + "1814": 10977, + "espn": 10978, + "welcomed": 10979, + "##aria": 10980, + "qualifier": 10981, + "glare": 10982, + "highland": 10983, + "timing": 10984, + "##cted": 10985, + "shells": 10986, + "eased": 10987, + "geometry": 10988, + "louder": 10989, + "exciting": 10990, + "slovakia": 10991, + "##sion": 10992, + "##iz": 10993, + "##lot": 10994, + "savings": 10995, + "prairie": 10996, + "##ques": 10997, + "marching": 10998, + "rafael": 10999, + "tonnes": 11000, + "##lled": 11001, + "curtain": 11002, + "preceding": 11003, + "shy": 11004, + "heal": 11005, + "greene": 11006, + "worthy": 11007, + "##pot": 11008, + "detachment": 11009, + "bury": 11010, + "sherman": 11011, + "##eck": 11012, + "reinforced": 11013, + "seeks": 11014, + "bottles": 11015, + "contracted": 11016, + "duchess": 11017, + "outfit": 11018, + "walsh": 11019, + "##sc": 11020, + "mickey": 11021, + "##ase": 11022, + "geoffrey": 11023, + "archer": 11024, + "squeeze": 11025, + "dawson": 11026, + "eliminate": 11027, + "invention": 11028, + "##enberg": 11029, + "neal": 11030, + "##eth": 11031, + "stance": 11032, + "dealer": 11033, + "coral": 11034, + "maple": 11035, + "retire": 11036, + "polo": 11037, + "simplified": 11038, + "##ht": 11039, + "1833": 11040, + "hid": 11041, + "watts": 11042, + "backwards": 11043, + "jules": 11044, + "##oke": 11045, + "genesis": 11046, + "mt": 11047, + "frames": 11048, + "rebounds": 11049, + "burma": 11050, + "woodland": 11051, + "moist": 11052, + "santos": 11053, + "whispers": 11054, + "drained": 11055, + "subspecies": 11056, + "##aa": 11057, + "streaming": 11058, + "ulster": 11059, + "burnt": 11060, + "correspondence": 11061, + "maternal": 11062, + "gerard": 11063, + "denis": 11064, + "stealing": 11065, + "##load": 11066, + "genius": 11067, + "duchy": 11068, + "##oria": 11069, + "inaugurated": 11070, + "momentum": 11071, + "suits": 11072, + "placement": 11073, + "sovereign": 11074, + "clause": 11075, + "thames": 11076, + "##hara": 11077, + "confederation": 11078, + "reservation": 11079, + "sketch": 11080, + "yankees": 11081, + "lets": 11082, + "rotten": 11083, + "charm": 11084, + "hal": 11085, + "verses": 11086, + "ultra": 11087, + "commercially": 11088, + "dot": 11089, + "salon": 11090, + "citation": 11091, + "adopt": 11092, + "winnipeg": 11093, + "mist": 11094, + "allocated": 11095, + "cairo": 11096, + "##boy": 11097, + "jenkins": 11098, + "interference": 11099, + "objectives": 11100, + "##wind": 11101, + "1820": 11102, + "portfolio": 11103, + "armoured": 11104, + "sectors": 11105, + "##eh": 11106, + "initiatives": 11107, + "##world": 11108, + "integrity": 11109, + "exercises": 11110, + "robe": 11111, + "tap": 11112, + "ab": 11113, + "gazed": 11114, + "##tones": 11115, + "distracted": 11116, + "rulers": 11117, + "111": 11118, + "favorable": 11119, + "jerome": 11120, + "tended": 11121, + "cart": 11122, + "factories": 11123, + "##eri": 11124, + "diplomat": 11125, + "valued": 11126, + "gravel": 11127, + "charitable": 11128, + "##try": 11129, + "calvin": 11130, + "exploring": 11131, + "chang": 11132, + "shepherd": 11133, + "terrace": 11134, + "pdf": 11135, + "pupil": 11136, + "##ural": 11137, + "reflects": 11138, + "ups": 11139, + "##rch": 11140, + "governors": 11141, + "shelf": 11142, + "depths": 11143, + "##nberg": 11144, + "trailed": 11145, + "crest": 11146, + "tackle": 11147, + "##nian": 11148, + "##ats": 11149, + "hatred": 11150, + "##kai": 11151, + "clare": 11152, + "makers": 11153, + "ethiopia": 11154, + "longtime": 11155, + "detected": 11156, + "embedded": 11157, + "lacking": 11158, + "slapped": 11159, + "rely": 11160, + "thomson": 11161, + "anticipation": 11162, + "iso": 11163, + "morton": 11164, + "successive": 11165, + "agnes": 11166, + "screenwriter": 11167, + "straightened": 11168, + "philippe": 11169, + "playwright": 11170, + "haunted": 11171, + "licence": 11172, + "iris": 11173, + "intentions": 11174, + "sutton": 11175, + "112": 11176, + "logical": 11177, + "correctly": 11178, + "##weight": 11179, + "branded": 11180, + "licked": 11181, + "tipped": 11182, + "silva": 11183, + "ricky": 11184, + "narrator": 11185, + "requests": 11186, + "##ents": 11187, + "greeted": 11188, + "supernatural": 11189, + "cow": 11190, + "##wald": 11191, + "lung": 11192, + "refusing": 11193, + "employer": 11194, + "strait": 11195, + "gaelic": 11196, + "liner": 11197, + "##piece": 11198, + "zoe": 11199, + "sabha": 11200, + "##mba": 11201, + "driveway": 11202, + "harvest": 11203, + "prints": 11204, + "bates": 11205, + "reluctantly": 11206, + "threshold": 11207, + "algebra": 11208, + "ira": 11209, + "wherever": 11210, + "coupled": 11211, + "240": 11212, + "assumption": 11213, + "picks": 11214, + "##air": 11215, + "designers": 11216, + "raids": 11217, + "gentlemen": 11218, + "##ean": 11219, + "roller": 11220, + "blowing": 11221, + "leipzig": 11222, + "locks": 11223, + "screw": 11224, + "dressing": 11225, + "strand": 11226, + "##lings": 11227, + "scar": 11228, + "dwarf": 11229, + "depicts": 11230, + "##nu": 11231, + "nods": 11232, + "##mine": 11233, + "differ": 11234, + "boris": 11235, + "##eur": 11236, + "yuan": 11237, + "flip": 11238, + "##gie": 11239, + "mob": 11240, + "invested": 11241, + "questioning": 11242, + "applying": 11243, + "##ture": 11244, + "shout": 11245, + "##sel": 11246, + "gameplay": 11247, + "blamed": 11248, + "illustrations": 11249, + "bothered": 11250, + "weakness": 11251, + "rehabilitation": 11252, + "##of": 11253, + "##zes": 11254, + "envelope": 11255, + "rumors": 11256, + "miners": 11257, + "leicester": 11258, + "subtle": 11259, + "kerry": 11260, + "##ico": 11261, + "ferguson": 11262, + "##fu": 11263, + "premiership": 11264, + "ne": 11265, + "##cat": 11266, + "bengali": 11267, + "prof": 11268, + "catches": 11269, + "remnants": 11270, + "dana": 11271, + "##rily": 11272, + "shouting": 11273, + "presidents": 11274, + "baltic": 11275, + "ought": 11276, + "ghosts": 11277, + "dances": 11278, + "sailors": 11279, + "shirley": 11280, + "fancy": 11281, + "dominic": 11282, + "##bie": 11283, + "madonna": 11284, + "##rick": 11285, + "bark": 11286, + "buttons": 11287, + "gymnasium": 11288, + "ashes": 11289, + "liver": 11290, + "toby": 11291, + "oath": 11292, + "providence": 11293, + "doyle": 11294, + "evangelical": 11295, + "nixon": 11296, + "cement": 11297, + "carnegie": 11298, + "embarked": 11299, + "hatch": 11300, + "surroundings": 11301, + "guarantee": 11302, + "needing": 11303, + "pirate": 11304, + "essence": 11305, + "##bee": 11306, + "filter": 11307, + "crane": 11308, + "hammond": 11309, + "projected": 11310, + "immune": 11311, + "percy": 11312, + "twelfth": 11313, + "##ult": 11314, + "regent": 11315, + "doctoral": 11316, + "damon": 11317, + "mikhail": 11318, + "##ichi": 11319, + "lu": 11320, + "critically": 11321, + "elect": 11322, + "realised": 11323, + "abortion": 11324, + "acute": 11325, + "screening": 11326, + "mythology": 11327, + "steadily": 11328, + "##fc": 11329, + "frown": 11330, + "nottingham": 11331, + "kirk": 11332, + "wa": 11333, + "minneapolis": 11334, + "##rra": 11335, + "module": 11336, + "algeria": 11337, + "mc": 11338, + "nautical": 11339, + "encounters": 11340, + "surprising": 11341, + "statues": 11342, + "availability": 11343, + "shirts": 11344, + "pie": 11345, + "alma": 11346, + "brows": 11347, + "munster": 11348, + "mack": 11349, + "soup": 11350, + "crater": 11351, + "tornado": 11352, + "sanskrit": 11353, + "cedar": 11354, + "explosive": 11355, + "bordered": 11356, + "dixon": 11357, + "planets": 11358, + "stamp": 11359, + "exam": 11360, + "happily": 11361, + "##bble": 11362, + "carriers": 11363, + "kidnapped": 11364, + "##vis": 11365, + "accommodation": 11366, + "emigrated": 11367, + "##met": 11368, + "knockout": 11369, + "correspondent": 11370, + "violation": 11371, + "profits": 11372, + "peaks": 11373, + "lang": 11374, + "specimen": 11375, + "agenda": 11376, + "ancestry": 11377, + "pottery": 11378, + "spelling": 11379, + "equations": 11380, + "obtaining": 11381, + "ki": 11382, + "linking": 11383, + "1825": 11384, + "debris": 11385, + "asylum": 11386, + "##20": 11387, + "buddhism": 11388, + "teddy": 11389, + "##ants": 11390, + "gazette": 11391, + "##nger": 11392, + "##sse": 11393, + "dental": 11394, + "eligibility": 11395, + "utc": 11396, + "fathers": 11397, + "averaged": 11398, + "zimbabwe": 11399, + "francesco": 11400, + "coloured": 11401, + "hissed": 11402, + "translator": 11403, + "lynch": 11404, + "mandate": 11405, + "humanities": 11406, + "mackenzie": 11407, + "uniforms": 11408, + "lin": 11409, + "##iana": 11410, + "##gio": 11411, + "asset": 11412, + "mhz": 11413, + "fitting": 11414, + "samantha": 11415, + "genera": 11416, + "wei": 11417, + "rim": 11418, + "beloved": 11419, + "shark": 11420, + "riot": 11421, + "entities": 11422, + "expressions": 11423, + "indo": 11424, + "carmen": 11425, + "slipping": 11426, + "owing": 11427, + "abbot": 11428, + "neighbor": 11429, + "sidney": 11430, + "##av": 11431, + "rats": 11432, + "recommendations": 11433, + "encouraging": 11434, + "squadrons": 11435, + "anticipated": 11436, + "commanders": 11437, + "conquered": 11438, + "##oto": 11439, + "donations": 11440, + "diagnosed": 11441, + "##mond": 11442, + "divide": 11443, + "##iva": 11444, + "guessed": 11445, + "decoration": 11446, + "vernon": 11447, + "auditorium": 11448, + "revelation": 11449, + "conversations": 11450, + "##kers": 11451, + "##power": 11452, + "herzegovina": 11453, + "dash": 11454, + "alike": 11455, + "protested": 11456, + "lateral": 11457, + "herman": 11458, + "accredited": 11459, + "mg": 11460, + "##gent": 11461, + "freeman": 11462, + "mel": 11463, + "fiji": 11464, + "crow": 11465, + "crimson": 11466, + "##rine": 11467, + "livestock": 11468, + "##pped": 11469, + "humanitarian": 11470, + "bored": 11471, + "oz": 11472, + "whip": 11473, + "##lene": 11474, + "##ali": 11475, + "legitimate": 11476, + "alter": 11477, + "grinning": 11478, + "spelled": 11479, + "anxious": 11480, + "oriental": 11481, + "wesley": 11482, + "##nin": 11483, + "##hole": 11484, + "carnival": 11485, + "controller": 11486, + "detect": 11487, + "##ssa": 11488, + "bowed": 11489, + "educator": 11490, + "kosovo": 11491, + "macedonia": 11492, + "##sin": 11493, + "occupy": 11494, + "mastering": 11495, + "stephanie": 11496, + "janeiro": 11497, + "para": 11498, + "unaware": 11499, + "nurses": 11500, + "noon": 11501, + "135": 11502, + "cam": 11503, + "hopefully": 11504, + "ranger": 11505, + "combine": 11506, + "sociology": 11507, + "polar": 11508, + "rica": 11509, + "##eer": 11510, + "neill": 11511, + "##sman": 11512, + "holocaust": 11513, + "##ip": 11514, + "doubled": 11515, + "lust": 11516, + "1828": 11517, + "109": 11518, + "decent": 11519, + "cooling": 11520, + "unveiled": 11521, + "##card": 11522, + "1829": 11523, + "nsw": 11524, + "homer": 11525, + "chapman": 11526, + "meyer": 11527, + "##gin": 11528, + "dive": 11529, + "mae": 11530, + "reagan": 11531, + "expertise": 11532, + "##gled": 11533, + "darwin": 11534, + "brooke": 11535, + "sided": 11536, + "prosecution": 11537, + "investigating": 11538, + "comprised": 11539, + "petroleum": 11540, + "genres": 11541, + "reluctant": 11542, + "differently": 11543, + "trilogy": 11544, + "johns": 11545, + "vegetables": 11546, + "corpse": 11547, + "highlighted": 11548, + "lounge": 11549, + "pension": 11550, + "unsuccessfully": 11551, + "elegant": 11552, + "aided": 11553, + "ivory": 11554, + "beatles": 11555, + "amelia": 11556, + "cain": 11557, + "dubai": 11558, + "sunny": 11559, + "immigrant": 11560, + "babe": 11561, + "click": 11562, + "##nder": 11563, + "underwater": 11564, + "pepper": 11565, + "combining": 11566, + "mumbled": 11567, + "atlas": 11568, + "horns": 11569, + "accessed": 11570, + "ballad": 11571, + "physicians": 11572, + "homeless": 11573, + "gestured": 11574, + "rpm": 11575, + "freak": 11576, + "louisville": 11577, + "corporations": 11578, + "patriots": 11579, + "prizes": 11580, + "rational": 11581, + "warn": 11582, + "modes": 11583, + "decorative": 11584, + "overnight": 11585, + "din": 11586, + "troubled": 11587, + "phantom": 11588, + "##ort": 11589, + "monarch": 11590, + "sheer": 11591, + "##dorf": 11592, + "generals": 11593, + "guidelines": 11594, + "organs": 11595, + "addresses": 11596, + "##zon": 11597, + "enhance": 11598, + "curling": 11599, + "parishes": 11600, + "cord": 11601, + "##kie": 11602, + "linux": 11603, + "caesar": 11604, + "deutsche": 11605, + "bavaria": 11606, + "##bia": 11607, + "coleman": 11608, + "cyclone": 11609, + "##eria": 11610, + "bacon": 11611, + "petty": 11612, + "##yama": 11613, + "##old": 11614, + "hampton": 11615, + "diagnosis": 11616, + "1824": 11617, + "throws": 11618, + "complexity": 11619, + "rita": 11620, + "disputed": 11621, + "##₃": 11622, + "pablo": 11623, + "##sch": 11624, + "marketed": 11625, + "trafficking": 11626, + "##ulus": 11627, + "examine": 11628, + "plague": 11629, + "formats": 11630, + "##oh": 11631, + "vault": 11632, + "faithful": 11633, + "##bourne": 11634, + "webster": 11635, + "##ox": 11636, + "highlights": 11637, + "##ient": 11638, + "##ann": 11639, + "phones": 11640, + "vacuum": 11641, + "sandwich": 11642, + "modeling": 11643, + "##gated": 11644, + "bolivia": 11645, + "clergy": 11646, + "qualities": 11647, + "isabel": 11648, + "##nas": 11649, + "##ars": 11650, + "wears": 11651, + "screams": 11652, + "reunited": 11653, + "annoyed": 11654, + "bra": 11655, + "##ancy": 11656, + "##rate": 11657, + "differential": 11658, + "transmitter": 11659, + "tattoo": 11660, + "container": 11661, + "poker": 11662, + "##och": 11663, + "excessive": 11664, + "resides": 11665, + "cowboys": 11666, + "##tum": 11667, + "augustus": 11668, + "trash": 11669, + "providers": 11670, + "statute": 11671, + "retreated": 11672, + "balcony": 11673, + "reversed": 11674, + "void": 11675, + "storey": 11676, + "preceded": 11677, + "masses": 11678, + "leap": 11679, + "laughs": 11680, + "neighborhoods": 11681, + "wards": 11682, + "schemes": 11683, + "falcon": 11684, + "santo": 11685, + "battlefield": 11686, + "pad": 11687, + "ronnie": 11688, + "thread": 11689, + "lesbian": 11690, + "venus": 11691, + "##dian": 11692, + "beg": 11693, + "sandstone": 11694, + "daylight": 11695, + "punched": 11696, + "gwen": 11697, + "analog": 11698, + "stroked": 11699, + "wwe": 11700, + "acceptable": 11701, + "measurements": 11702, + "dec": 11703, + "toxic": 11704, + "##kel": 11705, + "adequate": 11706, + "surgical": 11707, + "economist": 11708, + "parameters": 11709, + "varsity": 11710, + "##sberg": 11711, + "quantity": 11712, + "ella": 11713, + "##chy": 11714, + "##rton": 11715, + "countess": 11716, + "generating": 11717, + "precision": 11718, + "diamonds": 11719, + "expressway": 11720, + "ga": 11721, + "##ı": 11722, + "1821": 11723, + "uruguay": 11724, + "talents": 11725, + "galleries": 11726, + "expenses": 11727, + "scanned": 11728, + "colleague": 11729, + "outlets": 11730, + "ryder": 11731, + "lucien": 11732, + "##ila": 11733, + "paramount": 11734, + "##bon": 11735, + "syracuse": 11736, + "dim": 11737, + "fangs": 11738, + "gown": 11739, + "sweep": 11740, + "##sie": 11741, + "toyota": 11742, + "missionaries": 11743, + "websites": 11744, + "##nsis": 11745, + "sentences": 11746, + "adviser": 11747, + "val": 11748, + "trademark": 11749, + "spells": 11750, + "##plane": 11751, + "patience": 11752, + "starter": 11753, + "slim": 11754, + "##borg": 11755, + "toe": 11756, + "incredibly": 11757, + "shoots": 11758, + "elliot": 11759, + "nobility": 11760, + "##wyn": 11761, + "cowboy": 11762, + "endorsed": 11763, + "gardner": 11764, + "tendency": 11765, + "persuaded": 11766, + "organisms": 11767, + "emissions": 11768, + "kazakhstan": 11769, + "amused": 11770, + "boring": 11771, + "chips": 11772, + "themed": 11773, + "##hand": 11774, + "llc": 11775, + "constantinople": 11776, + "chasing": 11777, + "systematic": 11778, + "guatemala": 11779, + "borrowed": 11780, + "erin": 11781, + "carey": 11782, + "##hard": 11783, + "highlands": 11784, + "struggles": 11785, + "1810": 11786, + "##ifying": 11787, + "##ced": 11788, + "wong": 11789, + "exceptions": 11790, + "develops": 11791, + "enlarged": 11792, + "kindergarten": 11793, + "castro": 11794, + "##ern": 11795, + "##rina": 11796, + "leigh": 11797, + "zombie": 11798, + "juvenile": 11799, + "##most": 11800, + "consul": 11801, + "##nar": 11802, + "sailor": 11803, + "hyde": 11804, + "clarence": 11805, + "intensive": 11806, + "pinned": 11807, + "nasty": 11808, + "useless": 11809, + "jung": 11810, + "clayton": 11811, + "stuffed": 11812, + "exceptional": 11813, + "ix": 11814, + "apostolic": 11815, + "230": 11816, + "transactions": 11817, + "##dge": 11818, + "exempt": 11819, + "swinging": 11820, + "cove": 11821, + "religions": 11822, + "##ash": 11823, + "shields": 11824, + "dairy": 11825, + "bypass": 11826, + "190": 11827, + "pursuing": 11828, + "bug": 11829, + "joyce": 11830, + "bombay": 11831, + "chassis": 11832, + "southampton": 11833, + "chat": 11834, + "interact": 11835, + "redesignated": 11836, + "##pen": 11837, + "nascar": 11838, + "pray": 11839, + "salmon": 11840, + "rigid": 11841, + "regained": 11842, + "malaysian": 11843, + "grim": 11844, + "publicity": 11845, + "constituted": 11846, + "capturing": 11847, + "toilet": 11848, + "delegate": 11849, + "purely": 11850, + "tray": 11851, + "drift": 11852, + "loosely": 11853, + "striker": 11854, + "weakened": 11855, + "trinidad": 11856, + "mitch": 11857, + "itv": 11858, + "defines": 11859, + "transmitted": 11860, + "ming": 11861, + "scarlet": 11862, + "nodding": 11863, + "fitzgerald": 11864, + "fu": 11865, + "narrowly": 11866, + "sp": 11867, + "tooth": 11868, + "standings": 11869, + "virtue": 11870, + "##₁": 11871, + "##wara": 11872, + "##cting": 11873, + "chateau": 11874, + "gloves": 11875, + "lid": 11876, + "##nel": 11877, + "hurting": 11878, + "conservatory": 11879, + "##pel": 11880, + "sinclair": 11881, + "reopened": 11882, + "sympathy": 11883, + "nigerian": 11884, + "strode": 11885, + "advocated": 11886, + "optional": 11887, + "chronic": 11888, + "discharge": 11889, + "##rc": 11890, + "suck": 11891, + "compatible": 11892, + "laurel": 11893, + "stella": 11894, + "shi": 11895, + "fails": 11896, + "wage": 11897, + "dodge": 11898, + "128": 11899, + "informal": 11900, + "sorts": 11901, + "levi": 11902, + "buddha": 11903, + "villagers": 11904, + "##aka": 11905, + "chronicles": 11906, + "heavier": 11907, + "summoned": 11908, + "gateway": 11909, + "3000": 11910, + "eleventh": 11911, + "jewelry": 11912, + "translations": 11913, + "accordingly": 11914, + "seas": 11915, + "##ency": 11916, + "fiber": 11917, + "pyramid": 11918, + "cubic": 11919, + "dragging": 11920, + "##ista": 11921, + "caring": 11922, + "##ops": 11923, + "android": 11924, + "contacted": 11925, + "lunar": 11926, + "##dt": 11927, + "kai": 11928, + "lisbon": 11929, + "patted": 11930, + "1826": 11931, + "sacramento": 11932, + "theft": 11933, + "madagascar": 11934, + "subtropical": 11935, + "disputes": 11936, + "ta": 11937, + "holidays": 11938, + "piper": 11939, + "willow": 11940, + "mare": 11941, + "cane": 11942, + "itunes": 11943, + "newfoundland": 11944, + "benny": 11945, + "companions": 11946, + "dong": 11947, + "raj": 11948, + "observe": 11949, + "roar": 11950, + "charming": 11951, + "plaque": 11952, + "tibetan": 11953, + "fossils": 11954, + "enacted": 11955, + "manning": 11956, + "bubble": 11957, + "tina": 11958, + "tanzania": 11959, + "##eda": 11960, + "##hir": 11961, + "funk": 11962, + "swamp": 11963, + "deputies": 11964, + "cloak": 11965, + "ufc": 11966, + "scenario": 11967, + "par": 11968, + "scratch": 11969, + "metals": 11970, + "anthem": 11971, + "guru": 11972, + "engaging": 11973, + "specially": 11974, + "##boat": 11975, + "dialects": 11976, + "nineteen": 11977, + "cecil": 11978, + "duet": 11979, + "disability": 11980, + "messenger": 11981, + "unofficial": 11982, + "##lies": 11983, + "defunct": 11984, + "eds": 11985, + "moonlight": 11986, + "drainage": 11987, + "surname": 11988, + "puzzle": 11989, + "honda": 11990, + "switching": 11991, + "conservatives": 11992, + "mammals": 11993, + "knox": 11994, + "broadcaster": 11995, + "sidewalk": 11996, + "cope": 11997, + "##ried": 11998, + "benson": 11999, + "princes": 12000, + "peterson": 12001, + "##sal": 12002, + "bedford": 12003, + "sharks": 12004, + "eli": 12005, + "wreck": 12006, + "alberto": 12007, + "gasp": 12008, + "archaeology": 12009, + "lgbt": 12010, + "teaches": 12011, + "securities": 12012, + "madness": 12013, + "compromise": 12014, + "waving": 12015, + "coordination": 12016, + "davidson": 12017, + "visions": 12018, + "leased": 12019, + "possibilities": 12020, + "eighty": 12021, + "jun": 12022, + "fernandez": 12023, + "enthusiasm": 12024, + "assassin": 12025, + "sponsorship": 12026, + "reviewer": 12027, + "kingdoms": 12028, + "estonian": 12029, + "laboratories": 12030, + "##fy": 12031, + "##nal": 12032, + "applies": 12033, + "verb": 12034, + "celebrations": 12035, + "##zzo": 12036, + "rowing": 12037, + "lightweight": 12038, + "sadness": 12039, + "submit": 12040, + "mvp": 12041, + "balanced": 12042, + "dude": 12043, + "##vas": 12044, + "explicitly": 12045, + "metric": 12046, + "magnificent": 12047, + "mound": 12048, + "brett": 12049, + "mohammad": 12050, + "mistakes": 12051, + "irregular": 12052, + "##hing": 12053, + "##ass": 12054, + "sanders": 12055, + "betrayed": 12056, + "shipped": 12057, + "surge": 12058, + "##enburg": 12059, + "reporters": 12060, + "termed": 12061, + "georg": 12062, + "pity": 12063, + "verbal": 12064, + "bulls": 12065, + "abbreviated": 12066, + "enabling": 12067, + "appealed": 12068, + "##are": 12069, + "##atic": 12070, + "sicily": 12071, + "sting": 12072, + "heel": 12073, + "sweetheart": 12074, + "bart": 12075, + "spacecraft": 12076, + "brutal": 12077, + "monarchy": 12078, + "##tter": 12079, + "aberdeen": 12080, + "cameo": 12081, + "diane": 12082, + "##ub": 12083, + "survivor": 12084, + "clyde": 12085, + "##aries": 12086, + "complaint": 12087, + "##makers": 12088, + "clarinet": 12089, + "delicious": 12090, + "chilean": 12091, + "karnataka": 12092, + "coordinates": 12093, + "1818": 12094, + "panties": 12095, + "##rst": 12096, + "pretending": 12097, + "ar": 12098, + "dramatically": 12099, + "kiev": 12100, + "bella": 12101, + "tends": 12102, + "distances": 12103, + "113": 12104, + "catalog": 12105, + "launching": 12106, + "instances": 12107, + "telecommunications": 12108, + "portable": 12109, + "lindsay": 12110, + "vatican": 12111, + "##eim": 12112, + "angles": 12113, + "aliens": 12114, + "marker": 12115, + "stint": 12116, + "screens": 12117, + "bolton": 12118, + "##rne": 12119, + "judy": 12120, + "wool": 12121, + "benedict": 12122, + "plasma": 12123, + "europa": 12124, + "spark": 12125, + "imaging": 12126, + "filmmaker": 12127, + "swiftly": 12128, + "##een": 12129, + "contributor": 12130, + "##nor": 12131, + "opted": 12132, + "stamps": 12133, + "apologize": 12134, + "financing": 12135, + "butter": 12136, + "gideon": 12137, + "sophisticated": 12138, + "alignment": 12139, + "avery": 12140, + "chemicals": 12141, + "yearly": 12142, + "speculation": 12143, + "prominence": 12144, + "professionally": 12145, + "##ils": 12146, + "immortal": 12147, + "institutional": 12148, + "inception": 12149, + "wrists": 12150, + "identifying": 12151, + "tribunal": 12152, + "derives": 12153, + "gains": 12154, + "##wo": 12155, + "papal": 12156, + "preference": 12157, + "linguistic": 12158, + "vince": 12159, + "operative": 12160, + "brewery": 12161, + "##ont": 12162, + "unemployment": 12163, + "boyd": 12164, + "##ured": 12165, + "##outs": 12166, + "albeit": 12167, + "prophet": 12168, + "1813": 12169, + "bi": 12170, + "##rr": 12171, + "##face": 12172, + "##rad": 12173, + "quarterly": 12174, + "asteroid": 12175, + "cleaned": 12176, + "radius": 12177, + "temper": 12178, + "##llen": 12179, + "telugu": 12180, + "jerk": 12181, + "viscount": 12182, + "menu": 12183, + "##ote": 12184, + "glimpse": 12185, + "##aya": 12186, + "yacht": 12187, + "hawaiian": 12188, + "baden": 12189, + "##rl": 12190, + "laptop": 12191, + "readily": 12192, + "##gu": 12193, + "monetary": 12194, + "offshore": 12195, + "scots": 12196, + "watches": 12197, + "##yang": 12198, + "##arian": 12199, + "upgrade": 12200, + "needle": 12201, + "xbox": 12202, + "lea": 12203, + "encyclopedia": 12204, + "flank": 12205, + "fingertips": 12206, + "##pus": 12207, + "delight": 12208, + "teachings": 12209, + "confirm": 12210, + "roth": 12211, + "beaches": 12212, + "midway": 12213, + "winters": 12214, + "##iah": 12215, + "teasing": 12216, + "daytime": 12217, + "beverly": 12218, + "gambling": 12219, + "bonnie": 12220, + "##backs": 12221, + "regulated": 12222, + "clement": 12223, + "hermann": 12224, + "tricks": 12225, + "knot": 12226, + "##shing": 12227, + "##uring": 12228, + "##vre": 12229, + "detached": 12230, + "ecological": 12231, + "owed": 12232, + "specialty": 12233, + "byron": 12234, + "inventor": 12235, + "bats": 12236, + "stays": 12237, + "screened": 12238, + "unesco": 12239, + "midland": 12240, + "trim": 12241, + "affection": 12242, + "##ander": 12243, + "##rry": 12244, + "jess": 12245, + "thoroughly": 12246, + "feedback": 12247, + "##uma": 12248, + "chennai": 12249, + "strained": 12250, + "heartbeat": 12251, + "wrapping": 12252, + "overtime": 12253, + "pleaded": 12254, + "##sworth": 12255, + "mon": 12256, + "leisure": 12257, + "oclc": 12258, + "##tate": 12259, + "##ele": 12260, + "feathers": 12261, + "angelo": 12262, + "thirds": 12263, + "nuts": 12264, + "surveys": 12265, + "clever": 12266, + "gill": 12267, + "commentator": 12268, + "##dos": 12269, + "darren": 12270, + "rides": 12271, + "gibraltar": 12272, + "##nc": 12273, + "##mu": 12274, + "dissolution": 12275, + "dedication": 12276, + "shin": 12277, + "meals": 12278, + "saddle": 12279, + "elvis": 12280, + "reds": 12281, + "chaired": 12282, + "taller": 12283, + "appreciation": 12284, + "functioning": 12285, + "niece": 12286, + "favored": 12287, + "advocacy": 12288, + "robbie": 12289, + "criminals": 12290, + "suffolk": 12291, + "yugoslav": 12292, + "passport": 12293, + "constable": 12294, + "congressman": 12295, + "hastings": 12296, + "vera": 12297, + "##rov": 12298, + "consecrated": 12299, + "sparks": 12300, + "ecclesiastical": 12301, + "confined": 12302, + "##ovich": 12303, + "muller": 12304, + "floyd": 12305, + "nora": 12306, + "1822": 12307, + "paved": 12308, + "1827": 12309, + "cumberland": 12310, + "ned": 12311, + "saga": 12312, + "spiral": 12313, + "##flow": 12314, + "appreciated": 12315, + "yi": 12316, + "collaborative": 12317, + "treating": 12318, + "similarities": 12319, + "feminine": 12320, + "finishes": 12321, + "##ib": 12322, + "jade": 12323, + "import": 12324, + "##nse": 12325, + "##hot": 12326, + "champagne": 12327, + "mice": 12328, + "securing": 12329, + "celebrities": 12330, + "helsinki": 12331, + "attributes": 12332, + "##gos": 12333, + "cousins": 12334, + "phases": 12335, + "ache": 12336, + "lucia": 12337, + "gandhi": 12338, + "submission": 12339, + "vicar": 12340, + "spear": 12341, + "shine": 12342, + "tasmania": 12343, + "biting": 12344, + "detention": 12345, + "constitute": 12346, + "tighter": 12347, + "seasonal": 12348, + "##gus": 12349, + "terrestrial": 12350, + "matthews": 12351, + "##oka": 12352, + "effectiveness": 12353, + "parody": 12354, + "philharmonic": 12355, + "##onic": 12356, + "1816": 12357, + "strangers": 12358, + "encoded": 12359, + "consortium": 12360, + "guaranteed": 12361, + "regards": 12362, + "shifts": 12363, + "tortured": 12364, + "collision": 12365, + "supervisor": 12366, + "inform": 12367, + "broader": 12368, + "insight": 12369, + "theaters": 12370, + "armour": 12371, + "emeritus": 12372, + "blink": 12373, + "incorporates": 12374, + "mapping": 12375, + "##50": 12376, + "##ein": 12377, + "handball": 12378, + "flexible": 12379, + "##nta": 12380, + "substantially": 12381, + "generous": 12382, + "thief": 12383, + "##own": 12384, + "carr": 12385, + "loses": 12386, + "1793": 12387, + "prose": 12388, + "ucla": 12389, + "romeo": 12390, + "generic": 12391, + "metallic": 12392, + "realization": 12393, + "damages": 12394, + "mk": 12395, + "commissioners": 12396, + "zach": 12397, + "default": 12398, + "##ther": 12399, + "helicopters": 12400, + "lengthy": 12401, + "stems": 12402, + "spa": 12403, + "partnered": 12404, + "spectators": 12405, + "rogue": 12406, + "indication": 12407, + "penalties": 12408, + "teresa": 12409, + "1801": 12410, + "sen": 12411, + "##tric": 12412, + "dalton": 12413, + "##wich": 12414, + "irving": 12415, + "photographic": 12416, + "##vey": 12417, + "dell": 12418, + "deaf": 12419, + "peters": 12420, + "excluded": 12421, + "unsure": 12422, + "##vable": 12423, + "patterson": 12424, + "crawled": 12425, + "##zio": 12426, + "resided": 12427, + "whipped": 12428, + "latvia": 12429, + "slower": 12430, + "ecole": 12431, + "pipes": 12432, + "employers": 12433, + "maharashtra": 12434, + "comparable": 12435, + "va": 12436, + "textile": 12437, + "pageant": 12438, + "##gel": 12439, + "alphabet": 12440, + "binary": 12441, + "irrigation": 12442, + "chartered": 12443, + "choked": 12444, + "antoine": 12445, + "offs": 12446, + "waking": 12447, + "supplement": 12448, + "##wen": 12449, + "quantities": 12450, + "demolition": 12451, + "regain": 12452, + "locate": 12453, + "urdu": 12454, + "folks": 12455, + "alt": 12456, + "114": 12457, + "##mc": 12458, + "scary": 12459, + "andreas": 12460, + "whites": 12461, + "##ava": 12462, + "classrooms": 12463, + "mw": 12464, + "aesthetic": 12465, + "publishes": 12466, + "valleys": 12467, + "guides": 12468, + "cubs": 12469, + "johannes": 12470, + "bryant": 12471, + "conventions": 12472, + "affecting": 12473, + "##itt": 12474, + "drain": 12475, + "awesome": 12476, + "isolation": 12477, + "prosecutor": 12478, + "ambitious": 12479, + "apology": 12480, + "captive": 12481, + "downs": 12482, + "atmospheric": 12483, + "lorenzo": 12484, + "aisle": 12485, + "beef": 12486, + "foul": 12487, + "##onia": 12488, + "kidding": 12489, + "composite": 12490, + "disturbed": 12491, + "illusion": 12492, + "natives": 12493, + "##ffer": 12494, + "emi": 12495, + "rockets": 12496, + "riverside": 12497, + "wartime": 12498, + "painters": 12499, + "adolf": 12500, + "melted": 12501, + "##ail": 12502, + "uncertainty": 12503, + "simulation": 12504, + "hawks": 12505, + "progressed": 12506, + "meantime": 12507, + "builder": 12508, + "spray": 12509, + "breach": 12510, + "unhappy": 12511, + "regina": 12512, + "russians": 12513, + "##urg": 12514, + "determining": 12515, + "##tation": 12516, + "tram": 12517, + "1806": 12518, + "##quin": 12519, + "aging": 12520, + "##12": 12521, + "1823": 12522, + "garion": 12523, + "rented": 12524, + "mister": 12525, + "diaz": 12526, + "terminated": 12527, + "clip": 12528, + "1817": 12529, + "depend": 12530, + "nervously": 12531, + "disco": 12532, + "owe": 12533, + "defenders": 12534, + "shiva": 12535, + "notorious": 12536, + "disbelief": 12537, + "shiny": 12538, + "worcester": 12539, + "##gation": 12540, + "##yr": 12541, + "trailing": 12542, + "undertook": 12543, + "islander": 12544, + "belarus": 12545, + "limitations": 12546, + "watershed": 12547, + "fuller": 12548, + "overlooking": 12549, + "utilized": 12550, + "raphael": 12551, + "1819": 12552, + "synthetic": 12553, + "breakdown": 12554, + "klein": 12555, + "##nate": 12556, + "moaned": 12557, + "memoir": 12558, + "lamb": 12559, + "practicing": 12560, + "##erly": 12561, + "cellular": 12562, + "arrows": 12563, + "exotic": 12564, + "##graphy": 12565, + "witches": 12566, + "117": 12567, + "charted": 12568, + "rey": 12569, + "hut": 12570, + "hierarchy": 12571, + "subdivision": 12572, + "freshwater": 12573, + "giuseppe": 12574, + "aloud": 12575, + "reyes": 12576, + "qatar": 12577, + "marty": 12578, + "sideways": 12579, + "utterly": 12580, + "sexually": 12581, + "jude": 12582, + "prayers": 12583, + "mccarthy": 12584, + "softball": 12585, + "blend": 12586, + "damien": 12587, + "##gging": 12588, + "##metric": 12589, + "wholly": 12590, + "erupted": 12591, + "lebanese": 12592, + "negro": 12593, + "revenues": 12594, + "tasted": 12595, + "comparative": 12596, + "teamed": 12597, + "transaction": 12598, + "labeled": 12599, + "maori": 12600, + "sovereignty": 12601, + "parkway": 12602, + "trauma": 12603, + "gran": 12604, + "malay": 12605, + "121": 12606, + "advancement": 12607, + "descendant": 12608, + "2020": 12609, + "buzz": 12610, + "salvation": 12611, + "inventory": 12612, + "symbolic": 12613, + "##making": 12614, + "antarctica": 12615, + "mps": 12616, + "##gas": 12617, + "##bro": 12618, + "mohammed": 12619, + "myanmar": 12620, + "holt": 12621, + "submarines": 12622, + "tones": 12623, + "##lman": 12624, + "locker": 12625, + "patriarch": 12626, + "bangkok": 12627, + "emerson": 12628, + "remarks": 12629, + "predators": 12630, + "kin": 12631, + "afghan": 12632, + "confession": 12633, + "norwich": 12634, + "rental": 12635, + "emerge": 12636, + "advantages": 12637, + "##zel": 12638, + "rca": 12639, + "##hold": 12640, + "shortened": 12641, + "storms": 12642, + "aidan": 12643, + "##matic": 12644, + "autonomy": 12645, + "compliance": 12646, + "##quet": 12647, + "dudley": 12648, + "atp": 12649, + "##osis": 12650, + "1803": 12651, + "motto": 12652, + "documentation": 12653, + "summary": 12654, + "professors": 12655, + "spectacular": 12656, + "christina": 12657, + "archdiocese": 12658, + "flashing": 12659, + "innocence": 12660, + "remake": 12661, + "##dell": 12662, + "psychic": 12663, + "reef": 12664, + "scare": 12665, + "employ": 12666, + "rs": 12667, + "sticks": 12668, + "meg": 12669, + "gus": 12670, + "leans": 12671, + "##ude": 12672, + "accompany": 12673, + "bergen": 12674, + "tomas": 12675, + "##iko": 12676, + "doom": 12677, + "wages": 12678, + "pools": 12679, + "##nch": 12680, + "##bes": 12681, + "breasts": 12682, + "scholarly": 12683, + "alison": 12684, + "outline": 12685, + "brittany": 12686, + "breakthrough": 12687, + "willis": 12688, + "realistic": 12689, + "##cut": 12690, + "##boro": 12691, + "competitor": 12692, + "##stan": 12693, + "pike": 12694, + "picnic": 12695, + "icon": 12696, + "designing": 12697, + "commercials": 12698, + "washing": 12699, + "villain": 12700, + "skiing": 12701, + "micro": 12702, + "costumes": 12703, + "auburn": 12704, + "halted": 12705, + "executives": 12706, + "##hat": 12707, + "logistics": 12708, + "cycles": 12709, + "vowel": 12710, + "applicable": 12711, + "barrett": 12712, + "exclaimed": 12713, + "eurovision": 12714, + "eternity": 12715, + "ramon": 12716, + "##umi": 12717, + "##lls": 12718, + "modifications": 12719, + "sweeping": 12720, + "disgust": 12721, + "##uck": 12722, + "torch": 12723, + "aviv": 12724, + "ensuring": 12725, + "rude": 12726, + "dusty": 12727, + "sonic": 12728, + "donovan": 12729, + "outskirts": 12730, + "cu": 12731, + "pathway": 12732, + "##band": 12733, + "##gun": 12734, + "##lines": 12735, + "disciplines": 12736, + "acids": 12737, + "cadet": 12738, + "paired": 12739, + "##40": 12740, + "sketches": 12741, + "##sive": 12742, + "marriages": 12743, + "##⁺": 12744, + "folding": 12745, + "peers": 12746, + "slovak": 12747, + "implies": 12748, + "admired": 12749, + "##beck": 12750, + "1880s": 12751, + "leopold": 12752, + "instinct": 12753, + "attained": 12754, + "weston": 12755, + "megan": 12756, + "horace": 12757, + "##ination": 12758, + "dorsal": 12759, + "ingredients": 12760, + "evolutionary": 12761, + "##its": 12762, + "complications": 12763, + "deity": 12764, + "lethal": 12765, + "brushing": 12766, + "levy": 12767, + "deserted": 12768, + "institutes": 12769, + "posthumously": 12770, + "delivering": 12771, + "telescope": 12772, + "coronation": 12773, + "motivated": 12774, + "rapids": 12775, + "luc": 12776, + "flicked": 12777, + "pays": 12778, + "volcano": 12779, + "tanner": 12780, + "weighed": 12781, + "##nica": 12782, + "crowds": 12783, + "frankie": 12784, + "gifted": 12785, + "addressing": 12786, + "granddaughter": 12787, + "winding": 12788, + "##rna": 12789, + "constantine": 12790, + "gomez": 12791, + "##front": 12792, + "landscapes": 12793, + "rudolf": 12794, + "anthropology": 12795, + "slate": 12796, + "werewolf": 12797, + "##lio": 12798, + "astronomy": 12799, + "circa": 12800, + "rouge": 12801, + "dreaming": 12802, + "sack": 12803, + "knelt": 12804, + "drowned": 12805, + "naomi": 12806, + "prolific": 12807, + "tracked": 12808, + "freezing": 12809, + "herb": 12810, + "##dium": 12811, + "agony": 12812, + "randall": 12813, + "twisting": 12814, + "wendy": 12815, + "deposit": 12816, + "touches": 12817, + "vein": 12818, + "wheeler": 12819, + "##bbled": 12820, + "##bor": 12821, + "batted": 12822, + "retaining": 12823, + "tire": 12824, + "presently": 12825, + "compare": 12826, + "specification": 12827, + "daemon": 12828, + "nigel": 12829, + "##grave": 12830, + "merry": 12831, + "recommendation": 12832, + "czechoslovakia": 12833, + "sandra": 12834, + "ng": 12835, + "roma": 12836, + "##sts": 12837, + "lambert": 12838, + "inheritance": 12839, + "sheikh": 12840, + "winchester": 12841, + "cries": 12842, + "examining": 12843, + "##yle": 12844, + "comeback": 12845, + "cuisine": 12846, + "nave": 12847, + "##iv": 12848, + "ko": 12849, + "retrieve": 12850, + "tomatoes": 12851, + "barker": 12852, + "polished": 12853, + "defining": 12854, + "irene": 12855, + "lantern": 12856, + "personalities": 12857, + "begging": 12858, + "tract": 12859, + "swore": 12860, + "1809": 12861, + "175": 12862, + "##gic": 12863, + "omaha": 12864, + "brotherhood": 12865, + "##rley": 12866, + "haiti": 12867, + "##ots": 12868, + "exeter": 12869, + "##ete": 12870, + "##zia": 12871, + "steele": 12872, + "dumb": 12873, + "pearson": 12874, + "210": 12875, + "surveyed": 12876, + "elisabeth": 12877, + "trends": 12878, + "##ef": 12879, + "fritz": 12880, + "##rf": 12881, + "premium": 12882, + "bugs": 12883, + "fraction": 12884, + "calmly": 12885, + "viking": 12886, + "##birds": 12887, + "tug": 12888, + "inserted": 12889, + "unusually": 12890, + "##ield": 12891, + "confronted": 12892, + "distress": 12893, + "crashing": 12894, + "brent": 12895, + "turks": 12896, + "resign": 12897, + "##olo": 12898, + "cambodia": 12899, + "gabe": 12900, + "sauce": 12901, + "##kal": 12902, + "evelyn": 12903, + "116": 12904, + "extant": 12905, + "clusters": 12906, + "quarry": 12907, + "teenagers": 12908, + "luna": 12909, + "##lers": 12910, + "##ister": 12911, + "affiliation": 12912, + "drill": 12913, + "##ashi": 12914, + "panthers": 12915, + "scenic": 12916, + "libya": 12917, + "anita": 12918, + "strengthen": 12919, + "inscriptions": 12920, + "##cated": 12921, + "lace": 12922, + "sued": 12923, + "judith": 12924, + "riots": 12925, + "##uted": 12926, + "mint": 12927, + "##eta": 12928, + "preparations": 12929, + "midst": 12930, + "dub": 12931, + "challenger": 12932, + "##vich": 12933, + "mock": 12934, + "cf": 12935, + "displaced": 12936, + "wicket": 12937, + "breaths": 12938, + "enables": 12939, + "schmidt": 12940, + "analyst": 12941, + "##lum": 12942, + "ag": 12943, + "highlight": 12944, + "automotive": 12945, + "axe": 12946, + "josef": 12947, + "newark": 12948, + "sufficiently": 12949, + "resembles": 12950, + "50th": 12951, + "##pal": 12952, + "flushed": 12953, + "mum": 12954, + "traits": 12955, + "##ante": 12956, + "commodore": 12957, + "incomplete": 12958, + "warming": 12959, + "titular": 12960, + "ceremonial": 12961, + "ethical": 12962, + "118": 12963, + "celebrating": 12964, + "eighteenth": 12965, + "cao": 12966, + "lima": 12967, + "medalist": 12968, + "mobility": 12969, + "strips": 12970, + "snakes": 12971, + "##city": 12972, + "miniature": 12973, + "zagreb": 12974, + "barton": 12975, + "escapes": 12976, + "umbrella": 12977, + "automated": 12978, + "doubted": 12979, + "differs": 12980, + "cooled": 12981, + "georgetown": 12982, + "dresden": 12983, + "cooked": 12984, + "fade": 12985, + "wyatt": 12986, + "rna": 12987, + "jacobs": 12988, + "carlton": 12989, + "abundant": 12990, + "stereo": 12991, + "boost": 12992, + "madras": 12993, + "inning": 12994, + "##hia": 12995, + "spur": 12996, + "ip": 12997, + "malayalam": 12998, + "begged": 12999, + "osaka": 13000, + "groan": 13001, + "escaping": 13002, + "charging": 13003, + "dose": 13004, + "vista": 13005, + "##aj": 13006, + "bud": 13007, + "papa": 13008, + "communists": 13009, + "advocates": 13010, + "edged": 13011, + "tri": 13012, + "##cent": 13013, + "resemble": 13014, + "peaking": 13015, + "necklace": 13016, + "fried": 13017, + "montenegro": 13018, + "saxony": 13019, + "goose": 13020, + "glances": 13021, + "stuttgart": 13022, + "curator": 13023, + "recruit": 13024, + "grocery": 13025, + "sympathetic": 13026, + "##tting": 13027, + "##fort": 13028, + "127": 13029, + "lotus": 13030, + "randolph": 13031, + "ancestor": 13032, + "##rand": 13033, + "succeeding": 13034, + "jupiter": 13035, + "1798": 13036, + "macedonian": 13037, + "##heads": 13038, + "hiking": 13039, + "1808": 13040, + "handing": 13041, + "fischer": 13042, + "##itive": 13043, + "garbage": 13044, + "node": 13045, + "##pies": 13046, + "prone": 13047, + "singular": 13048, + "papua": 13049, + "inclined": 13050, + "attractions": 13051, + "italia": 13052, + "pouring": 13053, + "motioned": 13054, + "grandma": 13055, + "garnered": 13056, + "jacksonville": 13057, + "corp": 13058, + "ego": 13059, + "ringing": 13060, + "aluminum": 13061, + "##hausen": 13062, + "ordering": 13063, + "##foot": 13064, + "drawer": 13065, + "traders": 13066, + "synagogue": 13067, + "##play": 13068, + "##kawa": 13069, + "resistant": 13070, + "wandering": 13071, + "fragile": 13072, + "fiona": 13073, + "teased": 13074, + "var": 13075, + "hardcore": 13076, + "soaked": 13077, + "jubilee": 13078, + "decisive": 13079, + "exposition": 13080, + "mercer": 13081, + "poster": 13082, + "valencia": 13083, + "hale": 13084, + "kuwait": 13085, + "1811": 13086, + "##ises": 13087, + "##wr": 13088, + "##eed": 13089, + "tavern": 13090, + "gamma": 13091, + "122": 13092, + "johan": 13093, + "##uer": 13094, + "airways": 13095, + "amino": 13096, + "gil": 13097, + "##ury": 13098, + "vocational": 13099, + "domains": 13100, + "torres": 13101, + "##sp": 13102, + "generator": 13103, + "folklore": 13104, + "outcomes": 13105, + "##keeper": 13106, + "canberra": 13107, + "shooter": 13108, + "fl": 13109, + "beams": 13110, + "confrontation": 13111, + "##lling": 13112, + "##gram": 13113, + "feb": 13114, + "aligned": 13115, + "forestry": 13116, + "pipeline": 13117, + "jax": 13118, + "motorway": 13119, + "conception": 13120, + "decay": 13121, + "##tos": 13122, + "coffin": 13123, + "##cott": 13124, + "stalin": 13125, + "1805": 13126, + "escorted": 13127, + "minded": 13128, + "##nam": 13129, + "sitcom": 13130, + "purchasing": 13131, + "twilight": 13132, + "veronica": 13133, + "additions": 13134, + "passive": 13135, + "tensions": 13136, + "straw": 13137, + "123": 13138, + "frequencies": 13139, + "1804": 13140, + "refugee": 13141, + "cultivation": 13142, + "##iate": 13143, + "christie": 13144, + "clary": 13145, + "bulletin": 13146, + "crept": 13147, + "disposal": 13148, + "##rich": 13149, + "##zong": 13150, + "processor": 13151, + "crescent": 13152, + "##rol": 13153, + "bmw": 13154, + "emphasized": 13155, + "whale": 13156, + "nazis": 13157, + "aurora": 13158, + "##eng": 13159, + "dwelling": 13160, + "hauled": 13161, + "sponsors": 13162, + "toledo": 13163, + "mega": 13164, + "ideology": 13165, + "theatres": 13166, + "tessa": 13167, + "cerambycidae": 13168, + "saves": 13169, + "turtle": 13170, + "cone": 13171, + "suspects": 13172, + "kara": 13173, + "rusty": 13174, + "yelling": 13175, + "greeks": 13176, + "mozart": 13177, + "shades": 13178, + "cocked": 13179, + "participant": 13180, + "##tro": 13181, + "shire": 13182, + "spit": 13183, + "freeze": 13184, + "necessity": 13185, + "##cos": 13186, + "inmates": 13187, + "nielsen": 13188, + "councillors": 13189, + "loaned": 13190, + "uncommon": 13191, + "omar": 13192, + "peasants": 13193, + "botanical": 13194, + "offspring": 13195, + "daniels": 13196, + "formations": 13197, + "jokes": 13198, + "1794": 13199, + "pioneers": 13200, + "sigma": 13201, + "licensing": 13202, + "##sus": 13203, + "wheelchair": 13204, + "polite": 13205, + "1807": 13206, + "liquor": 13207, + "pratt": 13208, + "trustee": 13209, + "##uta": 13210, + "forewings": 13211, + "balloon": 13212, + "##zz": 13213, + "kilometre": 13214, + "camping": 13215, + "explicit": 13216, + "casually": 13217, + "shawn": 13218, + "foolish": 13219, + "teammates": 13220, + "nm": 13221, + "hassan": 13222, + "carrie": 13223, + "judged": 13224, + "satisfy": 13225, + "vanessa": 13226, + "knives": 13227, + "selective": 13228, + "cnn": 13229, + "flowed": 13230, + "##lice": 13231, + "eclipse": 13232, + "stressed": 13233, + "eliza": 13234, + "mathematician": 13235, + "cease": 13236, + "cultivated": 13237, + "##roy": 13238, + "commissions": 13239, + "browns": 13240, + "##ania": 13241, + "destroyers": 13242, + "sheridan": 13243, + "meadow": 13244, + "##rius": 13245, + "minerals": 13246, + "##cial": 13247, + "downstream": 13248, + "clash": 13249, + "gram": 13250, + "memoirs": 13251, + "ventures": 13252, + "baha": 13253, + "seymour": 13254, + "archie": 13255, + "midlands": 13256, + "edith": 13257, + "fare": 13258, + "flynn": 13259, + "invite": 13260, + "canceled": 13261, + "tiles": 13262, + "stabbed": 13263, + "boulder": 13264, + "incorporate": 13265, + "amended": 13266, + "camden": 13267, + "facial": 13268, + "mollusk": 13269, + "unreleased": 13270, + "descriptions": 13271, + "yoga": 13272, + "grabs": 13273, + "550": 13274, + "raises": 13275, + "ramp": 13276, + "shiver": 13277, + "##rose": 13278, + "coined": 13279, + "pioneering": 13280, + "tunes": 13281, + "qing": 13282, + "warwick": 13283, + "tops": 13284, + "119": 13285, + "melanie": 13286, + "giles": 13287, + "##rous": 13288, + "wandered": 13289, + "##inal": 13290, + "annexed": 13291, + "nov": 13292, + "30th": 13293, + "unnamed": 13294, + "##ished": 13295, + "organizational": 13296, + "airplane": 13297, + "normandy": 13298, + "stoke": 13299, + "whistle": 13300, + "blessing": 13301, + "violations": 13302, + "chased": 13303, + "holders": 13304, + "shotgun": 13305, + "##ctic": 13306, + "outlet": 13307, + "reactor": 13308, + "##vik": 13309, + "tires": 13310, + "tearing": 13311, + "shores": 13312, + "fortified": 13313, + "mascot": 13314, + "constituencies": 13315, + "nc": 13316, + "columnist": 13317, + "productive": 13318, + "tibet": 13319, + "##rta": 13320, + "lineage": 13321, + "hooked": 13322, + "oct": 13323, + "tapes": 13324, + "judging": 13325, + "cody": 13326, + "##gger": 13327, + "hansen": 13328, + "kashmir": 13329, + "triggered": 13330, + "##eva": 13331, + "solved": 13332, + "cliffs": 13333, + "##tree": 13334, + "resisted": 13335, + "anatomy": 13336, + "protesters": 13337, + "transparent": 13338, + "implied": 13339, + "##iga": 13340, + "injection": 13341, + "mattress": 13342, + "excluding": 13343, + "##mbo": 13344, + "defenses": 13345, + "helpless": 13346, + "devotion": 13347, + "##elli": 13348, + "growl": 13349, + "liberals": 13350, + "weber": 13351, + "phenomena": 13352, + "atoms": 13353, + "plug": 13354, + "##iff": 13355, + "mortality": 13356, + "apprentice": 13357, + "howe": 13358, + "convincing": 13359, + "aaa": 13360, + "swimmer": 13361, + "barber": 13362, + "leone": 13363, + "promptly": 13364, + "sodium": 13365, + "def": 13366, + "nowadays": 13367, + "arise": 13368, + "##oning": 13369, + "gloucester": 13370, + "corrected": 13371, + "dignity": 13372, + "norm": 13373, + "erie": 13374, + "##ders": 13375, + "elders": 13376, + "evacuated": 13377, + "sylvia": 13378, + "compression": 13379, + "##yar": 13380, + "hartford": 13381, + "pose": 13382, + "backpack": 13383, + "reasoning": 13384, + "accepts": 13385, + "24th": 13386, + "wipe": 13387, + "millimetres": 13388, + "marcel": 13389, + "##oda": 13390, + "dodgers": 13391, + "albion": 13392, + "1790": 13393, + "overwhelmed": 13394, + "aerospace": 13395, + "oaks": 13396, + "1795": 13397, + "showcase": 13398, + "acknowledge": 13399, + "recovering": 13400, + "nolan": 13401, + "ashe": 13402, + "hurts": 13403, + "geology": 13404, + "fashioned": 13405, + "disappearance": 13406, + "farewell": 13407, + "swollen": 13408, + "shrug": 13409, + "marquis": 13410, + "wimbledon": 13411, + "124": 13412, + "rue": 13413, + "1792": 13414, + "commemorate": 13415, + "reduces": 13416, + "experiencing": 13417, + "inevitable": 13418, + "calcutta": 13419, + "intel": 13420, + "##court": 13421, + "murderer": 13422, + "sticking": 13423, + "fisheries": 13424, + "imagery": 13425, + "bloom": 13426, + "280": 13427, + "brake": 13428, + "##inus": 13429, + "gustav": 13430, + "hesitation": 13431, + "memorable": 13432, + "po": 13433, + "viral": 13434, + "beans": 13435, + "accidents": 13436, + "tunisia": 13437, + "antenna": 13438, + "spilled": 13439, + "consort": 13440, + "treatments": 13441, + "aye": 13442, + "perimeter": 13443, + "##gard": 13444, + "donation": 13445, + "hostage": 13446, + "migrated": 13447, + "banker": 13448, + "addiction": 13449, + "apex": 13450, + "lil": 13451, + "trout": 13452, + "##ously": 13453, + "conscience": 13454, + "##nova": 13455, + "rams": 13456, + "sands": 13457, + "genome": 13458, + "passionate": 13459, + "troubles": 13460, + "##lets": 13461, + "##set": 13462, + "amid": 13463, + "##ibility": 13464, + "##ret": 13465, + "higgins": 13466, + "exceed": 13467, + "vikings": 13468, + "##vie": 13469, + "payne": 13470, + "##zan": 13471, + "muscular": 13472, + "##ste": 13473, + "defendant": 13474, + "sucking": 13475, + "##wal": 13476, + "ibrahim": 13477, + "fuselage": 13478, + "claudia": 13479, + "vfl": 13480, + "europeans": 13481, + "snails": 13482, + "interval": 13483, + "##garh": 13484, + "preparatory": 13485, + "statewide": 13486, + "tasked": 13487, + "lacrosse": 13488, + "viktor": 13489, + "##lation": 13490, + "angola": 13491, + "##hra": 13492, + "flint": 13493, + "implications": 13494, + "employs": 13495, + "teens": 13496, + "patrons": 13497, + "stall": 13498, + "weekends": 13499, + "barriers": 13500, + "scrambled": 13501, + "nucleus": 13502, + "tehran": 13503, + "jenna": 13504, + "parsons": 13505, + "lifelong": 13506, + "robots": 13507, + "displacement": 13508, + "5000": 13509, + "##bles": 13510, + "precipitation": 13511, + "##gt": 13512, + "knuckles": 13513, + "clutched": 13514, + "1802": 13515, + "marrying": 13516, + "ecology": 13517, + "marx": 13518, + "accusations": 13519, + "declare": 13520, + "scars": 13521, + "kolkata": 13522, + "mat": 13523, + "meadows": 13524, + "bermuda": 13525, + "skeleton": 13526, + "finalists": 13527, + "vintage": 13528, + "crawl": 13529, + "coordinate": 13530, + "affects": 13531, + "subjected": 13532, + "orchestral": 13533, + "mistaken": 13534, + "##tc": 13535, + "mirrors": 13536, + "dipped": 13537, + "relied": 13538, + "260": 13539, + "arches": 13540, + "candle": 13541, + "##nick": 13542, + "incorporating": 13543, + "wildly": 13544, + "fond": 13545, + "basilica": 13546, + "owl": 13547, + "fringe": 13548, + "rituals": 13549, + "whispering": 13550, + "stirred": 13551, + "feud": 13552, + "tertiary": 13553, + "slick": 13554, + "goat": 13555, + "honorable": 13556, + "whereby": 13557, + "skip": 13558, + "ricardo": 13559, + "stripes": 13560, + "parachute": 13561, + "adjoining": 13562, + "submerged": 13563, + "synthesizer": 13564, + "##gren": 13565, + "intend": 13566, + "positively": 13567, + "ninety": 13568, + "phi": 13569, + "beaver": 13570, + "partition": 13571, + "fellows": 13572, + "alexis": 13573, + "prohibition": 13574, + "carlisle": 13575, + "bizarre": 13576, + "fraternity": 13577, + "##bre": 13578, + "doubts": 13579, + "icy": 13580, + "cbc": 13581, + "aquatic": 13582, + "sneak": 13583, + "sonny": 13584, + "combines": 13585, + "airports": 13586, + "crude": 13587, + "supervised": 13588, + "spatial": 13589, + "merge": 13590, + "alfonso": 13591, + "##bic": 13592, + "corrupt": 13593, + "scan": 13594, + "undergo": 13595, + "##ams": 13596, + "disabilities": 13597, + "colombian": 13598, + "comparing": 13599, + "dolphins": 13600, + "perkins": 13601, + "##lish": 13602, + "reprinted": 13603, + "unanimous": 13604, + "bounced": 13605, + "hairs": 13606, + "underworld": 13607, + "midwest": 13608, + "semester": 13609, + "bucket": 13610, + "paperback": 13611, + "miniseries": 13612, + "coventry": 13613, + "demise": 13614, + "##leigh": 13615, + "demonstrations": 13616, + "sensor": 13617, + "rotating": 13618, + "yan": 13619, + "##hler": 13620, + "arrange": 13621, + "soils": 13622, + "##idge": 13623, + "hyderabad": 13624, + "labs": 13625, + "##dr": 13626, + "brakes": 13627, + "grandchildren": 13628, + "##nde": 13629, + "negotiated": 13630, + "rover": 13631, + "ferrari": 13632, + "continuation": 13633, + "directorate": 13634, + "augusta": 13635, + "stevenson": 13636, + "counterpart": 13637, + "gore": 13638, + "##rda": 13639, + "nursery": 13640, + "rican": 13641, + "ave": 13642, + "collectively": 13643, + "broadly": 13644, + "pastoral": 13645, + "repertoire": 13646, + "asserted": 13647, + "discovering": 13648, + "nordic": 13649, + "styled": 13650, + "fiba": 13651, + "cunningham": 13652, + "harley": 13653, + "middlesex": 13654, + "survives": 13655, + "tumor": 13656, + "tempo": 13657, + "zack": 13658, + "aiming": 13659, + "lok": 13660, + "urgent": 13661, + "##rade": 13662, + "##nto": 13663, + "devils": 13664, + "##ement": 13665, + "contractor": 13666, + "turin": 13667, + "##wl": 13668, + "##ool": 13669, + "bliss": 13670, + "repaired": 13671, + "simmons": 13672, + "moan": 13673, + "astronomical": 13674, + "cr": 13675, + "negotiate": 13676, + "lyric": 13677, + "1890s": 13678, + "lara": 13679, + "bred": 13680, + "clad": 13681, + "angus": 13682, + "pbs": 13683, + "##ience": 13684, + "engineered": 13685, + "posed": 13686, + "##lk": 13687, + "hernandez": 13688, + "possessions": 13689, + "elbows": 13690, + "psychiatric": 13691, + "strokes": 13692, + "confluence": 13693, + "electorate": 13694, + "lifts": 13695, + "campuses": 13696, + "lava": 13697, + "alps": 13698, + "##ep": 13699, + "##ution": 13700, + "##date": 13701, + "physicist": 13702, + "woody": 13703, + "##page": 13704, + "##ographic": 13705, + "##itis": 13706, + "juliet": 13707, + "reformation": 13708, + "sparhawk": 13709, + "320": 13710, + "complement": 13711, + "suppressed": 13712, + "jewel": 13713, + "##½": 13714, + "floated": 13715, + "##kas": 13716, + "continuity": 13717, + "sadly": 13718, + "##ische": 13719, + "inability": 13720, + "melting": 13721, + "scanning": 13722, + "paula": 13723, + "flour": 13724, + "judaism": 13725, + "safer": 13726, + "vague": 13727, + "##lm": 13728, + "solving": 13729, + "curb": 13730, + "##stown": 13731, + "financially": 13732, + "gable": 13733, + "bees": 13734, + "expired": 13735, + "miserable": 13736, + "cassidy": 13737, + "dominion": 13738, + "1789": 13739, + "cupped": 13740, + "145": 13741, + "robbery": 13742, + "facto": 13743, + "amos": 13744, + "warden": 13745, + "resume": 13746, + "tallest": 13747, + "marvin": 13748, + "ing": 13749, + "pounded": 13750, + "usd": 13751, + "declaring": 13752, + "gasoline": 13753, + "##aux": 13754, + "darkened": 13755, + "270": 13756, + "650": 13757, + "sophomore": 13758, + "##mere": 13759, + "erection": 13760, + "gossip": 13761, + "televised": 13762, + "risen": 13763, + "dial": 13764, + "##eu": 13765, + "pillars": 13766, + "##link": 13767, + "passages": 13768, + "profound": 13769, + "##tina": 13770, + "arabian": 13771, + "ashton": 13772, + "silicon": 13773, + "nail": 13774, + "##ead": 13775, + "##lated": 13776, + "##wer": 13777, + "##hardt": 13778, + "fleming": 13779, + "firearms": 13780, + "ducked": 13781, + "circuits": 13782, + "blows": 13783, + "waterloo": 13784, + "titans": 13785, + "##lina": 13786, + "atom": 13787, + "fireplace": 13788, + "cheshire": 13789, + "financed": 13790, + "activation": 13791, + "algorithms": 13792, + "##zzi": 13793, + "constituent": 13794, + "catcher": 13795, + "cherokee": 13796, + "partnerships": 13797, + "sexuality": 13798, + "platoon": 13799, + "tragic": 13800, + "vivian": 13801, + "guarded": 13802, + "whiskey": 13803, + "meditation": 13804, + "poetic": 13805, + "##late": 13806, + "##nga": 13807, + "##ake": 13808, + "porto": 13809, + "listeners": 13810, + "dominance": 13811, + "kendra": 13812, + "mona": 13813, + "chandler": 13814, + "factions": 13815, + "22nd": 13816, + "salisbury": 13817, + "attitudes": 13818, + "derivative": 13819, + "##ido": 13820, + "##haus": 13821, + "intake": 13822, + "paced": 13823, + "javier": 13824, + "illustrator": 13825, + "barrels": 13826, + "bias": 13827, + "cockpit": 13828, + "burnett": 13829, + "dreamed": 13830, + "ensuing": 13831, + "##anda": 13832, + "receptors": 13833, + "someday": 13834, + "hawkins": 13835, + "mattered": 13836, + "##lal": 13837, + "slavic": 13838, + "1799": 13839, + "jesuit": 13840, + "cameroon": 13841, + "wasted": 13842, + "tai": 13843, + "wax": 13844, + "lowering": 13845, + "victorious": 13846, + "freaking": 13847, + "outright": 13848, + "hancock": 13849, + "librarian": 13850, + "sensing": 13851, + "bald": 13852, + "calcium": 13853, + "myers": 13854, + "tablet": 13855, + "announcing": 13856, + "barack": 13857, + "shipyard": 13858, + "pharmaceutical": 13859, + "##uan": 13860, + "greenwich": 13861, + "flush": 13862, + "medley": 13863, + "patches": 13864, + "wolfgang": 13865, + "pt": 13866, + "speeches": 13867, + "acquiring": 13868, + "exams": 13869, + "nikolai": 13870, + "##gg": 13871, + "hayden": 13872, + "kannada": 13873, + "##type": 13874, + "reilly": 13875, + "##pt": 13876, + "waitress": 13877, + "abdomen": 13878, + "devastated": 13879, + "capped": 13880, + "pseudonym": 13881, + "pharmacy": 13882, + "fulfill": 13883, + "paraguay": 13884, + "1796": 13885, + "clicked": 13886, + "##trom": 13887, + "archipelago": 13888, + "syndicated": 13889, + "##hman": 13890, + "lumber": 13891, + "orgasm": 13892, + "rejection": 13893, + "clifford": 13894, + "lorraine": 13895, + "advent": 13896, + "mafia": 13897, + "rodney": 13898, + "brock": 13899, + "##ght": 13900, + "##used": 13901, + "##elia": 13902, + "cassette": 13903, + "chamberlain": 13904, + "despair": 13905, + "mongolia": 13906, + "sensors": 13907, + "developmental": 13908, + "upstream": 13909, + "##eg": 13910, + "##alis": 13911, + "spanning": 13912, + "165": 13913, + "trombone": 13914, + "basque": 13915, + "seeded": 13916, + "interred": 13917, + "renewable": 13918, + "rhys": 13919, + "leapt": 13920, + "revision": 13921, + "molecule": 13922, + "##ages": 13923, + "chord": 13924, + "vicious": 13925, + "nord": 13926, + "shivered": 13927, + "23rd": 13928, + "arlington": 13929, + "debts": 13930, + "corpus": 13931, + "sunrise": 13932, + "bays": 13933, + "blackburn": 13934, + "centimetres": 13935, + "##uded": 13936, + "shuddered": 13937, + "gm": 13938, + "strangely": 13939, + "gripping": 13940, + "cartoons": 13941, + "isabelle": 13942, + "orbital": 13943, + "##ppa": 13944, + "seals": 13945, + "proving": 13946, + "##lton": 13947, + "refusal": 13948, + "strengthened": 13949, + "bust": 13950, + "assisting": 13951, + "baghdad": 13952, + "batsman": 13953, + "portrayal": 13954, + "mara": 13955, + "pushes": 13956, + "spears": 13957, + "og": 13958, + "##cock": 13959, + "reside": 13960, + "nathaniel": 13961, + "brennan": 13962, + "1776": 13963, + "confirmation": 13964, + "caucus": 13965, + "##worthy": 13966, + "markings": 13967, + "yemen": 13968, + "nobles": 13969, + "ku": 13970, + "lazy": 13971, + "viewer": 13972, + "catalan": 13973, + "encompasses": 13974, + "sawyer": 13975, + "##fall": 13976, + "sparked": 13977, + "substances": 13978, + "patents": 13979, + "braves": 13980, + "arranger": 13981, + "evacuation": 13982, + "sergio": 13983, + "persuade": 13984, + "dover": 13985, + "tolerance": 13986, + "penguin": 13987, + "cum": 13988, + "jockey": 13989, + "insufficient": 13990, + "townships": 13991, + "occupying": 13992, + "declining": 13993, + "plural": 13994, + "processed": 13995, + "projection": 13996, + "puppet": 13997, + "flanders": 13998, + "introduces": 13999, + "liability": 14000, + "##yon": 14001, + "gymnastics": 14002, + "antwerp": 14003, + "taipei": 14004, + "hobart": 14005, + "candles": 14006, + "jeep": 14007, + "wes": 14008, + "observers": 14009, + "126": 14010, + "chaplain": 14011, + "bundle": 14012, + "glorious": 14013, + "##hine": 14014, + "hazel": 14015, + "flung": 14016, + "sol": 14017, + "excavations": 14018, + "dumped": 14019, + "stares": 14020, + "sh": 14021, + "bangalore": 14022, + "triangular": 14023, + "icelandic": 14024, + "intervals": 14025, + "expressing": 14026, + "turbine": 14027, + "##vers": 14028, + "songwriting": 14029, + "crafts": 14030, + "##igo": 14031, + "jasmine": 14032, + "ditch": 14033, + "rite": 14034, + "##ways": 14035, + "entertaining": 14036, + "comply": 14037, + "sorrow": 14038, + "wrestlers": 14039, + "basel": 14040, + "emirates": 14041, + "marian": 14042, + "rivera": 14043, + "helpful": 14044, + "##some": 14045, + "caution": 14046, + "downward": 14047, + "networking": 14048, + "##atory": 14049, + "##tered": 14050, + "darted": 14051, + "genocide": 14052, + "emergence": 14053, + "replies": 14054, + "specializing": 14055, + "spokesman": 14056, + "convenient": 14057, + "unlocked": 14058, + "fading": 14059, + "augustine": 14060, + "concentrations": 14061, + "resemblance": 14062, + "elijah": 14063, + "investigator": 14064, + "andhra": 14065, + "##uda": 14066, + "promotes": 14067, + "bean": 14068, + "##rrell": 14069, + "fleeing": 14070, + "wan": 14071, + "simone": 14072, + "announcer": 14073, + "##ame": 14074, + "##bby": 14075, + "lydia": 14076, + "weaver": 14077, + "132": 14078, + "residency": 14079, + "modification": 14080, + "##fest": 14081, + "stretches": 14082, + "##ast": 14083, + "alternatively": 14084, + "nat": 14085, + "lowe": 14086, + "lacks": 14087, + "##ented": 14088, + "pam": 14089, + "tile": 14090, + "concealed": 14091, + "inferior": 14092, + "abdullah": 14093, + "residences": 14094, + "tissues": 14095, + "vengeance": 14096, + "##ided": 14097, + "moisture": 14098, + "peculiar": 14099, + "groove": 14100, + "zip": 14101, + "bologna": 14102, + "jennings": 14103, + "ninja": 14104, + "oversaw": 14105, + "zombies": 14106, + "pumping": 14107, + "batch": 14108, + "livingston": 14109, + "emerald": 14110, + "installations": 14111, + "1797": 14112, + "peel": 14113, + "nitrogen": 14114, + "rama": 14115, + "##fying": 14116, + "##star": 14117, + "schooling": 14118, + "strands": 14119, + "responding": 14120, + "werner": 14121, + "##ost": 14122, + "lime": 14123, + "casa": 14124, + "accurately": 14125, + "targeting": 14126, + "##rod": 14127, + "underway": 14128, + "##uru": 14129, + "hemisphere": 14130, + "lester": 14131, + "##yard": 14132, + "occupies": 14133, + "2d": 14134, + "griffith": 14135, + "angrily": 14136, + "reorganized": 14137, + "##owing": 14138, + "courtney": 14139, + "deposited": 14140, + "##dd": 14141, + "##30": 14142, + "estadio": 14143, + "##ifies": 14144, + "dunn": 14145, + "exiled": 14146, + "##ying": 14147, + "checks": 14148, + "##combe": 14149, + "##о": 14150, + "##fly": 14151, + "successes": 14152, + "unexpectedly": 14153, + "blu": 14154, + "assessed": 14155, + "##flower": 14156, + "##ه": 14157, + "observing": 14158, + "sacked": 14159, + "spiders": 14160, + "kn": 14161, + "##tail": 14162, + "mu": 14163, + "nodes": 14164, + "prosperity": 14165, + "audrey": 14166, + "divisional": 14167, + "155": 14168, + "broncos": 14169, + "tangled": 14170, + "adjust": 14171, + "feeds": 14172, + "erosion": 14173, + "paolo": 14174, + "surf": 14175, + "directory": 14176, + "snatched": 14177, + "humid": 14178, + "admiralty": 14179, + "screwed": 14180, + "gt": 14181, + "reddish": 14182, + "##nese": 14183, + "modules": 14184, + "trench": 14185, + "lamps": 14186, + "bind": 14187, + "leah": 14188, + "bucks": 14189, + "competes": 14190, + "##nz": 14191, + "##form": 14192, + "transcription": 14193, + "##uc": 14194, + "isles": 14195, + "violently": 14196, + "clutching": 14197, + "pga": 14198, + "cyclist": 14199, + "inflation": 14200, + "flats": 14201, + "ragged": 14202, + "unnecessary": 14203, + "##hian": 14204, + "stubborn": 14205, + "coordinated": 14206, + "harriet": 14207, + "baba": 14208, + "disqualified": 14209, + "330": 14210, + "insect": 14211, + "wolfe": 14212, + "##fies": 14213, + "reinforcements": 14214, + "rocked": 14215, + "duel": 14216, + "winked": 14217, + "embraced": 14218, + "bricks": 14219, + "##raj": 14220, + "hiatus": 14221, + "defeats": 14222, + "pending": 14223, + "brightly": 14224, + "jealousy": 14225, + "##xton": 14226, + "##hm": 14227, + "##uki": 14228, + "lena": 14229, + "gdp": 14230, + "colorful": 14231, + "##dley": 14232, + "stein": 14233, + "kidney": 14234, + "##shu": 14235, + "underwear": 14236, + "wanderers": 14237, + "##haw": 14238, + "##icus": 14239, + "guardians": 14240, + "m³": 14241, + "roared": 14242, + "habits": 14243, + "##wise": 14244, + "permits": 14245, + "gp": 14246, + "uranium": 14247, + "punished": 14248, + "disguise": 14249, + "bundesliga": 14250, + "elise": 14251, + "dundee": 14252, + "erotic": 14253, + "partisan": 14254, + "pi": 14255, + "collectors": 14256, + "float": 14257, + "individually": 14258, + "rendering": 14259, + "behavioral": 14260, + "bucharest": 14261, + "ser": 14262, + "hare": 14263, + "valerie": 14264, + "corporal": 14265, + "nutrition": 14266, + "proportional": 14267, + "##isa": 14268, + "immense": 14269, + "##kis": 14270, + "pavement": 14271, + "##zie": 14272, + "##eld": 14273, + "sutherland": 14274, + "crouched": 14275, + "1775": 14276, + "##lp": 14277, + "suzuki": 14278, + "trades": 14279, + "endurance": 14280, + "operas": 14281, + "crosby": 14282, + "prayed": 14283, + "priory": 14284, + "rory": 14285, + "socially": 14286, + "##urn": 14287, + "gujarat": 14288, + "##pu": 14289, + "walton": 14290, + "cube": 14291, + "pasha": 14292, + "privilege": 14293, + "lennon": 14294, + "floods": 14295, + "thorne": 14296, + "waterfall": 14297, + "nipple": 14298, + "scouting": 14299, + "approve": 14300, + "##lov": 14301, + "minorities": 14302, + "voter": 14303, + "dwight": 14304, + "extensions": 14305, + "assure": 14306, + "ballroom": 14307, + "slap": 14308, + "dripping": 14309, + "privileges": 14310, + "rejoined": 14311, + "confessed": 14312, + "demonstrating": 14313, + "patriotic": 14314, + "yell": 14315, + "investor": 14316, + "##uth": 14317, + "pagan": 14318, + "slumped": 14319, + "squares": 14320, + "##cle": 14321, + "##kins": 14322, + "confront": 14323, + "bert": 14324, + "embarrassment": 14325, + "##aid": 14326, + "aston": 14327, + "urging": 14328, + "sweater": 14329, + "starr": 14330, + "yuri": 14331, + "brains": 14332, + "williamson": 14333, + "commuter": 14334, + "mortar": 14335, + "structured": 14336, + "selfish": 14337, + "exports": 14338, + "##jon": 14339, + "cds": 14340, + "##him": 14341, + "unfinished": 14342, + "##rre": 14343, + "mortgage": 14344, + "destinations": 14345, + "##nagar": 14346, + "canoe": 14347, + "solitary": 14348, + "buchanan": 14349, + "delays": 14350, + "magistrate": 14351, + "fk": 14352, + "##pling": 14353, + "motivation": 14354, + "##lier": 14355, + "##vier": 14356, + "recruiting": 14357, + "assess": 14358, + "##mouth": 14359, + "malik": 14360, + "antique": 14361, + "1791": 14362, + "pius": 14363, + "rahman": 14364, + "reich": 14365, + "tub": 14366, + "zhou": 14367, + "smashed": 14368, + "airs": 14369, + "galway": 14370, + "xii": 14371, + "conditioning": 14372, + "honduras": 14373, + "discharged": 14374, + "dexter": 14375, + "##pf": 14376, + "lionel": 14377, + "129": 14378, + "debates": 14379, + "lemon": 14380, + "tiffany": 14381, + "volunteered": 14382, + "dom": 14383, + "dioxide": 14384, + "procession": 14385, + "devi": 14386, + "sic": 14387, + "tremendous": 14388, + "advertisements": 14389, + "colts": 14390, + "transferring": 14391, + "verdict": 14392, + "hanover": 14393, + "decommissioned": 14394, + "utter": 14395, + "relate": 14396, + "pac": 14397, + "racism": 14398, + "##top": 14399, + "beacon": 14400, + "limp": 14401, + "similarity": 14402, + "terra": 14403, + "occurrence": 14404, + "ant": 14405, + "##how": 14406, + "becky": 14407, + "capt": 14408, + "updates": 14409, + "armament": 14410, + "richie": 14411, + "pal": 14412, + "##graph": 14413, + "halloween": 14414, + "mayo": 14415, + "##ssen": 14416, + "##bone": 14417, + "cara": 14418, + "serena": 14419, + "fcc": 14420, + "dolls": 14421, + "obligations": 14422, + "##dling": 14423, + "violated": 14424, + "lafayette": 14425, + "jakarta": 14426, + "exploitation": 14427, + "##ime": 14428, + "infamous": 14429, + "iconic": 14430, + "##lah": 14431, + "##park": 14432, + "kitty": 14433, + "moody": 14434, + "reginald": 14435, + "dread": 14436, + "spill": 14437, + "crystals": 14438, + "olivier": 14439, + "modeled": 14440, + "bluff": 14441, + "equilibrium": 14442, + "separating": 14443, + "notices": 14444, + "ordnance": 14445, + "extinction": 14446, + "onset": 14447, + "cosmic": 14448, + "attachment": 14449, + "sammy": 14450, + "expose": 14451, + "privy": 14452, + "anchored": 14453, + "##bil": 14454, + "abbott": 14455, + "admits": 14456, + "bending": 14457, + "baritone": 14458, + "emmanuel": 14459, + "policeman": 14460, + "vaughan": 14461, + "winged": 14462, + "climax": 14463, + "dresses": 14464, + "denny": 14465, + "polytechnic": 14466, + "mohamed": 14467, + "burmese": 14468, + "authentic": 14469, + "nikki": 14470, + "genetics": 14471, + "grandparents": 14472, + "homestead": 14473, + "gaza": 14474, + "postponed": 14475, + "metacritic": 14476, + "una": 14477, + "##sby": 14478, + "##bat": 14479, + "unstable": 14480, + "dissertation": 14481, + "##rial": 14482, + "##cian": 14483, + "curls": 14484, + "obscure": 14485, + "uncovered": 14486, + "bronx": 14487, + "praying": 14488, + "disappearing": 14489, + "##hoe": 14490, + "prehistoric": 14491, + "coke": 14492, + "turret": 14493, + "mutations": 14494, + "nonprofit": 14495, + "pits": 14496, + "monaco": 14497, + "##ي": 14498, + "##usion": 14499, + "prominently": 14500, + "dispatched": 14501, + "podium": 14502, + "##mir": 14503, + "uci": 14504, + "##uation": 14505, + "133": 14506, + "fortifications": 14507, + "birthplace": 14508, + "kendall": 14509, + "##lby": 14510, + "##oll": 14511, + "preacher": 14512, + "rack": 14513, + "goodman": 14514, + "##rman": 14515, + "persistent": 14516, + "##ott": 14517, + "countless": 14518, + "jaime": 14519, + "recorder": 14520, + "lexington": 14521, + "persecution": 14522, + "jumps": 14523, + "renewal": 14524, + "wagons": 14525, + "##11": 14526, + "crushing": 14527, + "##holder": 14528, + "decorations": 14529, + "##lake": 14530, + "abundance": 14531, + "wrath": 14532, + "laundry": 14533, + "£1": 14534, + "garde": 14535, + "##rp": 14536, + "jeanne": 14537, + "beetles": 14538, + "peasant": 14539, + "##sl": 14540, + "splitting": 14541, + "caste": 14542, + "sergei": 14543, + "##rer": 14544, + "##ema": 14545, + "scripts": 14546, + "##ively": 14547, + "rub": 14548, + "satellites": 14549, + "##vor": 14550, + "inscribed": 14551, + "verlag": 14552, + "scrapped": 14553, + "gale": 14554, + "packages": 14555, + "chick": 14556, + "potato": 14557, + "slogan": 14558, + "kathleen": 14559, + "arabs": 14560, + "##culture": 14561, + "counterparts": 14562, + "reminiscent": 14563, + "choral": 14564, + "##tead": 14565, + "rand": 14566, + "retains": 14567, + "bushes": 14568, + "dane": 14569, + "accomplish": 14570, + "courtesy": 14571, + "closes": 14572, + "##oth": 14573, + "slaughter": 14574, + "hague": 14575, + "krakow": 14576, + "lawson": 14577, + "tailed": 14578, + "elias": 14579, + "ginger": 14580, + "##ttes": 14581, + "canopy": 14582, + "betrayal": 14583, + "rebuilding": 14584, + "turf": 14585, + "##hof": 14586, + "frowning": 14587, + "allegiance": 14588, + "brigades": 14589, + "kicks": 14590, + "rebuild": 14591, + "polls": 14592, + "alias": 14593, + "nationalism": 14594, + "td": 14595, + "rowan": 14596, + "audition": 14597, + "bowie": 14598, + "fortunately": 14599, + "recognizes": 14600, + "harp": 14601, + "dillon": 14602, + "horrified": 14603, + "##oro": 14604, + "renault": 14605, + "##tics": 14606, + "ropes": 14607, + "##α": 14608, + "presumed": 14609, + "rewarded": 14610, + "infrared": 14611, + "wiping": 14612, + "accelerated": 14613, + "illustration": 14614, + "##rid": 14615, + "presses": 14616, + "practitioners": 14617, + "badminton": 14618, + "##iard": 14619, + "detained": 14620, + "##tera": 14621, + "recognizing": 14622, + "relates": 14623, + "misery": 14624, + "##sies": 14625, + "##tly": 14626, + "reproduction": 14627, + "piercing": 14628, + "potatoes": 14629, + "thornton": 14630, + "esther": 14631, + "manners": 14632, + "hbo": 14633, + "##aan": 14634, + "ours": 14635, + "bullshit": 14636, + "ernie": 14637, + "perennial": 14638, + "sensitivity": 14639, + "illuminated": 14640, + "rupert": 14641, + "##jin": 14642, + "##iss": 14643, + "##ear": 14644, + "rfc": 14645, + "nassau": 14646, + "##dock": 14647, + "staggered": 14648, + "socialism": 14649, + "##haven": 14650, + "appointments": 14651, + "nonsense": 14652, + "prestige": 14653, + "sharma": 14654, + "haul": 14655, + "##tical": 14656, + "solidarity": 14657, + "gps": 14658, + "##ook": 14659, + "##rata": 14660, + "igor": 14661, + "pedestrian": 14662, + "##uit": 14663, + "baxter": 14664, + "tenants": 14665, + "wires": 14666, + "medication": 14667, + "unlimited": 14668, + "guiding": 14669, + "impacts": 14670, + "diabetes": 14671, + "##rama": 14672, + "sasha": 14673, + "pas": 14674, + "clive": 14675, + "extraction": 14676, + "131": 14677, + "continually": 14678, + "constraints": 14679, + "##bilities": 14680, + "sonata": 14681, + "hunted": 14682, + "sixteenth": 14683, + "chu": 14684, + "planting": 14685, + "quote": 14686, + "mayer": 14687, + "pretended": 14688, + "abs": 14689, + "spat": 14690, + "##hua": 14691, + "ceramic": 14692, + "##cci": 14693, + "curtains": 14694, + "pigs": 14695, + "pitching": 14696, + "##dad": 14697, + "latvian": 14698, + "sore": 14699, + "dayton": 14700, + "##sted": 14701, + "##qi": 14702, + "patrols": 14703, + "slice": 14704, + "playground": 14705, + "##nted": 14706, + "shone": 14707, + "stool": 14708, + "apparatus": 14709, + "inadequate": 14710, + "mates": 14711, + "treason": 14712, + "##ija": 14713, + "desires": 14714, + "##liga": 14715, + "##croft": 14716, + "somalia": 14717, + "laurent": 14718, + "mir": 14719, + "leonardo": 14720, + "oracle": 14721, + "grape": 14722, + "obliged": 14723, + "chevrolet": 14724, + "thirteenth": 14725, + "stunning": 14726, + "enthusiastic": 14727, + "##ede": 14728, + "accounted": 14729, + "concludes": 14730, + "currents": 14731, + "basil": 14732, + "##kovic": 14733, + "drought": 14734, + "##rica": 14735, + "mai": 14736, + "##aire": 14737, + "shove": 14738, + "posting": 14739, + "##shed": 14740, + "pilgrimage": 14741, + "humorous": 14742, + "packing": 14743, + "fry": 14744, + "pencil": 14745, + "wines": 14746, + "smells": 14747, + "144": 14748, + "marilyn": 14749, + "aching": 14750, + "newest": 14751, + "clung": 14752, + "bon": 14753, + "neighbours": 14754, + "sanctioned": 14755, + "##pie": 14756, + "mug": 14757, + "##stock": 14758, + "drowning": 14759, + "##mma": 14760, + "hydraulic": 14761, + "##vil": 14762, + "hiring": 14763, + "reminder": 14764, + "lilly": 14765, + "investigators": 14766, + "##ncies": 14767, + "sour": 14768, + "##eous": 14769, + "compulsory": 14770, + "packet": 14771, + "##rion": 14772, + "##graphic": 14773, + "##elle": 14774, + "cannes": 14775, + "##inate": 14776, + "depressed": 14777, + "##rit": 14778, + "heroic": 14779, + "importantly": 14780, + "theresa": 14781, + "##tled": 14782, + "conway": 14783, + "saturn": 14784, + "marginal": 14785, + "rae": 14786, + "##xia": 14787, + "corresponds": 14788, + "royce": 14789, + "pact": 14790, + "jasper": 14791, + "explosives": 14792, + "packaging": 14793, + "aluminium": 14794, + "##ttered": 14795, + "denotes": 14796, + "rhythmic": 14797, + "spans": 14798, + "assignments": 14799, + "hereditary": 14800, + "outlined": 14801, + "originating": 14802, + "sundays": 14803, + "lad": 14804, + "reissued": 14805, + "greeting": 14806, + "beatrice": 14807, + "##dic": 14808, + "pillar": 14809, + "marcos": 14810, + "plots": 14811, + "handbook": 14812, + "alcoholic": 14813, + "judiciary": 14814, + "avant": 14815, + "slides": 14816, + "extract": 14817, + "masculine": 14818, + "blur": 14819, + "##eum": 14820, + "##force": 14821, + "homage": 14822, + "trembled": 14823, + "owens": 14824, + "hymn": 14825, + "trey": 14826, + "omega": 14827, + "signaling": 14828, + "socks": 14829, + "accumulated": 14830, + "reacted": 14831, + "attic": 14832, + "theo": 14833, + "lining": 14834, + "angie": 14835, + "distraction": 14836, + "primera": 14837, + "talbot": 14838, + "##key": 14839, + "1200": 14840, + "ti": 14841, + "creativity": 14842, + "billed": 14843, + "##hey": 14844, + "deacon": 14845, + "eduardo": 14846, + "identifies": 14847, + "proposition": 14848, + "dizzy": 14849, + "gunner": 14850, + "hogan": 14851, + "##yam": 14852, + "##pping": 14853, + "##hol": 14854, + "ja": 14855, + "##chan": 14856, + "jensen": 14857, + "reconstructed": 14858, + "##berger": 14859, + "clearance": 14860, + "darius": 14861, + "##nier": 14862, + "abe": 14863, + "harlem": 14864, + "plea": 14865, + "dei": 14866, + "circled": 14867, + "emotionally": 14868, + "notation": 14869, + "fascist": 14870, + "neville": 14871, + "exceeded": 14872, + "upwards": 14873, + "viable": 14874, + "ducks": 14875, + "##fo": 14876, + "workforce": 14877, + "racer": 14878, + "limiting": 14879, + "shri": 14880, + "##lson": 14881, + "possesses": 14882, + "1600": 14883, + "kerr": 14884, + "moths": 14885, + "devastating": 14886, + "laden": 14887, + "disturbing": 14888, + "locking": 14889, + "##cture": 14890, + "gal": 14891, + "fearing": 14892, + "accreditation": 14893, + "flavor": 14894, + "aide": 14895, + "1870s": 14896, + "mountainous": 14897, + "##baum": 14898, + "melt": 14899, + "##ures": 14900, + "motel": 14901, + "texture": 14902, + "servers": 14903, + "soda": 14904, + "##mb": 14905, + "herd": 14906, + "##nium": 14907, + "erect": 14908, + "puzzled": 14909, + "hum": 14910, + "peggy": 14911, + "examinations": 14912, + "gould": 14913, + "testified": 14914, + "geoff": 14915, + "ren": 14916, + "devised": 14917, + "sacks": 14918, + "##law": 14919, + "denial": 14920, + "posters": 14921, + "grunted": 14922, + "cesar": 14923, + "tutor": 14924, + "ec": 14925, + "gerry": 14926, + "offerings": 14927, + "byrne": 14928, + "falcons": 14929, + "combinations": 14930, + "ct": 14931, + "incoming": 14932, + "pardon": 14933, + "rocking": 14934, + "26th": 14935, + "avengers": 14936, + "flared": 14937, + "mankind": 14938, + "seller": 14939, + "uttar": 14940, + "loch": 14941, + "nadia": 14942, + "stroking": 14943, + "exposing": 14944, + "##hd": 14945, + "fertile": 14946, + "ancestral": 14947, + "instituted": 14948, + "##has": 14949, + "noises": 14950, + "prophecy": 14951, + "taxation": 14952, + "eminent": 14953, + "vivid": 14954, + "pol": 14955, + "##bol": 14956, + "dart": 14957, + "indirect": 14958, + "multimedia": 14959, + "notebook": 14960, + "upside": 14961, + "displaying": 14962, + "adrenaline": 14963, + "referenced": 14964, + "geometric": 14965, + "##iving": 14966, + "progression": 14967, + "##ddy": 14968, + "blunt": 14969, + "announce": 14970, + "##far": 14971, + "implementing": 14972, + "##lav": 14973, + "aggression": 14974, + "liaison": 14975, + "cooler": 14976, + "cares": 14977, + "headache": 14978, + "plantations": 14979, + "gorge": 14980, + "dots": 14981, + "impulse": 14982, + "thickness": 14983, + "ashamed": 14984, + "averaging": 14985, + "kathy": 14986, + "obligation": 14987, + "precursor": 14988, + "137": 14989, + "fowler": 14990, + "symmetry": 14991, + "thee": 14992, + "225": 14993, + "hears": 14994, + "##rai": 14995, + "undergoing": 14996, + "ads": 14997, + "butcher": 14998, + "bowler": 14999, + "##lip": 15000, + "cigarettes": 15001, + "subscription": 15002, + "goodness": 15003, + "##ically": 15004, + "browne": 15005, + "##hos": 15006, + "##tech": 15007, + "kyoto": 15008, + "donor": 15009, + "##erty": 15010, + "damaging": 15011, + "friction": 15012, + "drifting": 15013, + "expeditions": 15014, + "hardened": 15015, + "prostitution": 15016, + "152": 15017, + "fauna": 15018, + "blankets": 15019, + "claw": 15020, + "tossing": 15021, + "snarled": 15022, + "butterflies": 15023, + "recruits": 15024, + "investigative": 15025, + "coated": 15026, + "healed": 15027, + "138": 15028, + "communal": 15029, + "hai": 15030, + "xiii": 15031, + "academics": 15032, + "boone": 15033, + "psychologist": 15034, + "restless": 15035, + "lahore": 15036, + "stephens": 15037, + "mba": 15038, + "brendan": 15039, + "foreigners": 15040, + "printer": 15041, + "##pc": 15042, + "ached": 15043, + "explode": 15044, + "27th": 15045, + "deed": 15046, + "scratched": 15047, + "dared": 15048, + "##pole": 15049, + "cardiac": 15050, + "1780": 15051, + "okinawa": 15052, + "proto": 15053, + "commando": 15054, + "compelled": 15055, + "oddly": 15056, + "electrons": 15057, + "##base": 15058, + "replica": 15059, + "thanksgiving": 15060, + "##rist": 15061, + "sheila": 15062, + "deliberate": 15063, + "stafford": 15064, + "tidal": 15065, + "representations": 15066, + "hercules": 15067, + "ou": 15068, + "##path": 15069, + "##iated": 15070, + "kidnapping": 15071, + "lenses": 15072, + "##tling": 15073, + "deficit": 15074, + "samoa": 15075, + "mouths": 15076, + "consuming": 15077, + "computational": 15078, + "maze": 15079, + "granting": 15080, + "smirk": 15081, + "razor": 15082, + "fixture": 15083, + "ideals": 15084, + "inviting": 15085, + "aiden": 15086, + "nominal": 15087, + "##vs": 15088, + "issuing": 15089, + "julio": 15090, + "pitt": 15091, + "ramsey": 15092, + "docks": 15093, + "##oss": 15094, + "exhaust": 15095, + "##owed": 15096, + "bavarian": 15097, + "draped": 15098, + "anterior": 15099, + "mating": 15100, + "ethiopian": 15101, + "explores": 15102, + "noticing": 15103, + "##nton": 15104, + "discarded": 15105, + "convenience": 15106, + "hoffman": 15107, + "endowment": 15108, + "beasts": 15109, + "cartridge": 15110, + "mormon": 15111, + "paternal": 15112, + "probe": 15113, + "sleeves": 15114, + "interfere": 15115, + "lump": 15116, + "deadline": 15117, + "##rail": 15118, + "jenks": 15119, + "bulldogs": 15120, + "scrap": 15121, + "alternating": 15122, + "justified": 15123, + "reproductive": 15124, + "nam": 15125, + "seize": 15126, + "descending": 15127, + "secretariat": 15128, + "kirby": 15129, + "coupe": 15130, + "grouped": 15131, + "smash": 15132, + "panther": 15133, + "sedan": 15134, + "tapping": 15135, + "##18": 15136, + "lola": 15137, + "cheer": 15138, + "germanic": 15139, + "unfortunate": 15140, + "##eter": 15141, + "unrelated": 15142, + "##fan": 15143, + "subordinate": 15144, + "##sdale": 15145, + "suzanne": 15146, + "advertisement": 15147, + "##ility": 15148, + "horsepower": 15149, + "##lda": 15150, + "cautiously": 15151, + "discourse": 15152, + "luigi": 15153, + "##mans": 15154, + "##fields": 15155, + "noun": 15156, + "prevalent": 15157, + "mao": 15158, + "schneider": 15159, + "everett": 15160, + "surround": 15161, + "governorate": 15162, + "kira": 15163, + "##avia": 15164, + "westward": 15165, + "##take": 15166, + "misty": 15167, + "rails": 15168, + "sustainability": 15169, + "134": 15170, + "unused": 15171, + "##rating": 15172, + "packs": 15173, + "toast": 15174, + "unwilling": 15175, + "regulate": 15176, + "thy": 15177, + "suffrage": 15178, + "nile": 15179, + "awe": 15180, + "assam": 15181, + "definitions": 15182, + "travelers": 15183, + "affordable": 15184, + "##rb": 15185, + "conferred": 15186, + "sells": 15187, + "undefeated": 15188, + "beneficial": 15189, + "torso": 15190, + "basal": 15191, + "repeating": 15192, + "remixes": 15193, + "##pass": 15194, + "bahrain": 15195, + "cables": 15196, + "fang": 15197, + "##itated": 15198, + "excavated": 15199, + "numbering": 15200, + "statutory": 15201, + "##rey": 15202, + "deluxe": 15203, + "##lian": 15204, + "forested": 15205, + "ramirez": 15206, + "derbyshire": 15207, + "zeus": 15208, + "slamming": 15209, + "transfers": 15210, + "astronomer": 15211, + "banana": 15212, + "lottery": 15213, + "berg": 15214, + "histories": 15215, + "bamboo": 15216, + "##uchi": 15217, + "resurrection": 15218, + "posterior": 15219, + "bowls": 15220, + "vaguely": 15221, + "##thi": 15222, + "thou": 15223, + "preserving": 15224, + "tensed": 15225, + "offence": 15226, + "##inas": 15227, + "meyrick": 15228, + "callum": 15229, + "ridden": 15230, + "watt": 15231, + "langdon": 15232, + "tying": 15233, + "lowland": 15234, + "snorted": 15235, + "daring": 15236, + "truman": 15237, + "##hale": 15238, + "##girl": 15239, + "aura": 15240, + "overly": 15241, + "filing": 15242, + "weighing": 15243, + "goa": 15244, + "infections": 15245, + "philanthropist": 15246, + "saunders": 15247, + "eponymous": 15248, + "##owski": 15249, + "latitude": 15250, + "perspectives": 15251, + "reviewing": 15252, + "mets": 15253, + "commandant": 15254, + "radial": 15255, + "##kha": 15256, + "flashlight": 15257, + "reliability": 15258, + "koch": 15259, + "vowels": 15260, + "amazed": 15261, + "ada": 15262, + "elaine": 15263, + "supper": 15264, + "##rth": 15265, + "##encies": 15266, + "predator": 15267, + "debated": 15268, + "soviets": 15269, + "cola": 15270, + "##boards": 15271, + "##nah": 15272, + "compartment": 15273, + "crooked": 15274, + "arbitrary": 15275, + "fourteenth": 15276, + "##ctive": 15277, + "havana": 15278, + "majors": 15279, + "steelers": 15280, + "clips": 15281, + "profitable": 15282, + "ambush": 15283, + "exited": 15284, + "packers": 15285, + "##tile": 15286, + "nude": 15287, + "cracks": 15288, + "fungi": 15289, + "##е": 15290, + "limb": 15291, + "trousers": 15292, + "josie": 15293, + "shelby": 15294, + "tens": 15295, + "frederic": 15296, + "##ος": 15297, + "definite": 15298, + "smoothly": 15299, + "constellation": 15300, + "insult": 15301, + "baton": 15302, + "discs": 15303, + "lingering": 15304, + "##nco": 15305, + "conclusions": 15306, + "lent": 15307, + "staging": 15308, + "becker": 15309, + "grandpa": 15310, + "shaky": 15311, + "##tron": 15312, + "einstein": 15313, + "obstacles": 15314, + "sk": 15315, + "adverse": 15316, + "elle": 15317, + "economically": 15318, + "##moto": 15319, + "mccartney": 15320, + "thor": 15321, + "dismissal": 15322, + "motions": 15323, + "readings": 15324, + "nostrils": 15325, + "treatise": 15326, + "##pace": 15327, + "squeezing": 15328, + "evidently": 15329, + "prolonged": 15330, + "1783": 15331, + "venezuelan": 15332, + "je": 15333, + "marguerite": 15334, + "beirut": 15335, + "takeover": 15336, + "shareholders": 15337, + "##vent": 15338, + "denise": 15339, + "digit": 15340, + "airplay": 15341, + "norse": 15342, + "##bbling": 15343, + "imaginary": 15344, + "pills": 15345, + "hubert": 15346, + "blaze": 15347, + "vacated": 15348, + "eliminating": 15349, + "##ello": 15350, + "vine": 15351, + "mansfield": 15352, + "##tty": 15353, + "retrospective": 15354, + "barrow": 15355, + "borne": 15356, + "clutch": 15357, + "bail": 15358, + "forensic": 15359, + "weaving": 15360, + "##nett": 15361, + "##witz": 15362, + "desktop": 15363, + "citadel": 15364, + "promotions": 15365, + "worrying": 15366, + "dorset": 15367, + "ieee": 15368, + "subdivided": 15369, + "##iating": 15370, + "manned": 15371, + "expeditionary": 15372, + "pickup": 15373, + "synod": 15374, + "chuckle": 15375, + "185": 15376, + "barney": 15377, + "##rz": 15378, + "##ffin": 15379, + "functionality": 15380, + "karachi": 15381, + "litigation": 15382, + "meanings": 15383, + "uc": 15384, + "lick": 15385, + "turbo": 15386, + "anders": 15387, + "##ffed": 15388, + "execute": 15389, + "curl": 15390, + "oppose": 15391, + "ankles": 15392, + "typhoon": 15393, + "##د": 15394, + "##ache": 15395, + "##asia": 15396, + "linguistics": 15397, + "compassion": 15398, + "pressures": 15399, + "grazing": 15400, + "perfection": 15401, + "##iting": 15402, + "immunity": 15403, + "monopoly": 15404, + "muddy": 15405, + "backgrounds": 15406, + "136": 15407, + "namibia": 15408, + "francesca": 15409, + "monitors": 15410, + "attracting": 15411, + "stunt": 15412, + "tuition": 15413, + "##ии": 15414, + "vegetable": 15415, + "##mates": 15416, + "##quent": 15417, + "mgm": 15418, + "jen": 15419, + "complexes": 15420, + "forts": 15421, + "##ond": 15422, + "cellar": 15423, + "bites": 15424, + "seventeenth": 15425, + "royals": 15426, + "flemish": 15427, + "failures": 15428, + "mast": 15429, + "charities": 15430, + "##cular": 15431, + "peruvian": 15432, + "capitals": 15433, + "macmillan": 15434, + "ipswich": 15435, + "outward": 15436, + "frigate": 15437, + "postgraduate": 15438, + "folds": 15439, + "employing": 15440, + "##ouse": 15441, + "concurrently": 15442, + "fiery": 15443, + "##tai": 15444, + "contingent": 15445, + "nightmares": 15446, + "monumental": 15447, + "nicaragua": 15448, + "##kowski": 15449, + "lizard": 15450, + "mal": 15451, + "fielding": 15452, + "gig": 15453, + "reject": 15454, + "##pad": 15455, + "harding": 15456, + "##ipe": 15457, + "coastline": 15458, + "##cin": 15459, + "##nos": 15460, + "beethoven": 15461, + "humphrey": 15462, + "innovations": 15463, + "##tam": 15464, + "##nge": 15465, + "norris": 15466, + "doris": 15467, + "solicitor": 15468, + "huang": 15469, + "obey": 15470, + "141": 15471, + "##lc": 15472, + "niagara": 15473, + "##tton": 15474, + "shelves": 15475, + "aug": 15476, + "bourbon": 15477, + "curry": 15478, + "nightclub": 15479, + "specifications": 15480, + "hilton": 15481, + "##ndo": 15482, + "centennial": 15483, + "dispersed": 15484, + "worm": 15485, + "neglected": 15486, + "briggs": 15487, + "sm": 15488, + "font": 15489, + "kuala": 15490, + "uneasy": 15491, + "plc": 15492, + "##nstein": 15493, + "##bound": 15494, + "##aking": 15495, + "##burgh": 15496, + "awaiting": 15497, + "pronunciation": 15498, + "##bbed": 15499, + "##quest": 15500, + "eh": 15501, + "optimal": 15502, + "zhu": 15503, + "raped": 15504, + "greens": 15505, + "presided": 15506, + "brenda": 15507, + "worries": 15508, + "##life": 15509, + "venetian": 15510, + "marxist": 15511, + "turnout": 15512, + "##lius": 15513, + "refined": 15514, + "braced": 15515, + "sins": 15516, + "grasped": 15517, + "sunderland": 15518, + "nickel": 15519, + "speculated": 15520, + "lowell": 15521, + "cyrillic": 15522, + "communism": 15523, + "fundraising": 15524, + "resembling": 15525, + "colonists": 15526, + "mutant": 15527, + "freddie": 15528, + "usc": 15529, + "##mos": 15530, + "gratitude": 15531, + "##run": 15532, + "mural": 15533, + "##lous": 15534, + "chemist": 15535, + "wi": 15536, + "reminds": 15537, + "28th": 15538, + "steals": 15539, + "tess": 15540, + "pietro": 15541, + "##ingen": 15542, + "promoter": 15543, + "ri": 15544, + "microphone": 15545, + "honoured": 15546, + "rai": 15547, + "sant": 15548, + "##qui": 15549, + "feather": 15550, + "##nson": 15551, + "burlington": 15552, + "kurdish": 15553, + "terrorists": 15554, + "deborah": 15555, + "sickness": 15556, + "##wed": 15557, + "##eet": 15558, + "hazard": 15559, + "irritated": 15560, + "desperation": 15561, + "veil": 15562, + "clarity": 15563, + "##rik": 15564, + "jewels": 15565, + "xv": 15566, + "##gged": 15567, + "##ows": 15568, + "##cup": 15569, + "berkshire": 15570, + "unfair": 15571, + "mysteries": 15572, + "orchid": 15573, + "winced": 15574, + "exhaustion": 15575, + "renovations": 15576, + "stranded": 15577, + "obe": 15578, + "infinity": 15579, + "##nies": 15580, + "adapt": 15581, + "redevelopment": 15582, + "thanked": 15583, + "registry": 15584, + "olga": 15585, + "domingo": 15586, + "noir": 15587, + "tudor": 15588, + "ole": 15589, + "##atus": 15590, + "commenting": 15591, + "behaviors": 15592, + "##ais": 15593, + "crisp": 15594, + "pauline": 15595, + "probable": 15596, + "stirling": 15597, + "wigan": 15598, + "##bian": 15599, + "paralympics": 15600, + "panting": 15601, + "surpassed": 15602, + "##rew": 15603, + "luca": 15604, + "barred": 15605, + "pony": 15606, + "famed": 15607, + "##sters": 15608, + "cassandra": 15609, + "waiter": 15610, + "carolyn": 15611, + "exported": 15612, + "##orted": 15613, + "andres": 15614, + "destructive": 15615, + "deeds": 15616, + "jonah": 15617, + "castles": 15618, + "vacancy": 15619, + "suv": 15620, + "##glass": 15621, + "1788": 15622, + "orchard": 15623, + "yep": 15624, + "famine": 15625, + "belarusian": 15626, + "sprang": 15627, + "##forth": 15628, + "skinny": 15629, + "##mis": 15630, + "administrators": 15631, + "rotterdam": 15632, + "zambia": 15633, + "zhao": 15634, + "boiler": 15635, + "discoveries": 15636, + "##ride": 15637, + "##physics": 15638, + "lucius": 15639, + "disappointing": 15640, + "outreach": 15641, + "spoon": 15642, + "##frame": 15643, + "qualifications": 15644, + "unanimously": 15645, + "enjoys": 15646, + "regency": 15647, + "##iidae": 15648, + "stade": 15649, + "realism": 15650, + "veterinary": 15651, + "rodgers": 15652, + "dump": 15653, + "alain": 15654, + "chestnut": 15655, + "castile": 15656, + "censorship": 15657, + "rumble": 15658, + "gibbs": 15659, + "##itor": 15660, + "communion": 15661, + "reggae": 15662, + "inactivated": 15663, + "logs": 15664, + "loads": 15665, + "##houses": 15666, + "homosexual": 15667, + "##iano": 15668, + "ale": 15669, + "informs": 15670, + "##cas": 15671, + "phrases": 15672, + "plaster": 15673, + "linebacker": 15674, + "ambrose": 15675, + "kaiser": 15676, + "fascinated": 15677, + "850": 15678, + "limerick": 15679, + "recruitment": 15680, + "forge": 15681, + "mastered": 15682, + "##nding": 15683, + "leinster": 15684, + "rooted": 15685, + "threaten": 15686, + "##strom": 15687, + "borneo": 15688, + "##hes": 15689, + "suggestions": 15690, + "scholarships": 15691, + "propeller": 15692, + "documentaries": 15693, + "patronage": 15694, + "coats": 15695, + "constructing": 15696, + "invest": 15697, + "neurons": 15698, + "comet": 15699, + "entirety": 15700, + "shouts": 15701, + "identities": 15702, + "annoying": 15703, + "unchanged": 15704, + "wary": 15705, + "##antly": 15706, + "##ogy": 15707, + "neat": 15708, + "oversight": 15709, + "##kos": 15710, + "phillies": 15711, + "replay": 15712, + "constance": 15713, + "##kka": 15714, + "incarnation": 15715, + "humble": 15716, + "skies": 15717, + "minus": 15718, + "##acy": 15719, + "smithsonian": 15720, + "##chel": 15721, + "guerrilla": 15722, + "jar": 15723, + "cadets": 15724, + "##plate": 15725, + "surplus": 15726, + "audit": 15727, + "##aru": 15728, + "cracking": 15729, + "joanna": 15730, + "louisa": 15731, + "pacing": 15732, + "##lights": 15733, + "intentionally": 15734, + "##iri": 15735, + "diner": 15736, + "nwa": 15737, + "imprint": 15738, + "australians": 15739, + "tong": 15740, + "unprecedented": 15741, + "bunker": 15742, + "naive": 15743, + "specialists": 15744, + "ark": 15745, + "nichols": 15746, + "railing": 15747, + "leaked": 15748, + "pedal": 15749, + "##uka": 15750, + "shrub": 15751, + "longing": 15752, + "roofs": 15753, + "v8": 15754, + "captains": 15755, + "neural": 15756, + "tuned": 15757, + "##ntal": 15758, + "##jet": 15759, + "emission": 15760, + "medina": 15761, + "frantic": 15762, + "codex": 15763, + "definitive": 15764, + "sid": 15765, + "abolition": 15766, + "intensified": 15767, + "stocks": 15768, + "enrique": 15769, + "sustain": 15770, + "genoa": 15771, + "oxide": 15772, + "##written": 15773, + "clues": 15774, + "cha": 15775, + "##gers": 15776, + "tributaries": 15777, + "fragment": 15778, + "venom": 15779, + "##rity": 15780, + "##ente": 15781, + "##sca": 15782, + "muffled": 15783, + "vain": 15784, + "sire": 15785, + "laos": 15786, + "##ingly": 15787, + "##hana": 15788, + "hastily": 15789, + "snapping": 15790, + "surfaced": 15791, + "sentiment": 15792, + "motive": 15793, + "##oft": 15794, + "contests": 15795, + "approximate": 15796, + "mesa": 15797, + "luckily": 15798, + "dinosaur": 15799, + "exchanges": 15800, + "propelled": 15801, + "accord": 15802, + "bourne": 15803, + "relieve": 15804, + "tow": 15805, + "masks": 15806, + "offended": 15807, + "##ues": 15808, + "cynthia": 15809, + "##mmer": 15810, + "rains": 15811, + "bartender": 15812, + "zinc": 15813, + "reviewers": 15814, + "lois": 15815, + "##sai": 15816, + "legged": 15817, + "arrogant": 15818, + "rafe": 15819, + "rosie": 15820, + "comprise": 15821, + "handicap": 15822, + "blockade": 15823, + "inlet": 15824, + "lagoon": 15825, + "copied": 15826, + "drilling": 15827, + "shelley": 15828, + "petals": 15829, + "##inian": 15830, + "mandarin": 15831, + "obsolete": 15832, + "##inated": 15833, + "onward": 15834, + "arguably": 15835, + "productivity": 15836, + "cindy": 15837, + "praising": 15838, + "seldom": 15839, + "busch": 15840, + "discusses": 15841, + "raleigh": 15842, + "shortage": 15843, + "ranged": 15844, + "stanton": 15845, + "encouragement": 15846, + "firstly": 15847, + "conceded": 15848, + "overs": 15849, + "temporal": 15850, + "##uke": 15851, + "cbe": 15852, + "##bos": 15853, + "woo": 15854, + "certainty": 15855, + "pumps": 15856, + "##pton": 15857, + "stalked": 15858, + "##uli": 15859, + "lizzie": 15860, + "periodic": 15861, + "thieves": 15862, + "weaker": 15863, + "##night": 15864, + "gases": 15865, + "shoving": 15866, + "chooses": 15867, + "wc": 15868, + "##chemical": 15869, + "prompting": 15870, + "weights": 15871, + "##kill": 15872, + "robust": 15873, + "flanked": 15874, + "sticky": 15875, + "hu": 15876, + "tuberculosis": 15877, + "##eb": 15878, + "##eal": 15879, + "christchurch": 15880, + "resembled": 15881, + "wallet": 15882, + "reese": 15883, + "inappropriate": 15884, + "pictured": 15885, + "distract": 15886, + "fixing": 15887, + "fiddle": 15888, + "giggled": 15889, + "burger": 15890, + "heirs": 15891, + "hairy": 15892, + "mechanic": 15893, + "torque": 15894, + "apache": 15895, + "obsessed": 15896, + "chiefly": 15897, + "cheng": 15898, + "logging": 15899, + "##tag": 15900, + "extracted": 15901, + "meaningful": 15902, + "numb": 15903, + "##vsky": 15904, + "gloucestershire": 15905, + "reminding": 15906, + "##bay": 15907, + "unite": 15908, + "##lit": 15909, + "breeds": 15910, + "diminished": 15911, + "clown": 15912, + "glove": 15913, + "1860s": 15914, + "##ن": 15915, + "##ug": 15916, + "archibald": 15917, + "focal": 15918, + "freelance": 15919, + "sliced": 15920, + "depiction": 15921, + "##yk": 15922, + "organism": 15923, + "switches": 15924, + "sights": 15925, + "stray": 15926, + "crawling": 15927, + "##ril": 15928, + "lever": 15929, + "leningrad": 15930, + "interpretations": 15931, + "loops": 15932, + "anytime": 15933, + "reel": 15934, + "alicia": 15935, + "delighted": 15936, + "##ech": 15937, + "inhaled": 15938, + "xiv": 15939, + "suitcase": 15940, + "bernie": 15941, + "vega": 15942, + "licenses": 15943, + "northampton": 15944, + "exclusion": 15945, + "induction": 15946, + "monasteries": 15947, + "racecourse": 15948, + "homosexuality": 15949, + "##right": 15950, + "##sfield": 15951, + "##rky": 15952, + "dimitri": 15953, + "michele": 15954, + "alternatives": 15955, + "ions": 15956, + "commentators": 15957, + "genuinely": 15958, + "objected": 15959, + "pork": 15960, + "hospitality": 15961, + "fencing": 15962, + "stephan": 15963, + "warships": 15964, + "peripheral": 15965, + "wit": 15966, + "drunken": 15967, + "wrinkled": 15968, + "quentin": 15969, + "spends": 15970, + "departing": 15971, + "chung": 15972, + "numerical": 15973, + "spokesperson": 15974, + "##zone": 15975, + "johannesburg": 15976, + "caliber": 15977, + "killers": 15978, + "##udge": 15979, + "assumes": 15980, + "neatly": 15981, + "demographic": 15982, + "abigail": 15983, + "bloc": 15984, + "##vel": 15985, + "mounting": 15986, + "##lain": 15987, + "bentley": 15988, + "slightest": 15989, + "xu": 15990, + "recipients": 15991, + "##jk": 15992, + "merlin": 15993, + "##writer": 15994, + "seniors": 15995, + "prisons": 15996, + "blinking": 15997, + "hindwings": 15998, + "flickered": 15999, + "kappa": 16000, + "##hel": 16001, + "80s": 16002, + "strengthening": 16003, + "appealing": 16004, + "brewing": 16005, + "gypsy": 16006, + "mali": 16007, + "lashes": 16008, + "hulk": 16009, + "unpleasant": 16010, + "harassment": 16011, + "bio": 16012, + "treaties": 16013, + "predict": 16014, + "instrumentation": 16015, + "pulp": 16016, + "troupe": 16017, + "boiling": 16018, + "mantle": 16019, + "##ffe": 16020, + "ins": 16021, + "##vn": 16022, + "dividing": 16023, + "handles": 16024, + "verbs": 16025, + "##onal": 16026, + "coconut": 16027, + "senegal": 16028, + "340": 16029, + "thorough": 16030, + "gum": 16031, + "momentarily": 16032, + "##sto": 16033, + "cocaine": 16034, + "panicked": 16035, + "destined": 16036, + "##turing": 16037, + "teatro": 16038, + "denying": 16039, + "weary": 16040, + "captained": 16041, + "mans": 16042, + "##hawks": 16043, + "##code": 16044, + "wakefield": 16045, + "bollywood": 16046, + "thankfully": 16047, + "##16": 16048, + "cyril": 16049, + "##wu": 16050, + "amendments": 16051, + "##bahn": 16052, + "consultation": 16053, + "stud": 16054, + "reflections": 16055, + "kindness": 16056, + "1787": 16057, + "internally": 16058, + "##ovo": 16059, + "tex": 16060, + "mosaic": 16061, + "distribute": 16062, + "paddy": 16063, + "seeming": 16064, + "143": 16065, + "##hic": 16066, + "piers": 16067, + "##15": 16068, + "##mura": 16069, + "##verse": 16070, + "popularly": 16071, + "winger": 16072, + "kang": 16073, + "sentinel": 16074, + "mccoy": 16075, + "##anza": 16076, + "covenant": 16077, + "##bag": 16078, + "verge": 16079, + "fireworks": 16080, + "suppress": 16081, + "thrilled": 16082, + "dominate": 16083, + "##jar": 16084, + "swansea": 16085, + "##60": 16086, + "142": 16087, + "reconciliation": 16088, + "##ndi": 16089, + "stiffened": 16090, + "cue": 16091, + "dorian": 16092, + "##uf": 16093, + "damascus": 16094, + "amor": 16095, + "ida": 16096, + "foremost": 16097, + "##aga": 16098, + "porsche": 16099, + "unseen": 16100, + "dir": 16101, + "##had": 16102, + "##azi": 16103, + "stony": 16104, + "lexi": 16105, + "melodies": 16106, + "##nko": 16107, + "angular": 16108, + "integer": 16109, + "podcast": 16110, + "ants": 16111, + "inherent": 16112, + "jaws": 16113, + "justify": 16114, + "persona": 16115, + "##olved": 16116, + "josephine": 16117, + "##nr": 16118, + "##ressed": 16119, + "customary": 16120, + "flashes": 16121, + "gala": 16122, + "cyrus": 16123, + "glaring": 16124, + "backyard": 16125, + "ariel": 16126, + "physiology": 16127, + "greenland": 16128, + "html": 16129, + "stir": 16130, + "avon": 16131, + "atletico": 16132, + "finch": 16133, + "methodology": 16134, + "ked": 16135, + "##lent": 16136, + "mas": 16137, + "catholicism": 16138, + "townsend": 16139, + "branding": 16140, + "quincy": 16141, + "fits": 16142, + "containers": 16143, + "1777": 16144, + "ashore": 16145, + "aragon": 16146, + "##19": 16147, + "forearm": 16148, + "poisoning": 16149, + "##sd": 16150, + "adopting": 16151, + "conquer": 16152, + "grinding": 16153, + "amnesty": 16154, + "keller": 16155, + "finances": 16156, + "evaluate": 16157, + "forged": 16158, + "lankan": 16159, + "instincts": 16160, + "##uto": 16161, + "guam": 16162, + "bosnian": 16163, + "photographed": 16164, + "workplace": 16165, + "desirable": 16166, + "protector": 16167, + "##dog": 16168, + "allocation": 16169, + "intently": 16170, + "encourages": 16171, + "willy": 16172, + "##sten": 16173, + "bodyguard": 16174, + "electro": 16175, + "brighter": 16176, + "##ν": 16177, + "bihar": 16178, + "##chev": 16179, + "lasts": 16180, + "opener": 16181, + "amphibious": 16182, + "sal": 16183, + "verde": 16184, + "arte": 16185, + "##cope": 16186, + "captivity": 16187, + "vocabulary": 16188, + "yields": 16189, + "##tted": 16190, + "agreeing": 16191, + "desmond": 16192, + "pioneered": 16193, + "##chus": 16194, + "strap": 16195, + "campaigned": 16196, + "railroads": 16197, + "##ович": 16198, + "emblem": 16199, + "##dre": 16200, + "stormed": 16201, + "501": 16202, + "##ulous": 16203, + "marijuana": 16204, + "northumberland": 16205, + "##gn": 16206, + "##nath": 16207, + "bowen": 16208, + "landmarks": 16209, + "beaumont": 16210, + "##qua": 16211, + "danube": 16212, + "##bler": 16213, + "attorneys": 16214, + "th": 16215, + "ge": 16216, + "flyers": 16217, + "critique": 16218, + "villains": 16219, + "cass": 16220, + "mutation": 16221, + "acc": 16222, + "##0s": 16223, + "colombo": 16224, + "mckay": 16225, + "motif": 16226, + "sampling": 16227, + "concluding": 16228, + "syndicate": 16229, + "##rell": 16230, + "neon": 16231, + "stables": 16232, + "ds": 16233, + "warnings": 16234, + "clint": 16235, + "mourning": 16236, + "wilkinson": 16237, + "##tated": 16238, + "merrill": 16239, + "leopard": 16240, + "evenings": 16241, + "exhaled": 16242, + "emil": 16243, + "sonia": 16244, + "ezra": 16245, + "discrete": 16246, + "stove": 16247, + "farrell": 16248, + "fifteenth": 16249, + "prescribed": 16250, + "superhero": 16251, + "##rier": 16252, + "worms": 16253, + "helm": 16254, + "wren": 16255, + "##duction": 16256, + "##hc": 16257, + "expo": 16258, + "##rator": 16259, + "hq": 16260, + "unfamiliar": 16261, + "antony": 16262, + "prevents": 16263, + "acceleration": 16264, + "fiercely": 16265, + "mari": 16266, + "painfully": 16267, + "calculations": 16268, + "cheaper": 16269, + "ign": 16270, + "clifton": 16271, + "irvine": 16272, + "davenport": 16273, + "mozambique": 16274, + "##np": 16275, + "pierced": 16276, + "##evich": 16277, + "wonders": 16278, + "##wig": 16279, + "##cate": 16280, + "##iling": 16281, + "crusade": 16282, + "ware": 16283, + "##uel": 16284, + "enzymes": 16285, + "reasonably": 16286, + "mls": 16287, + "##coe": 16288, + "mater": 16289, + "ambition": 16290, + "bunny": 16291, + "eliot": 16292, + "kernel": 16293, + "##fin": 16294, + "asphalt": 16295, + "headmaster": 16296, + "torah": 16297, + "aden": 16298, + "lush": 16299, + "pins": 16300, + "waived": 16301, + "##care": 16302, + "##yas": 16303, + "joao": 16304, + "substrate": 16305, + "enforce": 16306, + "##grad": 16307, + "##ules": 16308, + "alvarez": 16309, + "selections": 16310, + "epidemic": 16311, + "tempted": 16312, + "##bit": 16313, + "bremen": 16314, + "translates": 16315, + "ensured": 16316, + "waterfront": 16317, + "29th": 16318, + "forrest": 16319, + "manny": 16320, + "malone": 16321, + "kramer": 16322, + "reigning": 16323, + "cookies": 16324, + "simpler": 16325, + "absorption": 16326, + "205": 16327, + "engraved": 16328, + "##ffy": 16329, + "evaluated": 16330, + "1778": 16331, + "haze": 16332, + "146": 16333, + "comforting": 16334, + "crossover": 16335, + "##abe": 16336, + "thorn": 16337, + "##rift": 16338, + "##imo": 16339, + "##pop": 16340, + "suppression": 16341, + "fatigue": 16342, + "cutter": 16343, + "##tr": 16344, + "201": 16345, + "wurttemberg": 16346, + "##orf": 16347, + "enforced": 16348, + "hovering": 16349, + "proprietary": 16350, + "gb": 16351, + "samurai": 16352, + "syllable": 16353, + "ascent": 16354, + "lacey": 16355, + "tick": 16356, + "lars": 16357, + "tractor": 16358, + "merchandise": 16359, + "rep": 16360, + "bouncing": 16361, + "defendants": 16362, + "##yre": 16363, + "huntington": 16364, + "##ground": 16365, + "##oko": 16366, + "standardized": 16367, + "##hor": 16368, + "##hima": 16369, + "assassinated": 16370, + "nu": 16371, + "predecessors": 16372, + "rainy": 16373, + "liar": 16374, + "assurance": 16375, + "lyrical": 16376, + "##uga": 16377, + "secondly": 16378, + "flattened": 16379, + "ios": 16380, + "parameter": 16381, + "undercover": 16382, + "##mity": 16383, + "bordeaux": 16384, + "punish": 16385, + "ridges": 16386, + "markers": 16387, + "exodus": 16388, + "inactive": 16389, + "hesitate": 16390, + "debbie": 16391, + "nyc": 16392, + "pledge": 16393, + "savoy": 16394, + "nagar": 16395, + "offset": 16396, + "organist": 16397, + "##tium": 16398, + "hesse": 16399, + "marin": 16400, + "converting": 16401, + "##iver": 16402, + "diagram": 16403, + "propulsion": 16404, + "pu": 16405, + "validity": 16406, + "reverted": 16407, + "supportive": 16408, + "##dc": 16409, + "ministries": 16410, + "clans": 16411, + "responds": 16412, + "proclamation": 16413, + "##inae": 16414, + "##ø": 16415, + "##rea": 16416, + "ein": 16417, + "pleading": 16418, + "patriot": 16419, + "sf": 16420, + "birch": 16421, + "islanders": 16422, + "strauss": 16423, + "hates": 16424, + "##dh": 16425, + "brandenburg": 16426, + "concession": 16427, + "rd": 16428, + "##ob": 16429, + "1900s": 16430, + "killings": 16431, + "textbook": 16432, + "antiquity": 16433, + "cinematography": 16434, + "wharf": 16435, + "embarrassing": 16436, + "setup": 16437, + "creed": 16438, + "farmland": 16439, + "inequality": 16440, + "centred": 16441, + "signatures": 16442, + "fallon": 16443, + "370": 16444, + "##ingham": 16445, + "##uts": 16446, + "ceylon": 16447, + "gazing": 16448, + "directive": 16449, + "laurie": 16450, + "##tern": 16451, + "globally": 16452, + "##uated": 16453, + "##dent": 16454, + "allah": 16455, + "excavation": 16456, + "threads": 16457, + "##cross": 16458, + "148": 16459, + "frantically": 16460, + "icc": 16461, + "utilize": 16462, + "determines": 16463, + "respiratory": 16464, + "thoughtful": 16465, + "receptions": 16466, + "##dicate": 16467, + "merging": 16468, + "chandra": 16469, + "seine": 16470, + "147": 16471, + "builders": 16472, + "builds": 16473, + "diagnostic": 16474, + "dev": 16475, + "visibility": 16476, + "goddamn": 16477, + "analyses": 16478, + "dhaka": 16479, + "cho": 16480, + "proves": 16481, + "chancel": 16482, + "concurrent": 16483, + "curiously": 16484, + "canadians": 16485, + "pumped": 16486, + "restoring": 16487, + "1850s": 16488, + "turtles": 16489, + "jaguar": 16490, + "sinister": 16491, + "spinal": 16492, + "traction": 16493, + "declan": 16494, + "vows": 16495, + "1784": 16496, + "glowed": 16497, + "capitalism": 16498, + "swirling": 16499, + "install": 16500, + "universidad": 16501, + "##lder": 16502, + "##oat": 16503, + "soloist": 16504, + "##genic": 16505, + "##oor": 16506, + "coincidence": 16507, + "beginnings": 16508, + "nissan": 16509, + "dip": 16510, + "resorts": 16511, + "caucasus": 16512, + "combustion": 16513, + "infectious": 16514, + "##eno": 16515, + "pigeon": 16516, + "serpent": 16517, + "##itating": 16518, + "conclude": 16519, + "masked": 16520, + "salad": 16521, + "jew": 16522, + "##gr": 16523, + "surreal": 16524, + "toni": 16525, + "##wc": 16526, + "harmonica": 16527, + "151": 16528, + "##gins": 16529, + "##etic": 16530, + "##coat": 16531, + "fishermen": 16532, + "intending": 16533, + "bravery": 16534, + "##wave": 16535, + "klaus": 16536, + "titan": 16537, + "wembley": 16538, + "taiwanese": 16539, + "ransom": 16540, + "40th": 16541, + "incorrect": 16542, + "hussein": 16543, + "eyelids": 16544, + "jp": 16545, + "cooke": 16546, + "dramas": 16547, + "utilities": 16548, + "##etta": 16549, + "##print": 16550, + "eisenhower": 16551, + "principally": 16552, + "granada": 16553, + "lana": 16554, + "##rak": 16555, + "openings": 16556, + "concord": 16557, + "##bl": 16558, + "bethany": 16559, + "connie": 16560, + "morality": 16561, + "sega": 16562, + "##mons": 16563, + "##nard": 16564, + "earnings": 16565, + "##kara": 16566, + "##cine": 16567, + "wii": 16568, + "communes": 16569, + "##rel": 16570, + "coma": 16571, + "composing": 16572, + "softened": 16573, + "severed": 16574, + "grapes": 16575, + "##17": 16576, + "nguyen": 16577, + "analyzed": 16578, + "warlord": 16579, + "hubbard": 16580, + "heavenly": 16581, + "behave": 16582, + "slovenian": 16583, + "##hit": 16584, + "##ony": 16585, + "hailed": 16586, + "filmmakers": 16587, + "trance": 16588, + "caldwell": 16589, + "skye": 16590, + "unrest": 16591, + "coward": 16592, + "likelihood": 16593, + "##aging": 16594, + "bern": 16595, + "sci": 16596, + "taliban": 16597, + "honolulu": 16598, + "propose": 16599, + "##wang": 16600, + "1700": 16601, + "browser": 16602, + "imagining": 16603, + "cobra": 16604, + "contributes": 16605, + "dukes": 16606, + "instinctively": 16607, + "conan": 16608, + "violinist": 16609, + "##ores": 16610, + "accessories": 16611, + "gradual": 16612, + "##amp": 16613, + "quotes": 16614, + "sioux": 16615, + "##dating": 16616, + "undertake": 16617, + "intercepted": 16618, + "sparkling": 16619, + "compressed": 16620, + "139": 16621, + "fungus": 16622, + "tombs": 16623, + "haley": 16624, + "imposing": 16625, + "rests": 16626, + "degradation": 16627, + "lincolnshire": 16628, + "retailers": 16629, + "wetlands": 16630, + "tulsa": 16631, + "distributor": 16632, + "dungeon": 16633, + "nun": 16634, + "greenhouse": 16635, + "convey": 16636, + "atlantis": 16637, + "aft": 16638, + "exits": 16639, + "oman": 16640, + "dresser": 16641, + "lyons": 16642, + "##sti": 16643, + "joking": 16644, + "eddy": 16645, + "judgement": 16646, + "omitted": 16647, + "digits": 16648, + "##cts": 16649, + "##game": 16650, + "juniors": 16651, + "##rae": 16652, + "cents": 16653, + "stricken": 16654, + "une": 16655, + "##ngo": 16656, + "wizards": 16657, + "weir": 16658, + "breton": 16659, + "nan": 16660, + "technician": 16661, + "fibers": 16662, + "liking": 16663, + "royalty": 16664, + "##cca": 16665, + "154": 16666, + "persia": 16667, + "terribly": 16668, + "magician": 16669, + "##rable": 16670, + "##unt": 16671, + "vance": 16672, + "cafeteria": 16673, + "booker": 16674, + "camille": 16675, + "warmer": 16676, + "##static": 16677, + "consume": 16678, + "cavern": 16679, + "gaps": 16680, + "compass": 16681, + "contemporaries": 16682, + "foyer": 16683, + "soothing": 16684, + "graveyard": 16685, + "maj": 16686, + "plunged": 16687, + "blush": 16688, + "##wear": 16689, + "cascade": 16690, + "demonstrates": 16691, + "ordinance": 16692, + "##nov": 16693, + "boyle": 16694, + "##lana": 16695, + "rockefeller": 16696, + "shaken": 16697, + "banjo": 16698, + "izzy": 16699, + "##ense": 16700, + "breathless": 16701, + "vines": 16702, + "##32": 16703, + "##eman": 16704, + "alterations": 16705, + "chromosome": 16706, + "dwellings": 16707, + "feudal": 16708, + "mole": 16709, + "153": 16710, + "catalonia": 16711, + "relics": 16712, + "tenant": 16713, + "mandated": 16714, + "##fm": 16715, + "fridge": 16716, + "hats": 16717, + "honesty": 16718, + "patented": 16719, + "raul": 16720, + "heap": 16721, + "cruisers": 16722, + "accusing": 16723, + "enlightenment": 16724, + "infants": 16725, + "wherein": 16726, + "chatham": 16727, + "contractors": 16728, + "zen": 16729, + "affinity": 16730, + "hc": 16731, + "osborne": 16732, + "piston": 16733, + "156": 16734, + "traps": 16735, + "maturity": 16736, + "##rana": 16737, + "lagos": 16738, + "##zal": 16739, + "peering": 16740, + "##nay": 16741, + "attendant": 16742, + "dealers": 16743, + "protocols": 16744, + "subset": 16745, + "prospects": 16746, + "biographical": 16747, + "##cre": 16748, + "artery": 16749, + "##zers": 16750, + "insignia": 16751, + "nuns": 16752, + "endured": 16753, + "##eration": 16754, + "recommend": 16755, + "schwartz": 16756, + "serbs": 16757, + "berger": 16758, + "cromwell": 16759, + "crossroads": 16760, + "##ctor": 16761, + "enduring": 16762, + "clasped": 16763, + "grounded": 16764, + "##bine": 16765, + "marseille": 16766, + "twitched": 16767, + "abel": 16768, + "choke": 16769, + "https": 16770, + "catalyst": 16771, + "moldova": 16772, + "italians": 16773, + "##tist": 16774, + "disastrous": 16775, + "wee": 16776, + "##oured": 16777, + "##nti": 16778, + "wwf": 16779, + "nope": 16780, + "##piration": 16781, + "##asa": 16782, + "expresses": 16783, + "thumbs": 16784, + "167": 16785, + "##nza": 16786, + "coca": 16787, + "1781": 16788, + "cheating": 16789, + "##ption": 16790, + "skipped": 16791, + "sensory": 16792, + "heidelberg": 16793, + "spies": 16794, + "satan": 16795, + "dangers": 16796, + "semifinal": 16797, + "202": 16798, + "bohemia": 16799, + "whitish": 16800, + "confusing": 16801, + "shipbuilding": 16802, + "relies": 16803, + "surgeons": 16804, + "landings": 16805, + "ravi": 16806, + "baku": 16807, + "moor": 16808, + "suffix": 16809, + "alejandro": 16810, + "##yana": 16811, + "litre": 16812, + "upheld": 16813, + "##unk": 16814, + "rajasthan": 16815, + "##rek": 16816, + "coaster": 16817, + "insists": 16818, + "posture": 16819, + "scenarios": 16820, + "etienne": 16821, + "favoured": 16822, + "appoint": 16823, + "transgender": 16824, + "elephants": 16825, + "poked": 16826, + "greenwood": 16827, + "defences": 16828, + "fulfilled": 16829, + "militant": 16830, + "somali": 16831, + "1758": 16832, + "chalk": 16833, + "potent": 16834, + "##ucci": 16835, + "migrants": 16836, + "wink": 16837, + "assistants": 16838, + "nos": 16839, + "restriction": 16840, + "activism": 16841, + "niger": 16842, + "##ario": 16843, + "colon": 16844, + "shaun": 16845, + "##sat": 16846, + "daphne": 16847, + "##erated": 16848, + "swam": 16849, + "congregations": 16850, + "reprise": 16851, + "considerations": 16852, + "magnet": 16853, + "playable": 16854, + "xvi": 16855, + "##р": 16856, + "overthrow": 16857, + "tobias": 16858, + "knob": 16859, + "chavez": 16860, + "coding": 16861, + "##mers": 16862, + "propped": 16863, + "katrina": 16864, + "orient": 16865, + "newcomer": 16866, + "##suke": 16867, + "temperate": 16868, + "##pool": 16869, + "farmhouse": 16870, + "interrogation": 16871, + "##vd": 16872, + "committing": 16873, + "##vert": 16874, + "forthcoming": 16875, + "strawberry": 16876, + "joaquin": 16877, + "macau": 16878, + "ponds": 16879, + "shocking": 16880, + "siberia": 16881, + "##cellular": 16882, + "chant": 16883, + "contributors": 16884, + "##nant": 16885, + "##ologists": 16886, + "sped": 16887, + "absorb": 16888, + "hail": 16889, + "1782": 16890, + "spared": 16891, + "##hore": 16892, + "barbados": 16893, + "karate": 16894, + "opus": 16895, + "originates": 16896, + "saul": 16897, + "##xie": 16898, + "evergreen": 16899, + "leaped": 16900, + "##rock": 16901, + "correlation": 16902, + "exaggerated": 16903, + "weekday": 16904, + "unification": 16905, + "bump": 16906, + "tracing": 16907, + "brig": 16908, + "afb": 16909, + "pathways": 16910, + "utilizing": 16911, + "##ners": 16912, + "mod": 16913, + "mb": 16914, + "disturbance": 16915, + "kneeling": 16916, + "##stad": 16917, + "##guchi": 16918, + "100th": 16919, + "pune": 16920, + "##thy": 16921, + "decreasing": 16922, + "168": 16923, + "manipulation": 16924, + "miriam": 16925, + "academia": 16926, + "ecosystem": 16927, + "occupational": 16928, + "rbi": 16929, + "##lem": 16930, + "rift": 16931, + "##14": 16932, + "rotary": 16933, + "stacked": 16934, + "incorporation": 16935, + "awakening": 16936, + "generators": 16937, + "guerrero": 16938, + "racist": 16939, + "##omy": 16940, + "cyber": 16941, + "derivatives": 16942, + "culminated": 16943, + "allie": 16944, + "annals": 16945, + "panzer": 16946, + "sainte": 16947, + "wikipedia": 16948, + "pops": 16949, + "zu": 16950, + "austro": 16951, + "##vate": 16952, + "algerian": 16953, + "politely": 16954, + "nicholson": 16955, + "mornings": 16956, + "educate": 16957, + "tastes": 16958, + "thrill": 16959, + "dartmouth": 16960, + "##gating": 16961, + "db": 16962, + "##jee": 16963, + "regan": 16964, + "differing": 16965, + "concentrating": 16966, + "choreography": 16967, + "divinity": 16968, + "##media": 16969, + "pledged": 16970, + "alexandre": 16971, + "routing": 16972, + "gregor": 16973, + "madeline": 16974, + "##idal": 16975, + "apocalypse": 16976, + "##hora": 16977, + "gunfire": 16978, + "culminating": 16979, + "elves": 16980, + "fined": 16981, + "liang": 16982, + "lam": 16983, + "programmed": 16984, + "tar": 16985, + "guessing": 16986, + "transparency": 16987, + "gabrielle": 16988, + "##gna": 16989, + "cancellation": 16990, + "flexibility": 16991, + "##lining": 16992, + "accession": 16993, + "shea": 16994, + "stronghold": 16995, + "nets": 16996, + "specializes": 16997, + "##rgan": 16998, + "abused": 16999, + "hasan": 17000, + "sgt": 17001, + "ling": 17002, + "exceeding": 17003, + "##₄": 17004, + "admiration": 17005, + "supermarket": 17006, + "##ark": 17007, + "photographers": 17008, + "specialised": 17009, + "tilt": 17010, + "resonance": 17011, + "hmm": 17012, + "perfume": 17013, + "380": 17014, + "sami": 17015, + "threatens": 17016, + "garland": 17017, + "botany": 17018, + "guarding": 17019, + "boiled": 17020, + "greet": 17021, + "puppy": 17022, + "russo": 17023, + "supplier": 17024, + "wilmington": 17025, + "vibrant": 17026, + "vijay": 17027, + "##bius": 17028, + "paralympic": 17029, + "grumbled": 17030, + "paige": 17031, + "faa": 17032, + "licking": 17033, + "margins": 17034, + "hurricanes": 17035, + "##gong": 17036, + "fest": 17037, + "grenade": 17038, + "ripping": 17039, + "##uz": 17040, + "counseling": 17041, + "weigh": 17042, + "##sian": 17043, + "needles": 17044, + "wiltshire": 17045, + "edison": 17046, + "costly": 17047, + "##not": 17048, + "fulton": 17049, + "tramway": 17050, + "redesigned": 17051, + "staffordshire": 17052, + "cache": 17053, + "gasping": 17054, + "watkins": 17055, + "sleepy": 17056, + "candidacy": 17057, + "##group": 17058, + "monkeys": 17059, + "timeline": 17060, + "throbbing": 17061, + "##bid": 17062, + "##sos": 17063, + "berth": 17064, + "uzbekistan": 17065, + "vanderbilt": 17066, + "bothering": 17067, + "overturned": 17068, + "ballots": 17069, + "gem": 17070, + "##iger": 17071, + "sunglasses": 17072, + "subscribers": 17073, + "hooker": 17074, + "compelling": 17075, + "ang": 17076, + "exceptionally": 17077, + "saloon": 17078, + "stab": 17079, + "##rdi": 17080, + "carla": 17081, + "terrifying": 17082, + "rom": 17083, + "##vision": 17084, + "coil": 17085, + "##oids": 17086, + "satisfying": 17087, + "vendors": 17088, + "31st": 17089, + "mackay": 17090, + "deities": 17091, + "overlooked": 17092, + "ambient": 17093, + "bahamas": 17094, + "felipe": 17095, + "olympia": 17096, + "whirled": 17097, + "botanist": 17098, + "advertised": 17099, + "tugging": 17100, + "##dden": 17101, + "disciples": 17102, + "morales": 17103, + "unionist": 17104, + "rites": 17105, + "foley": 17106, + "morse": 17107, + "motives": 17108, + "creepy": 17109, + "##₀": 17110, + "soo": 17111, + "##sz": 17112, + "bargain": 17113, + "highness": 17114, + "frightening": 17115, + "turnpike": 17116, + "tory": 17117, + "reorganization": 17118, + "##cer": 17119, + "depict": 17120, + "biographer": 17121, + "##walk": 17122, + "unopposed": 17123, + "manifesto": 17124, + "##gles": 17125, + "institut": 17126, + "emile": 17127, + "accidental": 17128, + "kapoor": 17129, + "##dam": 17130, + "kilkenny": 17131, + "cortex": 17132, + "lively": 17133, + "##13": 17134, + "romanesque": 17135, + "jain": 17136, + "shan": 17137, + "cannons": 17138, + "##ood": 17139, + "##ske": 17140, + "petrol": 17141, + "echoing": 17142, + "amalgamated": 17143, + "disappears": 17144, + "cautious": 17145, + "proposes": 17146, + "sanctions": 17147, + "trenton": 17148, + "##ر": 17149, + "flotilla": 17150, + "aus": 17151, + "contempt": 17152, + "tor": 17153, + "canary": 17154, + "cote": 17155, + "theirs": 17156, + "##hun": 17157, + "conceptual": 17158, + "deleted": 17159, + "fascinating": 17160, + "paso": 17161, + "blazing": 17162, + "elf": 17163, + "honourable": 17164, + "hutchinson": 17165, + "##eiro": 17166, + "##outh": 17167, + "##zin": 17168, + "surveyor": 17169, + "tee": 17170, + "amidst": 17171, + "wooded": 17172, + "reissue": 17173, + "intro": 17174, + "##ono": 17175, + "cobb": 17176, + "shelters": 17177, + "newsletter": 17178, + "hanson": 17179, + "brace": 17180, + "encoding": 17181, + "confiscated": 17182, + "dem": 17183, + "caravan": 17184, + "marino": 17185, + "scroll": 17186, + "melodic": 17187, + "cows": 17188, + "imam": 17189, + "##adi": 17190, + "##aneous": 17191, + "northward": 17192, + "searches": 17193, + "biodiversity": 17194, + "cora": 17195, + "310": 17196, + "roaring": 17197, + "##bers": 17198, + "connell": 17199, + "theologian": 17200, + "halo": 17201, + "compose": 17202, + "pathetic": 17203, + "unmarried": 17204, + "dynamo": 17205, + "##oot": 17206, + "az": 17207, + "calculation": 17208, + "toulouse": 17209, + "deserves": 17210, + "humour": 17211, + "nr": 17212, + "forgiveness": 17213, + "tam": 17214, + "undergone": 17215, + "martyr": 17216, + "pamela": 17217, + "myths": 17218, + "whore": 17219, + "counselor": 17220, + "hicks": 17221, + "290": 17222, + "heavens": 17223, + "battleship": 17224, + "electromagnetic": 17225, + "##bbs": 17226, + "stellar": 17227, + "establishments": 17228, + "presley": 17229, + "hopped": 17230, + "##chin": 17231, + "temptation": 17232, + "90s": 17233, + "wills": 17234, + "nas": 17235, + "##yuan": 17236, + "nhs": 17237, + "##nya": 17238, + "seminars": 17239, + "##yev": 17240, + "adaptations": 17241, + "gong": 17242, + "asher": 17243, + "lex": 17244, + "indicator": 17245, + "sikh": 17246, + "tobago": 17247, + "cites": 17248, + "goin": 17249, + "##yte": 17250, + "satirical": 17251, + "##gies": 17252, + "characterised": 17253, + "correspond": 17254, + "bubbles": 17255, + "lure": 17256, + "participates": 17257, + "##vid": 17258, + "eruption": 17259, + "skate": 17260, + "therapeutic": 17261, + "1785": 17262, + "canals": 17263, + "wholesale": 17264, + "defaulted": 17265, + "sac": 17266, + "460": 17267, + "petit": 17268, + "##zzled": 17269, + "virgil": 17270, + "leak": 17271, + "ravens": 17272, + "256": 17273, + "portraying": 17274, + "##yx": 17275, + "ghetto": 17276, + "creators": 17277, + "dams": 17278, + "portray": 17279, + "vicente": 17280, + "##rington": 17281, + "fae": 17282, + "namesake": 17283, + "bounty": 17284, + "##arium": 17285, + "joachim": 17286, + "##ota": 17287, + "##iser": 17288, + "aforementioned": 17289, + "axle": 17290, + "snout": 17291, + "depended": 17292, + "dismantled": 17293, + "reuben": 17294, + "480": 17295, + "##ibly": 17296, + "gallagher": 17297, + "##lau": 17298, + "##pd": 17299, + "earnest": 17300, + "##ieu": 17301, + "##iary": 17302, + "inflicted": 17303, + "objections": 17304, + "##llar": 17305, + "asa": 17306, + "gritted": 17307, + "##athy": 17308, + "jericho": 17309, + "##sea": 17310, + "##was": 17311, + "flick": 17312, + "underside": 17313, + "ceramics": 17314, + "undead": 17315, + "substituted": 17316, + "195": 17317, + "eastward": 17318, + "undoubtedly": 17319, + "wheeled": 17320, + "chimney": 17321, + "##iche": 17322, + "guinness": 17323, + "cb": 17324, + "##ager": 17325, + "siding": 17326, + "##bell": 17327, + "traitor": 17328, + "baptiste": 17329, + "disguised": 17330, + "inauguration": 17331, + "149": 17332, + "tipperary": 17333, + "choreographer": 17334, + "perched": 17335, + "warmed": 17336, + "stationary": 17337, + "eco": 17338, + "##ike": 17339, + "##ntes": 17340, + "bacterial": 17341, + "##aurus": 17342, + "flores": 17343, + "phosphate": 17344, + "##core": 17345, + "attacker": 17346, + "invaders": 17347, + "alvin": 17348, + "intersects": 17349, + "a1": 17350, + "indirectly": 17351, + "immigrated": 17352, + "businessmen": 17353, + "cornelius": 17354, + "valves": 17355, + "narrated": 17356, + "pill": 17357, + "sober": 17358, + "ul": 17359, + "nationale": 17360, + "monastic": 17361, + "applicants": 17362, + "scenery": 17363, + "##jack": 17364, + "161": 17365, + "motifs": 17366, + "constitutes": 17367, + "cpu": 17368, + "##osh": 17369, + "jurisdictions": 17370, + "sd": 17371, + "tuning": 17372, + "irritation": 17373, + "woven": 17374, + "##uddin": 17375, + "fertility": 17376, + "gao": 17377, + "##erie": 17378, + "antagonist": 17379, + "impatient": 17380, + "glacial": 17381, + "hides": 17382, + "boarded": 17383, + "denominations": 17384, + "interception": 17385, + "##jas": 17386, + "cookie": 17387, + "nicola": 17388, + "##tee": 17389, + "algebraic": 17390, + "marquess": 17391, + "bahn": 17392, + "parole": 17393, + "buyers": 17394, + "bait": 17395, + "turbines": 17396, + "paperwork": 17397, + "bestowed": 17398, + "natasha": 17399, + "renee": 17400, + "oceans": 17401, + "purchases": 17402, + "157": 17403, + "vaccine": 17404, + "215": 17405, + "##tock": 17406, + "fixtures": 17407, + "playhouse": 17408, + "integrate": 17409, + "jai": 17410, + "oswald": 17411, + "intellectuals": 17412, + "##cky": 17413, + "booked": 17414, + "nests": 17415, + "mortimer": 17416, + "##isi": 17417, + "obsession": 17418, + "sept": 17419, + "##gler": 17420, + "##sum": 17421, + "440": 17422, + "scrutiny": 17423, + "simultaneous": 17424, + "squinted": 17425, + "##shin": 17426, + "collects": 17427, + "oven": 17428, + "shankar": 17429, + "penned": 17430, + "remarkably": 17431, + "##я": 17432, + "slips": 17433, + "luggage": 17434, + "spectral": 17435, + "1786": 17436, + "collaborations": 17437, + "louie": 17438, + "consolidation": 17439, + "##ailed": 17440, + "##ivating": 17441, + "420": 17442, + "hoover": 17443, + "blackpool": 17444, + "harness": 17445, + "ignition": 17446, + "vest": 17447, + "tails": 17448, + "belmont": 17449, + "mongol": 17450, + "skinner": 17451, + "##nae": 17452, + "visually": 17453, + "mage": 17454, + "derry": 17455, + "##tism": 17456, + "##unce": 17457, + "stevie": 17458, + "transitional": 17459, + "##rdy": 17460, + "redskins": 17461, + "drying": 17462, + "prep": 17463, + "prospective": 17464, + "##21": 17465, + "annoyance": 17466, + "oversee": 17467, + "##loaded": 17468, + "fills": 17469, + "##books": 17470, + "##iki": 17471, + "announces": 17472, + "fda": 17473, + "scowled": 17474, + "respects": 17475, + "prasad": 17476, + "mystic": 17477, + "tucson": 17478, + "##vale": 17479, + "revue": 17480, + "springer": 17481, + "bankrupt": 17482, + "1772": 17483, + "aristotle": 17484, + "salvatore": 17485, + "habsburg": 17486, + "##geny": 17487, + "dal": 17488, + "natal": 17489, + "nut": 17490, + "pod": 17491, + "chewing": 17492, + "darts": 17493, + "moroccan": 17494, + "walkover": 17495, + "rosario": 17496, + "lenin": 17497, + "punjabi": 17498, + "##ße": 17499, + "grossed": 17500, + "scattering": 17501, + "wired": 17502, + "invasive": 17503, + "hui": 17504, + "polynomial": 17505, + "corridors": 17506, + "wakes": 17507, + "gina": 17508, + "portrays": 17509, + "##cratic": 17510, + "arid": 17511, + "retreating": 17512, + "erich": 17513, + "irwin": 17514, + "sniper": 17515, + "##dha": 17516, + "linen": 17517, + "lindsey": 17518, + "maneuver": 17519, + "butch": 17520, + "shutting": 17521, + "socio": 17522, + "bounce": 17523, + "commemorative": 17524, + "postseason": 17525, + "jeremiah": 17526, + "pines": 17527, + "275": 17528, + "mystical": 17529, + "beads": 17530, + "bp": 17531, + "abbas": 17532, + "furnace": 17533, + "bidding": 17534, + "consulted": 17535, + "assaulted": 17536, + "empirical": 17537, + "rubble": 17538, + "enclosure": 17539, + "sob": 17540, + "weakly": 17541, + "cancel": 17542, + "polly": 17543, + "yielded": 17544, + "##emann": 17545, + "curly": 17546, + "prediction": 17547, + "battered": 17548, + "70s": 17549, + "vhs": 17550, + "jacqueline": 17551, + "render": 17552, + "sails": 17553, + "barked": 17554, + "detailing": 17555, + "grayson": 17556, + "riga": 17557, + "sloane": 17558, + "raging": 17559, + "##yah": 17560, + "herbs": 17561, + "bravo": 17562, + "##athlon": 17563, + "alloy": 17564, + "giggle": 17565, + "imminent": 17566, + "suffers": 17567, + "assumptions": 17568, + "waltz": 17569, + "##itate": 17570, + "accomplishments": 17571, + "##ited": 17572, + "bathing": 17573, + "remixed": 17574, + "deception": 17575, + "prefix": 17576, + "##emia": 17577, + "deepest": 17578, + "##tier": 17579, + "##eis": 17580, + "balkan": 17581, + "frogs": 17582, + "##rong": 17583, + "slab": 17584, + "##pate": 17585, + "philosophers": 17586, + "peterborough": 17587, + "grains": 17588, + "imports": 17589, + "dickinson": 17590, + "rwanda": 17591, + "##atics": 17592, + "1774": 17593, + "dirk": 17594, + "lan": 17595, + "tablets": 17596, + "##rove": 17597, + "clone": 17598, + "##rice": 17599, + "caretaker": 17600, + "hostilities": 17601, + "mclean": 17602, + "##gre": 17603, + "regimental": 17604, + "treasures": 17605, + "norms": 17606, + "impose": 17607, + "tsar": 17608, + "tango": 17609, + "diplomacy": 17610, + "variously": 17611, + "complain": 17612, + "192": 17613, + "recognise": 17614, + "arrests": 17615, + "1779": 17616, + "celestial": 17617, + "pulitzer": 17618, + "##dus": 17619, + "bing": 17620, + "libretto": 17621, + "##moor": 17622, + "adele": 17623, + "splash": 17624, + "##rite": 17625, + "expectation": 17626, + "lds": 17627, + "confronts": 17628, + "##izer": 17629, + "spontaneous": 17630, + "harmful": 17631, + "wedge": 17632, + "entrepreneurs": 17633, + "buyer": 17634, + "##ope": 17635, + "bilingual": 17636, + "translate": 17637, + "rugged": 17638, + "conner": 17639, + "circulated": 17640, + "uae": 17641, + "eaton": 17642, + "##gra": 17643, + "##zzle": 17644, + "lingered": 17645, + "lockheed": 17646, + "vishnu": 17647, + "reelection": 17648, + "alonso": 17649, + "##oom": 17650, + "joints": 17651, + "yankee": 17652, + "headline": 17653, + "cooperate": 17654, + "heinz": 17655, + "laureate": 17656, + "invading": 17657, + "##sford": 17658, + "echoes": 17659, + "scandinavian": 17660, + "##dham": 17661, + "hugging": 17662, + "vitamin": 17663, + "salute": 17664, + "micah": 17665, + "hind": 17666, + "trader": 17667, + "##sper": 17668, + "radioactive": 17669, + "##ndra": 17670, + "militants": 17671, + "poisoned": 17672, + "ratified": 17673, + "remark": 17674, + "campeonato": 17675, + "deprived": 17676, + "wander": 17677, + "prop": 17678, + "##dong": 17679, + "outlook": 17680, + "##tani": 17681, + "##rix": 17682, + "##eye": 17683, + "chiang": 17684, + "darcy": 17685, + "##oping": 17686, + "mandolin": 17687, + "spice": 17688, + "statesman": 17689, + "babylon": 17690, + "182": 17691, + "walled": 17692, + "forgetting": 17693, + "afro": 17694, + "##cap": 17695, + "158": 17696, + "giorgio": 17697, + "buffer": 17698, + "##polis": 17699, + "planetary": 17700, + "##gis": 17701, + "overlap": 17702, + "terminals": 17703, + "kinda": 17704, + "centenary": 17705, + "##bir": 17706, + "arising": 17707, + "manipulate": 17708, + "elm": 17709, + "ke": 17710, + "1770": 17711, + "ak": 17712, + "##tad": 17713, + "chrysler": 17714, + "mapped": 17715, + "moose": 17716, + "pomeranian": 17717, + "quad": 17718, + "macarthur": 17719, + "assemblies": 17720, + "shoreline": 17721, + "recalls": 17722, + "stratford": 17723, + "##rted": 17724, + "noticeable": 17725, + "##evic": 17726, + "imp": 17727, + "##rita": 17728, + "##sque": 17729, + "accustomed": 17730, + "supplying": 17731, + "tents": 17732, + "disgusted": 17733, + "vogue": 17734, + "sipped": 17735, + "filters": 17736, + "khz": 17737, + "reno": 17738, + "selecting": 17739, + "luftwaffe": 17740, + "mcmahon": 17741, + "tyne": 17742, + "masterpiece": 17743, + "carriages": 17744, + "collided": 17745, + "dunes": 17746, + "exercised": 17747, + "flare": 17748, + "remembers": 17749, + "muzzle": 17750, + "##mobile": 17751, + "heck": 17752, + "##rson": 17753, + "burgess": 17754, + "lunged": 17755, + "middleton": 17756, + "boycott": 17757, + "bilateral": 17758, + "##sity": 17759, + "hazardous": 17760, + "lumpur": 17761, + "multiplayer": 17762, + "spotlight": 17763, + "jackets": 17764, + "goldman": 17765, + "liege": 17766, + "porcelain": 17767, + "rag": 17768, + "waterford": 17769, + "benz": 17770, + "attracts": 17771, + "hopeful": 17772, + "battling": 17773, + "ottomans": 17774, + "kensington": 17775, + "baked": 17776, + "hymns": 17777, + "cheyenne": 17778, + "lattice": 17779, + "levine": 17780, + "borrow": 17781, + "polymer": 17782, + "clashes": 17783, + "michaels": 17784, + "monitored": 17785, + "commitments": 17786, + "denounced": 17787, + "##25": 17788, + "##von": 17789, + "cavity": 17790, + "##oney": 17791, + "hobby": 17792, + "akin": 17793, + "##holders": 17794, + "futures": 17795, + "intricate": 17796, + "cornish": 17797, + "patty": 17798, + "##oned": 17799, + "illegally": 17800, + "dolphin": 17801, + "##lag": 17802, + "barlow": 17803, + "yellowish": 17804, + "maddie": 17805, + "apologized": 17806, + "luton": 17807, + "plagued": 17808, + "##puram": 17809, + "nana": 17810, + "##rds": 17811, + "sway": 17812, + "fanny": 17813, + "łodz": 17814, + "##rino": 17815, + "psi": 17816, + "suspicions": 17817, + "hanged": 17818, + "##eding": 17819, + "initiate": 17820, + "charlton": 17821, + "##por": 17822, + "nak": 17823, + "competent": 17824, + "235": 17825, + "analytical": 17826, + "annex": 17827, + "wardrobe": 17828, + "reservations": 17829, + "##rma": 17830, + "sect": 17831, + "162": 17832, + "fairfax": 17833, + "hedge": 17834, + "piled": 17835, + "buckingham": 17836, + "uneven": 17837, + "bauer": 17838, + "simplicity": 17839, + "snyder": 17840, + "interpret": 17841, + "accountability": 17842, + "donors": 17843, + "moderately": 17844, + "byrd": 17845, + "continents": 17846, + "##cite": 17847, + "##max": 17848, + "disciple": 17849, + "hr": 17850, + "jamaican": 17851, + "ping": 17852, + "nominees": 17853, + "##uss": 17854, + "mongolian": 17855, + "diver": 17856, + "attackers": 17857, + "eagerly": 17858, + "ideological": 17859, + "pillows": 17860, + "miracles": 17861, + "apartheid": 17862, + "revolver": 17863, + "sulfur": 17864, + "clinics": 17865, + "moran": 17866, + "163": 17867, + "##enko": 17868, + "ile": 17869, + "katy": 17870, + "rhetoric": 17871, + "##icated": 17872, + "chronology": 17873, + "recycling": 17874, + "##hrer": 17875, + "elongated": 17876, + "mughal": 17877, + "pascal": 17878, + "profiles": 17879, + "vibration": 17880, + "databases": 17881, + "domination": 17882, + "##fare": 17883, + "##rant": 17884, + "matthias": 17885, + "digest": 17886, + "rehearsal": 17887, + "polling": 17888, + "weiss": 17889, + "initiation": 17890, + "reeves": 17891, + "clinging": 17892, + "flourished": 17893, + "impress": 17894, + "ngo": 17895, + "##hoff": 17896, + "##ume": 17897, + "buckley": 17898, + "symposium": 17899, + "rhythms": 17900, + "weed": 17901, + "emphasize": 17902, + "transforming": 17903, + "##taking": 17904, + "##gence": 17905, + "##yman": 17906, + "accountant": 17907, + "analyze": 17908, + "flicker": 17909, + "foil": 17910, + "priesthood": 17911, + "voluntarily": 17912, + "decreases": 17913, + "##80": 17914, + "##hya": 17915, + "slater": 17916, + "sv": 17917, + "charting": 17918, + "mcgill": 17919, + "##lde": 17920, + "moreno": 17921, + "##iu": 17922, + "besieged": 17923, + "zur": 17924, + "robes": 17925, + "##phic": 17926, + "admitting": 17927, + "api": 17928, + "deported": 17929, + "turmoil": 17930, + "peyton": 17931, + "earthquakes": 17932, + "##ares": 17933, + "nationalists": 17934, + "beau": 17935, + "clair": 17936, + "brethren": 17937, + "interrupt": 17938, + "welch": 17939, + "curated": 17940, + "galerie": 17941, + "requesting": 17942, + "164": 17943, + "##ested": 17944, + "impending": 17945, + "steward": 17946, + "viper": 17947, + "##vina": 17948, + "complaining": 17949, + "beautifully": 17950, + "brandy": 17951, + "foam": 17952, + "nl": 17953, + "1660": 17954, + "##cake": 17955, + "alessandro": 17956, + "punches": 17957, + "laced": 17958, + "explanations": 17959, + "##lim": 17960, + "attribute": 17961, + "clit": 17962, + "reggie": 17963, + "discomfort": 17964, + "##cards": 17965, + "smoothed": 17966, + "whales": 17967, + "##cene": 17968, + "adler": 17969, + "countered": 17970, + "duffy": 17971, + "disciplinary": 17972, + "widening": 17973, + "recipe": 17974, + "reliance": 17975, + "conducts": 17976, + "goats": 17977, + "gradient": 17978, + "preaching": 17979, + "##shaw": 17980, + "matilda": 17981, + "quasi": 17982, + "striped": 17983, + "meridian": 17984, + "cannabis": 17985, + "cordoba": 17986, + "certificates": 17987, + "##agh": 17988, + "##tering": 17989, + "graffiti": 17990, + "hangs": 17991, + "pilgrims": 17992, + "repeats": 17993, + "##ych": 17994, + "revive": 17995, + "urine": 17996, + "etat": 17997, + "##hawk": 17998, + "fueled": 17999, + "belts": 18000, + "fuzzy": 18001, + "susceptible": 18002, + "##hang": 18003, + "mauritius": 18004, + "salle": 18005, + "sincere": 18006, + "beers": 18007, + "hooks": 18008, + "##cki": 18009, + "arbitration": 18010, + "entrusted": 18011, + "advise": 18012, + "sniffed": 18013, + "seminar": 18014, + "junk": 18015, + "donnell": 18016, + "processors": 18017, + "principality": 18018, + "strapped": 18019, + "celia": 18020, + "mendoza": 18021, + "everton": 18022, + "fortunes": 18023, + "prejudice": 18024, + "starving": 18025, + "reassigned": 18026, + "steamer": 18027, + "##lund": 18028, + "tuck": 18029, + "evenly": 18030, + "foreman": 18031, + "##ffen": 18032, + "dans": 18033, + "375": 18034, + "envisioned": 18035, + "slit": 18036, + "##xy": 18037, + "baseman": 18038, + "liberia": 18039, + "rosemary": 18040, + "##weed": 18041, + "electrified": 18042, + "periodically": 18043, + "potassium": 18044, + "stride": 18045, + "contexts": 18046, + "sperm": 18047, + "slade": 18048, + "mariners": 18049, + "influx": 18050, + "bianca": 18051, + "subcommittee": 18052, + "##rane": 18053, + "spilling": 18054, + "icao": 18055, + "estuary": 18056, + "##nock": 18057, + "delivers": 18058, + "iphone": 18059, + "##ulata": 18060, + "isa": 18061, + "mira": 18062, + "bohemian": 18063, + "dessert": 18064, + "##sbury": 18065, + "welcoming": 18066, + "proudly": 18067, + "slowing": 18068, + "##chs": 18069, + "musee": 18070, + "ascension": 18071, + "russ": 18072, + "##vian": 18073, + "waits": 18074, + "##psy": 18075, + "africans": 18076, + "exploit": 18077, + "##morphic": 18078, + "gov": 18079, + "eccentric": 18080, + "crab": 18081, + "peck": 18082, + "##ull": 18083, + "entrances": 18084, + "formidable": 18085, + "marketplace": 18086, + "groom": 18087, + "bolted": 18088, + "metabolism": 18089, + "patton": 18090, + "robbins": 18091, + "courier": 18092, + "payload": 18093, + "endure": 18094, + "##ifier": 18095, + "andes": 18096, + "refrigerator": 18097, + "##pr": 18098, + "ornate": 18099, + "##uca": 18100, + "ruthless": 18101, + "illegitimate": 18102, + "masonry": 18103, + "strasbourg": 18104, + "bikes": 18105, + "adobe": 18106, + "##³": 18107, + "apples": 18108, + "quintet": 18109, + "willingly": 18110, + "niche": 18111, + "bakery": 18112, + "corpses": 18113, + "energetic": 18114, + "##cliffe": 18115, + "##sser": 18116, + "##ards": 18117, + "177": 18118, + "centimeters": 18119, + "centro": 18120, + "fuscous": 18121, + "cretaceous": 18122, + "rancho": 18123, + "##yde": 18124, + "andrei": 18125, + "telecom": 18126, + "tottenham": 18127, + "oasis": 18128, + "ordination": 18129, + "vulnerability": 18130, + "presiding": 18131, + "corey": 18132, + "cp": 18133, + "penguins": 18134, + "sims": 18135, + "##pis": 18136, + "malawi": 18137, + "piss": 18138, + "##48": 18139, + "correction": 18140, + "##cked": 18141, + "##ffle": 18142, + "##ryn": 18143, + "countdown": 18144, + "detectives": 18145, + "psychiatrist": 18146, + "psychedelic": 18147, + "dinosaurs": 18148, + "blouse": 18149, + "##get": 18150, + "choi": 18151, + "vowed": 18152, + "##oz": 18153, + "randomly": 18154, + "##pol": 18155, + "49ers": 18156, + "scrub": 18157, + "blanche": 18158, + "bruins": 18159, + "dusseldorf": 18160, + "##using": 18161, + "unwanted": 18162, + "##ums": 18163, + "212": 18164, + "dominique": 18165, + "elevations": 18166, + "headlights": 18167, + "om": 18168, + "laguna": 18169, + "##oga": 18170, + "1750": 18171, + "famously": 18172, + "ignorance": 18173, + "shrewsbury": 18174, + "##aine": 18175, + "ajax": 18176, + "breuning": 18177, + "che": 18178, + "confederacy": 18179, + "greco": 18180, + "overhaul": 18181, + "##screen": 18182, + "paz": 18183, + "skirts": 18184, + "disagreement": 18185, + "cruelty": 18186, + "jagged": 18187, + "phoebe": 18188, + "shifter": 18189, + "hovered": 18190, + "viruses": 18191, + "##wes": 18192, + "mandy": 18193, + "##lined": 18194, + "##gc": 18195, + "landlord": 18196, + "squirrel": 18197, + "dashed": 18198, + "##ι": 18199, + "ornamental": 18200, + "gag": 18201, + "wally": 18202, + "grange": 18203, + "literal": 18204, + "spurs": 18205, + "undisclosed": 18206, + "proceeding": 18207, + "yin": 18208, + "##text": 18209, + "billie": 18210, + "orphan": 18211, + "spanned": 18212, + "humidity": 18213, + "indy": 18214, + "weighted": 18215, + "presentations": 18216, + "explosions": 18217, + "lucian": 18218, + "##tary": 18219, + "vaughn": 18220, + "hindus": 18221, + "##anga": 18222, + "##hell": 18223, + "psycho": 18224, + "171": 18225, + "daytona": 18226, + "protects": 18227, + "efficiently": 18228, + "rematch": 18229, + "sly": 18230, + "tandem": 18231, + "##oya": 18232, + "rebranded": 18233, + "impaired": 18234, + "hee": 18235, + "metropolis": 18236, + "peach": 18237, + "godfrey": 18238, + "diaspora": 18239, + "ethnicity": 18240, + "prosperous": 18241, + "gleaming": 18242, + "dar": 18243, + "grossing": 18244, + "playback": 18245, + "##rden": 18246, + "stripe": 18247, + "pistols": 18248, + "##tain": 18249, + "births": 18250, + "labelled": 18251, + "##cating": 18252, + "172": 18253, + "rudy": 18254, + "alba": 18255, + "##onne": 18256, + "aquarium": 18257, + "hostility": 18258, + "##gb": 18259, + "##tase": 18260, + "shudder": 18261, + "sumatra": 18262, + "hardest": 18263, + "lakers": 18264, + "consonant": 18265, + "creeping": 18266, + "demos": 18267, + "homicide": 18268, + "capsule": 18269, + "zeke": 18270, + "liberties": 18271, + "expulsion": 18272, + "pueblo": 18273, + "##comb": 18274, + "trait": 18275, + "transporting": 18276, + "##ddin": 18277, + "##neck": 18278, + "##yna": 18279, + "depart": 18280, + "gregg": 18281, + "mold": 18282, + "ledge": 18283, + "hangar": 18284, + "oldham": 18285, + "playboy": 18286, + "termination": 18287, + "analysts": 18288, + "gmbh": 18289, + "romero": 18290, + "##itic": 18291, + "insist": 18292, + "cradle": 18293, + "filthy": 18294, + "brightness": 18295, + "slash": 18296, + "shootout": 18297, + "deposed": 18298, + "bordering": 18299, + "##truct": 18300, + "isis": 18301, + "microwave": 18302, + "tumbled": 18303, + "sheltered": 18304, + "cathy": 18305, + "werewolves": 18306, + "messy": 18307, + "andersen": 18308, + "convex": 18309, + "clapped": 18310, + "clinched": 18311, + "satire": 18312, + "wasting": 18313, + "edo": 18314, + "vc": 18315, + "rufus": 18316, + "##jak": 18317, + "mont": 18318, + "##etti": 18319, + "poznan": 18320, + "##keeping": 18321, + "restructuring": 18322, + "transverse": 18323, + "##rland": 18324, + "azerbaijani": 18325, + "slovene": 18326, + "gestures": 18327, + "roommate": 18328, + "choking": 18329, + "shear": 18330, + "##quist": 18331, + "vanguard": 18332, + "oblivious": 18333, + "##hiro": 18334, + "disagreed": 18335, + "baptism": 18336, + "##lich": 18337, + "coliseum": 18338, + "##aceae": 18339, + "salvage": 18340, + "societe": 18341, + "cory": 18342, + "locke": 18343, + "relocation": 18344, + "relying": 18345, + "versailles": 18346, + "ahl": 18347, + "swelling": 18348, + "##elo": 18349, + "cheerful": 18350, + "##word": 18351, + "##edes": 18352, + "gin": 18353, + "sarajevo": 18354, + "obstacle": 18355, + "diverted": 18356, + "##nac": 18357, + "messed": 18358, + "thoroughbred": 18359, + "fluttered": 18360, + "utrecht": 18361, + "chewed": 18362, + "acquaintance": 18363, + "assassins": 18364, + "dispatch": 18365, + "mirza": 18366, + "##wart": 18367, + "nike": 18368, + "salzburg": 18369, + "swell": 18370, + "yen": 18371, + "##gee": 18372, + "idle": 18373, + "ligue": 18374, + "samson": 18375, + "##nds": 18376, + "##igh": 18377, + "playful": 18378, + "spawned": 18379, + "##cise": 18380, + "tease": 18381, + "##case": 18382, + "burgundy": 18383, + "##bot": 18384, + "stirring": 18385, + "skeptical": 18386, + "interceptions": 18387, + "marathi": 18388, + "##dies": 18389, + "bedrooms": 18390, + "aroused": 18391, + "pinch": 18392, + "##lik": 18393, + "preferences": 18394, + "tattoos": 18395, + "buster": 18396, + "digitally": 18397, + "projecting": 18398, + "rust": 18399, + "##ital": 18400, + "kitten": 18401, + "priorities": 18402, + "addison": 18403, + "pseudo": 18404, + "##guard": 18405, + "dusk": 18406, + "icons": 18407, + "sermon": 18408, + "##psis": 18409, + "##iba": 18410, + "bt": 18411, + "##lift": 18412, + "##xt": 18413, + "ju": 18414, + "truce": 18415, + "rink": 18416, + "##dah": 18417, + "##wy": 18418, + "defects": 18419, + "psychiatry": 18420, + "offences": 18421, + "calculate": 18422, + "glucose": 18423, + "##iful": 18424, + "##rized": 18425, + "##unda": 18426, + "francaise": 18427, + "##hari": 18428, + "richest": 18429, + "warwickshire": 18430, + "carly": 18431, + "1763": 18432, + "purity": 18433, + "redemption": 18434, + "lending": 18435, + "##cious": 18436, + "muse": 18437, + "bruises": 18438, + "cerebral": 18439, + "aero": 18440, + "carving": 18441, + "##name": 18442, + "preface": 18443, + "terminology": 18444, + "invade": 18445, + "monty": 18446, + "##int": 18447, + "anarchist": 18448, + "blurred": 18449, + "##iled": 18450, + "rossi": 18451, + "treats": 18452, + "guts": 18453, + "shu": 18454, + "foothills": 18455, + "ballads": 18456, + "undertaking": 18457, + "premise": 18458, + "cecilia": 18459, + "affiliates": 18460, + "blasted": 18461, + "conditional": 18462, + "wilder": 18463, + "minors": 18464, + "drone": 18465, + "rudolph": 18466, + "buffy": 18467, + "swallowing": 18468, + "horton": 18469, + "attested": 18470, + "##hop": 18471, + "rutherford": 18472, + "howell": 18473, + "primetime": 18474, + "livery": 18475, + "penal": 18476, + "##bis": 18477, + "minimize": 18478, + "hydro": 18479, + "wrecked": 18480, + "wrought": 18481, + "palazzo": 18482, + "##gling": 18483, + "cans": 18484, + "vernacular": 18485, + "friedman": 18486, + "nobleman": 18487, + "shale": 18488, + "walnut": 18489, + "danielle": 18490, + "##ection": 18491, + "##tley": 18492, + "sears": 18493, + "##kumar": 18494, + "chords": 18495, + "lend": 18496, + "flipping": 18497, + "streamed": 18498, + "por": 18499, + "dracula": 18500, + "gallons": 18501, + "sacrifices": 18502, + "gamble": 18503, + "orphanage": 18504, + "##iman": 18505, + "mckenzie": 18506, + "##gible": 18507, + "boxers": 18508, + "daly": 18509, + "##balls": 18510, + "##ان": 18511, + "208": 18512, + "##ific": 18513, + "##rative": 18514, + "##iq": 18515, + "exploited": 18516, + "slated": 18517, + "##uity": 18518, + "circling": 18519, + "hillary": 18520, + "pinched": 18521, + "goldberg": 18522, + "provost": 18523, + "campaigning": 18524, + "lim": 18525, + "piles": 18526, + "ironically": 18527, + "jong": 18528, + "mohan": 18529, + "successors": 18530, + "usaf": 18531, + "##tem": 18532, + "##ught": 18533, + "autobiographical": 18534, + "haute": 18535, + "preserves": 18536, + "##ending": 18537, + "acquitted": 18538, + "comparisons": 18539, + "203": 18540, + "hydroelectric": 18541, + "gangs": 18542, + "cypriot": 18543, + "torpedoes": 18544, + "rushes": 18545, + "chrome": 18546, + "derive": 18547, + "bumps": 18548, + "instability": 18549, + "fiat": 18550, + "pets": 18551, + "##mbe": 18552, + "silas": 18553, + "dye": 18554, + "reckless": 18555, + "settler": 18556, + "##itation": 18557, + "info": 18558, + "heats": 18559, + "##writing": 18560, + "176": 18561, + "canonical": 18562, + "maltese": 18563, + "fins": 18564, + "mushroom": 18565, + "stacy": 18566, + "aspen": 18567, + "avid": 18568, + "##kur": 18569, + "##loading": 18570, + "vickers": 18571, + "gaston": 18572, + "hillside": 18573, + "statutes": 18574, + "wilde": 18575, + "gail": 18576, + "kung": 18577, + "sabine": 18578, + "comfortably": 18579, + "motorcycles": 18580, + "##rgo": 18581, + "169": 18582, + "pneumonia": 18583, + "fetch": 18584, + "##sonic": 18585, + "axel": 18586, + "faintly": 18587, + "parallels": 18588, + "##oop": 18589, + "mclaren": 18590, + "spouse": 18591, + "compton": 18592, + "interdisciplinary": 18593, + "miner": 18594, + "##eni": 18595, + "181": 18596, + "clamped": 18597, + "##chal": 18598, + "##llah": 18599, + "separates": 18600, + "versa": 18601, + "##mler": 18602, + "scarborough": 18603, + "labrador": 18604, + "##lity": 18605, + "##osing": 18606, + "rutgers": 18607, + "hurdles": 18608, + "como": 18609, + "166": 18610, + "burt": 18611, + "divers": 18612, + "##100": 18613, + "wichita": 18614, + "cade": 18615, + "coincided": 18616, + "##erson": 18617, + "bruised": 18618, + "mla": 18619, + "##pper": 18620, + "vineyard": 18621, + "##ili": 18622, + "##brush": 18623, + "notch": 18624, + "mentioning": 18625, + "jase": 18626, + "hearted": 18627, + "kits": 18628, + "doe": 18629, + "##acle": 18630, + "pomerania": 18631, + "##ady": 18632, + "ronan": 18633, + "seizure": 18634, + "pavel": 18635, + "problematic": 18636, + "##zaki": 18637, + "domenico": 18638, + "##ulin": 18639, + "catering": 18640, + "penelope": 18641, + "dependence": 18642, + "parental": 18643, + "emilio": 18644, + "ministerial": 18645, + "atkinson": 18646, + "##bolic": 18647, + "clarkson": 18648, + "chargers": 18649, + "colby": 18650, + "grill": 18651, + "peeked": 18652, + "arises": 18653, + "summon": 18654, + "##aged": 18655, + "fools": 18656, + "##grapher": 18657, + "faculties": 18658, + "qaeda": 18659, + "##vial": 18660, + "garner": 18661, + "refurbished": 18662, + "##hwa": 18663, + "geelong": 18664, + "disasters": 18665, + "nudged": 18666, + "bs": 18667, + "shareholder": 18668, + "lori": 18669, + "algae": 18670, + "reinstated": 18671, + "rot": 18672, + "##ades": 18673, + "##nous": 18674, + "invites": 18675, + "stainless": 18676, + "183": 18677, + "inclusive": 18678, + "##itude": 18679, + "diocesan": 18680, + "til": 18681, + "##icz": 18682, + "denomination": 18683, + "##xa": 18684, + "benton": 18685, + "floral": 18686, + "registers": 18687, + "##ider": 18688, + "##erman": 18689, + "##kell": 18690, + "absurd": 18691, + "brunei": 18692, + "guangzhou": 18693, + "hitter": 18694, + "retaliation": 18695, + "##uled": 18696, + "##eve": 18697, + "blanc": 18698, + "nh": 18699, + "consistency": 18700, + "contamination": 18701, + "##eres": 18702, + "##rner": 18703, + "dire": 18704, + "palermo": 18705, + "broadcasters": 18706, + "diaries": 18707, + "inspire": 18708, + "vols": 18709, + "brewer": 18710, + "tightening": 18711, + "ky": 18712, + "mixtape": 18713, + "hormone": 18714, + "##tok": 18715, + "stokes": 18716, + "##color": 18717, + "##dly": 18718, + "##ssi": 18719, + "pg": 18720, + "##ometer": 18721, + "##lington": 18722, + "sanitation": 18723, + "##tility": 18724, + "intercontinental": 18725, + "apps": 18726, + "##adt": 18727, + "¹⁄₂": 18728, + "cylinders": 18729, + "economies": 18730, + "favourable": 18731, + "unison": 18732, + "croix": 18733, + "gertrude": 18734, + "odyssey": 18735, + "vanity": 18736, + "dangling": 18737, + "##logists": 18738, + "upgrades": 18739, + "dice": 18740, + "middleweight": 18741, + "practitioner": 18742, + "##ight": 18743, + "206": 18744, + "henrik": 18745, + "parlor": 18746, + "orion": 18747, + "angered": 18748, + "lac": 18749, + "python": 18750, + "blurted": 18751, + "##rri": 18752, + "sensual": 18753, + "intends": 18754, + "swings": 18755, + "angled": 18756, + "##phs": 18757, + "husky": 18758, + "attain": 18759, + "peerage": 18760, + "precinct": 18761, + "textiles": 18762, + "cheltenham": 18763, + "shuffled": 18764, + "dai": 18765, + "confess": 18766, + "tasting": 18767, + "bhutan": 18768, + "##riation": 18769, + "tyrone": 18770, + "segregation": 18771, + "abrupt": 18772, + "ruiz": 18773, + "##rish": 18774, + "smirked": 18775, + "blackwell": 18776, + "confidential": 18777, + "browning": 18778, + "amounted": 18779, + "##put": 18780, + "vase": 18781, + "scarce": 18782, + "fabulous": 18783, + "raided": 18784, + "staple": 18785, + "guyana": 18786, + "unemployed": 18787, + "glider": 18788, + "shay": 18789, + "##tow": 18790, + "carmine": 18791, + "troll": 18792, + "intervene": 18793, + "squash": 18794, + "superstar": 18795, + "##uce": 18796, + "cylindrical": 18797, + "len": 18798, + "roadway": 18799, + "researched": 18800, + "handy": 18801, + "##rium": 18802, + "##jana": 18803, + "meta": 18804, + "lao": 18805, + "declares": 18806, + "##rring": 18807, + "##tadt": 18808, + "##elin": 18809, + "##kova": 18810, + "willem": 18811, + "shrubs": 18812, + "napoleonic": 18813, + "realms": 18814, + "skater": 18815, + "qi": 18816, + "volkswagen": 18817, + "##ł": 18818, + "tad": 18819, + "hara": 18820, + "archaeologist": 18821, + "awkwardly": 18822, + "eerie": 18823, + "##kind": 18824, + "wiley": 18825, + "##heimer": 18826, + "##24": 18827, + "titus": 18828, + "organizers": 18829, + "cfl": 18830, + "crusaders": 18831, + "lama": 18832, + "usb": 18833, + "vent": 18834, + "enraged": 18835, + "thankful": 18836, + "occupants": 18837, + "maximilian": 18838, + "##gaard": 18839, + "possessing": 18840, + "textbooks": 18841, + "##oran": 18842, + "collaborator": 18843, + "quaker": 18844, + "##ulo": 18845, + "avalanche": 18846, + "mono": 18847, + "silky": 18848, + "straits": 18849, + "isaiah": 18850, + "mustang": 18851, + "surged": 18852, + "resolutions": 18853, + "potomac": 18854, + "descend": 18855, + "cl": 18856, + "kilograms": 18857, + "plato": 18858, + "strains": 18859, + "saturdays": 18860, + "##olin": 18861, + "bernstein": 18862, + "##ype": 18863, + "holstein": 18864, + "ponytail": 18865, + "##watch": 18866, + "belize": 18867, + "conversely": 18868, + "heroine": 18869, + "perpetual": 18870, + "##ylus": 18871, + "charcoal": 18872, + "piedmont": 18873, + "glee": 18874, + "negotiating": 18875, + "backdrop": 18876, + "prologue": 18877, + "##jah": 18878, + "##mmy": 18879, + "pasadena": 18880, + "climbs": 18881, + "ramos": 18882, + "sunni": 18883, + "##holm": 18884, + "##tner": 18885, + "##tri": 18886, + "anand": 18887, + "deficiency": 18888, + "hertfordshire": 18889, + "stout": 18890, + "##avi": 18891, + "aperture": 18892, + "orioles": 18893, + "##irs": 18894, + "doncaster": 18895, + "intrigued": 18896, + "bombed": 18897, + "coating": 18898, + "otis": 18899, + "##mat": 18900, + "cocktail": 18901, + "##jit": 18902, + "##eto": 18903, + "amir": 18904, + "arousal": 18905, + "sar": 18906, + "##proof": 18907, + "##act": 18908, + "##ories": 18909, + "dixie": 18910, + "pots": 18911, + "##bow": 18912, + "whereabouts": 18913, + "159": 18914, + "##fted": 18915, + "drains": 18916, + "bullying": 18917, + "cottages": 18918, + "scripture": 18919, + "coherent": 18920, + "fore": 18921, + "poe": 18922, + "appetite": 18923, + "##uration": 18924, + "sampled": 18925, + "##ators": 18926, + "##dp": 18927, + "derrick": 18928, + "rotor": 18929, + "jays": 18930, + "peacock": 18931, + "installment": 18932, + "##rro": 18933, + "advisors": 18934, + "##coming": 18935, + "rodeo": 18936, + "scotch": 18937, + "##mot": 18938, + "##db": 18939, + "##fen": 18940, + "##vant": 18941, + "ensued": 18942, + "rodrigo": 18943, + "dictatorship": 18944, + "martyrs": 18945, + "twenties": 18946, + "##н": 18947, + "towed": 18948, + "incidence": 18949, + "marta": 18950, + "rainforest": 18951, + "sai": 18952, + "scaled": 18953, + "##cles": 18954, + "oceanic": 18955, + "qualifiers": 18956, + "symphonic": 18957, + "mcbride": 18958, + "dislike": 18959, + "generalized": 18960, + "aubrey": 18961, + "colonization": 18962, + "##iation": 18963, + "##lion": 18964, + "##ssing": 18965, + "disliked": 18966, + "lublin": 18967, + "salesman": 18968, + "##ulates": 18969, + "spherical": 18970, + "whatsoever": 18971, + "sweating": 18972, + "avalon": 18973, + "contention": 18974, + "punt": 18975, + "severity": 18976, + "alderman": 18977, + "atari": 18978, + "##dina": 18979, + "##grant": 18980, + "##rop": 18981, + "scarf": 18982, + "seville": 18983, + "vertices": 18984, + "annexation": 18985, + "fairfield": 18986, + "fascination": 18987, + "inspiring": 18988, + "launches": 18989, + "palatinate": 18990, + "regretted": 18991, + "##rca": 18992, + "feral": 18993, + "##iom": 18994, + "elk": 18995, + "nap": 18996, + "olsen": 18997, + "reddy": 18998, + "yong": 18999, + "##leader": 19000, + "##iae": 19001, + "garment": 19002, + "transports": 19003, + "feng": 19004, + "gracie": 19005, + "outrage": 19006, + "viceroy": 19007, + "insides": 19008, + "##esis": 19009, + "breakup": 19010, + "grady": 19011, + "organizer": 19012, + "softer": 19013, + "grimaced": 19014, + "222": 19015, + "murals": 19016, + "galicia": 19017, + "arranging": 19018, + "vectors": 19019, + "##rsten": 19020, + "bas": 19021, + "##sb": 19022, + "##cens": 19023, + "sloan": 19024, + "##eka": 19025, + "bitten": 19026, + "ara": 19027, + "fender": 19028, + "nausea": 19029, + "bumped": 19030, + "kris": 19031, + "banquet": 19032, + "comrades": 19033, + "detector": 19034, + "persisted": 19035, + "##llan": 19036, + "adjustment": 19037, + "endowed": 19038, + "cinemas": 19039, + "##shot": 19040, + "sellers": 19041, + "##uman": 19042, + "peek": 19043, + "epa": 19044, + "kindly": 19045, + "neglect": 19046, + "simpsons": 19047, + "talon": 19048, + "mausoleum": 19049, + "runaway": 19050, + "hangul": 19051, + "lookout": 19052, + "##cic": 19053, + "rewards": 19054, + "coughed": 19055, + "acquainted": 19056, + "chloride": 19057, + "##ald": 19058, + "quicker": 19059, + "accordion": 19060, + "neolithic": 19061, + "##qa": 19062, + "artemis": 19063, + "coefficient": 19064, + "lenny": 19065, + "pandora": 19066, + "tx": 19067, + "##xed": 19068, + "ecstasy": 19069, + "litter": 19070, + "segunda": 19071, + "chairperson": 19072, + "gemma": 19073, + "hiss": 19074, + "rumor": 19075, + "vow": 19076, + "nasal": 19077, + "antioch": 19078, + "compensate": 19079, + "patiently": 19080, + "transformers": 19081, + "##eded": 19082, + "judo": 19083, + "morrow": 19084, + "penis": 19085, + "posthumous": 19086, + "philips": 19087, + "bandits": 19088, + "husbands": 19089, + "denote": 19090, + "flaming": 19091, + "##any": 19092, + "##phones": 19093, + "langley": 19094, + "yorker": 19095, + "1760": 19096, + "walters": 19097, + "##uo": 19098, + "##kle": 19099, + "gubernatorial": 19100, + "fatty": 19101, + "samsung": 19102, + "leroy": 19103, + "outlaw": 19104, + "##nine": 19105, + "unpublished": 19106, + "poole": 19107, + "jakob": 19108, + "##ᵢ": 19109, + "##ₙ": 19110, + "crete": 19111, + "distorted": 19112, + "superiority": 19113, + "##dhi": 19114, + "intercept": 19115, + "crust": 19116, + "mig": 19117, + "claus": 19118, + "crashes": 19119, + "positioning": 19120, + "188": 19121, + "stallion": 19122, + "301": 19123, + "frontal": 19124, + "armistice": 19125, + "##estinal": 19126, + "elton": 19127, + "aj": 19128, + "encompassing": 19129, + "camel": 19130, + "commemorated": 19131, + "malaria": 19132, + "woodward": 19133, + "calf": 19134, + "cigar": 19135, + "penetrate": 19136, + "##oso": 19137, + "willard": 19138, + "##rno": 19139, + "##uche": 19140, + "illustrate": 19141, + "amusing": 19142, + "convergence": 19143, + "noteworthy": 19144, + "##lma": 19145, + "##rva": 19146, + "journeys": 19147, + "realise": 19148, + "manfred": 19149, + "##sable": 19150, + "410": 19151, + "##vocation": 19152, + "hearings": 19153, + "fiance": 19154, + "##posed": 19155, + "educators": 19156, + "provoked": 19157, + "adjusting": 19158, + "##cturing": 19159, + "modular": 19160, + "stockton": 19161, + "paterson": 19162, + "vlad": 19163, + "rejects": 19164, + "electors": 19165, + "selena": 19166, + "maureen": 19167, + "##tres": 19168, + "uber": 19169, + "##rce": 19170, + "swirled": 19171, + "##num": 19172, + "proportions": 19173, + "nanny": 19174, + "pawn": 19175, + "naturalist": 19176, + "parma": 19177, + "apostles": 19178, + "awoke": 19179, + "ethel": 19180, + "wen": 19181, + "##bey": 19182, + "monsoon": 19183, + "overview": 19184, + "##inating": 19185, + "mccain": 19186, + "rendition": 19187, + "risky": 19188, + "adorned": 19189, + "##ih": 19190, + "equestrian": 19191, + "germain": 19192, + "nj": 19193, + "conspicuous": 19194, + "confirming": 19195, + "##yoshi": 19196, + "shivering": 19197, + "##imeter": 19198, + "milestone": 19199, + "rumours": 19200, + "flinched": 19201, + "bounds": 19202, + "smacked": 19203, + "token": 19204, + "##bei": 19205, + "lectured": 19206, + "automobiles": 19207, + "##shore": 19208, + "impacted": 19209, + "##iable": 19210, + "nouns": 19211, + "nero": 19212, + "##leaf": 19213, + "ismail": 19214, + "prostitute": 19215, + "trams": 19216, + "##lace": 19217, + "bridget": 19218, + "sud": 19219, + "stimulus": 19220, + "impressions": 19221, + "reins": 19222, + "revolves": 19223, + "##oud": 19224, + "##gned": 19225, + "giro": 19226, + "honeymoon": 19227, + "##swell": 19228, + "criterion": 19229, + "##sms": 19230, + "##uil": 19231, + "libyan": 19232, + "prefers": 19233, + "##osition": 19234, + "211": 19235, + "preview": 19236, + "sucks": 19237, + "accusation": 19238, + "bursts": 19239, + "metaphor": 19240, + "diffusion": 19241, + "tolerate": 19242, + "faye": 19243, + "betting": 19244, + "cinematographer": 19245, + "liturgical": 19246, + "specials": 19247, + "bitterly": 19248, + "humboldt": 19249, + "##ckle": 19250, + "flux": 19251, + "rattled": 19252, + "##itzer": 19253, + "archaeologists": 19254, + "odor": 19255, + "authorised": 19256, + "marshes": 19257, + "discretion": 19258, + "##ов": 19259, + "alarmed": 19260, + "archaic": 19261, + "inverse": 19262, + "##leton": 19263, + "explorers": 19264, + "##pine": 19265, + "drummond": 19266, + "tsunami": 19267, + "woodlands": 19268, + "##minate": 19269, + "##tland": 19270, + "booklet": 19271, + "insanity": 19272, + "owning": 19273, + "insert": 19274, + "crafted": 19275, + "calculus": 19276, + "##tore": 19277, + "receivers": 19278, + "##bt": 19279, + "stung": 19280, + "##eca": 19281, + "##nched": 19282, + "prevailing": 19283, + "travellers": 19284, + "eyeing": 19285, + "lila": 19286, + "graphs": 19287, + "##borne": 19288, + "178": 19289, + "julien": 19290, + "##won": 19291, + "morale": 19292, + "adaptive": 19293, + "therapist": 19294, + "erica": 19295, + "cw": 19296, + "libertarian": 19297, + "bowman": 19298, + "pitches": 19299, + "vita": 19300, + "##ional": 19301, + "crook": 19302, + "##ads": 19303, + "##entation": 19304, + "caledonia": 19305, + "mutiny": 19306, + "##sible": 19307, + "1840s": 19308, + "automation": 19309, + "##ß": 19310, + "flock": 19311, + "##pia": 19312, + "ironic": 19313, + "pathology": 19314, + "##imus": 19315, + "remarried": 19316, + "##22": 19317, + "joker": 19318, + "withstand": 19319, + "energies": 19320, + "##att": 19321, + "shropshire": 19322, + "hostages": 19323, + "madeleine": 19324, + "tentatively": 19325, + "conflicting": 19326, + "mateo": 19327, + "recipes": 19328, + "euros": 19329, + "ol": 19330, + "mercenaries": 19331, + "nico": 19332, + "##ndon": 19333, + "albuquerque": 19334, + "augmented": 19335, + "mythical": 19336, + "bel": 19337, + "freud": 19338, + "##child": 19339, + "cough": 19340, + "##lica": 19341, + "365": 19342, + "freddy": 19343, + "lillian": 19344, + "genetically": 19345, + "nuremberg": 19346, + "calder": 19347, + "209": 19348, + "bonn": 19349, + "outdoors": 19350, + "paste": 19351, + "suns": 19352, + "urgency": 19353, + "vin": 19354, + "restraint": 19355, + "tyson": 19356, + "##cera": 19357, + "##selle": 19358, + "barrage": 19359, + "bethlehem": 19360, + "kahn": 19361, + "##par": 19362, + "mounts": 19363, + "nippon": 19364, + "barony": 19365, + "happier": 19366, + "ryu": 19367, + "makeshift": 19368, + "sheldon": 19369, + "blushed": 19370, + "castillo": 19371, + "barking": 19372, + "listener": 19373, + "taped": 19374, + "bethel": 19375, + "fluent": 19376, + "headlines": 19377, + "pornography": 19378, + "rum": 19379, + "disclosure": 19380, + "sighing": 19381, + "mace": 19382, + "doubling": 19383, + "gunther": 19384, + "manly": 19385, + "##plex": 19386, + "rt": 19387, + "interventions": 19388, + "physiological": 19389, + "forwards": 19390, + "emerges": 19391, + "##tooth": 19392, + "##gny": 19393, + "compliment": 19394, + "rib": 19395, + "recession": 19396, + "visibly": 19397, + "barge": 19398, + "faults": 19399, + "connector": 19400, + "exquisite": 19401, + "prefect": 19402, + "##rlin": 19403, + "patio": 19404, + "##cured": 19405, + "elevators": 19406, + "brandt": 19407, + "italics": 19408, + "pena": 19409, + "173": 19410, + "wasp": 19411, + "satin": 19412, + "ea": 19413, + "botswana": 19414, + "graceful": 19415, + "respectable": 19416, + "##jima": 19417, + "##rter": 19418, + "##oic": 19419, + "franciscan": 19420, + "generates": 19421, + "##dl": 19422, + "alfredo": 19423, + "disgusting": 19424, + "##olate": 19425, + "##iously": 19426, + "sherwood": 19427, + "warns": 19428, + "cod": 19429, + "promo": 19430, + "cheryl": 19431, + "sino": 19432, + "##ة": 19433, + "##escu": 19434, + "twitch": 19435, + "##zhi": 19436, + "brownish": 19437, + "thom": 19438, + "ortiz": 19439, + "##dron": 19440, + "densely": 19441, + "##beat": 19442, + "carmel": 19443, + "reinforce": 19444, + "##bana": 19445, + "187": 19446, + "anastasia": 19447, + "downhill": 19448, + "vertex": 19449, + "contaminated": 19450, + "remembrance": 19451, + "harmonic": 19452, + "homework": 19453, + "##sol": 19454, + "fiancee": 19455, + "gears": 19456, + "olds": 19457, + "angelica": 19458, + "loft": 19459, + "ramsay": 19460, + "quiz": 19461, + "colliery": 19462, + "sevens": 19463, + "##cape": 19464, + "autism": 19465, + "##hil": 19466, + "walkway": 19467, + "##boats": 19468, + "ruben": 19469, + "abnormal": 19470, + "ounce": 19471, + "khmer": 19472, + "##bbe": 19473, + "zachary": 19474, + "bedside": 19475, + "morphology": 19476, + "punching": 19477, + "##olar": 19478, + "sparrow": 19479, + "convinces": 19480, + "##35": 19481, + "hewitt": 19482, + "queer": 19483, + "remastered": 19484, + "rods": 19485, + "mabel": 19486, + "solemn": 19487, + "notified": 19488, + "lyricist": 19489, + "symmetric": 19490, + "##xide": 19491, + "174": 19492, + "encore": 19493, + "passports": 19494, + "wildcats": 19495, + "##uni": 19496, + "baja": 19497, + "##pac": 19498, + "mildly": 19499, + "##ease": 19500, + "bleed": 19501, + "commodity": 19502, + "mounds": 19503, + "glossy": 19504, + "orchestras": 19505, + "##omo": 19506, + "damian": 19507, + "prelude": 19508, + "ambitions": 19509, + "##vet": 19510, + "awhile": 19511, + "remotely": 19512, + "##aud": 19513, + "asserts": 19514, + "imply": 19515, + "##iques": 19516, + "distinctly": 19517, + "modelling": 19518, + "remedy": 19519, + "##dded": 19520, + "windshield": 19521, + "dani": 19522, + "xiao": 19523, + "##endra": 19524, + "audible": 19525, + "powerplant": 19526, + "1300": 19527, + "invalid": 19528, + "elemental": 19529, + "acquisitions": 19530, + "##hala": 19531, + "immaculate": 19532, + "libby": 19533, + "plata": 19534, + "smuggling": 19535, + "ventilation": 19536, + "denoted": 19537, + "minh": 19538, + "##morphism": 19539, + "430": 19540, + "differed": 19541, + "dion": 19542, + "kelley": 19543, + "lore": 19544, + "mocking": 19545, + "sabbath": 19546, + "spikes": 19547, + "hygiene": 19548, + "drown": 19549, + "runoff": 19550, + "stylized": 19551, + "tally": 19552, + "liberated": 19553, + "aux": 19554, + "interpreter": 19555, + "righteous": 19556, + "aba": 19557, + "siren": 19558, + "reaper": 19559, + "pearce": 19560, + "millie": 19561, + "##cier": 19562, + "##yra": 19563, + "gaius": 19564, + "##iso": 19565, + "captures": 19566, + "##ttering": 19567, + "dorm": 19568, + "claudio": 19569, + "##sic": 19570, + "benches": 19571, + "knighted": 19572, + "blackness": 19573, + "##ored": 19574, + "discount": 19575, + "fumble": 19576, + "oxidation": 19577, + "routed": 19578, + "##ς": 19579, + "novak": 19580, + "perpendicular": 19581, + "spoiled": 19582, + "fracture": 19583, + "splits": 19584, + "##urt": 19585, + "pads": 19586, + "topology": 19587, + "##cats": 19588, + "axes": 19589, + "fortunate": 19590, + "offenders": 19591, + "protestants": 19592, + "esteem": 19593, + "221": 19594, + "broadband": 19595, + "convened": 19596, + "frankly": 19597, + "hound": 19598, + "prototypes": 19599, + "isil": 19600, + "facilitated": 19601, + "keel": 19602, + "##sher": 19603, + "sahara": 19604, + "awaited": 19605, + "bubba": 19606, + "orb": 19607, + "prosecutors": 19608, + "186": 19609, + "hem": 19610, + "520": 19611, + "##xing": 19612, + "relaxing": 19613, + "remnant": 19614, + "romney": 19615, + "sorted": 19616, + "slalom": 19617, + "stefano": 19618, + "ulrich": 19619, + "##active": 19620, + "exemption": 19621, + "folder": 19622, + "pauses": 19623, + "foliage": 19624, + "hitchcock": 19625, + "epithet": 19626, + "204": 19627, + "criticisms": 19628, + "##aca": 19629, + "ballistic": 19630, + "brody": 19631, + "hinduism": 19632, + "chaotic": 19633, + "youths": 19634, + "equals": 19635, + "##pala": 19636, + "pts": 19637, + "thicker": 19638, + "analogous": 19639, + "capitalist": 19640, + "improvised": 19641, + "overseeing": 19642, + "sinatra": 19643, + "ascended": 19644, + "beverage": 19645, + "##tl": 19646, + "straightforward": 19647, + "##kon": 19648, + "curran": 19649, + "##west": 19650, + "bois": 19651, + "325": 19652, + "induce": 19653, + "surveying": 19654, + "emperors": 19655, + "sax": 19656, + "unpopular": 19657, + "##kk": 19658, + "cartoonist": 19659, + "fused": 19660, + "##mble": 19661, + "unto": 19662, + "##yuki": 19663, + "localities": 19664, + "##cko": 19665, + "##ln": 19666, + "darlington": 19667, + "slain": 19668, + "academie": 19669, + "lobbying": 19670, + "sediment": 19671, + "puzzles": 19672, + "##grass": 19673, + "defiance": 19674, + "dickens": 19675, + "manifest": 19676, + "tongues": 19677, + "alumnus": 19678, + "arbor": 19679, + "coincide": 19680, + "184": 19681, + "appalachian": 19682, + "mustafa": 19683, + "examiner": 19684, + "cabaret": 19685, + "traumatic": 19686, + "yves": 19687, + "bracelet": 19688, + "draining": 19689, + "heroin": 19690, + "magnum": 19691, + "baths": 19692, + "odessa": 19693, + "consonants": 19694, + "mitsubishi": 19695, + "##gua": 19696, + "kellan": 19697, + "vaudeville": 19698, + "##fr": 19699, + "joked": 19700, + "null": 19701, + "straps": 19702, + "probation": 19703, + "##ław": 19704, + "ceded": 19705, + "interfaces": 19706, + "##pas": 19707, + "##zawa": 19708, + "blinding": 19709, + "viet": 19710, + "224": 19711, + "rothschild": 19712, + "museo": 19713, + "640": 19714, + "huddersfield": 19715, + "##vr": 19716, + "tactic": 19717, + "##storm": 19718, + "brackets": 19719, + "dazed": 19720, + "incorrectly": 19721, + "##vu": 19722, + "reg": 19723, + "glazed": 19724, + "fearful": 19725, + "manifold": 19726, + "benefited": 19727, + "irony": 19728, + "##sun": 19729, + "stumbling": 19730, + "##rte": 19731, + "willingness": 19732, + "balkans": 19733, + "mei": 19734, + "wraps": 19735, + "##aba": 19736, + "injected": 19737, + "##lea": 19738, + "gu": 19739, + "syed": 19740, + "harmless": 19741, + "##hammer": 19742, + "bray": 19743, + "takeoff": 19744, + "poppy": 19745, + "timor": 19746, + "cardboard": 19747, + "astronaut": 19748, + "purdue": 19749, + "weeping": 19750, + "southbound": 19751, + "cursing": 19752, + "stalls": 19753, + "diagonal": 19754, + "##neer": 19755, + "lamar": 19756, + "bryce": 19757, + "comte": 19758, + "weekdays": 19759, + "harrington": 19760, + "##uba": 19761, + "negatively": 19762, + "##see": 19763, + "lays": 19764, + "grouping": 19765, + "##cken": 19766, + "##henko": 19767, + "affirmed": 19768, + "halle": 19769, + "modernist": 19770, + "##lai": 19771, + "hodges": 19772, + "smelling": 19773, + "aristocratic": 19774, + "baptized": 19775, + "dismiss": 19776, + "justification": 19777, + "oilers": 19778, + "##now": 19779, + "coupling": 19780, + "qin": 19781, + "snack": 19782, + "healer": 19783, + "##qing": 19784, + "gardener": 19785, + "layla": 19786, + "battled": 19787, + "formulated": 19788, + "stephenson": 19789, + "gravitational": 19790, + "##gill": 19791, + "##jun": 19792, + "1768": 19793, + "granny": 19794, + "coordinating": 19795, + "suites": 19796, + "##cd": 19797, + "##ioned": 19798, + "monarchs": 19799, + "##cote": 19800, + "##hips": 19801, + "sep": 19802, + "blended": 19803, + "apr": 19804, + "barrister": 19805, + "deposition": 19806, + "fia": 19807, + "mina": 19808, + "policemen": 19809, + "paranoid": 19810, + "##pressed": 19811, + "churchyard": 19812, + "covert": 19813, + "crumpled": 19814, + "creep": 19815, + "abandoning": 19816, + "tr": 19817, + "transmit": 19818, + "conceal": 19819, + "barr": 19820, + "understands": 19821, + "readiness": 19822, + "spire": 19823, + "##cology": 19824, + "##enia": 19825, + "##erry": 19826, + "610": 19827, + "startling": 19828, + "unlock": 19829, + "vida": 19830, + "bowled": 19831, + "slots": 19832, + "##nat": 19833, + "##islav": 19834, + "spaced": 19835, + "trusting": 19836, + "admire": 19837, + "rig": 19838, + "##ink": 19839, + "slack": 19840, + "##70": 19841, + "mv": 19842, + "207": 19843, + "casualty": 19844, + "##wei": 19845, + "classmates": 19846, + "##odes": 19847, + "##rar": 19848, + "##rked": 19849, + "amherst": 19850, + "furnished": 19851, + "evolve": 19852, + "foundry": 19853, + "menace": 19854, + "mead": 19855, + "##lein": 19856, + "flu": 19857, + "wesleyan": 19858, + "##kled": 19859, + "monterey": 19860, + "webber": 19861, + "##vos": 19862, + "wil": 19863, + "##mith": 19864, + "##на": 19865, + "bartholomew": 19866, + "justices": 19867, + "restrained": 19868, + "##cke": 19869, + "amenities": 19870, + "191": 19871, + "mediated": 19872, + "sewage": 19873, + "trenches": 19874, + "ml": 19875, + "mainz": 19876, + "##thus": 19877, + "1800s": 19878, + "##cula": 19879, + "##inski": 19880, + "caine": 19881, + "bonding": 19882, + "213": 19883, + "converts": 19884, + "spheres": 19885, + "superseded": 19886, + "marianne": 19887, + "crypt": 19888, + "sweaty": 19889, + "ensign": 19890, + "historia": 19891, + "##br": 19892, + "spruce": 19893, + "##post": 19894, + "##ask": 19895, + "forks": 19896, + "thoughtfully": 19897, + "yukon": 19898, + "pamphlet": 19899, + "ames": 19900, + "##uter": 19901, + "karma": 19902, + "##yya": 19903, + "bryn": 19904, + "negotiation": 19905, + "sighs": 19906, + "incapable": 19907, + "##mbre": 19908, + "##ntial": 19909, + "actresses": 19910, + "taft": 19911, + "##mill": 19912, + "luce": 19913, + "prevailed": 19914, + "##amine": 19915, + "1773": 19916, + "motionless": 19917, + "envoy": 19918, + "testify": 19919, + "investing": 19920, + "sculpted": 19921, + "instructors": 19922, + "provence": 19923, + "kali": 19924, + "cullen": 19925, + "horseback": 19926, + "##while": 19927, + "goodwin": 19928, + "##jos": 19929, + "gaa": 19930, + "norte": 19931, + "##ldon": 19932, + "modify": 19933, + "wavelength": 19934, + "abd": 19935, + "214": 19936, + "skinned": 19937, + "sprinter": 19938, + "forecast": 19939, + "scheduling": 19940, + "marries": 19941, + "squared": 19942, + "tentative": 19943, + "##chman": 19944, + "boer": 19945, + "##isch": 19946, + "bolts": 19947, + "swap": 19948, + "fisherman": 19949, + "assyrian": 19950, + "impatiently": 19951, + "guthrie": 19952, + "martins": 19953, + "murdoch": 19954, + "194": 19955, + "tanya": 19956, + "nicely": 19957, + "dolly": 19958, + "lacy": 19959, + "med": 19960, + "##45": 19961, + "syn": 19962, + "decks": 19963, + "fashionable": 19964, + "millionaire": 19965, + "##ust": 19966, + "surfing": 19967, + "##ml": 19968, + "##ision": 19969, + "heaved": 19970, + "tammy": 19971, + "consulate": 19972, + "attendees": 19973, + "routinely": 19974, + "197": 19975, + "fuse": 19976, + "saxophonist": 19977, + "backseat": 19978, + "malaya": 19979, + "##lord": 19980, + "scowl": 19981, + "tau": 19982, + "##ishly": 19983, + "193": 19984, + "sighted": 19985, + "steaming": 19986, + "##rks": 19987, + "303": 19988, + "911": 19989, + "##holes": 19990, + "##hong": 19991, + "ching": 19992, + "##wife": 19993, + "bless": 19994, + "conserved": 19995, + "jurassic": 19996, + "stacey": 19997, + "unix": 19998, + "zion": 19999, + "chunk": 20000, + "rigorous": 20001, + "blaine": 20002, + "198": 20003, + "peabody": 20004, + "slayer": 20005, + "dismay": 20006, + "brewers": 20007, + "nz": 20008, + "##jer": 20009, + "det": 20010, + "##glia": 20011, + "glover": 20012, + "postwar": 20013, + "int": 20014, + "penetration": 20015, + "sylvester": 20016, + "imitation": 20017, + "vertically": 20018, + "airlift": 20019, + "heiress": 20020, + "knoxville": 20021, + "viva": 20022, + "##uin": 20023, + "390": 20024, + "macon": 20025, + "##rim": 20026, + "##fighter": 20027, + "##gonal": 20028, + "janice": 20029, + "##orescence": 20030, + "##wari": 20031, + "marius": 20032, + "belongings": 20033, + "leicestershire": 20034, + "196": 20035, + "blanco": 20036, + "inverted": 20037, + "preseason": 20038, + "sanity": 20039, + "sobbing": 20040, + "##due": 20041, + "##elt": 20042, + "##dled": 20043, + "collingwood": 20044, + "regeneration": 20045, + "flickering": 20046, + "shortest": 20047, + "##mount": 20048, + "##osi": 20049, + "feminism": 20050, + "##lat": 20051, + "sherlock": 20052, + "cabinets": 20053, + "fumbled": 20054, + "northbound": 20055, + "precedent": 20056, + "snaps": 20057, + "##mme": 20058, + "researching": 20059, + "##akes": 20060, + "guillaume": 20061, + "insights": 20062, + "manipulated": 20063, + "vapor": 20064, + "neighbour": 20065, + "sap": 20066, + "gangster": 20067, + "frey": 20068, + "f1": 20069, + "stalking": 20070, + "scarcely": 20071, + "callie": 20072, + "barnett": 20073, + "tendencies": 20074, + "audi": 20075, + "doomed": 20076, + "assessing": 20077, + "slung": 20078, + "panchayat": 20079, + "ambiguous": 20080, + "bartlett": 20081, + "##etto": 20082, + "distributing": 20083, + "violating": 20084, + "wolverhampton": 20085, + "##hetic": 20086, + "swami": 20087, + "histoire": 20088, + "##urus": 20089, + "liable": 20090, + "pounder": 20091, + "groin": 20092, + "hussain": 20093, + "larsen": 20094, + "popping": 20095, + "surprises": 20096, + "##atter": 20097, + "vie": 20098, + "curt": 20099, + "##station": 20100, + "mute": 20101, + "relocate": 20102, + "musicals": 20103, + "authorization": 20104, + "richter": 20105, + "##sef": 20106, + "immortality": 20107, + "tna": 20108, + "bombings": 20109, + "##press": 20110, + "deteriorated": 20111, + "yiddish": 20112, + "##acious": 20113, + "robbed": 20114, + "colchester": 20115, + "cs": 20116, + "pmid": 20117, + "ao": 20118, + "verified": 20119, + "balancing": 20120, + "apostle": 20121, + "swayed": 20122, + "recognizable": 20123, + "oxfordshire": 20124, + "retention": 20125, + "nottinghamshire": 20126, + "contender": 20127, + "judd": 20128, + "invitational": 20129, + "shrimp": 20130, + "uhf": 20131, + "##icient": 20132, + "cleaner": 20133, + "longitudinal": 20134, + "tanker": 20135, + "##mur": 20136, + "acronym": 20137, + "broker": 20138, + "koppen": 20139, + "sundance": 20140, + "suppliers": 20141, + "##gil": 20142, + "4000": 20143, + "clipped": 20144, + "fuels": 20145, + "petite": 20146, + "##anne": 20147, + "landslide": 20148, + "helene": 20149, + "diversion": 20150, + "populous": 20151, + "landowners": 20152, + "auspices": 20153, + "melville": 20154, + "quantitative": 20155, + "##xes": 20156, + "ferries": 20157, + "nicky": 20158, + "##llus": 20159, + "doo": 20160, + "haunting": 20161, + "roche": 20162, + "carver": 20163, + "downed": 20164, + "unavailable": 20165, + "##pathy": 20166, + "approximation": 20167, + "hiroshima": 20168, + "##hue": 20169, + "garfield": 20170, + "valle": 20171, + "comparatively": 20172, + "keyboardist": 20173, + "traveler": 20174, + "##eit": 20175, + "congestion": 20176, + "calculating": 20177, + "subsidiaries": 20178, + "##bate": 20179, + "serb": 20180, + "modernization": 20181, + "fairies": 20182, + "deepened": 20183, + "ville": 20184, + "averages": 20185, + "##lore": 20186, + "inflammatory": 20187, + "tonga": 20188, + "##itch": 20189, + "co₂": 20190, + "squads": 20191, + "##hea": 20192, + "gigantic": 20193, + "serum": 20194, + "enjoyment": 20195, + "retailer": 20196, + "verona": 20197, + "35th": 20198, + "cis": 20199, + "##phobic": 20200, + "magna": 20201, + "technicians": 20202, + "##vati": 20203, + "arithmetic": 20204, + "##sport": 20205, + "levin": 20206, + "##dation": 20207, + "amtrak": 20208, + "chow": 20209, + "sienna": 20210, + "##eyer": 20211, + "backstage": 20212, + "entrepreneurship": 20213, + "##otic": 20214, + "learnt": 20215, + "tao": 20216, + "##udy": 20217, + "worcestershire": 20218, + "formulation": 20219, + "baggage": 20220, + "hesitant": 20221, + "bali": 20222, + "sabotage": 20223, + "##kari": 20224, + "barren": 20225, + "enhancing": 20226, + "murmur": 20227, + "pl": 20228, + "freshly": 20229, + "putnam": 20230, + "syntax": 20231, + "aces": 20232, + "medicines": 20233, + "resentment": 20234, + "bandwidth": 20235, + "##sier": 20236, + "grins": 20237, + "chili": 20238, + "guido": 20239, + "##sei": 20240, + "framing": 20241, + "implying": 20242, + "gareth": 20243, + "lissa": 20244, + "genevieve": 20245, + "pertaining": 20246, + "admissions": 20247, + "geo": 20248, + "thorpe": 20249, + "proliferation": 20250, + "sato": 20251, + "bela": 20252, + "analyzing": 20253, + "parting": 20254, + "##gor": 20255, + "awakened": 20256, + "##isman": 20257, + "huddled": 20258, + "secrecy": 20259, + "##kling": 20260, + "hush": 20261, + "gentry": 20262, + "540": 20263, + "dungeons": 20264, + "##ego": 20265, + "coasts": 20266, + "##utz": 20267, + "sacrificed": 20268, + "##chule": 20269, + "landowner": 20270, + "mutually": 20271, + "prevalence": 20272, + "programmer": 20273, + "adolescent": 20274, + "disrupted": 20275, + "seaside": 20276, + "gee": 20277, + "trusts": 20278, + "vamp": 20279, + "georgie": 20280, + "##nesian": 20281, + "##iol": 20282, + "schedules": 20283, + "sindh": 20284, + "##market": 20285, + "etched": 20286, + "hm": 20287, + "sparse": 20288, + "bey": 20289, + "beaux": 20290, + "scratching": 20291, + "gliding": 20292, + "unidentified": 20293, + "216": 20294, + "collaborating": 20295, + "gems": 20296, + "jesuits": 20297, + "oro": 20298, + "accumulation": 20299, + "shaping": 20300, + "mbe": 20301, + "anal": 20302, + "##xin": 20303, + "231": 20304, + "enthusiasts": 20305, + "newscast": 20306, + "##egan": 20307, + "janata": 20308, + "dewey": 20309, + "parkinson": 20310, + "179": 20311, + "ankara": 20312, + "biennial": 20313, + "towering": 20314, + "dd": 20315, + "inconsistent": 20316, + "950": 20317, + "##chet": 20318, + "thriving": 20319, + "terminate": 20320, + "cabins": 20321, + "furiously": 20322, + "eats": 20323, + "advocating": 20324, + "donkey": 20325, + "marley": 20326, + "muster": 20327, + "phyllis": 20328, + "leiden": 20329, + "##user": 20330, + "grassland": 20331, + "glittering": 20332, + "iucn": 20333, + "loneliness": 20334, + "217": 20335, + "memorandum": 20336, + "armenians": 20337, + "##ddle": 20338, + "popularized": 20339, + "rhodesia": 20340, + "60s": 20341, + "lame": 20342, + "##illon": 20343, + "sans": 20344, + "bikini": 20345, + "header": 20346, + "orbits": 20347, + "##xx": 20348, + "##finger": 20349, + "##ulator": 20350, + "sharif": 20351, + "spines": 20352, + "biotechnology": 20353, + "strolled": 20354, + "naughty": 20355, + "yates": 20356, + "##wire": 20357, + "fremantle": 20358, + "milo": 20359, + "##mour": 20360, + "abducted": 20361, + "removes": 20362, + "##atin": 20363, + "humming": 20364, + "wonderland": 20365, + "##chrome": 20366, + "##ester": 20367, + "hume": 20368, + "pivotal": 20369, + "##rates": 20370, + "armand": 20371, + "grams": 20372, + "believers": 20373, + "elector": 20374, + "rte": 20375, + "apron": 20376, + "bis": 20377, + "scraped": 20378, + "##yria": 20379, + "endorsement": 20380, + "initials": 20381, + "##llation": 20382, + "eps": 20383, + "dotted": 20384, + "hints": 20385, + "buzzing": 20386, + "emigration": 20387, + "nearer": 20388, + "##tom": 20389, + "indicators": 20390, + "##ulu": 20391, + "coarse": 20392, + "neutron": 20393, + "protectorate": 20394, + "##uze": 20395, + "directional": 20396, + "exploits": 20397, + "pains": 20398, + "loire": 20399, + "1830s": 20400, + "proponents": 20401, + "guggenheim": 20402, + "rabbits": 20403, + "ritchie": 20404, + "305": 20405, + "hectare": 20406, + "inputs": 20407, + "hutton": 20408, + "##raz": 20409, + "verify": 20410, + "##ako": 20411, + "boilers": 20412, + "longitude": 20413, + "##lev": 20414, + "skeletal": 20415, + "yer": 20416, + "emilia": 20417, + "citrus": 20418, + "compromised": 20419, + "##gau": 20420, + "pokemon": 20421, + "prescription": 20422, + "paragraph": 20423, + "eduard": 20424, + "cadillac": 20425, + "attire": 20426, + "categorized": 20427, + "kenyan": 20428, + "weddings": 20429, + "charley": 20430, + "##bourg": 20431, + "entertain": 20432, + "monmouth": 20433, + "##lles": 20434, + "nutrients": 20435, + "davey": 20436, + "mesh": 20437, + "incentive": 20438, + "practised": 20439, + "ecosystems": 20440, + "kemp": 20441, + "subdued": 20442, + "overheard": 20443, + "##rya": 20444, + "bodily": 20445, + "maxim": 20446, + "##nius": 20447, + "apprenticeship": 20448, + "ursula": 20449, + "##fight": 20450, + "lodged": 20451, + "rug": 20452, + "silesian": 20453, + "unconstitutional": 20454, + "patel": 20455, + "inspected": 20456, + "coyote": 20457, + "unbeaten": 20458, + "##hak": 20459, + "34th": 20460, + "disruption": 20461, + "convict": 20462, + "parcel": 20463, + "##cl": 20464, + "##nham": 20465, + "collier": 20466, + "implicated": 20467, + "mallory": 20468, + "##iac": 20469, + "##lab": 20470, + "susannah": 20471, + "winkler": 20472, + "##rber": 20473, + "shia": 20474, + "phelps": 20475, + "sediments": 20476, + "graphical": 20477, + "robotic": 20478, + "##sner": 20479, + "adulthood": 20480, + "mart": 20481, + "smoked": 20482, + "##isto": 20483, + "kathryn": 20484, + "clarified": 20485, + "##aran": 20486, + "divides": 20487, + "convictions": 20488, + "oppression": 20489, + "pausing": 20490, + "burying": 20491, + "##mt": 20492, + "federico": 20493, + "mathias": 20494, + "eileen": 20495, + "##tana": 20496, + "kite": 20497, + "hunched": 20498, + "##acies": 20499, + "189": 20500, + "##atz": 20501, + "disadvantage": 20502, + "liza": 20503, + "kinetic": 20504, + "greedy": 20505, + "paradox": 20506, + "yokohama": 20507, + "dowager": 20508, + "trunks": 20509, + "ventured": 20510, + "##gement": 20511, + "gupta": 20512, + "vilnius": 20513, + "olaf": 20514, + "##thest": 20515, + "crimean": 20516, + "hopper": 20517, + "##ej": 20518, + "progressively": 20519, + "arturo": 20520, + "mouthed": 20521, + "arrondissement": 20522, + "##fusion": 20523, + "rubin": 20524, + "simulcast": 20525, + "oceania": 20526, + "##orum": 20527, + "##stra": 20528, + "##rred": 20529, + "busiest": 20530, + "intensely": 20531, + "navigator": 20532, + "cary": 20533, + "##vine": 20534, + "##hini": 20535, + "##bies": 20536, + "fife": 20537, + "rowe": 20538, + "rowland": 20539, + "posing": 20540, + "insurgents": 20541, + "shafts": 20542, + "lawsuits": 20543, + "activate": 20544, + "conor": 20545, + "inward": 20546, + "culturally": 20547, + "garlic": 20548, + "265": 20549, + "##eering": 20550, + "eclectic": 20551, + "##hui": 20552, + "##kee": 20553, + "##nl": 20554, + "furrowed": 20555, + "vargas": 20556, + "meteorological": 20557, + "rendezvous": 20558, + "##aus": 20559, + "culinary": 20560, + "commencement": 20561, + "##dition": 20562, + "quota": 20563, + "##notes": 20564, + "mommy": 20565, + "salaries": 20566, + "overlapping": 20567, + "mule": 20568, + "##iology": 20569, + "##mology": 20570, + "sums": 20571, + "wentworth": 20572, + "##isk": 20573, + "##zione": 20574, + "mainline": 20575, + "subgroup": 20576, + "##illy": 20577, + "hack": 20578, + "plaintiff": 20579, + "verdi": 20580, + "bulb": 20581, + "differentiation": 20582, + "engagements": 20583, + "multinational": 20584, + "supplemented": 20585, + "bertrand": 20586, + "caller": 20587, + "regis": 20588, + "##naire": 20589, + "##sler": 20590, + "##arts": 20591, + "##imated": 20592, + "blossom": 20593, + "propagation": 20594, + "kilometer": 20595, + "viaduct": 20596, + "vineyards": 20597, + "##uate": 20598, + "beckett": 20599, + "optimization": 20600, + "golfer": 20601, + "songwriters": 20602, + "seminal": 20603, + "semitic": 20604, + "thud": 20605, + "volatile": 20606, + "evolving": 20607, + "ridley": 20608, + "##wley": 20609, + "trivial": 20610, + "distributions": 20611, + "scandinavia": 20612, + "jiang": 20613, + "##ject": 20614, + "wrestled": 20615, + "insistence": 20616, + "##dio": 20617, + "emphasizes": 20618, + "napkin": 20619, + "##ods": 20620, + "adjunct": 20621, + "rhyme": 20622, + "##ricted": 20623, + "##eti": 20624, + "hopeless": 20625, + "surrounds": 20626, + "tremble": 20627, + "32nd": 20628, + "smoky": 20629, + "##ntly": 20630, + "oils": 20631, + "medicinal": 20632, + "padded": 20633, + "steer": 20634, + "wilkes": 20635, + "219": 20636, + "255": 20637, + "concessions": 20638, + "hue": 20639, + "uniquely": 20640, + "blinded": 20641, + "landon": 20642, + "yahoo": 20643, + "##lane": 20644, + "hendrix": 20645, + "commemorating": 20646, + "dex": 20647, + "specify": 20648, + "chicks": 20649, + "##ggio": 20650, + "intercity": 20651, + "1400": 20652, + "morley": 20653, + "##torm": 20654, + "highlighting": 20655, + "##oting": 20656, + "pang": 20657, + "oblique": 20658, + "stalled": 20659, + "##liner": 20660, + "flirting": 20661, + "newborn": 20662, + "1769": 20663, + "bishopric": 20664, + "shaved": 20665, + "232": 20666, + "currie": 20667, + "##ush": 20668, + "dharma": 20669, + "spartan": 20670, + "##ooped": 20671, + "favorites": 20672, + "smug": 20673, + "novella": 20674, + "sirens": 20675, + "abusive": 20676, + "creations": 20677, + "espana": 20678, + "##lage": 20679, + "paradigm": 20680, + "semiconductor": 20681, + "sheen": 20682, + "##rdo": 20683, + "##yen": 20684, + "##zak": 20685, + "nrl": 20686, + "renew": 20687, + "##pose": 20688, + "##tur": 20689, + "adjutant": 20690, + "marches": 20691, + "norma": 20692, + "##enity": 20693, + "ineffective": 20694, + "weimar": 20695, + "grunt": 20696, + "##gat": 20697, + "lordship": 20698, + "plotting": 20699, + "expenditure": 20700, + "infringement": 20701, + "lbs": 20702, + "refrain": 20703, + "av": 20704, + "mimi": 20705, + "mistakenly": 20706, + "postmaster": 20707, + "1771": 20708, + "##bara": 20709, + "ras": 20710, + "motorsports": 20711, + "tito": 20712, + "199": 20713, + "subjective": 20714, + "##zza": 20715, + "bully": 20716, + "stew": 20717, + "##kaya": 20718, + "prescott": 20719, + "1a": 20720, + "##raphic": 20721, + "##zam": 20722, + "bids": 20723, + "styling": 20724, + "paranormal": 20725, + "reeve": 20726, + "sneaking": 20727, + "exploding": 20728, + "katz": 20729, + "akbar": 20730, + "migrant": 20731, + "syllables": 20732, + "indefinitely": 20733, + "##ogical": 20734, + "destroys": 20735, + "replaces": 20736, + "applause": 20737, + "##phine": 20738, + "pest": 20739, + "##fide": 20740, + "218": 20741, + "articulated": 20742, + "bertie": 20743, + "##thing": 20744, + "##cars": 20745, + "##ptic": 20746, + "courtroom": 20747, + "crowley": 20748, + "aesthetics": 20749, + "cummings": 20750, + "tehsil": 20751, + "hormones": 20752, + "titanic": 20753, + "dangerously": 20754, + "##ibe": 20755, + "stadion": 20756, + "jaenelle": 20757, + "auguste": 20758, + "ciudad": 20759, + "##chu": 20760, + "mysore": 20761, + "partisans": 20762, + "##sio": 20763, + "lucan": 20764, + "philipp": 20765, + "##aly": 20766, + "debating": 20767, + "henley": 20768, + "interiors": 20769, + "##rano": 20770, + "##tious": 20771, + "homecoming": 20772, + "beyonce": 20773, + "usher": 20774, + "henrietta": 20775, + "prepares": 20776, + "weeds": 20777, + "##oman": 20778, + "ely": 20779, + "plucked": 20780, + "##pire": 20781, + "##dable": 20782, + "luxurious": 20783, + "##aq": 20784, + "artifact": 20785, + "password": 20786, + "pasture": 20787, + "juno": 20788, + "maddy": 20789, + "minsk": 20790, + "##dder": 20791, + "##ologies": 20792, + "##rone": 20793, + "assessments": 20794, + "martian": 20795, + "royalist": 20796, + "1765": 20797, + "examines": 20798, + "##mani": 20799, + "##rge": 20800, + "nino": 20801, + "223": 20802, + "parry": 20803, + "scooped": 20804, + "relativity": 20805, + "##eli": 20806, + "##uting": 20807, + "##cao": 20808, + "congregational": 20809, + "noisy": 20810, + "traverse": 20811, + "##agawa": 20812, + "strikeouts": 20813, + "nickelodeon": 20814, + "obituary": 20815, + "transylvania": 20816, + "binds": 20817, + "depictions": 20818, + "polk": 20819, + "trolley": 20820, + "##yed": 20821, + "##lard": 20822, + "breeders": 20823, + "##under": 20824, + "dryly": 20825, + "hokkaido": 20826, + "1762": 20827, + "strengths": 20828, + "stacks": 20829, + "bonaparte": 20830, + "connectivity": 20831, + "neared": 20832, + "prostitutes": 20833, + "stamped": 20834, + "anaheim": 20835, + "gutierrez": 20836, + "sinai": 20837, + "##zzling": 20838, + "bram": 20839, + "fresno": 20840, + "madhya": 20841, + "##86": 20842, + "proton": 20843, + "##lena": 20844, + "##llum": 20845, + "##phon": 20846, + "reelected": 20847, + "wanda": 20848, + "##anus": 20849, + "##lb": 20850, + "ample": 20851, + "distinguishing": 20852, + "##yler": 20853, + "grasping": 20854, + "sermons": 20855, + "tomato": 20856, + "bland": 20857, + "stimulation": 20858, + "avenues": 20859, + "##eux": 20860, + "spreads": 20861, + "scarlett": 20862, + "fern": 20863, + "pentagon": 20864, + "assert": 20865, + "baird": 20866, + "chesapeake": 20867, + "ir": 20868, + "calmed": 20869, + "distortion": 20870, + "fatalities": 20871, + "##olis": 20872, + "correctional": 20873, + "pricing": 20874, + "##astic": 20875, + "##gina": 20876, + "prom": 20877, + "dammit": 20878, + "ying": 20879, + "collaborate": 20880, + "##chia": 20881, + "welterweight": 20882, + "33rd": 20883, + "pointer": 20884, + "substitution": 20885, + "bonded": 20886, + "umpire": 20887, + "communicating": 20888, + "multitude": 20889, + "paddle": 20890, + "##obe": 20891, + "federally": 20892, + "intimacy": 20893, + "##insky": 20894, + "betray": 20895, + "ssr": 20896, + "##lett": 20897, + "##lean": 20898, + "##lves": 20899, + "##therapy": 20900, + "airbus": 20901, + "##tery": 20902, + "functioned": 20903, + "ud": 20904, + "bearer": 20905, + "biomedical": 20906, + "netflix": 20907, + "##hire": 20908, + "##nca": 20909, + "condom": 20910, + "brink": 20911, + "ik": 20912, + "##nical": 20913, + "macy": 20914, + "##bet": 20915, + "flap": 20916, + "gma": 20917, + "experimented": 20918, + "jelly": 20919, + "lavender": 20920, + "##icles": 20921, + "##ulia": 20922, + "munro": 20923, + "##mian": 20924, + "##tial": 20925, + "rye": 20926, + "##rle": 20927, + "60th": 20928, + "gigs": 20929, + "hottest": 20930, + "rotated": 20931, + "predictions": 20932, + "fuji": 20933, + "bu": 20934, + "##erence": 20935, + "##omi": 20936, + "barangay": 20937, + "##fulness": 20938, + "##sas": 20939, + "clocks": 20940, + "##rwood": 20941, + "##liness": 20942, + "cereal": 20943, + "roe": 20944, + "wight": 20945, + "decker": 20946, + "uttered": 20947, + "babu": 20948, + "onion": 20949, + "xml": 20950, + "forcibly": 20951, + "##df": 20952, + "petra": 20953, + "sarcasm": 20954, + "hartley": 20955, + "peeled": 20956, + "storytelling": 20957, + "##42": 20958, + "##xley": 20959, + "##ysis": 20960, + "##ffa": 20961, + "fibre": 20962, + "kiel": 20963, + "auditor": 20964, + "fig": 20965, + "harald": 20966, + "greenville": 20967, + "##berries": 20968, + "geographically": 20969, + "nell": 20970, + "quartz": 20971, + "##athic": 20972, + "cemeteries": 20973, + "##lr": 20974, + "crossings": 20975, + "nah": 20976, + "holloway": 20977, + "reptiles": 20978, + "chun": 20979, + "sichuan": 20980, + "snowy": 20981, + "660": 20982, + "corrections": 20983, + "##ivo": 20984, + "zheng": 20985, + "ambassadors": 20986, + "blacksmith": 20987, + "fielded": 20988, + "fluids": 20989, + "hardcover": 20990, + "turnover": 20991, + "medications": 20992, + "melvin": 20993, + "academies": 20994, + "##erton": 20995, + "ro": 20996, + "roach": 20997, + "absorbing": 20998, + "spaniards": 20999, + "colton": 21000, + "##founded": 21001, + "outsider": 21002, + "espionage": 21003, + "kelsey": 21004, + "245": 21005, + "edible": 21006, + "##ulf": 21007, + "dora": 21008, + "establishes": 21009, + "##sham": 21010, + "##tries": 21011, + "contracting": 21012, + "##tania": 21013, + "cinematic": 21014, + "costello": 21015, + "nesting": 21016, + "##uron": 21017, + "connolly": 21018, + "duff": 21019, + "##nology": 21020, + "mma": 21021, + "##mata": 21022, + "fergus": 21023, + "sexes": 21024, + "gi": 21025, + "optics": 21026, + "spectator": 21027, + "woodstock": 21028, + "banning": 21029, + "##hee": 21030, + "##fle": 21031, + "differentiate": 21032, + "outfielder": 21033, + "refinery": 21034, + "226": 21035, + "312": 21036, + "gerhard": 21037, + "horde": 21038, + "lair": 21039, + "drastically": 21040, + "##udi": 21041, + "landfall": 21042, + "##cheng": 21043, + "motorsport": 21044, + "odi": 21045, + "##achi": 21046, + "predominant": 21047, + "quay": 21048, + "skins": 21049, + "##ental": 21050, + "edna": 21051, + "harshly": 21052, + "complementary": 21053, + "murdering": 21054, + "##aves": 21055, + "wreckage": 21056, + "##90": 21057, + "ono": 21058, + "outstretched": 21059, + "lennox": 21060, + "munitions": 21061, + "galen": 21062, + "reconcile": 21063, + "470": 21064, + "scalp": 21065, + "bicycles": 21066, + "gillespie": 21067, + "questionable": 21068, + "rosenberg": 21069, + "guillermo": 21070, + "hostel": 21071, + "jarvis": 21072, + "kabul": 21073, + "volvo": 21074, + "opium": 21075, + "yd": 21076, + "##twined": 21077, + "abuses": 21078, + "decca": 21079, + "outpost": 21080, + "##cino": 21081, + "sensible": 21082, + "neutrality": 21083, + "##64": 21084, + "ponce": 21085, + "anchorage": 21086, + "atkins": 21087, + "turrets": 21088, + "inadvertently": 21089, + "disagree": 21090, + "libre": 21091, + "vodka": 21092, + "reassuring": 21093, + "weighs": 21094, + "##yal": 21095, + "glide": 21096, + "jumper": 21097, + "ceilings": 21098, + "repertory": 21099, + "outs": 21100, + "stain": 21101, + "##bial": 21102, + "envy": 21103, + "##ucible": 21104, + "smashing": 21105, + "heightened": 21106, + "policing": 21107, + "hyun": 21108, + "mixes": 21109, + "lai": 21110, + "prima": 21111, + "##ples": 21112, + "celeste": 21113, + "##bina": 21114, + "lucrative": 21115, + "intervened": 21116, + "kc": 21117, + "manually": 21118, + "##rned": 21119, + "stature": 21120, + "staffed": 21121, + "bun": 21122, + "bastards": 21123, + "nairobi": 21124, + "priced": 21125, + "##auer": 21126, + "thatcher": 21127, + "##kia": 21128, + "tripped": 21129, + "comune": 21130, + "##ogan": 21131, + "##pled": 21132, + "brasil": 21133, + "incentives": 21134, + "emanuel": 21135, + "hereford": 21136, + "musica": 21137, + "##kim": 21138, + "benedictine": 21139, + "biennale": 21140, + "##lani": 21141, + "eureka": 21142, + "gardiner": 21143, + "rb": 21144, + "knocks": 21145, + "sha": 21146, + "##ael": 21147, + "##elled": 21148, + "##onate": 21149, + "efficacy": 21150, + "ventura": 21151, + "masonic": 21152, + "sanford": 21153, + "maize": 21154, + "leverage": 21155, + "##feit": 21156, + "capacities": 21157, + "santana": 21158, + "##aur": 21159, + "novelty": 21160, + "vanilla": 21161, + "##cter": 21162, + "##tour": 21163, + "benin": 21164, + "##oir": 21165, + "##rain": 21166, + "neptune": 21167, + "drafting": 21168, + "tallinn": 21169, + "##cable": 21170, + "humiliation": 21171, + "##boarding": 21172, + "schleswig": 21173, + "fabian": 21174, + "bernardo": 21175, + "liturgy": 21176, + "spectacle": 21177, + "sweeney": 21178, + "pont": 21179, + "routledge": 21180, + "##tment": 21181, + "cosmos": 21182, + "ut": 21183, + "hilt": 21184, + "sleek": 21185, + "universally": 21186, + "##eville": 21187, + "##gawa": 21188, + "typed": 21189, + "##dry": 21190, + "favors": 21191, + "allegheny": 21192, + "glaciers": 21193, + "##rly": 21194, + "recalling": 21195, + "aziz": 21196, + "##log": 21197, + "parasite": 21198, + "requiem": 21199, + "auf": 21200, + "##berto": 21201, + "##llin": 21202, + "illumination": 21203, + "##breaker": 21204, + "##issa": 21205, + "festivities": 21206, + "bows": 21207, + "govern": 21208, + "vibe": 21209, + "vp": 21210, + "333": 21211, + "sprawled": 21212, + "larson": 21213, + "pilgrim": 21214, + "bwf": 21215, + "leaping": 21216, + "##rts": 21217, + "##ssel": 21218, + "alexei": 21219, + "greyhound": 21220, + "hoarse": 21221, + "##dler": 21222, + "##oration": 21223, + "seneca": 21224, + "##cule": 21225, + "gaping": 21226, + "##ulously": 21227, + "##pura": 21228, + "cinnamon": 21229, + "##gens": 21230, + "##rricular": 21231, + "craven": 21232, + "fantasies": 21233, + "houghton": 21234, + "engined": 21235, + "reigned": 21236, + "dictator": 21237, + "supervising": 21238, + "##oris": 21239, + "bogota": 21240, + "commentaries": 21241, + "unnatural": 21242, + "fingernails": 21243, + "spirituality": 21244, + "tighten": 21245, + "##tm": 21246, + "canadiens": 21247, + "protesting": 21248, + "intentional": 21249, + "cheers": 21250, + "sparta": 21251, + "##ytic": 21252, + "##iere": 21253, + "##zine": 21254, + "widen": 21255, + "belgarath": 21256, + "controllers": 21257, + "dodd": 21258, + "iaaf": 21259, + "navarre": 21260, + "##ication": 21261, + "defect": 21262, + "squire": 21263, + "steiner": 21264, + "whisky": 21265, + "##mins": 21266, + "560": 21267, + "inevitably": 21268, + "tome": 21269, + "##gold": 21270, + "chew": 21271, + "##uid": 21272, + "##lid": 21273, + "elastic": 21274, + "##aby": 21275, + "streaked": 21276, + "alliances": 21277, + "jailed": 21278, + "regal": 21279, + "##ined": 21280, + "##phy": 21281, + "czechoslovak": 21282, + "narration": 21283, + "absently": 21284, + "##uld": 21285, + "bluegrass": 21286, + "guangdong": 21287, + "quran": 21288, + "criticizing": 21289, + "hose": 21290, + "hari": 21291, + "##liest": 21292, + "##owa": 21293, + "skier": 21294, + "streaks": 21295, + "deploy": 21296, + "##lom": 21297, + "raft": 21298, + "bose": 21299, + "dialed": 21300, + "huff": 21301, + "##eira": 21302, + "haifa": 21303, + "simplest": 21304, + "bursting": 21305, + "endings": 21306, + "ib": 21307, + "sultanate": 21308, + "##titled": 21309, + "franks": 21310, + "whitman": 21311, + "ensures": 21312, + "sven": 21313, + "##ggs": 21314, + "collaborators": 21315, + "forster": 21316, + "organising": 21317, + "ui": 21318, + "banished": 21319, + "napier": 21320, + "injustice": 21321, + "teller": 21322, + "layered": 21323, + "thump": 21324, + "##otti": 21325, + "roc": 21326, + "battleships": 21327, + "evidenced": 21328, + "fugitive": 21329, + "sadie": 21330, + "robotics": 21331, + "##roud": 21332, + "equatorial": 21333, + "geologist": 21334, + "##iza": 21335, + "yielding": 21336, + "##bron": 21337, + "##sr": 21338, + "internationale": 21339, + "mecca": 21340, + "##diment": 21341, + "sbs": 21342, + "skyline": 21343, + "toad": 21344, + "uploaded": 21345, + "reflective": 21346, + "undrafted": 21347, + "lal": 21348, + "leafs": 21349, + "bayern": 21350, + "##dai": 21351, + "lakshmi": 21352, + "shortlisted": 21353, + "##stick": 21354, + "##wicz": 21355, + "camouflage": 21356, + "donate": 21357, + "af": 21358, + "christi": 21359, + "lau": 21360, + "##acio": 21361, + "disclosed": 21362, + "nemesis": 21363, + "1761": 21364, + "assemble": 21365, + "straining": 21366, + "northamptonshire": 21367, + "tal": 21368, + "##asi": 21369, + "bernardino": 21370, + "premature": 21371, + "heidi": 21372, + "42nd": 21373, + "coefficients": 21374, + "galactic": 21375, + "reproduce": 21376, + "buzzed": 21377, + "sensations": 21378, + "zionist": 21379, + "monsieur": 21380, + "myrtle": 21381, + "##eme": 21382, + "archery": 21383, + "strangled": 21384, + "musically": 21385, + "viewpoint": 21386, + "antiquities": 21387, + "bei": 21388, + "trailers": 21389, + "seahawks": 21390, + "cured": 21391, + "pee": 21392, + "preferring": 21393, + "tasmanian": 21394, + "lange": 21395, + "sul": 21396, + "##mail": 21397, + "##working": 21398, + "colder": 21399, + "overland": 21400, + "lucivar": 21401, + "massey": 21402, + "gatherings": 21403, + "haitian": 21404, + "##smith": 21405, + "disapproval": 21406, + "flaws": 21407, + "##cco": 21408, + "##enbach": 21409, + "1766": 21410, + "npr": 21411, + "##icular": 21412, + "boroughs": 21413, + "creole": 21414, + "forums": 21415, + "techno": 21416, + "1755": 21417, + "dent": 21418, + "abdominal": 21419, + "streetcar": 21420, + "##eson": 21421, + "##stream": 21422, + "procurement": 21423, + "gemini": 21424, + "predictable": 21425, + "##tya": 21426, + "acheron": 21427, + "christoph": 21428, + "feeder": 21429, + "fronts": 21430, + "vendor": 21431, + "bernhard": 21432, + "jammu": 21433, + "tumors": 21434, + "slang": 21435, + "##uber": 21436, + "goaltender": 21437, + "twists": 21438, + "curving": 21439, + "manson": 21440, + "vuelta": 21441, + "mer": 21442, + "peanut": 21443, + "confessions": 21444, + "pouch": 21445, + "unpredictable": 21446, + "allowance": 21447, + "theodor": 21448, + "vascular": 21449, + "##factory": 21450, + "bala": 21451, + "authenticity": 21452, + "metabolic": 21453, + "coughing": 21454, + "nanjing": 21455, + "##cea": 21456, + "pembroke": 21457, + "##bard": 21458, + "splendid": 21459, + "36th": 21460, + "ff": 21461, + "hourly": 21462, + "##ahu": 21463, + "elmer": 21464, + "handel": 21465, + "##ivate": 21466, + "awarding": 21467, + "thrusting": 21468, + "dl": 21469, + "experimentation": 21470, + "##hesion": 21471, + "##46": 21472, + "caressed": 21473, + "entertained": 21474, + "steak": 21475, + "##rangle": 21476, + "biologist": 21477, + "orphans": 21478, + "baroness": 21479, + "oyster": 21480, + "stepfather": 21481, + "##dridge": 21482, + "mirage": 21483, + "reefs": 21484, + "speeding": 21485, + "##31": 21486, + "barons": 21487, + "1764": 21488, + "227": 21489, + "inhabit": 21490, + "preached": 21491, + "repealed": 21492, + "##tral": 21493, + "honoring": 21494, + "boogie": 21495, + "captives": 21496, + "administer": 21497, + "johanna": 21498, + "##imate": 21499, + "gel": 21500, + "suspiciously": 21501, + "1767": 21502, + "sobs": 21503, + "##dington": 21504, + "backbone": 21505, + "hayward": 21506, + "garry": 21507, + "##folding": 21508, + "##nesia": 21509, + "maxi": 21510, + "##oof": 21511, + "##ppe": 21512, + "ellison": 21513, + "galileo": 21514, + "##stand": 21515, + "crimea": 21516, + "frenzy": 21517, + "amour": 21518, + "bumper": 21519, + "matrices": 21520, + "natalia": 21521, + "baking": 21522, + "garth": 21523, + "palestinians": 21524, + "##grove": 21525, + "smack": 21526, + "conveyed": 21527, + "ensembles": 21528, + "gardening": 21529, + "##manship": 21530, + "##rup": 21531, + "##stituting": 21532, + "1640": 21533, + "harvesting": 21534, + "topography": 21535, + "jing": 21536, + "shifters": 21537, + "dormitory": 21538, + "##carriage": 21539, + "##lston": 21540, + "ist": 21541, + "skulls": 21542, + "##stadt": 21543, + "dolores": 21544, + "jewellery": 21545, + "sarawak": 21546, + "##wai": 21547, + "##zier": 21548, + "fences": 21549, + "christy": 21550, + "confinement": 21551, + "tumbling": 21552, + "credibility": 21553, + "fir": 21554, + "stench": 21555, + "##bria": 21556, + "##plication": 21557, + "##nged": 21558, + "##sam": 21559, + "virtues": 21560, + "##belt": 21561, + "marjorie": 21562, + "pba": 21563, + "##eem": 21564, + "##made": 21565, + "celebrates": 21566, + "schooner": 21567, + "agitated": 21568, + "barley": 21569, + "fulfilling": 21570, + "anthropologist": 21571, + "##pro": 21572, + "restrict": 21573, + "novi": 21574, + "regulating": 21575, + "##nent": 21576, + "padres": 21577, + "##rani": 21578, + "##hesive": 21579, + "loyola": 21580, + "tabitha": 21581, + "milky": 21582, + "olson": 21583, + "proprietor": 21584, + "crambidae": 21585, + "guarantees": 21586, + "intercollegiate": 21587, + "ljubljana": 21588, + "hilda": 21589, + "##sko": 21590, + "ignorant": 21591, + "hooded": 21592, + "##lts": 21593, + "sardinia": 21594, + "##lidae": 21595, + "##vation": 21596, + "frontman": 21597, + "privileged": 21598, + "witchcraft": 21599, + "##gp": 21600, + "jammed": 21601, + "laude": 21602, + "poking": 21603, + "##than": 21604, + "bracket": 21605, + "amazement": 21606, + "yunnan": 21607, + "##erus": 21608, + "maharaja": 21609, + "linnaeus": 21610, + "264": 21611, + "commissioning": 21612, + "milano": 21613, + "peacefully": 21614, + "##logies": 21615, + "akira": 21616, + "rani": 21617, + "regulator": 21618, + "##36": 21619, + "grasses": 21620, + "##rance": 21621, + "luzon": 21622, + "crows": 21623, + "compiler": 21624, + "gretchen": 21625, + "seaman": 21626, + "edouard": 21627, + "tab": 21628, + "buccaneers": 21629, + "ellington": 21630, + "hamlets": 21631, + "whig": 21632, + "socialists": 21633, + "##anto": 21634, + "directorial": 21635, + "easton": 21636, + "mythological": 21637, + "##kr": 21638, + "##vary": 21639, + "rhineland": 21640, + "semantic": 21641, + "taut": 21642, + "dune": 21643, + "inventions": 21644, + "succeeds": 21645, + "##iter": 21646, + "replication": 21647, + "branched": 21648, + "##pired": 21649, + "jul": 21650, + "prosecuted": 21651, + "kangaroo": 21652, + "penetrated": 21653, + "##avian": 21654, + "middlesbrough": 21655, + "doses": 21656, + "bleak": 21657, + "madam": 21658, + "predatory": 21659, + "relentless": 21660, + "##vili": 21661, + "reluctance": 21662, + "##vir": 21663, + "hailey": 21664, + "crore": 21665, + "silvery": 21666, + "1759": 21667, + "monstrous": 21668, + "swimmers": 21669, + "transmissions": 21670, + "hawthorn": 21671, + "informing": 21672, + "##eral": 21673, + "toilets": 21674, + "caracas": 21675, + "crouch": 21676, + "kb": 21677, + "##sett": 21678, + "295": 21679, + "cartel": 21680, + "hadley": 21681, + "##aling": 21682, + "alexia": 21683, + "yvonne": 21684, + "##biology": 21685, + "cinderella": 21686, + "eton": 21687, + "superb": 21688, + "blizzard": 21689, + "stabbing": 21690, + "industrialist": 21691, + "maximus": 21692, + "##gm": 21693, + "##orus": 21694, + "groves": 21695, + "maud": 21696, + "clade": 21697, + "oversized": 21698, + "comedic": 21699, + "##bella": 21700, + "rosen": 21701, + "nomadic": 21702, + "fulham": 21703, + "montane": 21704, + "beverages": 21705, + "galaxies": 21706, + "redundant": 21707, + "swarm": 21708, + "##rot": 21709, + "##folia": 21710, + "##llis": 21711, + "buckinghamshire": 21712, + "fen": 21713, + "bearings": 21714, + "bahadur": 21715, + "##rom": 21716, + "gilles": 21717, + "phased": 21718, + "dynamite": 21719, + "faber": 21720, + "benoit": 21721, + "vip": 21722, + "##ount": 21723, + "##wd": 21724, + "booking": 21725, + "fractured": 21726, + "tailored": 21727, + "anya": 21728, + "spices": 21729, + "westwood": 21730, + "cairns": 21731, + "auditions": 21732, + "inflammation": 21733, + "steamed": 21734, + "##rocity": 21735, + "##acion": 21736, + "##urne": 21737, + "skyla": 21738, + "thereof": 21739, + "watford": 21740, + "torment": 21741, + "archdeacon": 21742, + "transforms": 21743, + "lulu": 21744, + "demeanor": 21745, + "fucked": 21746, + "serge": 21747, + "##sor": 21748, + "mckenna": 21749, + "minas": 21750, + "entertainer": 21751, + "##icide": 21752, + "caress": 21753, + "originate": 21754, + "residue": 21755, + "##sty": 21756, + "1740": 21757, + "##ilised": 21758, + "##org": 21759, + "beech": 21760, + "##wana": 21761, + "subsidies": 21762, + "##ghton": 21763, + "emptied": 21764, + "gladstone": 21765, + "ru": 21766, + "firefighters": 21767, + "voodoo": 21768, + "##rcle": 21769, + "het": 21770, + "nightingale": 21771, + "tamara": 21772, + "edmond": 21773, + "ingredient": 21774, + "weaknesses": 21775, + "silhouette": 21776, + "285": 21777, + "compatibility": 21778, + "withdrawing": 21779, + "hampson": 21780, + "##mona": 21781, + "anguish": 21782, + "giggling": 21783, + "##mber": 21784, + "bookstore": 21785, + "##jiang": 21786, + "southernmost": 21787, + "tilting": 21788, + "##vance": 21789, + "bai": 21790, + "economical": 21791, + "rf": 21792, + "briefcase": 21793, + "dreadful": 21794, + "hinted": 21795, + "projections": 21796, + "shattering": 21797, + "totaling": 21798, + "##rogate": 21799, + "analogue": 21800, + "indicted": 21801, + "periodical": 21802, + "fullback": 21803, + "##dman": 21804, + "haynes": 21805, + "##tenberg": 21806, + "##ffs": 21807, + "##ishment": 21808, + "1745": 21809, + "thirst": 21810, + "stumble": 21811, + "penang": 21812, + "vigorous": 21813, + "##ddling": 21814, + "##kor": 21815, + "##lium": 21816, + "octave": 21817, + "##ove": 21818, + "##enstein": 21819, + "##inen": 21820, + "##ones": 21821, + "siberian": 21822, + "##uti": 21823, + "cbn": 21824, + "repeal": 21825, + "swaying": 21826, + "##vington": 21827, + "khalid": 21828, + "tanaka": 21829, + "unicorn": 21830, + "otago": 21831, + "plastered": 21832, + "lobe": 21833, + "riddle": 21834, + "##rella": 21835, + "perch": 21836, + "##ishing": 21837, + "croydon": 21838, + "filtered": 21839, + "graeme": 21840, + "tripoli": 21841, + "##ossa": 21842, + "crocodile": 21843, + "##chers": 21844, + "sufi": 21845, + "mined": 21846, + "##tung": 21847, + "inferno": 21848, + "lsu": 21849, + "##phi": 21850, + "swelled": 21851, + "utilizes": 21852, + "£2": 21853, + "cale": 21854, + "periodicals": 21855, + "styx": 21856, + "hike": 21857, + "informally": 21858, + "coop": 21859, + "lund": 21860, + "##tidae": 21861, + "ala": 21862, + "hen": 21863, + "qui": 21864, + "transformations": 21865, + "disposed": 21866, + "sheath": 21867, + "chickens": 21868, + "##cade": 21869, + "fitzroy": 21870, + "sas": 21871, + "silesia": 21872, + "unacceptable": 21873, + "odisha": 21874, + "1650": 21875, + "sabrina": 21876, + "pe": 21877, + "spokane": 21878, + "ratios": 21879, + "athena": 21880, + "massage": 21881, + "shen": 21882, + "dilemma": 21883, + "##drum": 21884, + "##riz": 21885, + "##hul": 21886, + "corona": 21887, + "doubtful": 21888, + "niall": 21889, + "##pha": 21890, + "##bino": 21891, + "fines": 21892, + "cite": 21893, + "acknowledging": 21894, + "bangor": 21895, + "ballard": 21896, + "bathurst": 21897, + "##resh": 21898, + "huron": 21899, + "mustered": 21900, + "alzheimer": 21901, + "garments": 21902, + "kinase": 21903, + "tyre": 21904, + "warship": 21905, + "##cp": 21906, + "flashback": 21907, + "pulmonary": 21908, + "braun": 21909, + "cheat": 21910, + "kamal": 21911, + "cyclists": 21912, + "constructions": 21913, + "grenades": 21914, + "ndp": 21915, + "traveller": 21916, + "excuses": 21917, + "stomped": 21918, + "signalling": 21919, + "trimmed": 21920, + "futsal": 21921, + "mosques": 21922, + "relevance": 21923, + "##wine": 21924, + "wta": 21925, + "##23": 21926, + "##vah": 21927, + "##lter": 21928, + "hoc": 21929, + "##riding": 21930, + "optimistic": 21931, + "##´s": 21932, + "deco": 21933, + "sim": 21934, + "interacting": 21935, + "rejecting": 21936, + "moniker": 21937, + "waterways": 21938, + "##ieri": 21939, + "##oku": 21940, + "mayors": 21941, + "gdansk": 21942, + "outnumbered": 21943, + "pearls": 21944, + "##ended": 21945, + "##hampton": 21946, + "fairs": 21947, + "totals": 21948, + "dominating": 21949, + "262": 21950, + "notions": 21951, + "stairway": 21952, + "compiling": 21953, + "pursed": 21954, + "commodities": 21955, + "grease": 21956, + "yeast": 21957, + "##jong": 21958, + "carthage": 21959, + "griffiths": 21960, + "residual": 21961, + "amc": 21962, + "contraction": 21963, + "laird": 21964, + "sapphire": 21965, + "##marine": 21966, + "##ivated": 21967, + "amalgamation": 21968, + "dissolve": 21969, + "inclination": 21970, + "lyle": 21971, + "packaged": 21972, + "altitudes": 21973, + "suez": 21974, + "canons": 21975, + "graded": 21976, + "lurched": 21977, + "narrowing": 21978, + "boasts": 21979, + "guise": 21980, + "wed": 21981, + "enrico": 21982, + "##ovsky": 21983, + "rower": 21984, + "scarred": 21985, + "bree": 21986, + "cub": 21987, + "iberian": 21988, + "protagonists": 21989, + "bargaining": 21990, + "proposing": 21991, + "trainers": 21992, + "voyages": 21993, + "vans": 21994, + "fishes": 21995, + "##aea": 21996, + "##ivist": 21997, + "##verance": 21998, + "encryption": 21999, + "artworks": 22000, + "kazan": 22001, + "sabre": 22002, + "cleopatra": 22003, + "hepburn": 22004, + "rotting": 22005, + "supremacy": 22006, + "mecklenburg": 22007, + "##brate": 22008, + "burrows": 22009, + "hazards": 22010, + "outgoing": 22011, + "flair": 22012, + "organizes": 22013, + "##ctions": 22014, + "scorpion": 22015, + "##usions": 22016, + "boo": 22017, + "234": 22018, + "chevalier": 22019, + "dunedin": 22020, + "slapping": 22021, + "##34": 22022, + "ineligible": 22023, + "pensions": 22024, + "##38": 22025, + "##omic": 22026, + "manufactures": 22027, + "emails": 22028, + "bismarck": 22029, + "238": 22030, + "weakening": 22031, + "blackish": 22032, + "ding": 22033, + "mcgee": 22034, + "quo": 22035, + "##rling": 22036, + "northernmost": 22037, + "xx": 22038, + "manpower": 22039, + "greed": 22040, + "sampson": 22041, + "clicking": 22042, + "##ange": 22043, + "##horpe": 22044, + "##inations": 22045, + "##roving": 22046, + "torre": 22047, + "##eptive": 22048, + "##moral": 22049, + "symbolism": 22050, + "38th": 22051, + "asshole": 22052, + "meritorious": 22053, + "outfits": 22054, + "splashed": 22055, + "biographies": 22056, + "sprung": 22057, + "astros": 22058, + "##tale": 22059, + "302": 22060, + "737": 22061, + "filly": 22062, + "raoul": 22063, + "nw": 22064, + "tokugawa": 22065, + "linden": 22066, + "clubhouse": 22067, + "##apa": 22068, + "tracts": 22069, + "romano": 22070, + "##pio": 22071, + "putin": 22072, + "tags": 22073, + "##note": 22074, + "chained": 22075, + "dickson": 22076, + "gunshot": 22077, + "moe": 22078, + "gunn": 22079, + "rashid": 22080, + "##tails": 22081, + "zipper": 22082, + "##bas": 22083, + "##nea": 22084, + "contrasted": 22085, + "##ply": 22086, + "##udes": 22087, + "plum": 22088, + "pharaoh": 22089, + "##pile": 22090, + "aw": 22091, + "comedies": 22092, + "ingrid": 22093, + "sandwiches": 22094, + "subdivisions": 22095, + "1100": 22096, + "mariana": 22097, + "nokia": 22098, + "kamen": 22099, + "hz": 22100, + "delaney": 22101, + "veto": 22102, + "herring": 22103, + "##words": 22104, + "possessive": 22105, + "outlines": 22106, + "##roup": 22107, + "siemens": 22108, + "stairwell": 22109, + "rc": 22110, + "gallantry": 22111, + "messiah": 22112, + "palais": 22113, + "yells": 22114, + "233": 22115, + "zeppelin": 22116, + "##dm": 22117, + "bolivar": 22118, + "##cede": 22119, + "smackdown": 22120, + "mckinley": 22121, + "##mora": 22122, + "##yt": 22123, + "muted": 22124, + "geologic": 22125, + "finely": 22126, + "unitary": 22127, + "avatar": 22128, + "hamas": 22129, + "maynard": 22130, + "rees": 22131, + "bog": 22132, + "contrasting": 22133, + "##rut": 22134, + "liv": 22135, + "chico": 22136, + "disposition": 22137, + "pixel": 22138, + "##erate": 22139, + "becca": 22140, + "dmitry": 22141, + "yeshiva": 22142, + "narratives": 22143, + "##lva": 22144, + "##ulton": 22145, + "mercenary": 22146, + "sharpe": 22147, + "tempered": 22148, + "navigate": 22149, + "stealth": 22150, + "amassed": 22151, + "keynes": 22152, + "##lini": 22153, + "untouched": 22154, + "##rrie": 22155, + "havoc": 22156, + "lithium": 22157, + "##fighting": 22158, + "abyss": 22159, + "graf": 22160, + "southward": 22161, + "wolverine": 22162, + "balloons": 22163, + "implements": 22164, + "ngos": 22165, + "transitions": 22166, + "##icum": 22167, + "ambushed": 22168, + "concacaf": 22169, + "dormant": 22170, + "economists": 22171, + "##dim": 22172, + "costing": 22173, + "csi": 22174, + "rana": 22175, + "universite": 22176, + "boulders": 22177, + "verity": 22178, + "##llon": 22179, + "collin": 22180, + "mellon": 22181, + "misses": 22182, + "cypress": 22183, + "fluorescent": 22184, + "lifeless": 22185, + "spence": 22186, + "##ulla": 22187, + "crewe": 22188, + "shepard": 22189, + "pak": 22190, + "revelations": 22191, + "##م": 22192, + "jolly": 22193, + "gibbons": 22194, + "paw": 22195, + "##dro": 22196, + "##quel": 22197, + "freeing": 22198, + "##test": 22199, + "shack": 22200, + "fries": 22201, + "palatine": 22202, + "##51": 22203, + "##hiko": 22204, + "accompaniment": 22205, + "cruising": 22206, + "recycled": 22207, + "##aver": 22208, + "erwin": 22209, + "sorting": 22210, + "synthesizers": 22211, + "dyke": 22212, + "realities": 22213, + "sg": 22214, + "strides": 22215, + "enslaved": 22216, + "wetland": 22217, + "##ghan": 22218, + "competence": 22219, + "gunpowder": 22220, + "grassy": 22221, + "maroon": 22222, + "reactors": 22223, + "objection": 22224, + "##oms": 22225, + "carlson": 22226, + "gearbox": 22227, + "macintosh": 22228, + "radios": 22229, + "shelton": 22230, + "##sho": 22231, + "clergyman": 22232, + "prakash": 22233, + "254": 22234, + "mongols": 22235, + "trophies": 22236, + "oricon": 22237, + "228": 22238, + "stimuli": 22239, + "twenty20": 22240, + "cantonese": 22241, + "cortes": 22242, + "mirrored": 22243, + "##saurus": 22244, + "bhp": 22245, + "cristina": 22246, + "melancholy": 22247, + "##lating": 22248, + "enjoyable": 22249, + "nuevo": 22250, + "##wny": 22251, + "downfall": 22252, + "schumacher": 22253, + "##ind": 22254, + "banging": 22255, + "lausanne": 22256, + "rumbled": 22257, + "paramilitary": 22258, + "reflex": 22259, + "ax": 22260, + "amplitude": 22261, + "migratory": 22262, + "##gall": 22263, + "##ups": 22264, + "midi": 22265, + "barnard": 22266, + "lastly": 22267, + "sherry": 22268, + "##hp": 22269, + "##nall": 22270, + "keystone": 22271, + "##kra": 22272, + "carleton": 22273, + "slippery": 22274, + "##53": 22275, + "coloring": 22276, + "foe": 22277, + "socket": 22278, + "otter": 22279, + "##rgos": 22280, + "mats": 22281, + "##tose": 22282, + "consultants": 22283, + "bafta": 22284, + "bison": 22285, + "topping": 22286, + "##km": 22287, + "490": 22288, + "primal": 22289, + "abandonment": 22290, + "transplant": 22291, + "atoll": 22292, + "hideous": 22293, + "mort": 22294, + "pained": 22295, + "reproduced": 22296, + "tae": 22297, + "howling": 22298, + "##turn": 22299, + "unlawful": 22300, + "billionaire": 22301, + "hotter": 22302, + "poised": 22303, + "lansing": 22304, + "##chang": 22305, + "dinamo": 22306, + "retro": 22307, + "messing": 22308, + "nfc": 22309, + "domesday": 22310, + "##mina": 22311, + "blitz": 22312, + "timed": 22313, + "##athing": 22314, + "##kley": 22315, + "ascending": 22316, + "gesturing": 22317, + "##izations": 22318, + "signaled": 22319, + "tis": 22320, + "chinatown": 22321, + "mermaid": 22322, + "savanna": 22323, + "jameson": 22324, + "##aint": 22325, + "catalina": 22326, + "##pet": 22327, + "##hers": 22328, + "cochrane": 22329, + "cy": 22330, + "chatting": 22331, + "##kus": 22332, + "alerted": 22333, + "computation": 22334, + "mused": 22335, + "noelle": 22336, + "majestic": 22337, + "mohawk": 22338, + "campo": 22339, + "octagonal": 22340, + "##sant": 22341, + "##hend": 22342, + "241": 22343, + "aspiring": 22344, + "##mart": 22345, + "comprehend": 22346, + "iona": 22347, + "paralyzed": 22348, + "shimmering": 22349, + "swindon": 22350, + "rhone": 22351, + "##eley": 22352, + "reputed": 22353, + "configurations": 22354, + "pitchfork": 22355, + "agitation": 22356, + "francais": 22357, + "gillian": 22358, + "lipstick": 22359, + "##ilo": 22360, + "outsiders": 22361, + "pontifical": 22362, + "resisting": 22363, + "bitterness": 22364, + "sewer": 22365, + "rockies": 22366, + "##edd": 22367, + "##ucher": 22368, + "misleading": 22369, + "1756": 22370, + "exiting": 22371, + "galloway": 22372, + "##nging": 22373, + "risked": 22374, + "##heart": 22375, + "246": 22376, + "commemoration": 22377, + "schultz": 22378, + "##rka": 22379, + "integrating": 22380, + "##rsa": 22381, + "poses": 22382, + "shrieked": 22383, + "##weiler": 22384, + "guineas": 22385, + "gladys": 22386, + "jerking": 22387, + "owls": 22388, + "goldsmith": 22389, + "nightly": 22390, + "penetrating": 22391, + "##unced": 22392, + "lia": 22393, + "##33": 22394, + "ignited": 22395, + "betsy": 22396, + "##aring": 22397, + "##thorpe": 22398, + "follower": 22399, + "vigorously": 22400, + "##rave": 22401, + "coded": 22402, + "kiran": 22403, + "knit": 22404, + "zoology": 22405, + "tbilisi": 22406, + "##28": 22407, + "##bered": 22408, + "repository": 22409, + "govt": 22410, + "deciduous": 22411, + "dino": 22412, + "growling": 22413, + "##bba": 22414, + "enhancement": 22415, + "unleashed": 22416, + "chanting": 22417, + "pussy": 22418, + "biochemistry": 22419, + "##eric": 22420, + "kettle": 22421, + "repression": 22422, + "toxicity": 22423, + "nrhp": 22424, + "##arth": 22425, + "##kko": 22426, + "##bush": 22427, + "ernesto": 22428, + "commended": 22429, + "outspoken": 22430, + "242": 22431, + "mca": 22432, + "parchment": 22433, + "sms": 22434, + "kristen": 22435, + "##aton": 22436, + "bisexual": 22437, + "raked": 22438, + "glamour": 22439, + "navajo": 22440, + "a2": 22441, + "conditioned": 22442, + "showcased": 22443, + "##hma": 22444, + "spacious": 22445, + "youthful": 22446, + "##esa": 22447, + "usl": 22448, + "appliances": 22449, + "junta": 22450, + "brest": 22451, + "layne": 22452, + "conglomerate": 22453, + "enchanted": 22454, + "chao": 22455, + "loosened": 22456, + "picasso": 22457, + "circulating": 22458, + "inspect": 22459, + "montevideo": 22460, + "##centric": 22461, + "##kti": 22462, + "piazza": 22463, + "spurred": 22464, + "##aith": 22465, + "bari": 22466, + "freedoms": 22467, + "poultry": 22468, + "stamford": 22469, + "lieu": 22470, + "##ect": 22471, + "indigo": 22472, + "sarcastic": 22473, + "bahia": 22474, + "stump": 22475, + "attach": 22476, + "dvds": 22477, + "frankenstein": 22478, + "lille": 22479, + "approx": 22480, + "scriptures": 22481, + "pollen": 22482, + "##script": 22483, + "nmi": 22484, + "overseen": 22485, + "##ivism": 22486, + "tides": 22487, + "proponent": 22488, + "newmarket": 22489, + "inherit": 22490, + "milling": 22491, + "##erland": 22492, + "centralized": 22493, + "##rou": 22494, + "distributors": 22495, + "credentials": 22496, + "drawers": 22497, + "abbreviation": 22498, + "##lco": 22499, + "##xon": 22500, + "downing": 22501, + "uncomfortably": 22502, + "ripe": 22503, + "##oes": 22504, + "erase": 22505, + "franchises": 22506, + "##ever": 22507, + "populace": 22508, + "##bery": 22509, + "##khar": 22510, + "decomposition": 22511, + "pleas": 22512, + "##tet": 22513, + "daryl": 22514, + "sabah": 22515, + "##stle": 22516, + "##wide": 22517, + "fearless": 22518, + "genie": 22519, + "lesions": 22520, + "annette": 22521, + "##ogist": 22522, + "oboe": 22523, + "appendix": 22524, + "nair": 22525, + "dripped": 22526, + "petitioned": 22527, + "maclean": 22528, + "mosquito": 22529, + "parrot": 22530, + "rpg": 22531, + "hampered": 22532, + "1648": 22533, + "operatic": 22534, + "reservoirs": 22535, + "##tham": 22536, + "irrelevant": 22537, + "jolt": 22538, + "summarized": 22539, + "##fp": 22540, + "medallion": 22541, + "##taff": 22542, + "##−": 22543, + "clawed": 22544, + "harlow": 22545, + "narrower": 22546, + "goddard": 22547, + "marcia": 22548, + "bodied": 22549, + "fremont": 22550, + "suarez": 22551, + "altering": 22552, + "tempest": 22553, + "mussolini": 22554, + "porn": 22555, + "##isms": 22556, + "sweetly": 22557, + "oversees": 22558, + "walkers": 22559, + "solitude": 22560, + "grimly": 22561, + "shrines": 22562, + "hk": 22563, + "ich": 22564, + "supervisors": 22565, + "hostess": 22566, + "dietrich": 22567, + "legitimacy": 22568, + "brushes": 22569, + "expressive": 22570, + "##yp": 22571, + "dissipated": 22572, + "##rse": 22573, + "localized": 22574, + "systemic": 22575, + "##nikov": 22576, + "gettysburg": 22577, + "##js": 22578, + "##uaries": 22579, + "dialogues": 22580, + "muttering": 22581, + "251": 22582, + "housekeeper": 22583, + "sicilian": 22584, + "discouraged": 22585, + "##frey": 22586, + "beamed": 22587, + "kaladin": 22588, + "halftime": 22589, + "kidnap": 22590, + "##amo": 22591, + "##llet": 22592, + "1754": 22593, + "synonymous": 22594, + "depleted": 22595, + "instituto": 22596, + "insulin": 22597, + "reprised": 22598, + "##opsis": 22599, + "clashed": 22600, + "##ctric": 22601, + "interrupting": 22602, + "radcliffe": 22603, + "insisting": 22604, + "medici": 22605, + "1715": 22606, + "ejected": 22607, + "playfully": 22608, + "turbulent": 22609, + "##47": 22610, + "starvation": 22611, + "##rini": 22612, + "shipment": 22613, + "rebellious": 22614, + "petersen": 22615, + "verification": 22616, + "merits": 22617, + "##rified": 22618, + "cakes": 22619, + "##charged": 22620, + "1757": 22621, + "milford": 22622, + "shortages": 22623, + "spying": 22624, + "fidelity": 22625, + "##aker": 22626, + "emitted": 22627, + "storylines": 22628, + "harvested": 22629, + "seismic": 22630, + "##iform": 22631, + "cheung": 22632, + "kilda": 22633, + "theoretically": 22634, + "barbie": 22635, + "lynx": 22636, + "##rgy": 22637, + "##tius": 22638, + "goblin": 22639, + "mata": 22640, + "poisonous": 22641, + "##nburg": 22642, + "reactive": 22643, + "residues": 22644, + "obedience": 22645, + "##евич": 22646, + "conjecture": 22647, + "##rac": 22648, + "401": 22649, + "hating": 22650, + "sixties": 22651, + "kicker": 22652, + "moaning": 22653, + "motown": 22654, + "##bha": 22655, + "emancipation": 22656, + "neoclassical": 22657, + "##hering": 22658, + "consoles": 22659, + "ebert": 22660, + "professorship": 22661, + "##tures": 22662, + "sustaining": 22663, + "assaults": 22664, + "obeyed": 22665, + "affluent": 22666, + "incurred": 22667, + "tornadoes": 22668, + "##eber": 22669, + "##zow": 22670, + "emphasizing": 22671, + "highlanders": 22672, + "cheated": 22673, + "helmets": 22674, + "##ctus": 22675, + "internship": 22676, + "terence": 22677, + "bony": 22678, + "executions": 22679, + "legislators": 22680, + "berries": 22681, + "peninsular": 22682, + "tinged": 22683, + "##aco": 22684, + "1689": 22685, + "amplifier": 22686, + "corvette": 22687, + "ribbons": 22688, + "lavish": 22689, + "pennant": 22690, + "##lander": 22691, + "worthless": 22692, + "##chfield": 22693, + "##forms": 22694, + "mariano": 22695, + "pyrenees": 22696, + "expenditures": 22697, + "##icides": 22698, + "chesterfield": 22699, + "mandir": 22700, + "tailor": 22701, + "39th": 22702, + "sergey": 22703, + "nestled": 22704, + "willed": 22705, + "aristocracy": 22706, + "devotees": 22707, + "goodnight": 22708, + "raaf": 22709, + "rumored": 22710, + "weaponry": 22711, + "remy": 22712, + "appropriations": 22713, + "harcourt": 22714, + "burr": 22715, + "riaa": 22716, + "##lence": 22717, + "limitation": 22718, + "unnoticed": 22719, + "guo": 22720, + "soaking": 22721, + "swamps": 22722, + "##tica": 22723, + "collapsing": 22724, + "tatiana": 22725, + "descriptive": 22726, + "brigham": 22727, + "psalm": 22728, + "##chment": 22729, + "maddox": 22730, + "##lization": 22731, + "patti": 22732, + "caliph": 22733, + "##aja": 22734, + "akron": 22735, + "injuring": 22736, + "serra": 22737, + "##ganj": 22738, + "basins": 22739, + "##sari": 22740, + "astonished": 22741, + "launcher": 22742, + "##church": 22743, + "hilary": 22744, + "wilkins": 22745, + "sewing": 22746, + "##sf": 22747, + "stinging": 22748, + "##fia": 22749, + "##ncia": 22750, + "underwood": 22751, + "startup": 22752, + "##ition": 22753, + "compilations": 22754, + "vibrations": 22755, + "embankment": 22756, + "jurist": 22757, + "##nity": 22758, + "bard": 22759, + "juventus": 22760, + "groundwater": 22761, + "kern": 22762, + "palaces": 22763, + "helium": 22764, + "boca": 22765, + "cramped": 22766, + "marissa": 22767, + "soto": 22768, + "##worm": 22769, + "jae": 22770, + "princely": 22771, + "##ggy": 22772, + "faso": 22773, + "bazaar": 22774, + "warmly": 22775, + "##voking": 22776, + "229": 22777, + "pairing": 22778, + "##lite": 22779, + "##grate": 22780, + "##nets": 22781, + "wien": 22782, + "freaked": 22783, + "ulysses": 22784, + "rebirth": 22785, + "##alia": 22786, + "##rent": 22787, + "mummy": 22788, + "guzman": 22789, + "jimenez": 22790, + "stilled": 22791, + "##nitz": 22792, + "trajectory": 22793, + "tha": 22794, + "woken": 22795, + "archival": 22796, + "professions": 22797, + "##pts": 22798, + "##pta": 22799, + "hilly": 22800, + "shadowy": 22801, + "shrink": 22802, + "##bolt": 22803, + "norwood": 22804, + "glued": 22805, + "migrate": 22806, + "stereotypes": 22807, + "devoid": 22808, + "##pheus": 22809, + "625": 22810, + "evacuate": 22811, + "horrors": 22812, + "infancy": 22813, + "gotham": 22814, + "knowles": 22815, + "optic": 22816, + "downloaded": 22817, + "sachs": 22818, + "kingsley": 22819, + "parramatta": 22820, + "darryl": 22821, + "mor": 22822, + "##onale": 22823, + "shady": 22824, + "commence": 22825, + "confesses": 22826, + "kan": 22827, + "##meter": 22828, + "##placed": 22829, + "marlborough": 22830, + "roundabout": 22831, + "regents": 22832, + "frigates": 22833, + "io": 22834, + "##imating": 22835, + "gothenburg": 22836, + "revoked": 22837, + "carvings": 22838, + "clockwise": 22839, + "convertible": 22840, + "intruder": 22841, + "##sche": 22842, + "banged": 22843, + "##ogo": 22844, + "vicky": 22845, + "bourgeois": 22846, + "##mony": 22847, + "dupont": 22848, + "footing": 22849, + "##gum": 22850, + "pd": 22851, + "##real": 22852, + "buckle": 22853, + "yun": 22854, + "penthouse": 22855, + "sane": 22856, + "720": 22857, + "serviced": 22858, + "stakeholders": 22859, + "neumann": 22860, + "bb": 22861, + "##eers": 22862, + "comb": 22863, + "##gam": 22864, + "catchment": 22865, + "pinning": 22866, + "rallies": 22867, + "typing": 22868, + "##elles": 22869, + "forefront": 22870, + "freiburg": 22871, + "sweetie": 22872, + "giacomo": 22873, + "widowed": 22874, + "goodwill": 22875, + "worshipped": 22876, + "aspirations": 22877, + "midday": 22878, + "##vat": 22879, + "fishery": 22880, + "##trick": 22881, + "bournemouth": 22882, + "turk": 22883, + "243": 22884, + "hearth": 22885, + "ethanol": 22886, + "guadalajara": 22887, + "murmurs": 22888, + "sl": 22889, + "##uge": 22890, + "afforded": 22891, + "scripted": 22892, + "##hta": 22893, + "wah": 22894, + "##jn": 22895, + "coroner": 22896, + "translucent": 22897, + "252": 22898, + "memorials": 22899, + "puck": 22900, + "progresses": 22901, + "clumsy": 22902, + "##race": 22903, + "315": 22904, + "candace": 22905, + "recounted": 22906, + "##27": 22907, + "##slin": 22908, + "##uve": 22909, + "filtering": 22910, + "##mac": 22911, + "howl": 22912, + "strata": 22913, + "heron": 22914, + "leveled": 22915, + "##ays": 22916, + "dubious": 22917, + "##oja": 22918, + "##т": 22919, + "##wheel": 22920, + "citations": 22921, + "exhibiting": 22922, + "##laya": 22923, + "##mics": 22924, + "##pods": 22925, + "turkic": 22926, + "##lberg": 22927, + "injunction": 22928, + "##ennial": 22929, + "##mit": 22930, + "antibodies": 22931, + "##44": 22932, + "organise": 22933, + "##rigues": 22934, + "cardiovascular": 22935, + "cushion": 22936, + "inverness": 22937, + "##zquez": 22938, + "dia": 22939, + "cocoa": 22940, + "sibling": 22941, + "##tman": 22942, + "##roid": 22943, + "expanse": 22944, + "feasible": 22945, + "tunisian": 22946, + "algiers": 22947, + "##relli": 22948, + "rus": 22949, + "bloomberg": 22950, + "dso": 22951, + "westphalia": 22952, + "bro": 22953, + "tacoma": 22954, + "281": 22955, + "downloads": 22956, + "##ours": 22957, + "konrad": 22958, + "duran": 22959, + "##hdi": 22960, + "continuum": 22961, + "jett": 22962, + "compares": 22963, + "legislator": 22964, + "secession": 22965, + "##nable": 22966, + "##gues": 22967, + "##zuka": 22968, + "translating": 22969, + "reacher": 22970, + "##gley": 22971, + "##ła": 22972, + "aleppo": 22973, + "##agi": 22974, + "tc": 22975, + "orchards": 22976, + "trapping": 22977, + "linguist": 22978, + "versatile": 22979, + "drumming": 22980, + "postage": 22981, + "calhoun": 22982, + "superiors": 22983, + "##mx": 22984, + "barefoot": 22985, + "leary": 22986, + "##cis": 22987, + "ignacio": 22988, + "alfa": 22989, + "kaplan": 22990, + "##rogen": 22991, + "bratislava": 22992, + "mori": 22993, + "##vot": 22994, + "disturb": 22995, + "haas": 22996, + "313": 22997, + "cartridges": 22998, + "gilmore": 22999, + "radiated": 23000, + "salford": 23001, + "tunic": 23002, + "hades": 23003, + "##ulsive": 23004, + "archeological": 23005, + "delilah": 23006, + "magistrates": 23007, + "auditioned": 23008, + "brewster": 23009, + "charters": 23010, + "empowerment": 23011, + "blogs": 23012, + "cappella": 23013, + "dynasties": 23014, + "iroquois": 23015, + "whipping": 23016, + "##krishna": 23017, + "raceway": 23018, + "truths": 23019, + "myra": 23020, + "weaken": 23021, + "judah": 23022, + "mcgregor": 23023, + "##horse": 23024, + "mic": 23025, + "refueling": 23026, + "37th": 23027, + "burnley": 23028, + "bosses": 23029, + "markus": 23030, + "premio": 23031, + "query": 23032, + "##gga": 23033, + "dunbar": 23034, + "##economic": 23035, + "darkest": 23036, + "lyndon": 23037, + "sealing": 23038, + "commendation": 23039, + "reappeared": 23040, + "##mun": 23041, + "addicted": 23042, + "ezio": 23043, + "slaughtered": 23044, + "satisfactory": 23045, + "shuffle": 23046, + "##eves": 23047, + "##thic": 23048, + "##uj": 23049, + "fortification": 23050, + "warrington": 23051, + "##otto": 23052, + "resurrected": 23053, + "fargo": 23054, + "mane": 23055, + "##utable": 23056, + "##lei": 23057, + "##space": 23058, + "foreword": 23059, + "ox": 23060, + "##aris": 23061, + "##vern": 23062, + "abrams": 23063, + "hua": 23064, + "##mento": 23065, + "sakura": 23066, + "##alo": 23067, + "uv": 23068, + "sentimental": 23069, + "##skaya": 23070, + "midfield": 23071, + "##eses": 23072, + "sturdy": 23073, + "scrolls": 23074, + "macleod": 23075, + "##kyu": 23076, + "entropy": 23077, + "##lance": 23078, + "mitochondrial": 23079, + "cicero": 23080, + "excelled": 23081, + "thinner": 23082, + "convoys": 23083, + "perceive": 23084, + "##oslav": 23085, + "##urable": 23086, + "systematically": 23087, + "grind": 23088, + "burkina": 23089, + "287": 23090, + "##tagram": 23091, + "ops": 23092, + "##aman": 23093, + "guantanamo": 23094, + "##cloth": 23095, + "##tite": 23096, + "forcefully": 23097, + "wavy": 23098, + "##jou": 23099, + "pointless": 23100, + "##linger": 23101, + "##tze": 23102, + "layton": 23103, + "portico": 23104, + "superficial": 23105, + "clerical": 23106, + "outlaws": 23107, + "##hism": 23108, + "burials": 23109, + "muir": 23110, + "##inn": 23111, + "creditors": 23112, + "hauling": 23113, + "rattle": 23114, + "##leg": 23115, + "calais": 23116, + "monde": 23117, + "archers": 23118, + "reclaimed": 23119, + "dwell": 23120, + "wexford": 23121, + "hellenic": 23122, + "falsely": 23123, + "remorse": 23124, + "##tek": 23125, + "dough": 23126, + "furnishings": 23127, + "##uttered": 23128, + "gabon": 23129, + "neurological": 23130, + "novice": 23131, + "##igraphy": 23132, + "contemplated": 23133, + "pulpit": 23134, + "nightstand": 23135, + "saratoga": 23136, + "##istan": 23137, + "documenting": 23138, + "pulsing": 23139, + "taluk": 23140, + "##firmed": 23141, + "busted": 23142, + "marital": 23143, + "##rien": 23144, + "disagreements": 23145, + "wasps": 23146, + "##yes": 23147, + "hodge": 23148, + "mcdonnell": 23149, + "mimic": 23150, + "fran": 23151, + "pendant": 23152, + "dhabi": 23153, + "musa": 23154, + "##nington": 23155, + "congratulations": 23156, + "argent": 23157, + "darrell": 23158, + "concussion": 23159, + "losers": 23160, + "regrets": 23161, + "thessaloniki": 23162, + "reversal": 23163, + "donaldson": 23164, + "hardwood": 23165, + "thence": 23166, + "achilles": 23167, + "ritter": 23168, + "##eran": 23169, + "demonic": 23170, + "jurgen": 23171, + "prophets": 23172, + "goethe": 23173, + "eki": 23174, + "classmate": 23175, + "buff": 23176, + "##cking": 23177, + "yank": 23178, + "irrational": 23179, + "##inging": 23180, + "perished": 23181, + "seductive": 23182, + "qur": 23183, + "sourced": 23184, + "##crat": 23185, + "##typic": 23186, + "mustard": 23187, + "ravine": 23188, + "barre": 23189, + "horizontally": 23190, + "characterization": 23191, + "phylogenetic": 23192, + "boise": 23193, + "##dit": 23194, + "##runner": 23195, + "##tower": 23196, + "brutally": 23197, + "intercourse": 23198, + "seduce": 23199, + "##bbing": 23200, + "fay": 23201, + "ferris": 23202, + "ogden": 23203, + "amar": 23204, + "nik": 23205, + "unarmed": 23206, + "##inator": 23207, + "evaluating": 23208, + "kyrgyzstan": 23209, + "sweetness": 23210, + "##lford": 23211, + "##oki": 23212, + "mccormick": 23213, + "meiji": 23214, + "notoriety": 23215, + "stimulate": 23216, + "disrupt": 23217, + "figuring": 23218, + "instructional": 23219, + "mcgrath": 23220, + "##zoo": 23221, + "groundbreaking": 23222, + "##lto": 23223, + "flinch": 23224, + "khorasan": 23225, + "agrarian": 23226, + "bengals": 23227, + "mixer": 23228, + "radiating": 23229, + "##sov": 23230, + "ingram": 23231, + "pitchers": 23232, + "nad": 23233, + "tariff": 23234, + "##cript": 23235, + "tata": 23236, + "##codes": 23237, + "##emi": 23238, + "##ungen": 23239, + "appellate": 23240, + "lehigh": 23241, + "##bled": 23242, + "##giri": 23243, + "brawl": 23244, + "duct": 23245, + "texans": 23246, + "##ciation": 23247, + "##ropolis": 23248, + "skipper": 23249, + "speculative": 23250, + "vomit": 23251, + "doctrines": 23252, + "stresses": 23253, + "253": 23254, + "davy": 23255, + "graders": 23256, + "whitehead": 23257, + "jozef": 23258, + "timely": 23259, + "cumulative": 23260, + "haryana": 23261, + "paints": 23262, + "appropriately": 23263, + "boon": 23264, + "cactus": 23265, + "##ales": 23266, + "##pid": 23267, + "dow": 23268, + "legions": 23269, + "##pit": 23270, + "perceptions": 23271, + "1730": 23272, + "picturesque": 23273, + "##yse": 23274, + "periphery": 23275, + "rune": 23276, + "wr": 23277, + "##aha": 23278, + "celtics": 23279, + "sentencing": 23280, + "whoa": 23281, + "##erin": 23282, + "confirms": 23283, + "variance": 23284, + "425": 23285, + "moines": 23286, + "mathews": 23287, + "spade": 23288, + "rave": 23289, + "m1": 23290, + "fronted": 23291, + "fx": 23292, + "blending": 23293, + "alleging": 23294, + "reared": 23295, + "##gl": 23296, + "237": 23297, + "##paper": 23298, + "grassroots": 23299, + "eroded": 23300, + "##free": 23301, + "##physical": 23302, + "directs": 23303, + "ordeal": 23304, + "##sław": 23305, + "accelerate": 23306, + "hacker": 23307, + "rooftop": 23308, + "##inia": 23309, + "lev": 23310, + "buys": 23311, + "cebu": 23312, + "devote": 23313, + "##lce": 23314, + "specialising": 23315, + "##ulsion": 23316, + "choreographed": 23317, + "repetition": 23318, + "warehouses": 23319, + "##ryl": 23320, + "paisley": 23321, + "tuscany": 23322, + "analogy": 23323, + "sorcerer": 23324, + "hash": 23325, + "huts": 23326, + "shards": 23327, + "descends": 23328, + "exclude": 23329, + "nix": 23330, + "chaplin": 23331, + "gaga": 23332, + "ito": 23333, + "vane": 23334, + "##drich": 23335, + "causeway": 23336, + "misconduct": 23337, + "limo": 23338, + "orchestrated": 23339, + "glands": 23340, + "jana": 23341, + "##kot": 23342, + "u2": 23343, + "##mple": 23344, + "##sons": 23345, + "branching": 23346, + "contrasts": 23347, + "scoop": 23348, + "longed": 23349, + "##virus": 23350, + "chattanooga": 23351, + "##75": 23352, + "syrup": 23353, + "cornerstone": 23354, + "##tized": 23355, + "##mind": 23356, + "##iaceae": 23357, + "careless": 23358, + "precedence": 23359, + "frescoes": 23360, + "##uet": 23361, + "chilled": 23362, + "consult": 23363, + "modelled": 23364, + "snatch": 23365, + "peat": 23366, + "##thermal": 23367, + "caucasian": 23368, + "humane": 23369, + "relaxation": 23370, + "spins": 23371, + "temperance": 23372, + "##lbert": 23373, + "occupations": 23374, + "lambda": 23375, + "hybrids": 23376, + "moons": 23377, + "mp3": 23378, + "##oese": 23379, + "247": 23380, + "rolf": 23381, + "societal": 23382, + "yerevan": 23383, + "ness": 23384, + "##ssler": 23385, + "befriended": 23386, + "mechanized": 23387, + "nominate": 23388, + "trough": 23389, + "boasted": 23390, + "cues": 23391, + "seater": 23392, + "##hom": 23393, + "bends": 23394, + "##tangle": 23395, + "conductors": 23396, + "emptiness": 23397, + "##lmer": 23398, + "eurasian": 23399, + "adriatic": 23400, + "tian": 23401, + "##cie": 23402, + "anxiously": 23403, + "lark": 23404, + "propellers": 23405, + "chichester": 23406, + "jock": 23407, + "ev": 23408, + "2a": 23409, + "##holding": 23410, + "credible": 23411, + "recounts": 23412, + "tori": 23413, + "loyalist": 23414, + "abduction": 23415, + "##hoot": 23416, + "##redo": 23417, + "nepali": 23418, + "##mite": 23419, + "ventral": 23420, + "tempting": 23421, + "##ango": 23422, + "##crats": 23423, + "steered": 23424, + "##wice": 23425, + "javelin": 23426, + "dipping": 23427, + "laborers": 23428, + "prentice": 23429, + "looming": 23430, + "titanium": 23431, + "##ː": 23432, + "badges": 23433, + "emir": 23434, + "tensor": 23435, + "##ntation": 23436, + "egyptians": 23437, + "rash": 23438, + "denies": 23439, + "hawthorne": 23440, + "lombard": 23441, + "showers": 23442, + "wehrmacht": 23443, + "dietary": 23444, + "trojan": 23445, + "##reus": 23446, + "welles": 23447, + "executing": 23448, + "horseshoe": 23449, + "lifeboat": 23450, + "##lak": 23451, + "elsa": 23452, + "infirmary": 23453, + "nearing": 23454, + "roberta": 23455, + "boyer": 23456, + "mutter": 23457, + "trillion": 23458, + "joanne": 23459, + "##fine": 23460, + "##oked": 23461, + "sinks": 23462, + "vortex": 23463, + "uruguayan": 23464, + "clasp": 23465, + "sirius": 23466, + "##block": 23467, + "accelerator": 23468, + "prohibit": 23469, + "sunken": 23470, + "byu": 23471, + "chronological": 23472, + "diplomats": 23473, + "ochreous": 23474, + "510": 23475, + "symmetrical": 23476, + "1644": 23477, + "maia": 23478, + "##tology": 23479, + "salts": 23480, + "reigns": 23481, + "atrocities": 23482, + "##ия": 23483, + "hess": 23484, + "bared": 23485, + "issn": 23486, + "##vyn": 23487, + "cater": 23488, + "saturated": 23489, + "##cycle": 23490, + "##isse": 23491, + "sable": 23492, + "voyager": 23493, + "dyer": 23494, + "yusuf": 23495, + "##inge": 23496, + "fountains": 23497, + "wolff": 23498, + "##39": 23499, + "##nni": 23500, + "engraving": 23501, + "rollins": 23502, + "atheist": 23503, + "ominous": 23504, + "##ault": 23505, + "herr": 23506, + "chariot": 23507, + "martina": 23508, + "strung": 23509, + "##fell": 23510, + "##farlane": 23511, + "horrific": 23512, + "sahib": 23513, + "gazes": 23514, + "saetan": 23515, + "erased": 23516, + "ptolemy": 23517, + "##olic": 23518, + "flushing": 23519, + "lauderdale": 23520, + "analytic": 23521, + "##ices": 23522, + "530": 23523, + "navarro": 23524, + "beak": 23525, + "gorilla": 23526, + "herrera": 23527, + "broom": 23528, + "guadalupe": 23529, + "raiding": 23530, + "sykes": 23531, + "311": 23532, + "bsc": 23533, + "deliveries": 23534, + "1720": 23535, + "invasions": 23536, + "carmichael": 23537, + "tajikistan": 23538, + "thematic": 23539, + "ecumenical": 23540, + "sentiments": 23541, + "onstage": 23542, + "##rians": 23543, + "##brand": 23544, + "##sume": 23545, + "catastrophic": 23546, + "flanks": 23547, + "molten": 23548, + "##arns": 23549, + "waller": 23550, + "aimee": 23551, + "terminating": 23552, + "##icing": 23553, + "alternately": 23554, + "##oche": 23555, + "nehru": 23556, + "printers": 23557, + "outraged": 23558, + "##eving": 23559, + "empires": 23560, + "template": 23561, + "banners": 23562, + "repetitive": 23563, + "za": 23564, + "##oise": 23565, + "vegetarian": 23566, + "##tell": 23567, + "guiana": 23568, + "opt": 23569, + "cavendish": 23570, + "lucknow": 23571, + "synthesized": 23572, + "##hani": 23573, + "##mada": 23574, + "finalized": 23575, + "##ctable": 23576, + "fictitious": 23577, + "mayoral": 23578, + "unreliable": 23579, + "##enham": 23580, + "embracing": 23581, + "peppers": 23582, + "rbis": 23583, + "##chio": 23584, + "##neo": 23585, + "inhibition": 23586, + "slashed": 23587, + "togo": 23588, + "orderly": 23589, + "embroidered": 23590, + "safari": 23591, + "salty": 23592, + "236": 23593, + "barron": 23594, + "benito": 23595, + "totaled": 23596, + "##dak": 23597, + "pubs": 23598, + "simulated": 23599, + "caden": 23600, + "devin": 23601, + "tolkien": 23602, + "momma": 23603, + "welding": 23604, + "sesame": 23605, + "##ept": 23606, + "gottingen": 23607, + "hardness": 23608, + "630": 23609, + "shaman": 23610, + "temeraire": 23611, + "620": 23612, + "adequately": 23613, + "pediatric": 23614, + "##kit": 23615, + "ck": 23616, + "assertion": 23617, + "radicals": 23618, + "composure": 23619, + "cadence": 23620, + "seafood": 23621, + "beaufort": 23622, + "lazarus": 23623, + "mani": 23624, + "warily": 23625, + "cunning": 23626, + "kurdistan": 23627, + "249": 23628, + "cantata": 23629, + "##kir": 23630, + "ares": 23631, + "##41": 23632, + "##clusive": 23633, + "nape": 23634, + "townland": 23635, + "geared": 23636, + "insulted": 23637, + "flutter": 23638, + "boating": 23639, + "violate": 23640, + "draper": 23641, + "dumping": 23642, + "malmo": 23643, + "##hh": 23644, + "##romatic": 23645, + "firearm": 23646, + "alta": 23647, + "bono": 23648, + "obscured": 23649, + "##clave": 23650, + "exceeds": 23651, + "panorama": 23652, + "unbelievable": 23653, + "##train": 23654, + "preschool": 23655, + "##essed": 23656, + "disconnected": 23657, + "installing": 23658, + "rescuing": 23659, + "secretaries": 23660, + "accessibility": 23661, + "##castle": 23662, + "##drive": 23663, + "##ifice": 23664, + "##film": 23665, + "bouts": 23666, + "slug": 23667, + "waterway": 23668, + "mindanao": 23669, + "##buro": 23670, + "##ratic": 23671, + "halves": 23672, + "##ل": 23673, + "calming": 23674, + "liter": 23675, + "maternity": 23676, + "adorable": 23677, + "bragg": 23678, + "electrification": 23679, + "mcc": 23680, + "##dote": 23681, + "roxy": 23682, + "schizophrenia": 23683, + "##body": 23684, + "munoz": 23685, + "kaye": 23686, + "whaling": 23687, + "239": 23688, + "mil": 23689, + "tingling": 23690, + "tolerant": 23691, + "##ago": 23692, + "unconventional": 23693, + "volcanoes": 23694, + "##finder": 23695, + "deportivo": 23696, + "##llie": 23697, + "robson": 23698, + "kaufman": 23699, + "neuroscience": 23700, + "wai": 23701, + "deportation": 23702, + "masovian": 23703, + "scraping": 23704, + "converse": 23705, + "##bh": 23706, + "hacking": 23707, + "bulge": 23708, + "##oun": 23709, + "administratively": 23710, + "yao": 23711, + "580": 23712, + "amp": 23713, + "mammoth": 23714, + "booster": 23715, + "claremont": 23716, + "hooper": 23717, + "nomenclature": 23718, + "pursuits": 23719, + "mclaughlin": 23720, + "melinda": 23721, + "##sul": 23722, + "catfish": 23723, + "barclay": 23724, + "substrates": 23725, + "taxa": 23726, + "zee": 23727, + "originals": 23728, + "kimberly": 23729, + "packets": 23730, + "padma": 23731, + "##ality": 23732, + "borrowing": 23733, + "ostensibly": 23734, + "solvent": 23735, + "##bri": 23736, + "##genesis": 23737, + "##mist": 23738, + "lukas": 23739, + "shreveport": 23740, + "veracruz": 23741, + "##ь": 23742, + "##lou": 23743, + "##wives": 23744, + "cheney": 23745, + "tt": 23746, + "anatolia": 23747, + "hobbs": 23748, + "##zyn": 23749, + "cyclic": 23750, + "radiant": 23751, + "alistair": 23752, + "greenish": 23753, + "siena": 23754, + "dat": 23755, + "independents": 23756, + "##bation": 23757, + "conform": 23758, + "pieter": 23759, + "hyper": 23760, + "applicant": 23761, + "bradshaw": 23762, + "spores": 23763, + "telangana": 23764, + "vinci": 23765, + "inexpensive": 23766, + "nuclei": 23767, + "322": 23768, + "jang": 23769, + "nme": 23770, + "soho": 23771, + "spd": 23772, + "##ign": 23773, + "cradled": 23774, + "receptionist": 23775, + "pow": 23776, + "##43": 23777, + "##rika": 23778, + "fascism": 23779, + "##ifer": 23780, + "experimenting": 23781, + "##ading": 23782, + "##iec": 23783, + "##region": 23784, + "345": 23785, + "jocelyn": 23786, + "maris": 23787, + "stair": 23788, + "nocturnal": 23789, + "toro": 23790, + "constabulary": 23791, + "elgin": 23792, + "##kker": 23793, + "msc": 23794, + "##giving": 23795, + "##schen": 23796, + "##rase": 23797, + "doherty": 23798, + "doping": 23799, + "sarcastically": 23800, + "batter": 23801, + "maneuvers": 23802, + "##cano": 23803, + "##apple": 23804, + "##gai": 23805, + "##git": 23806, + "intrinsic": 23807, + "##nst": 23808, + "##stor": 23809, + "1753": 23810, + "showtime": 23811, + "cafes": 23812, + "gasps": 23813, + "lviv": 23814, + "ushered": 23815, + "##thed": 23816, + "fours": 23817, + "restart": 23818, + "astonishment": 23819, + "transmitting": 23820, + "flyer": 23821, + "shrugs": 23822, + "##sau": 23823, + "intriguing": 23824, + "cones": 23825, + "dictated": 23826, + "mushrooms": 23827, + "medial": 23828, + "##kovsky": 23829, + "##elman": 23830, + "escorting": 23831, + "gaped": 23832, + "##26": 23833, + "godfather": 23834, + "##door": 23835, + "##sell": 23836, + "djs": 23837, + "recaptured": 23838, + "timetable": 23839, + "vila": 23840, + "1710": 23841, + "3a": 23842, + "aerodrome": 23843, + "mortals": 23844, + "scientology": 23845, + "##orne": 23846, + "angelina": 23847, + "mag": 23848, + "convection": 23849, + "unpaid": 23850, + "insertion": 23851, + "intermittent": 23852, + "lego": 23853, + "##nated": 23854, + "endeavor": 23855, + "kota": 23856, + "pereira": 23857, + "##lz": 23858, + "304": 23859, + "bwv": 23860, + "glamorgan": 23861, + "insults": 23862, + "agatha": 23863, + "fey": 23864, + "##cend": 23865, + "fleetwood": 23866, + "mahogany": 23867, + "protruding": 23868, + "steamship": 23869, + "zeta": 23870, + "##arty": 23871, + "mcguire": 23872, + "suspense": 23873, + "##sphere": 23874, + "advising": 23875, + "urges": 23876, + "##wala": 23877, + "hurriedly": 23878, + "meteor": 23879, + "gilded": 23880, + "inline": 23881, + "arroyo": 23882, + "stalker": 23883, + "##oge": 23884, + "excitedly": 23885, + "revered": 23886, + "##cure": 23887, + "earle": 23888, + "introductory": 23889, + "##break": 23890, + "##ilde": 23891, + "mutants": 23892, + "puff": 23893, + "pulses": 23894, + "reinforcement": 23895, + "##haling": 23896, + "curses": 23897, + "lizards": 23898, + "stalk": 23899, + "correlated": 23900, + "##fixed": 23901, + "fallout": 23902, + "macquarie": 23903, + "##unas": 23904, + "bearded": 23905, + "denton": 23906, + "heaving": 23907, + "802": 23908, + "##ocation": 23909, + "winery": 23910, + "assign": 23911, + "dortmund": 23912, + "##lkirk": 23913, + "everest": 23914, + "invariant": 23915, + "charismatic": 23916, + "susie": 23917, + "##elling": 23918, + "bled": 23919, + "lesley": 23920, + "telegram": 23921, + "sumner": 23922, + "bk": 23923, + "##ogen": 23924, + "##к": 23925, + "wilcox": 23926, + "needy": 23927, + "colbert": 23928, + "duval": 23929, + "##iferous": 23930, + "##mbled": 23931, + "allotted": 23932, + "attends": 23933, + "imperative": 23934, + "##hita": 23935, + "replacements": 23936, + "hawker": 23937, + "##inda": 23938, + "insurgency": 23939, + "##zee": 23940, + "##eke": 23941, + "casts": 23942, + "##yla": 23943, + "680": 23944, + "ives": 23945, + "transitioned": 23946, + "##pack": 23947, + "##powering": 23948, + "authoritative": 23949, + "baylor": 23950, + "flex": 23951, + "cringed": 23952, + "plaintiffs": 23953, + "woodrow": 23954, + "##skie": 23955, + "drastic": 23956, + "ape": 23957, + "aroma": 23958, + "unfolded": 23959, + "commotion": 23960, + "nt": 23961, + "preoccupied": 23962, + "theta": 23963, + "routines": 23964, + "lasers": 23965, + "privatization": 23966, + "wand": 23967, + "domino": 23968, + "ek": 23969, + "clenching": 23970, + "nsa": 23971, + "strategically": 23972, + "showered": 23973, + "bile": 23974, + "handkerchief": 23975, + "pere": 23976, + "storing": 23977, + "christophe": 23978, + "insulting": 23979, + "316": 23980, + "nakamura": 23981, + "romani": 23982, + "asiatic": 23983, + "magdalena": 23984, + "palma": 23985, + "cruises": 23986, + "stripping": 23987, + "405": 23988, + "konstantin": 23989, + "soaring": 23990, + "##berman": 23991, + "colloquially": 23992, + "forerunner": 23993, + "havilland": 23994, + "incarcerated": 23995, + "parasites": 23996, + "sincerity": 23997, + "##utus": 23998, + "disks": 23999, + "plank": 24000, + "saigon": 24001, + "##ining": 24002, + "corbin": 24003, + "homo": 24004, + "ornaments": 24005, + "powerhouse": 24006, + "##tlement": 24007, + "chong": 24008, + "fastened": 24009, + "feasibility": 24010, + "idf": 24011, + "morphological": 24012, + "usable": 24013, + "##nish": 24014, + "##zuki": 24015, + "aqueduct": 24016, + "jaguars": 24017, + "keepers": 24018, + "##flies": 24019, + "aleksandr": 24020, + "faust": 24021, + "assigns": 24022, + "ewing": 24023, + "bacterium": 24024, + "hurled": 24025, + "tricky": 24026, + "hungarians": 24027, + "integers": 24028, + "wallis": 24029, + "321": 24030, + "yamaha": 24031, + "##isha": 24032, + "hushed": 24033, + "oblivion": 24034, + "aviator": 24035, + "evangelist": 24036, + "friars": 24037, + "##eller": 24038, + "monograph": 24039, + "ode": 24040, + "##nary": 24041, + "airplanes": 24042, + "labourers": 24043, + "charms": 24044, + "##nee": 24045, + "1661": 24046, + "hagen": 24047, + "tnt": 24048, + "rudder": 24049, + "fiesta": 24050, + "transcript": 24051, + "dorothea": 24052, + "ska": 24053, + "inhibitor": 24054, + "maccabi": 24055, + "retorted": 24056, + "raining": 24057, + "encompassed": 24058, + "clauses": 24059, + "menacing": 24060, + "1642": 24061, + "lineman": 24062, + "##gist": 24063, + "vamps": 24064, + "##ape": 24065, + "##dick": 24066, + "gloom": 24067, + "##rera": 24068, + "dealings": 24069, + "easing": 24070, + "seekers": 24071, + "##nut": 24072, + "##pment": 24073, + "helens": 24074, + "unmanned": 24075, + "##anu": 24076, + "##isson": 24077, + "basics": 24078, + "##amy": 24079, + "##ckman": 24080, + "adjustments": 24081, + "1688": 24082, + "brutality": 24083, + "horne": 24084, + "##zell": 24085, + "sui": 24086, + "##55": 24087, + "##mable": 24088, + "aggregator": 24089, + "##thal": 24090, + "rhino": 24091, + "##drick": 24092, + "##vira": 24093, + "counters": 24094, + "zoom": 24095, + "##01": 24096, + "##rting": 24097, + "mn": 24098, + "montenegrin": 24099, + "packard": 24100, + "##unciation": 24101, + "##♭": 24102, + "##kki": 24103, + "reclaim": 24104, + "scholastic": 24105, + "thugs": 24106, + "pulsed": 24107, + "##icia": 24108, + "syriac": 24109, + "quan": 24110, + "saddam": 24111, + "banda": 24112, + "kobe": 24113, + "blaming": 24114, + "buddies": 24115, + "dissent": 24116, + "##lusion": 24117, + "##usia": 24118, + "corbett": 24119, + "jaya": 24120, + "delle": 24121, + "erratic": 24122, + "lexie": 24123, + "##hesis": 24124, + "435": 24125, + "amiga": 24126, + "hermes": 24127, + "##pressing": 24128, + "##leen": 24129, + "chapels": 24130, + "gospels": 24131, + "jamal": 24132, + "##uating": 24133, + "compute": 24134, + "revolving": 24135, + "warp": 24136, + "##sso": 24137, + "##thes": 24138, + "armory": 24139, + "##eras": 24140, + "##gol": 24141, + "antrim": 24142, + "loki": 24143, + "##kow": 24144, + "##asian": 24145, + "##good": 24146, + "##zano": 24147, + "braid": 24148, + "handwriting": 24149, + "subdistrict": 24150, + "funky": 24151, + "pantheon": 24152, + "##iculate": 24153, + "concurrency": 24154, + "estimation": 24155, + "improper": 24156, + "juliana": 24157, + "##his": 24158, + "newcomers": 24159, + "johnstone": 24160, + "staten": 24161, + "communicated": 24162, + "##oco": 24163, + "##alle": 24164, + "sausage": 24165, + "stormy": 24166, + "##stered": 24167, + "##tters": 24168, + "superfamily": 24169, + "##grade": 24170, + "acidic": 24171, + "collateral": 24172, + "tabloid": 24173, + "##oped": 24174, + "##rza": 24175, + "bladder": 24176, + "austen": 24177, + "##ellant": 24178, + "mcgraw": 24179, + "##hay": 24180, + "hannibal": 24181, + "mein": 24182, + "aquino": 24183, + "lucifer": 24184, + "wo": 24185, + "badger": 24186, + "boar": 24187, + "cher": 24188, + "christensen": 24189, + "greenberg": 24190, + "interruption": 24191, + "##kken": 24192, + "jem": 24193, + "244": 24194, + "mocked": 24195, + "bottoms": 24196, + "cambridgeshire": 24197, + "##lide": 24198, + "sprawling": 24199, + "##bbly": 24200, + "eastwood": 24201, + "ghent": 24202, + "synth": 24203, + "##buck": 24204, + "advisers": 24205, + "##bah": 24206, + "nominally": 24207, + "hapoel": 24208, + "qu": 24209, + "daggers": 24210, + "estranged": 24211, + "fabricated": 24212, + "towels": 24213, + "vinnie": 24214, + "wcw": 24215, + "misunderstanding": 24216, + "anglia": 24217, + "nothin": 24218, + "unmistakable": 24219, + "##dust": 24220, + "##lova": 24221, + "chilly": 24222, + "marquette": 24223, + "truss": 24224, + "##edge": 24225, + "##erine": 24226, + "reece": 24227, + "##lty": 24228, + "##chemist": 24229, + "##connected": 24230, + "272": 24231, + "308": 24232, + "41st": 24233, + "bash": 24234, + "raion": 24235, + "waterfalls": 24236, + "##ump": 24237, + "##main": 24238, + "labyrinth": 24239, + "queue": 24240, + "theorist": 24241, + "##istle": 24242, + "bharatiya": 24243, + "flexed": 24244, + "soundtracks": 24245, + "rooney": 24246, + "leftist": 24247, + "patrolling": 24248, + "wharton": 24249, + "plainly": 24250, + "alleviate": 24251, + "eastman": 24252, + "schuster": 24253, + "topographic": 24254, + "engages": 24255, + "immensely": 24256, + "unbearable": 24257, + "fairchild": 24258, + "1620": 24259, + "dona": 24260, + "lurking": 24261, + "parisian": 24262, + "oliveira": 24263, + "ia": 24264, + "indictment": 24265, + "hahn": 24266, + "bangladeshi": 24267, + "##aster": 24268, + "vivo": 24269, + "##uming": 24270, + "##ential": 24271, + "antonia": 24272, + "expects": 24273, + "indoors": 24274, + "kildare": 24275, + "harlan": 24276, + "##logue": 24277, + "##ogenic": 24278, + "##sities": 24279, + "forgiven": 24280, + "##wat": 24281, + "childish": 24282, + "tavi": 24283, + "##mide": 24284, + "##orra": 24285, + "plausible": 24286, + "grimm": 24287, + "successively": 24288, + "scooted": 24289, + "##bola": 24290, + "##dget": 24291, + "##rith": 24292, + "spartans": 24293, + "emery": 24294, + "flatly": 24295, + "azure": 24296, + "epilogue": 24297, + "##wark": 24298, + "flourish": 24299, + "##iny": 24300, + "##tracted": 24301, + "##overs": 24302, + "##oshi": 24303, + "bestseller": 24304, + "distressed": 24305, + "receipt": 24306, + "spitting": 24307, + "hermit": 24308, + "topological": 24309, + "##cot": 24310, + "drilled": 24311, + "subunit": 24312, + "francs": 24313, + "##layer": 24314, + "eel": 24315, + "##fk": 24316, + "##itas": 24317, + "octopus": 24318, + "footprint": 24319, + "petitions": 24320, + "ufo": 24321, + "##say": 24322, + "##foil": 24323, + "interfering": 24324, + "leaking": 24325, + "palo": 24326, + "##metry": 24327, + "thistle": 24328, + "valiant": 24329, + "##pic": 24330, + "narayan": 24331, + "mcpherson": 24332, + "##fast": 24333, + "gonzales": 24334, + "##ym": 24335, + "##enne": 24336, + "dustin": 24337, + "novgorod": 24338, + "solos": 24339, + "##zman": 24340, + "doin": 24341, + "##raph": 24342, + "##patient": 24343, + "##meyer": 24344, + "soluble": 24345, + "ashland": 24346, + "cuffs": 24347, + "carole": 24348, + "pendleton": 24349, + "whistling": 24350, + "vassal": 24351, + "##river": 24352, + "deviation": 24353, + "revisited": 24354, + "constituents": 24355, + "rallied": 24356, + "rotate": 24357, + "loomed": 24358, + "##eil": 24359, + "##nting": 24360, + "amateurs": 24361, + "augsburg": 24362, + "auschwitz": 24363, + "crowns": 24364, + "skeletons": 24365, + "##cona": 24366, + "bonnet": 24367, + "257": 24368, + "dummy": 24369, + "globalization": 24370, + "simeon": 24371, + "sleeper": 24372, + "mandal": 24373, + "differentiated": 24374, + "##crow": 24375, + "##mare": 24376, + "milne": 24377, + "bundled": 24378, + "exasperated": 24379, + "talmud": 24380, + "owes": 24381, + "segregated": 24382, + "##feng": 24383, + "##uary": 24384, + "dentist": 24385, + "piracy": 24386, + "props": 24387, + "##rang": 24388, + "devlin": 24389, + "##torium": 24390, + "malicious": 24391, + "paws": 24392, + "##laid": 24393, + "dependency": 24394, + "##ergy": 24395, + "##fers": 24396, + "##enna": 24397, + "258": 24398, + "pistons": 24399, + "rourke": 24400, + "jed": 24401, + "grammatical": 24402, + "tres": 24403, + "maha": 24404, + "wig": 24405, + "512": 24406, + "ghostly": 24407, + "jayne": 24408, + "##achal": 24409, + "##creen": 24410, + "##ilis": 24411, + "##lins": 24412, + "##rence": 24413, + "designate": 24414, + "##with": 24415, + "arrogance": 24416, + "cambodian": 24417, + "clones": 24418, + "showdown": 24419, + "throttle": 24420, + "twain": 24421, + "##ception": 24422, + "lobes": 24423, + "metz": 24424, + "nagoya": 24425, + "335": 24426, + "braking": 24427, + "##furt": 24428, + "385": 24429, + "roaming": 24430, + "##minster": 24431, + "amin": 24432, + "crippled": 24433, + "##37": 24434, + "##llary": 24435, + "indifferent": 24436, + "hoffmann": 24437, + "idols": 24438, + "intimidating": 24439, + "1751": 24440, + "261": 24441, + "influenza": 24442, + "memo": 24443, + "onions": 24444, + "1748": 24445, + "bandage": 24446, + "consciously": 24447, + "##landa": 24448, + "##rage": 24449, + "clandestine": 24450, + "observes": 24451, + "swiped": 24452, + "tangle": 24453, + "##ener": 24454, + "##jected": 24455, + "##trum": 24456, + "##bill": 24457, + "##lta": 24458, + "hugs": 24459, + "congresses": 24460, + "josiah": 24461, + "spirited": 24462, + "##dek": 24463, + "humanist": 24464, + "managerial": 24465, + "filmmaking": 24466, + "inmate": 24467, + "rhymes": 24468, + "debuting": 24469, + "grimsby": 24470, + "ur": 24471, + "##laze": 24472, + "duplicate": 24473, + "vigor": 24474, + "##tf": 24475, + "republished": 24476, + "bolshevik": 24477, + "refurbishment": 24478, + "antibiotics": 24479, + "martini": 24480, + "methane": 24481, + "newscasts": 24482, + "royale": 24483, + "horizons": 24484, + "levant": 24485, + "iain": 24486, + "visas": 24487, + "##ischen": 24488, + "paler": 24489, + "##around": 24490, + "manifestation": 24491, + "snuck": 24492, + "alf": 24493, + "chop": 24494, + "futile": 24495, + "pedestal": 24496, + "rehab": 24497, + "##kat": 24498, + "bmg": 24499, + "kerman": 24500, + "res": 24501, + "fairbanks": 24502, + "jarrett": 24503, + "abstraction": 24504, + "saharan": 24505, + "##zek": 24506, + "1746": 24507, + "procedural": 24508, + "clearer": 24509, + "kincaid": 24510, + "sash": 24511, + "luciano": 24512, + "##ffey": 24513, + "crunch": 24514, + "helmut": 24515, + "##vara": 24516, + "revolutionaries": 24517, + "##tute": 24518, + "creamy": 24519, + "leach": 24520, + "##mmon": 24521, + "1747": 24522, + "permitting": 24523, + "nes": 24524, + "plight": 24525, + "wendell": 24526, + "##lese": 24527, + "contra": 24528, + "ts": 24529, + "clancy": 24530, + "ipa": 24531, + "mach": 24532, + "staples": 24533, + "autopsy": 24534, + "disturbances": 24535, + "nueva": 24536, + "karin": 24537, + "pontiac": 24538, + "##uding": 24539, + "proxy": 24540, + "venerable": 24541, + "haunt": 24542, + "leto": 24543, + "bergman": 24544, + "expands": 24545, + "##helm": 24546, + "wal": 24547, + "##pipe": 24548, + "canning": 24549, + "celine": 24550, + "cords": 24551, + "obesity": 24552, + "##enary": 24553, + "intrusion": 24554, + "planner": 24555, + "##phate": 24556, + "reasoned": 24557, + "sequencing": 24558, + "307": 24559, + "harrow": 24560, + "##chon": 24561, + "##dora": 24562, + "marred": 24563, + "mcintyre": 24564, + "repay": 24565, + "tarzan": 24566, + "darting": 24567, + "248": 24568, + "harrisburg": 24569, + "margarita": 24570, + "repulsed": 24571, + "##hur": 24572, + "##lding": 24573, + "belinda": 24574, + "hamburger": 24575, + "novo": 24576, + "compliant": 24577, + "runways": 24578, + "bingham": 24579, + "registrar": 24580, + "skyscraper": 24581, + "ic": 24582, + "cuthbert": 24583, + "improvisation": 24584, + "livelihood": 24585, + "##corp": 24586, + "##elial": 24587, + "admiring": 24588, + "##dened": 24589, + "sporadic": 24590, + "believer": 24591, + "casablanca": 24592, + "popcorn": 24593, + "##29": 24594, + "asha": 24595, + "shovel": 24596, + "##bek": 24597, + "##dice": 24598, + "coiled": 24599, + "tangible": 24600, + "##dez": 24601, + "casper": 24602, + "elsie": 24603, + "resin": 24604, + "tenderness": 24605, + "rectory": 24606, + "##ivision": 24607, + "avail": 24608, + "sonar": 24609, + "##mori": 24610, + "boutique": 24611, + "##dier": 24612, + "guerre": 24613, + "bathed": 24614, + "upbringing": 24615, + "vaulted": 24616, + "sandals": 24617, + "blessings": 24618, + "##naut": 24619, + "##utnant": 24620, + "1680": 24621, + "306": 24622, + "foxes": 24623, + "pia": 24624, + "corrosion": 24625, + "hesitantly": 24626, + "confederates": 24627, + "crystalline": 24628, + "footprints": 24629, + "shapiro": 24630, + "tirana": 24631, + "valentin": 24632, + "drones": 24633, + "45th": 24634, + "microscope": 24635, + "shipments": 24636, + "texted": 24637, + "inquisition": 24638, + "wry": 24639, + "guernsey": 24640, + "unauthorized": 24641, + "resigning": 24642, + "760": 24643, + "ripple": 24644, + "schubert": 24645, + "stu": 24646, + "reassure": 24647, + "felony": 24648, + "##ardo": 24649, + "brittle": 24650, + "koreans": 24651, + "##havan": 24652, + "##ives": 24653, + "dun": 24654, + "implicit": 24655, + "tyres": 24656, + "##aldi": 24657, + "##lth": 24658, + "magnolia": 24659, + "##ehan": 24660, + "##puri": 24661, + "##poulos": 24662, + "aggressively": 24663, + "fei": 24664, + "gr": 24665, + "familiarity": 24666, + "##poo": 24667, + "indicative": 24668, + "##trust": 24669, + "fundamentally": 24670, + "jimmie": 24671, + "overrun": 24672, + "395": 24673, + "anchors": 24674, + "moans": 24675, + "##opus": 24676, + "britannia": 24677, + "armagh": 24678, + "##ggle": 24679, + "purposely": 24680, + "seizing": 24681, + "##vao": 24682, + "bewildered": 24683, + "mundane": 24684, + "avoidance": 24685, + "cosmopolitan": 24686, + "geometridae": 24687, + "quartermaster": 24688, + "caf": 24689, + "415": 24690, + "chatter": 24691, + "engulfed": 24692, + "gleam": 24693, + "purge": 24694, + "##icate": 24695, + "juliette": 24696, + "jurisprudence": 24697, + "guerra": 24698, + "revisions": 24699, + "##bn": 24700, + "casimir": 24701, + "brew": 24702, + "##jm": 24703, + "1749": 24704, + "clapton": 24705, + "cloudy": 24706, + "conde": 24707, + "hermitage": 24708, + "278": 24709, + "simulations": 24710, + "torches": 24711, + "vincenzo": 24712, + "matteo": 24713, + "##rill": 24714, + "hidalgo": 24715, + "booming": 24716, + "westbound": 24717, + "accomplishment": 24718, + "tentacles": 24719, + "unaffected": 24720, + "##sius": 24721, + "annabelle": 24722, + "flopped": 24723, + "sloping": 24724, + "##litz": 24725, + "dreamer": 24726, + "interceptor": 24727, + "vu": 24728, + "##loh": 24729, + "consecration": 24730, + "copying": 24731, + "messaging": 24732, + "breaker": 24733, + "climates": 24734, + "hospitalized": 24735, + "1752": 24736, + "torino": 24737, + "afternoons": 24738, + "winfield": 24739, + "witnessing": 24740, + "##teacher": 24741, + "breakers": 24742, + "choirs": 24743, + "sawmill": 24744, + "coldly": 24745, + "##ege": 24746, + "sipping": 24747, + "haste": 24748, + "uninhabited": 24749, + "conical": 24750, + "bibliography": 24751, + "pamphlets": 24752, + "severn": 24753, + "edict": 24754, + "##oca": 24755, + "deux": 24756, + "illnesses": 24757, + "grips": 24758, + "##pl": 24759, + "rehearsals": 24760, + "sis": 24761, + "thinkers": 24762, + "tame": 24763, + "##keepers": 24764, + "1690": 24765, + "acacia": 24766, + "reformer": 24767, + "##osed": 24768, + "##rys": 24769, + "shuffling": 24770, + "##iring": 24771, + "##shima": 24772, + "eastbound": 24773, + "ionic": 24774, + "rhea": 24775, + "flees": 24776, + "littered": 24777, + "##oum": 24778, + "rocker": 24779, + "vomiting": 24780, + "groaning": 24781, + "champ": 24782, + "overwhelmingly": 24783, + "civilizations": 24784, + "paces": 24785, + "sloop": 24786, + "adoptive": 24787, + "##tish": 24788, + "skaters": 24789, + "##vres": 24790, + "aiding": 24791, + "mango": 24792, + "##joy": 24793, + "nikola": 24794, + "shriek": 24795, + "##ignon": 24796, + "pharmaceuticals": 24797, + "##mg": 24798, + "tuna": 24799, + "calvert": 24800, + "gustavo": 24801, + "stocked": 24802, + "yearbook": 24803, + "##urai": 24804, + "##mana": 24805, + "computed": 24806, + "subsp": 24807, + "riff": 24808, + "hanoi": 24809, + "kelvin": 24810, + "hamid": 24811, + "moors": 24812, + "pastures": 24813, + "summons": 24814, + "jihad": 24815, + "nectar": 24816, + "##ctors": 24817, + "bayou": 24818, + "untitled": 24819, + "pleasing": 24820, + "vastly": 24821, + "republics": 24822, + "intellect": 24823, + "##η": 24824, + "##ulio": 24825, + "##tou": 24826, + "crumbling": 24827, + "stylistic": 24828, + "sb": 24829, + "##ی": 24830, + "consolation": 24831, + "frequented": 24832, + "h₂o": 24833, + "walden": 24834, + "widows": 24835, + "##iens": 24836, + "404": 24837, + "##ignment": 24838, + "chunks": 24839, + "improves": 24840, + "288": 24841, + "grit": 24842, + "recited": 24843, + "##dev": 24844, + "snarl": 24845, + "sociological": 24846, + "##arte": 24847, + "##gul": 24848, + "inquired": 24849, + "##held": 24850, + "bruise": 24851, + "clube": 24852, + "consultancy": 24853, + "homogeneous": 24854, + "hornets": 24855, + "multiplication": 24856, + "pasta": 24857, + "prick": 24858, + "savior": 24859, + "##grin": 24860, + "##kou": 24861, + "##phile": 24862, + "yoon": 24863, + "##gara": 24864, + "grimes": 24865, + "vanishing": 24866, + "cheering": 24867, + "reacting": 24868, + "bn": 24869, + "distillery": 24870, + "##quisite": 24871, + "##vity": 24872, + "coe": 24873, + "dockyard": 24874, + "massif": 24875, + "##jord": 24876, + "escorts": 24877, + "voss": 24878, + "##valent": 24879, + "byte": 24880, + "chopped": 24881, + "hawke": 24882, + "illusions": 24883, + "workings": 24884, + "floats": 24885, + "##koto": 24886, + "##vac": 24887, + "kv": 24888, + "annapolis": 24889, + "madden": 24890, + "##onus": 24891, + "alvaro": 24892, + "noctuidae": 24893, + "##cum": 24894, + "##scopic": 24895, + "avenge": 24896, + "steamboat": 24897, + "forte": 24898, + "illustrates": 24899, + "erika": 24900, + "##trip": 24901, + "570": 24902, + "dew": 24903, + "nationalities": 24904, + "bran": 24905, + "manifested": 24906, + "thirsty": 24907, + "diversified": 24908, + "muscled": 24909, + "reborn": 24910, + "##standing": 24911, + "arson": 24912, + "##lessness": 24913, + "##dran": 24914, + "##logram": 24915, + "##boys": 24916, + "##kushima": 24917, + "##vious": 24918, + "willoughby": 24919, + "##phobia": 24920, + "286": 24921, + "alsace": 24922, + "dashboard": 24923, + "yuki": 24924, + "##chai": 24925, + "granville": 24926, + "myspace": 24927, + "publicized": 24928, + "tricked": 24929, + "##gang": 24930, + "adjective": 24931, + "##ater": 24932, + "relic": 24933, + "reorganisation": 24934, + "enthusiastically": 24935, + "indications": 24936, + "saxe": 24937, + "##lassified": 24938, + "consolidate": 24939, + "iec": 24940, + "padua": 24941, + "helplessly": 24942, + "ramps": 24943, + "renaming": 24944, + "regulars": 24945, + "pedestrians": 24946, + "accents": 24947, + "convicts": 24948, + "inaccurate": 24949, + "lowers": 24950, + "mana": 24951, + "##pati": 24952, + "barrie": 24953, + "bjp": 24954, + "outta": 24955, + "someplace": 24956, + "berwick": 24957, + "flanking": 24958, + "invoked": 24959, + "marrow": 24960, + "sparsely": 24961, + "excerpts": 24962, + "clothed": 24963, + "rei": 24964, + "##ginal": 24965, + "wept": 24966, + "##straße": 24967, + "##vish": 24968, + "alexa": 24969, + "excel": 24970, + "##ptive": 24971, + "membranes": 24972, + "aquitaine": 24973, + "creeks": 24974, + "cutler": 24975, + "sheppard": 24976, + "implementations": 24977, + "ns": 24978, + "##dur": 24979, + "fragrance": 24980, + "budge": 24981, + "concordia": 24982, + "magnesium": 24983, + "marcelo": 24984, + "##antes": 24985, + "gladly": 24986, + "vibrating": 24987, + "##rral": 24988, + "##ggles": 24989, + "montrose": 24990, + "##omba": 24991, + "lew": 24992, + "seamus": 24993, + "1630": 24994, + "cocky": 24995, + "##ament": 24996, + "##uen": 24997, + "bjorn": 24998, + "##rrick": 24999, + "fielder": 25000, + "fluttering": 25001, + "##lase": 25002, + "methyl": 25003, + "kimberley": 25004, + "mcdowell": 25005, + "reductions": 25006, + "barbed": 25007, + "##jic": 25008, + "##tonic": 25009, + "aeronautical": 25010, + "condensed": 25011, + "distracting": 25012, + "##promising": 25013, + "huffed": 25014, + "##cala": 25015, + "##sle": 25016, + "claudius": 25017, + "invincible": 25018, + "missy": 25019, + "pious": 25020, + "balthazar": 25021, + "ci": 25022, + "##lang": 25023, + "butte": 25024, + "combo": 25025, + "orson": 25026, + "##dication": 25027, + "myriad": 25028, + "1707": 25029, + "silenced": 25030, + "##fed": 25031, + "##rh": 25032, + "coco": 25033, + "netball": 25034, + "yourselves": 25035, + "##oza": 25036, + "clarify": 25037, + "heller": 25038, + "peg": 25039, + "durban": 25040, + "etudes": 25041, + "offender": 25042, + "roast": 25043, + "blackmail": 25044, + "curvature": 25045, + "##woods": 25046, + "vile": 25047, + "309": 25048, + "illicit": 25049, + "suriname": 25050, + "##linson": 25051, + "overture": 25052, + "1685": 25053, + "bubbling": 25054, + "gymnast": 25055, + "tucking": 25056, + "##mming": 25057, + "##ouin": 25058, + "maldives": 25059, + "##bala": 25060, + "gurney": 25061, + "##dda": 25062, + "##eased": 25063, + "##oides": 25064, + "backside": 25065, + "pinto": 25066, + "jars": 25067, + "racehorse": 25068, + "tending": 25069, + "##rdial": 25070, + "baronetcy": 25071, + "wiener": 25072, + "duly": 25073, + "##rke": 25074, + "barbarian": 25075, + "cupping": 25076, + "flawed": 25077, + "##thesis": 25078, + "bertha": 25079, + "pleistocene": 25080, + "puddle": 25081, + "swearing": 25082, + "##nob": 25083, + "##tically": 25084, + "fleeting": 25085, + "prostate": 25086, + "amulet": 25087, + "educating": 25088, + "##mined": 25089, + "##iti": 25090, + "##tler": 25091, + "75th": 25092, + "jens": 25093, + "respondents": 25094, + "analytics": 25095, + "cavaliers": 25096, + "papacy": 25097, + "raju": 25098, + "##iente": 25099, + "##ulum": 25100, + "##tip": 25101, + "funnel": 25102, + "271": 25103, + "disneyland": 25104, + "##lley": 25105, + "sociologist": 25106, + "##iam": 25107, + "2500": 25108, + "faulkner": 25109, + "louvre": 25110, + "menon": 25111, + "##dson": 25112, + "276": 25113, + "##ower": 25114, + "afterlife": 25115, + "mannheim": 25116, + "peptide": 25117, + "referees": 25118, + "comedians": 25119, + "meaningless": 25120, + "##anger": 25121, + "##laise": 25122, + "fabrics": 25123, + "hurley": 25124, + "renal": 25125, + "sleeps": 25126, + "##bour": 25127, + "##icle": 25128, + "breakout": 25129, + "kristin": 25130, + "roadside": 25131, + "animator": 25132, + "clover": 25133, + "disdain": 25134, + "unsafe": 25135, + "redesign": 25136, + "##urity": 25137, + "firth": 25138, + "barnsley": 25139, + "portage": 25140, + "reset": 25141, + "narrows": 25142, + "268": 25143, + "commandos": 25144, + "expansive": 25145, + "speechless": 25146, + "tubular": 25147, + "##lux": 25148, + "essendon": 25149, + "eyelashes": 25150, + "smashwords": 25151, + "##yad": 25152, + "##bang": 25153, + "##claim": 25154, + "craved": 25155, + "sprinted": 25156, + "chet": 25157, + "somme": 25158, + "astor": 25159, + "wrocław": 25160, + "orton": 25161, + "266": 25162, + "bane": 25163, + "##erving": 25164, + "##uing": 25165, + "mischief": 25166, + "##amps": 25167, + "##sund": 25168, + "scaling": 25169, + "terre": 25170, + "##xious": 25171, + "impairment": 25172, + "offenses": 25173, + "undermine": 25174, + "moi": 25175, + "soy": 25176, + "contiguous": 25177, + "arcadia": 25178, + "inuit": 25179, + "seam": 25180, + "##tops": 25181, + "macbeth": 25182, + "rebelled": 25183, + "##icative": 25184, + "##iot": 25185, + "590": 25186, + "elaborated": 25187, + "frs": 25188, + "uniformed": 25189, + "##dberg": 25190, + "259": 25191, + "powerless": 25192, + "priscilla": 25193, + "stimulated": 25194, + "980": 25195, + "qc": 25196, + "arboretum": 25197, + "frustrating": 25198, + "trieste": 25199, + "bullock": 25200, + "##nified": 25201, + "enriched": 25202, + "glistening": 25203, + "intern": 25204, + "##adia": 25205, + "locus": 25206, + "nouvelle": 25207, + "ollie": 25208, + "ike": 25209, + "lash": 25210, + "starboard": 25211, + "ee": 25212, + "tapestry": 25213, + "headlined": 25214, + "hove": 25215, + "rigged": 25216, + "##vite": 25217, + "pollock": 25218, + "##yme": 25219, + "thrive": 25220, + "clustered": 25221, + "cas": 25222, + "roi": 25223, + "gleamed": 25224, + "olympiad": 25225, + "##lino": 25226, + "pressured": 25227, + "regimes": 25228, + "##hosis": 25229, + "##lick": 25230, + "ripley": 25231, + "##ophone": 25232, + "kickoff": 25233, + "gallon": 25234, + "rockwell": 25235, + "##arable": 25236, + "crusader": 25237, + "glue": 25238, + "revolutions": 25239, + "scrambling": 25240, + "1714": 25241, + "grover": 25242, + "##jure": 25243, + "englishman": 25244, + "aztec": 25245, + "263": 25246, + "contemplating": 25247, + "coven": 25248, + "ipad": 25249, + "preach": 25250, + "triumphant": 25251, + "tufts": 25252, + "##esian": 25253, + "rotational": 25254, + "##phus": 25255, + "328": 25256, + "falkland": 25257, + "##brates": 25258, + "strewn": 25259, + "clarissa": 25260, + "rejoin": 25261, + "environmentally": 25262, + "glint": 25263, + "banded": 25264, + "drenched": 25265, + "moat": 25266, + "albanians": 25267, + "johor": 25268, + "rr": 25269, + "maestro": 25270, + "malley": 25271, + "nouveau": 25272, + "shaded": 25273, + "taxonomy": 25274, + "v6": 25275, + "adhere": 25276, + "bunk": 25277, + "airfields": 25278, + "##ritan": 25279, + "1741": 25280, + "encompass": 25281, + "remington": 25282, + "tran": 25283, + "##erative": 25284, + "amelie": 25285, + "mazda": 25286, + "friar": 25287, + "morals": 25288, + "passions": 25289, + "##zai": 25290, + "breadth": 25291, + "vis": 25292, + "##hae": 25293, + "argus": 25294, + "burnham": 25295, + "caressing": 25296, + "insider": 25297, + "rudd": 25298, + "##imov": 25299, + "##mini": 25300, + "##rso": 25301, + "italianate": 25302, + "murderous": 25303, + "textual": 25304, + "wainwright": 25305, + "armada": 25306, + "bam": 25307, + "weave": 25308, + "timer": 25309, + "##taken": 25310, + "##nh": 25311, + "fra": 25312, + "##crest": 25313, + "ardent": 25314, + "salazar": 25315, + "taps": 25316, + "tunis": 25317, + "##ntino": 25318, + "allegro": 25319, + "gland": 25320, + "philanthropic": 25321, + "##chester": 25322, + "implication": 25323, + "##optera": 25324, + "esq": 25325, + "judas": 25326, + "noticeably": 25327, + "wynn": 25328, + "##dara": 25329, + "inched": 25330, + "indexed": 25331, + "crises": 25332, + "villiers": 25333, + "bandit": 25334, + "royalties": 25335, + "patterned": 25336, + "cupboard": 25337, + "interspersed": 25338, + "accessory": 25339, + "isla": 25340, + "kendrick": 25341, + "entourage": 25342, + "stitches": 25343, + "##esthesia": 25344, + "headwaters": 25345, + "##ior": 25346, + "interlude": 25347, + "distraught": 25348, + "draught": 25349, + "1727": 25350, + "##basket": 25351, + "biased": 25352, + "sy": 25353, + "transient": 25354, + "triad": 25355, + "subgenus": 25356, + "adapting": 25357, + "kidd": 25358, + "shortstop": 25359, + "##umatic": 25360, + "dimly": 25361, + "spiked": 25362, + "mcleod": 25363, + "reprint": 25364, + "nellie": 25365, + "pretoria": 25366, + "windmill": 25367, + "##cek": 25368, + "singled": 25369, + "##mps": 25370, + "273": 25371, + "reunite": 25372, + "##orous": 25373, + "747": 25374, + "bankers": 25375, + "outlying": 25376, + "##omp": 25377, + "##ports": 25378, + "##tream": 25379, + "apologies": 25380, + "cosmetics": 25381, + "patsy": 25382, + "##deh": 25383, + "##ocks": 25384, + "##yson": 25385, + "bender": 25386, + "nantes": 25387, + "serene": 25388, + "##nad": 25389, + "lucha": 25390, + "mmm": 25391, + "323": 25392, + "##cius": 25393, + "##gli": 25394, + "cmll": 25395, + "coinage": 25396, + "nestor": 25397, + "juarez": 25398, + "##rook": 25399, + "smeared": 25400, + "sprayed": 25401, + "twitching": 25402, + "sterile": 25403, + "irina": 25404, + "embodied": 25405, + "juveniles": 25406, + "enveloped": 25407, + "miscellaneous": 25408, + "cancers": 25409, + "dq": 25410, + "gulped": 25411, + "luisa": 25412, + "crested": 25413, + "swat": 25414, + "donegal": 25415, + "ref": 25416, + "##anov": 25417, + "##acker": 25418, + "hearst": 25419, + "mercantile": 25420, + "##lika": 25421, + "doorbell": 25422, + "ua": 25423, + "vicki": 25424, + "##alla": 25425, + "##som": 25426, + "bilbao": 25427, + "psychologists": 25428, + "stryker": 25429, + "sw": 25430, + "horsemen": 25431, + "turkmenistan": 25432, + "wits": 25433, + "##national": 25434, + "anson": 25435, + "mathew": 25436, + "screenings": 25437, + "##umb": 25438, + "rihanna": 25439, + "##agne": 25440, + "##nessy": 25441, + "aisles": 25442, + "##iani": 25443, + "##osphere": 25444, + "hines": 25445, + "kenton": 25446, + "saskatoon": 25447, + "tasha": 25448, + "truncated": 25449, + "##champ": 25450, + "##itan": 25451, + "mildred": 25452, + "advises": 25453, + "fredrik": 25454, + "interpreting": 25455, + "inhibitors": 25456, + "##athi": 25457, + "spectroscopy": 25458, + "##hab": 25459, + "##kong": 25460, + "karim": 25461, + "panda": 25462, + "##oia": 25463, + "##nail": 25464, + "##vc": 25465, + "conqueror": 25466, + "kgb": 25467, + "leukemia": 25468, + "##dity": 25469, + "arrivals": 25470, + "cheered": 25471, + "pisa": 25472, + "phosphorus": 25473, + "shielded": 25474, + "##riated": 25475, + "mammal": 25476, + "unitarian": 25477, + "urgently": 25478, + "chopin": 25479, + "sanitary": 25480, + "##mission": 25481, + "spicy": 25482, + "drugged": 25483, + "hinges": 25484, + "##tort": 25485, + "tipping": 25486, + "trier": 25487, + "impoverished": 25488, + "westchester": 25489, + "##caster": 25490, + "267": 25491, + "epoch": 25492, + "nonstop": 25493, + "##gman": 25494, + "##khov": 25495, + "aromatic": 25496, + "centrally": 25497, + "cerro": 25498, + "##tively": 25499, + "##vio": 25500, + "billions": 25501, + "modulation": 25502, + "sedimentary": 25503, + "283": 25504, + "facilitating": 25505, + "outrageous": 25506, + "goldstein": 25507, + "##eak": 25508, + "##kt": 25509, + "ld": 25510, + "maitland": 25511, + "penultimate": 25512, + "pollard": 25513, + "##dance": 25514, + "fleets": 25515, + "spaceship": 25516, + "vertebrae": 25517, + "##nig": 25518, + "alcoholism": 25519, + "als": 25520, + "recital": 25521, + "##bham": 25522, + "##ference": 25523, + "##omics": 25524, + "m2": 25525, + "##bm": 25526, + "trois": 25527, + "##tropical": 25528, + "##в": 25529, + "commemorates": 25530, + "##meric": 25531, + "marge": 25532, + "##raction": 25533, + "1643": 25534, + "670": 25535, + "cosmetic": 25536, + "ravaged": 25537, + "##ige": 25538, + "catastrophe": 25539, + "eng": 25540, + "##shida": 25541, + "albrecht": 25542, + "arterial": 25543, + "bellamy": 25544, + "decor": 25545, + "harmon": 25546, + "##rde": 25547, + "bulbs": 25548, + "synchronized": 25549, + "vito": 25550, + "easiest": 25551, + "shetland": 25552, + "shielding": 25553, + "wnba": 25554, + "##glers": 25555, + "##ssar": 25556, + "##riam": 25557, + "brianna": 25558, + "cumbria": 25559, + "##aceous": 25560, + "##rard": 25561, + "cores": 25562, + "thayer": 25563, + "##nsk": 25564, + "brood": 25565, + "hilltop": 25566, + "luminous": 25567, + "carts": 25568, + "keynote": 25569, + "larkin": 25570, + "logos": 25571, + "##cta": 25572, + "##ا": 25573, + "##mund": 25574, + "##quay": 25575, + "lilith": 25576, + "tinted": 25577, + "277": 25578, + "wrestle": 25579, + "mobilization": 25580, + "##uses": 25581, + "sequential": 25582, + "siam": 25583, + "bloomfield": 25584, + "takahashi": 25585, + "274": 25586, + "##ieving": 25587, + "presenters": 25588, + "ringo": 25589, + "blazed": 25590, + "witty": 25591, + "##oven": 25592, + "##ignant": 25593, + "devastation": 25594, + "haydn": 25595, + "harmed": 25596, + "newt": 25597, + "therese": 25598, + "##peed": 25599, + "gershwin": 25600, + "molina": 25601, + "rabbis": 25602, + "sudanese": 25603, + "001": 25604, + "innate": 25605, + "restarted": 25606, + "##sack": 25607, + "##fus": 25608, + "slices": 25609, + "wb": 25610, + "##shah": 25611, + "enroll": 25612, + "hypothetical": 25613, + "hysterical": 25614, + "1743": 25615, + "fabio": 25616, + "indefinite": 25617, + "warped": 25618, + "##hg": 25619, + "exchanging": 25620, + "525": 25621, + "unsuitable": 25622, + "##sboro": 25623, + "gallo": 25624, + "1603": 25625, + "bret": 25626, + "cobalt": 25627, + "homemade": 25628, + "##hunter": 25629, + "mx": 25630, + "operatives": 25631, + "##dhar": 25632, + "terraces": 25633, + "durable": 25634, + "latch": 25635, + "pens": 25636, + "whorls": 25637, + "##ctuated": 25638, + "##eaux": 25639, + "billing": 25640, + "ligament": 25641, + "succumbed": 25642, + "##gly": 25643, + "regulators": 25644, + "spawn": 25645, + "##brick": 25646, + "##stead": 25647, + "filmfare": 25648, + "rochelle": 25649, + "##nzo": 25650, + "1725": 25651, + "circumstance": 25652, + "saber": 25653, + "supplements": 25654, + "##nsky": 25655, + "##tson": 25656, + "crowe": 25657, + "wellesley": 25658, + "carrot": 25659, + "##9th": 25660, + "##movable": 25661, + "primate": 25662, + "drury": 25663, + "sincerely": 25664, + "topical": 25665, + "##mad": 25666, + "##rao": 25667, + "callahan": 25668, + "kyiv": 25669, + "smarter": 25670, + "tits": 25671, + "undo": 25672, + "##yeh": 25673, + "announcements": 25674, + "anthologies": 25675, + "barrio": 25676, + "nebula": 25677, + "##islaus": 25678, + "##shaft": 25679, + "##tyn": 25680, + "bodyguards": 25681, + "2021": 25682, + "assassinate": 25683, + "barns": 25684, + "emmett": 25685, + "scully": 25686, + "##mah": 25687, + "##yd": 25688, + "##eland": 25689, + "##tino": 25690, + "##itarian": 25691, + "demoted": 25692, + "gorman": 25693, + "lashed": 25694, + "prized": 25695, + "adventist": 25696, + "writ": 25697, + "##gui": 25698, + "alla": 25699, + "invertebrates": 25700, + "##ausen": 25701, + "1641": 25702, + "amman": 25703, + "1742": 25704, + "align": 25705, + "healy": 25706, + "redistribution": 25707, + "##gf": 25708, + "##rize": 25709, + "insulation": 25710, + "##drop": 25711, + "adherents": 25712, + "hezbollah": 25713, + "vitro": 25714, + "ferns": 25715, + "yanking": 25716, + "269": 25717, + "php": 25718, + "registering": 25719, + "uppsala": 25720, + "cheerleading": 25721, + "confines": 25722, + "mischievous": 25723, + "tully": 25724, + "##ross": 25725, + "49th": 25726, + "docked": 25727, + "roam": 25728, + "stipulated": 25729, + "pumpkin": 25730, + "##bry": 25731, + "prompt": 25732, + "##ezer": 25733, + "blindly": 25734, + "shuddering": 25735, + "craftsmen": 25736, + "frail": 25737, + "scented": 25738, + "katharine": 25739, + "scramble": 25740, + "shaggy": 25741, + "sponge": 25742, + "helix": 25743, + "zaragoza": 25744, + "279": 25745, + "##52": 25746, + "43rd": 25747, + "backlash": 25748, + "fontaine": 25749, + "seizures": 25750, + "posse": 25751, + "cowan": 25752, + "nonfiction": 25753, + "telenovela": 25754, + "wwii": 25755, + "hammered": 25756, + "undone": 25757, + "##gpur": 25758, + "encircled": 25759, + "irs": 25760, + "##ivation": 25761, + "artefacts": 25762, + "oneself": 25763, + "searing": 25764, + "smallpox": 25765, + "##belle": 25766, + "##osaurus": 25767, + "shandong": 25768, + "breached": 25769, + "upland": 25770, + "blushing": 25771, + "rankin": 25772, + "infinitely": 25773, + "psyche": 25774, + "tolerated": 25775, + "docking": 25776, + "evicted": 25777, + "##col": 25778, + "unmarked": 25779, + "##lving": 25780, + "gnome": 25781, + "lettering": 25782, + "litres": 25783, + "musique": 25784, + "##oint": 25785, + "benevolent": 25786, + "##jal": 25787, + "blackened": 25788, + "##anna": 25789, + "mccall": 25790, + "racers": 25791, + "tingle": 25792, + "##ocene": 25793, + "##orestation": 25794, + "introductions": 25795, + "radically": 25796, + "292": 25797, + "##hiff": 25798, + "##باد": 25799, + "1610": 25800, + "1739": 25801, + "munchen": 25802, + "plead": 25803, + "##nka": 25804, + "condo": 25805, + "scissors": 25806, + "##sight": 25807, + "##tens": 25808, + "apprehension": 25809, + "##cey": 25810, + "##yin": 25811, + "hallmark": 25812, + "watering": 25813, + "formulas": 25814, + "sequels": 25815, + "##llas": 25816, + "aggravated": 25817, + "bae": 25818, + "commencing": 25819, + "##building": 25820, + "enfield": 25821, + "prohibits": 25822, + "marne": 25823, + "vedic": 25824, + "civilized": 25825, + "euclidean": 25826, + "jagger": 25827, + "beforehand": 25828, + "blasts": 25829, + "dumont": 25830, + "##arney": 25831, + "##nem": 25832, + "740": 25833, + "conversions": 25834, + "hierarchical": 25835, + "rios": 25836, + "simulator": 25837, + "##dya": 25838, + "##lellan": 25839, + "hedges": 25840, + "oleg": 25841, + "thrusts": 25842, + "shadowed": 25843, + "darby": 25844, + "maximize": 25845, + "1744": 25846, + "gregorian": 25847, + "##nded": 25848, + "##routed": 25849, + "sham": 25850, + "unspecified": 25851, + "##hog": 25852, + "emory": 25853, + "factual": 25854, + "##smo": 25855, + "##tp": 25856, + "fooled": 25857, + "##rger": 25858, + "ortega": 25859, + "wellness": 25860, + "marlon": 25861, + "##oton": 25862, + "##urance": 25863, + "casket": 25864, + "keating": 25865, + "ley": 25866, + "enclave": 25867, + "##ayan": 25868, + "char": 25869, + "influencing": 25870, + "jia": 25871, + "##chenko": 25872, + "412": 25873, + "ammonia": 25874, + "erebidae": 25875, + "incompatible": 25876, + "violins": 25877, + "cornered": 25878, + "##arat": 25879, + "grooves": 25880, + "astronauts": 25881, + "columbian": 25882, + "rampant": 25883, + "fabrication": 25884, + "kyushu": 25885, + "mahmud": 25886, + "vanish": 25887, + "##dern": 25888, + "mesopotamia": 25889, + "##lete": 25890, + "ict": 25891, + "##rgen": 25892, + "caspian": 25893, + "kenji": 25894, + "pitted": 25895, + "##vered": 25896, + "999": 25897, + "grimace": 25898, + "roanoke": 25899, + "tchaikovsky": 25900, + "twinned": 25901, + "##analysis": 25902, + "##awan": 25903, + "xinjiang": 25904, + "arias": 25905, + "clemson": 25906, + "kazakh": 25907, + "sizable": 25908, + "1662": 25909, + "##khand": 25910, + "##vard": 25911, + "plunge": 25912, + "tatum": 25913, + "vittorio": 25914, + "##nden": 25915, + "cholera": 25916, + "##dana": 25917, + "##oper": 25918, + "bracing": 25919, + "indifference": 25920, + "projectile": 25921, + "superliga": 25922, + "##chee": 25923, + "realises": 25924, + "upgrading": 25925, + "299": 25926, + "porte": 25927, + "retribution": 25928, + "##vies": 25929, + "nk": 25930, + "stil": 25931, + "##resses": 25932, + "ama": 25933, + "bureaucracy": 25934, + "blackberry": 25935, + "bosch": 25936, + "testosterone": 25937, + "collapses": 25938, + "greer": 25939, + "##pathic": 25940, + "ioc": 25941, + "fifties": 25942, + "malls": 25943, + "##erved": 25944, + "bao": 25945, + "baskets": 25946, + "adolescents": 25947, + "siegfried": 25948, + "##osity": 25949, + "##tosis": 25950, + "mantra": 25951, + "detecting": 25952, + "existent": 25953, + "fledgling": 25954, + "##cchi": 25955, + "dissatisfied": 25956, + "gan": 25957, + "telecommunication": 25958, + "mingled": 25959, + "sobbed": 25960, + "6000": 25961, + "controversies": 25962, + "outdated": 25963, + "taxis": 25964, + "##raus": 25965, + "fright": 25966, + "slams": 25967, + "##lham": 25968, + "##fect": 25969, + "##tten": 25970, + "detectors": 25971, + "fetal": 25972, + "tanned": 25973, + "##uw": 25974, + "fray": 25975, + "goth": 25976, + "olympian": 25977, + "skipping": 25978, + "mandates": 25979, + "scratches": 25980, + "sheng": 25981, + "unspoken": 25982, + "hyundai": 25983, + "tracey": 25984, + "hotspur": 25985, + "restrictive": 25986, + "##buch": 25987, + "americana": 25988, + "mundo": 25989, + "##bari": 25990, + "burroughs": 25991, + "diva": 25992, + "vulcan": 25993, + "##6th": 25994, + "distinctions": 25995, + "thumping": 25996, + "##ngen": 25997, + "mikey": 25998, + "sheds": 25999, + "fide": 26000, + "rescues": 26001, + "springsteen": 26002, + "vested": 26003, + "valuation": 26004, + "##ece": 26005, + "##ely": 26006, + "pinnacle": 26007, + "rake": 26008, + "sylvie": 26009, + "##edo": 26010, + "almond": 26011, + "quivering": 26012, + "##irus": 26013, + "alteration": 26014, + "faltered": 26015, + "##wad": 26016, + "51st": 26017, + "hydra": 26018, + "ticked": 26019, + "##kato": 26020, + "recommends": 26021, + "##dicated": 26022, + "antigua": 26023, + "arjun": 26024, + "stagecoach": 26025, + "wilfred": 26026, + "trickle": 26027, + "pronouns": 26028, + "##pon": 26029, + "aryan": 26030, + "nighttime": 26031, + "##anian": 26032, + "gall": 26033, + "pea": 26034, + "stitch": 26035, + "##hei": 26036, + "leung": 26037, + "milos": 26038, + "##dini": 26039, + "eritrea": 26040, + "nexus": 26041, + "starved": 26042, + "snowfall": 26043, + "kant": 26044, + "parasitic": 26045, + "cot": 26046, + "discus": 26047, + "hana": 26048, + "strikers": 26049, + "appleton": 26050, + "kitchens": 26051, + "##erina": 26052, + "##partisan": 26053, + "##itha": 26054, + "##vius": 26055, + "disclose": 26056, + "metis": 26057, + "##channel": 26058, + "1701": 26059, + "tesla": 26060, + "##vera": 26061, + "fitch": 26062, + "1735": 26063, + "blooded": 26064, + "##tila": 26065, + "decimal": 26066, + "##tang": 26067, + "##bai": 26068, + "cyclones": 26069, + "eun": 26070, + "bottled": 26071, + "peas": 26072, + "pensacola": 26073, + "basha": 26074, + "bolivian": 26075, + "crabs": 26076, + "boil": 26077, + "lanterns": 26078, + "partridge": 26079, + "roofed": 26080, + "1645": 26081, + "necks": 26082, + "##phila": 26083, + "opined": 26084, + "patting": 26085, + "##kla": 26086, + "##lland": 26087, + "chuckles": 26088, + "volta": 26089, + "whereupon": 26090, + "##nche": 26091, + "devout": 26092, + "euroleague": 26093, + "suicidal": 26094, + "##dee": 26095, + "inherently": 26096, + "involuntary": 26097, + "knitting": 26098, + "nasser": 26099, + "##hide": 26100, + "puppets": 26101, + "colourful": 26102, + "courageous": 26103, + "southend": 26104, + "stills": 26105, + "miraculous": 26106, + "hodgson": 26107, + "richer": 26108, + "rochdale": 26109, + "ethernet": 26110, + "greta": 26111, + "uniting": 26112, + "prism": 26113, + "umm": 26114, + "##haya": 26115, + "##itical": 26116, + "##utation": 26117, + "deterioration": 26118, + "pointe": 26119, + "prowess": 26120, + "##ropriation": 26121, + "lids": 26122, + "scranton": 26123, + "billings": 26124, + "subcontinent": 26125, + "##koff": 26126, + "##scope": 26127, + "brute": 26128, + "kellogg": 26129, + "psalms": 26130, + "degraded": 26131, + "##vez": 26132, + "stanisław": 26133, + "##ructured": 26134, + "ferreira": 26135, + "pun": 26136, + "astonishing": 26137, + "gunnar": 26138, + "##yat": 26139, + "arya": 26140, + "prc": 26141, + "gottfried": 26142, + "##tight": 26143, + "excursion": 26144, + "##ographer": 26145, + "dina": 26146, + "##quil": 26147, + "##nare": 26148, + "huffington": 26149, + "illustrious": 26150, + "wilbur": 26151, + "gundam": 26152, + "verandah": 26153, + "##zard": 26154, + "naacp": 26155, + "##odle": 26156, + "constructive": 26157, + "fjord": 26158, + "kade": 26159, + "##naud": 26160, + "generosity": 26161, + "thrilling": 26162, + "baseline": 26163, + "cayman": 26164, + "frankish": 26165, + "plastics": 26166, + "accommodations": 26167, + "zoological": 26168, + "##fting": 26169, + "cedric": 26170, + "qb": 26171, + "motorized": 26172, + "##dome": 26173, + "##otted": 26174, + "squealed": 26175, + "tackled": 26176, + "canucks": 26177, + "budgets": 26178, + "situ": 26179, + "asthma": 26180, + "dail": 26181, + "gabled": 26182, + "grasslands": 26183, + "whimpered": 26184, + "writhing": 26185, + "judgments": 26186, + "##65": 26187, + "minnie": 26188, + "pv": 26189, + "##carbon": 26190, + "bananas": 26191, + "grille": 26192, + "domes": 26193, + "monique": 26194, + "odin": 26195, + "maguire": 26196, + "markham": 26197, + "tierney": 26198, + "##estra": 26199, + "##chua": 26200, + "libel": 26201, + "poke": 26202, + "speedy": 26203, + "atrium": 26204, + "laval": 26205, + "notwithstanding": 26206, + "##edly": 26207, + "fai": 26208, + "kala": 26209, + "##sur": 26210, + "robb": 26211, + "##sma": 26212, + "listings": 26213, + "luz": 26214, + "supplementary": 26215, + "tianjin": 26216, + "##acing": 26217, + "enzo": 26218, + "jd": 26219, + "ric": 26220, + "scanner": 26221, + "croats": 26222, + "transcribed": 26223, + "##49": 26224, + "arden": 26225, + "cv": 26226, + "##hair": 26227, + "##raphy": 26228, + "##lver": 26229, + "##uy": 26230, + "357": 26231, + "seventies": 26232, + "staggering": 26233, + "alam": 26234, + "horticultural": 26235, + "hs": 26236, + "regression": 26237, + "timbers": 26238, + "blasting": 26239, + "##ounded": 26240, + "montagu": 26241, + "manipulating": 26242, + "##cit": 26243, + "catalytic": 26244, + "1550": 26245, + "troopers": 26246, + "##meo": 26247, + "condemnation": 26248, + "fitzpatrick": 26249, + "##oire": 26250, + "##roved": 26251, + "inexperienced": 26252, + "1670": 26253, + "castes": 26254, + "##lative": 26255, + "outing": 26256, + "314": 26257, + "dubois": 26258, + "flicking": 26259, + "quarrel": 26260, + "ste": 26261, + "learners": 26262, + "1625": 26263, + "iq": 26264, + "whistled": 26265, + "##class": 26266, + "282": 26267, + "classify": 26268, + "tariffs": 26269, + "temperament": 26270, + "355": 26271, + "folly": 26272, + "liszt": 26273, + "##yles": 26274, + "immersed": 26275, + "jordanian": 26276, + "ceasefire": 26277, + "apparel": 26278, + "extras": 26279, + "maru": 26280, + "fished": 26281, + "##bio": 26282, + "harta": 26283, + "stockport": 26284, + "assortment": 26285, + "craftsman": 26286, + "paralysis": 26287, + "transmitters": 26288, + "##cola": 26289, + "blindness": 26290, + "##wk": 26291, + "fatally": 26292, + "proficiency": 26293, + "solemnly": 26294, + "##orno": 26295, + "repairing": 26296, + "amore": 26297, + "groceries": 26298, + "ultraviolet": 26299, + "##chase": 26300, + "schoolhouse": 26301, + "##tua": 26302, + "resurgence": 26303, + "nailed": 26304, + "##otype": 26305, + "##×": 26306, + "ruse": 26307, + "saliva": 26308, + "diagrams": 26309, + "##tructing": 26310, + "albans": 26311, + "rann": 26312, + "thirties": 26313, + "1b": 26314, + "antennas": 26315, + "hilarious": 26316, + "cougars": 26317, + "paddington": 26318, + "stats": 26319, + "##eger": 26320, + "breakaway": 26321, + "ipod": 26322, + "reza": 26323, + "authorship": 26324, + "prohibiting": 26325, + "scoffed": 26326, + "##etz": 26327, + "##ttle": 26328, + "conscription": 26329, + "defected": 26330, + "trondheim": 26331, + "##fires": 26332, + "ivanov": 26333, + "keenan": 26334, + "##adan": 26335, + "##ciful": 26336, + "##fb": 26337, + "##slow": 26338, + "locating": 26339, + "##ials": 26340, + "##tford": 26341, + "cadiz": 26342, + "basalt": 26343, + "blankly": 26344, + "interned": 26345, + "rags": 26346, + "rattling": 26347, + "##tick": 26348, + "carpathian": 26349, + "reassured": 26350, + "sync": 26351, + "bum": 26352, + "guildford": 26353, + "iss": 26354, + "staunch": 26355, + "##onga": 26356, + "astronomers": 26357, + "sera": 26358, + "sofie": 26359, + "emergencies": 26360, + "susquehanna": 26361, + "##heard": 26362, + "duc": 26363, + "mastery": 26364, + "vh1": 26365, + "williamsburg": 26366, + "bayer": 26367, + "buckled": 26368, + "craving": 26369, + "##khan": 26370, + "##rdes": 26371, + "bloomington": 26372, + "##write": 26373, + "alton": 26374, + "barbecue": 26375, + "##bians": 26376, + "justine": 26377, + "##hri": 26378, + "##ndt": 26379, + "delightful": 26380, + "smartphone": 26381, + "newtown": 26382, + "photon": 26383, + "retrieval": 26384, + "peugeot": 26385, + "hissing": 26386, + "##monium": 26387, + "##orough": 26388, + "flavors": 26389, + "lighted": 26390, + "relaunched": 26391, + "tainted": 26392, + "##games": 26393, + "##lysis": 26394, + "anarchy": 26395, + "microscopic": 26396, + "hopping": 26397, + "adept": 26398, + "evade": 26399, + "evie": 26400, + "##beau": 26401, + "inhibit": 26402, + "sinn": 26403, + "adjustable": 26404, + "hurst": 26405, + "intuition": 26406, + "wilton": 26407, + "cisco": 26408, + "44th": 26409, + "lawful": 26410, + "lowlands": 26411, + "stockings": 26412, + "thierry": 26413, + "##dalen": 26414, + "##hila": 26415, + "##nai": 26416, + "fates": 26417, + "prank": 26418, + "tb": 26419, + "maison": 26420, + "lobbied": 26421, + "provocative": 26422, + "1724": 26423, + "4a": 26424, + "utopia": 26425, + "##qual": 26426, + "carbonate": 26427, + "gujarati": 26428, + "purcell": 26429, + "##rford": 26430, + "curtiss": 26431, + "##mei": 26432, + "overgrown": 26433, + "arenas": 26434, + "mediation": 26435, + "swallows": 26436, + "##rnik": 26437, + "respectful": 26438, + "turnbull": 26439, + "##hedron": 26440, + "##hope": 26441, + "alyssa": 26442, + "ozone": 26443, + "##ʻi": 26444, + "ami": 26445, + "gestapo": 26446, + "johansson": 26447, + "snooker": 26448, + "canteen": 26449, + "cuff": 26450, + "declines": 26451, + "empathy": 26452, + "stigma": 26453, + "##ags": 26454, + "##iner": 26455, + "##raine": 26456, + "taxpayers": 26457, + "gui": 26458, + "volga": 26459, + "##wright": 26460, + "##copic": 26461, + "lifespan": 26462, + "overcame": 26463, + "tattooed": 26464, + "enactment": 26465, + "giggles": 26466, + "##ador": 26467, + "##camp": 26468, + "barrington": 26469, + "bribe": 26470, + "obligatory": 26471, + "orbiting": 26472, + "peng": 26473, + "##enas": 26474, + "elusive": 26475, + "sucker": 26476, + "##vating": 26477, + "cong": 26478, + "hardship": 26479, + "empowered": 26480, + "anticipating": 26481, + "estrada": 26482, + "cryptic": 26483, + "greasy": 26484, + "detainees": 26485, + "planck": 26486, + "sudbury": 26487, + "plaid": 26488, + "dod": 26489, + "marriott": 26490, + "kayla": 26491, + "##ears": 26492, + "##vb": 26493, + "##zd": 26494, + "mortally": 26495, + "##hein": 26496, + "cognition": 26497, + "radha": 26498, + "319": 26499, + "liechtenstein": 26500, + "meade": 26501, + "richly": 26502, + "argyle": 26503, + "harpsichord": 26504, + "liberalism": 26505, + "trumpets": 26506, + "lauded": 26507, + "tyrant": 26508, + "salsa": 26509, + "tiled": 26510, + "lear": 26511, + "promoters": 26512, + "reused": 26513, + "slicing": 26514, + "trident": 26515, + "##chuk": 26516, + "##gami": 26517, + "##lka": 26518, + "cantor": 26519, + "checkpoint": 26520, + "##points": 26521, + "gaul": 26522, + "leger": 26523, + "mammalian": 26524, + "##tov": 26525, + "##aar": 26526, + "##schaft": 26527, + "doha": 26528, + "frenchman": 26529, + "nirvana": 26530, + "##vino": 26531, + "delgado": 26532, + "headlining": 26533, + "##eron": 26534, + "##iography": 26535, + "jug": 26536, + "tko": 26537, + "1649": 26538, + "naga": 26539, + "intersections": 26540, + "##jia": 26541, + "benfica": 26542, + "nawab": 26543, + "##suka": 26544, + "ashford": 26545, + "gulp": 26546, + "##deck": 26547, + "##vill": 26548, + "##rug": 26549, + "brentford": 26550, + "frazier": 26551, + "pleasures": 26552, + "dunne": 26553, + "potsdam": 26554, + "shenzhen": 26555, + "dentistry": 26556, + "##tec": 26557, + "flanagan": 26558, + "##dorff": 26559, + "##hear": 26560, + "chorale": 26561, + "dinah": 26562, + "prem": 26563, + "quezon": 26564, + "##rogated": 26565, + "relinquished": 26566, + "sutra": 26567, + "terri": 26568, + "##pani": 26569, + "flaps": 26570, + "##rissa": 26571, + "poly": 26572, + "##rnet": 26573, + "homme": 26574, + "aback": 26575, + "##eki": 26576, + "linger": 26577, + "womb": 26578, + "##kson": 26579, + "##lewood": 26580, + "doorstep": 26581, + "orthodoxy": 26582, + "threaded": 26583, + "westfield": 26584, + "##rval": 26585, + "dioceses": 26586, + "fridays": 26587, + "subsided": 26588, + "##gata": 26589, + "loyalists": 26590, + "##biotic": 26591, + "##ettes": 26592, + "letterman": 26593, + "lunatic": 26594, + "prelate": 26595, + "tenderly": 26596, + "invariably": 26597, + "souza": 26598, + "thug": 26599, + "winslow": 26600, + "##otide": 26601, + "furlongs": 26602, + "gogh": 26603, + "jeopardy": 26604, + "##runa": 26605, + "pegasus": 26606, + "##umble": 26607, + "humiliated": 26608, + "standalone": 26609, + "tagged": 26610, + "##roller": 26611, + "freshmen": 26612, + "klan": 26613, + "##bright": 26614, + "attaining": 26615, + "initiating": 26616, + "transatlantic": 26617, + "logged": 26618, + "viz": 26619, + "##uance": 26620, + "1723": 26621, + "combatants": 26622, + "intervening": 26623, + "stephane": 26624, + "chieftain": 26625, + "despised": 26626, + "grazed": 26627, + "317": 26628, + "cdc": 26629, + "galveston": 26630, + "godzilla": 26631, + "macro": 26632, + "simulate": 26633, + "##planes": 26634, + "parades": 26635, + "##esses": 26636, + "960": 26637, + "##ductive": 26638, + "##unes": 26639, + "equator": 26640, + "overdose": 26641, + "##cans": 26642, + "##hosh": 26643, + "##lifting": 26644, + "joshi": 26645, + "epstein": 26646, + "sonora": 26647, + "treacherous": 26648, + "aquatics": 26649, + "manchu": 26650, + "responsive": 26651, + "##sation": 26652, + "supervisory": 26653, + "##christ": 26654, + "##llins": 26655, + "##ibar": 26656, + "##balance": 26657, + "##uso": 26658, + "kimball": 26659, + "karlsruhe": 26660, + "mab": 26661, + "##emy": 26662, + "ignores": 26663, + "phonetic": 26664, + "reuters": 26665, + "spaghetti": 26666, + "820": 26667, + "almighty": 26668, + "danzig": 26669, + "rumbling": 26670, + "tombstone": 26671, + "designations": 26672, + "lured": 26673, + "outset": 26674, + "##felt": 26675, + "supermarkets": 26676, + "##wt": 26677, + "grupo": 26678, + "kei": 26679, + "kraft": 26680, + "susanna": 26681, + "##blood": 26682, + "comprehension": 26683, + "genealogy": 26684, + "##aghan": 26685, + "##verted": 26686, + "redding": 26687, + "##ythe": 26688, + "1722": 26689, + "bowing": 26690, + "##pore": 26691, + "##roi": 26692, + "lest": 26693, + "sharpened": 26694, + "fulbright": 26695, + "valkyrie": 26696, + "sikhs": 26697, + "##unds": 26698, + "swans": 26699, + "bouquet": 26700, + "merritt": 26701, + "##tage": 26702, + "##venting": 26703, + "commuted": 26704, + "redhead": 26705, + "clerks": 26706, + "leasing": 26707, + "cesare": 26708, + "dea": 26709, + "hazy": 26710, + "##vances": 26711, + "fledged": 26712, + "greenfield": 26713, + "servicemen": 26714, + "##gical": 26715, + "armando": 26716, + "blackout": 26717, + "dt": 26718, + "sagged": 26719, + "downloadable": 26720, + "intra": 26721, + "potion": 26722, + "pods": 26723, + "##4th": 26724, + "##mism": 26725, + "xp": 26726, + "attendants": 26727, + "gambia": 26728, + "stale": 26729, + "##ntine": 26730, + "plump": 26731, + "asteroids": 26732, + "rediscovered": 26733, + "buds": 26734, + "flea": 26735, + "hive": 26736, + "##neas": 26737, + "1737": 26738, + "classifications": 26739, + "debuts": 26740, + "##eles": 26741, + "olympus": 26742, + "scala": 26743, + "##eurs": 26744, + "##gno": 26745, + "##mute": 26746, + "hummed": 26747, + "sigismund": 26748, + "visuals": 26749, + "wiggled": 26750, + "await": 26751, + "pilasters": 26752, + "clench": 26753, + "sulfate": 26754, + "##ances": 26755, + "bellevue": 26756, + "enigma": 26757, + "trainee": 26758, + "snort": 26759, + "##sw": 26760, + "clouded": 26761, + "denim": 26762, + "##rank": 26763, + "##rder": 26764, + "churning": 26765, + "hartman": 26766, + "lodges": 26767, + "riches": 26768, + "sima": 26769, + "##missible": 26770, + "accountable": 26771, + "socrates": 26772, + "regulates": 26773, + "mueller": 26774, + "##cr": 26775, + "1702": 26776, + "avoids": 26777, + "solids": 26778, + "himalayas": 26779, + "nutrient": 26780, + "pup": 26781, + "##jevic": 26782, + "squat": 26783, + "fades": 26784, + "nec": 26785, + "##lates": 26786, + "##pina": 26787, + "##rona": 26788, + "##ου": 26789, + "privateer": 26790, + "tequila": 26791, + "##gative": 26792, + "##mpton": 26793, + "apt": 26794, + "hornet": 26795, + "immortals": 26796, + "##dou": 26797, + "asturias": 26798, + "cleansing": 26799, + "dario": 26800, + "##rries": 26801, + "##anta": 26802, + "etymology": 26803, + "servicing": 26804, + "zhejiang": 26805, + "##venor": 26806, + "##nx": 26807, + "horned": 26808, + "erasmus": 26809, + "rayon": 26810, + "relocating": 26811, + "£10": 26812, + "##bags": 26813, + "escalated": 26814, + "promenade": 26815, + "stubble": 26816, + "2010s": 26817, + "artisans": 26818, + "axial": 26819, + "liquids": 26820, + "mora": 26821, + "sho": 26822, + "yoo": 26823, + "##tsky": 26824, + "bundles": 26825, + "oldies": 26826, + "##nally": 26827, + "notification": 26828, + "bastion": 26829, + "##ths": 26830, + "sparkle": 26831, + "##lved": 26832, + "1728": 26833, + "leash": 26834, + "pathogen": 26835, + "highs": 26836, + "##hmi": 26837, + "immature": 26838, + "880": 26839, + "gonzaga": 26840, + "ignatius": 26841, + "mansions": 26842, + "monterrey": 26843, + "sweets": 26844, + "bryson": 26845, + "##loe": 26846, + "polled": 26847, + "regatta": 26848, + "brightest": 26849, + "pei": 26850, + "rosy": 26851, + "squid": 26852, + "hatfield": 26853, + "payroll": 26854, + "addict": 26855, + "meath": 26856, + "cornerback": 26857, + "heaviest": 26858, + "lodging": 26859, + "##mage": 26860, + "capcom": 26861, + "rippled": 26862, + "##sily": 26863, + "barnet": 26864, + "mayhem": 26865, + "ymca": 26866, + "snuggled": 26867, + "rousseau": 26868, + "##cute": 26869, + "blanchard": 26870, + "284": 26871, + "fragmented": 26872, + "leighton": 26873, + "chromosomes": 26874, + "risking": 26875, + "##md": 26876, + "##strel": 26877, + "##utter": 26878, + "corinne": 26879, + "coyotes": 26880, + "cynical": 26881, + "hiroshi": 26882, + "yeomanry": 26883, + "##ractive": 26884, + "ebook": 26885, + "grading": 26886, + "mandela": 26887, + "plume": 26888, + "agustin": 26889, + "magdalene": 26890, + "##rkin": 26891, + "bea": 26892, + "femme": 26893, + "trafford": 26894, + "##coll": 26895, + "##lun": 26896, + "##tance": 26897, + "52nd": 26898, + "fourier": 26899, + "upton": 26900, + "##mental": 26901, + "camilla": 26902, + "gust": 26903, + "iihf": 26904, + "islamabad": 26905, + "longevity": 26906, + "##kala": 26907, + "feldman": 26908, + "netting": 26909, + "##rization": 26910, + "endeavour": 26911, + "foraging": 26912, + "mfa": 26913, + "orr": 26914, + "##open": 26915, + "greyish": 26916, + "contradiction": 26917, + "graz": 26918, + "##ruff": 26919, + "handicapped": 26920, + "marlene": 26921, + "tweed": 26922, + "oaxaca": 26923, + "spp": 26924, + "campos": 26925, + "miocene": 26926, + "pri": 26927, + "configured": 26928, + "cooks": 26929, + "pluto": 26930, + "cozy": 26931, + "pornographic": 26932, + "##entes": 26933, + "70th": 26934, + "fairness": 26935, + "glided": 26936, + "jonny": 26937, + "lynne": 26938, + "rounding": 26939, + "sired": 26940, + "##emon": 26941, + "##nist": 26942, + "remade": 26943, + "uncover": 26944, + "##mack": 26945, + "complied": 26946, + "lei": 26947, + "newsweek": 26948, + "##jured": 26949, + "##parts": 26950, + "##enting": 26951, + "##pg": 26952, + "293": 26953, + "finer": 26954, + "guerrillas": 26955, + "athenian": 26956, + "deng": 26957, + "disused": 26958, + "stepmother": 26959, + "accuse": 26960, + "gingerly": 26961, + "seduction": 26962, + "521": 26963, + "confronting": 26964, + "##walker": 26965, + "##going": 26966, + "gora": 26967, + "nostalgia": 26968, + "sabres": 26969, + "virginity": 26970, + "wrenched": 26971, + "##minated": 26972, + "syndication": 26973, + "wielding": 26974, + "eyre": 26975, + "##56": 26976, + "##gnon": 26977, + "##igny": 26978, + "behaved": 26979, + "taxpayer": 26980, + "sweeps": 26981, + "##growth": 26982, + "childless": 26983, + "gallant": 26984, + "##ywood": 26985, + "amplified": 26986, + "geraldine": 26987, + "scrape": 26988, + "##ffi": 26989, + "babylonian": 26990, + "fresco": 26991, + "##rdan": 26992, + "##kney": 26993, + "##position": 26994, + "1718": 26995, + "restricting": 26996, + "tack": 26997, + "fukuoka": 26998, + "osborn": 26999, + "selector": 27000, + "partnering": 27001, + "##dlow": 27002, + "318": 27003, + "gnu": 27004, + "kia": 27005, + "tak": 27006, + "whitley": 27007, + "gables": 27008, + "##54": 27009, + "##mania": 27010, + "mri": 27011, + "softness": 27012, + "immersion": 27013, + "##bots": 27014, + "##evsky": 27015, + "1713": 27016, + "chilling": 27017, + "insignificant": 27018, + "pcs": 27019, + "##uis": 27020, + "elites": 27021, + "lina": 27022, + "purported": 27023, + "supplemental": 27024, + "teaming": 27025, + "##americana": 27026, + "##dding": 27027, + "##inton": 27028, + "proficient": 27029, + "rouen": 27030, + "##nage": 27031, + "##rret": 27032, + "niccolo": 27033, + "selects": 27034, + "##bread": 27035, + "fluffy": 27036, + "1621": 27037, + "gruff": 27038, + "knotted": 27039, + "mukherjee": 27040, + "polgara": 27041, + "thrash": 27042, + "nicholls": 27043, + "secluded": 27044, + "smoothing": 27045, + "thru": 27046, + "corsica": 27047, + "loaf": 27048, + "whitaker": 27049, + "inquiries": 27050, + "##rrier": 27051, + "##kam": 27052, + "indochina": 27053, + "289": 27054, + "marlins": 27055, + "myles": 27056, + "peking": 27057, + "##tea": 27058, + "extracts": 27059, + "pastry": 27060, + "superhuman": 27061, + "connacht": 27062, + "vogel": 27063, + "##ditional": 27064, + "##het": 27065, + "##udged": 27066, + "##lash": 27067, + "gloss": 27068, + "quarries": 27069, + "refit": 27070, + "teaser": 27071, + "##alic": 27072, + "##gaon": 27073, + "20s": 27074, + "materialized": 27075, + "sling": 27076, + "camped": 27077, + "pickering": 27078, + "tung": 27079, + "tracker": 27080, + "pursuant": 27081, + "##cide": 27082, + "cranes": 27083, + "soc": 27084, + "##cini": 27085, + "##typical": 27086, + "##viere": 27087, + "anhalt": 27088, + "overboard": 27089, + "workout": 27090, + "chores": 27091, + "fares": 27092, + "orphaned": 27093, + "stains": 27094, + "##logie": 27095, + "fenton": 27096, + "surpassing": 27097, + "joyah": 27098, + "triggers": 27099, + "##itte": 27100, + "grandmaster": 27101, + "##lass": 27102, + "##lists": 27103, + "clapping": 27104, + "fraudulent": 27105, + "ledger": 27106, + "nagasaki": 27107, + "##cor": 27108, + "##nosis": 27109, + "##tsa": 27110, + "eucalyptus": 27111, + "tun": 27112, + "##icio": 27113, + "##rney": 27114, + "##tara": 27115, + "dax": 27116, + "heroism": 27117, + "ina": 27118, + "wrexham": 27119, + "onboard": 27120, + "unsigned": 27121, + "##dates": 27122, + "moshe": 27123, + "galley": 27124, + "winnie": 27125, + "droplets": 27126, + "exiles": 27127, + "praises": 27128, + "watered": 27129, + "noodles": 27130, + "##aia": 27131, + "fein": 27132, + "adi": 27133, + "leland": 27134, + "multicultural": 27135, + "stink": 27136, + "bingo": 27137, + "comets": 27138, + "erskine": 27139, + "modernized": 27140, + "canned": 27141, + "constraint": 27142, + "domestically": 27143, + "chemotherapy": 27144, + "featherweight": 27145, + "stifled": 27146, + "##mum": 27147, + "darkly": 27148, + "irresistible": 27149, + "refreshing": 27150, + "hasty": 27151, + "isolate": 27152, + "##oys": 27153, + "kitchener": 27154, + "planners": 27155, + "##wehr": 27156, + "cages": 27157, + "yarn": 27158, + "implant": 27159, + "toulon": 27160, + "elects": 27161, + "childbirth": 27162, + "yue": 27163, + "##lind": 27164, + "##lone": 27165, + "cn": 27166, + "rightful": 27167, + "sportsman": 27168, + "junctions": 27169, + "remodeled": 27170, + "specifies": 27171, + "##rgh": 27172, + "291": 27173, + "##oons": 27174, + "complimented": 27175, + "##urgent": 27176, + "lister": 27177, + "ot": 27178, + "##logic": 27179, + "bequeathed": 27180, + "cheekbones": 27181, + "fontana": 27182, + "gabby": 27183, + "##dial": 27184, + "amadeus": 27185, + "corrugated": 27186, + "maverick": 27187, + "resented": 27188, + "triangles": 27189, + "##hered": 27190, + "##usly": 27191, + "nazareth": 27192, + "tyrol": 27193, + "1675": 27194, + "assent": 27195, + "poorer": 27196, + "sectional": 27197, + "aegean": 27198, + "##cous": 27199, + "296": 27200, + "nylon": 27201, + "ghanaian": 27202, + "##egorical": 27203, + "##weig": 27204, + "cushions": 27205, + "forbid": 27206, + "fusiliers": 27207, + "obstruction": 27208, + "somerville": 27209, + "##scia": 27210, + "dime": 27211, + "earrings": 27212, + "elliptical": 27213, + "leyte": 27214, + "oder": 27215, + "polymers": 27216, + "timmy": 27217, + "atm": 27218, + "midtown": 27219, + "piloted": 27220, + "settles": 27221, + "continual": 27222, + "externally": 27223, + "mayfield": 27224, + "##uh": 27225, + "enrichment": 27226, + "henson": 27227, + "keane": 27228, + "persians": 27229, + "1733": 27230, + "benji": 27231, + "braden": 27232, + "pep": 27233, + "324": 27234, + "##efe": 27235, + "contenders": 27236, + "pepsi": 27237, + "valet": 27238, + "##isches": 27239, + "298": 27240, + "##asse": 27241, + "##earing": 27242, + "goofy": 27243, + "stroll": 27244, + "##amen": 27245, + "authoritarian": 27246, + "occurrences": 27247, + "adversary": 27248, + "ahmedabad": 27249, + "tangent": 27250, + "toppled": 27251, + "dorchester": 27252, + "1672": 27253, + "modernism": 27254, + "marxism": 27255, + "islamist": 27256, + "charlemagne": 27257, + "exponential": 27258, + "racks": 27259, + "unicode": 27260, + "brunette": 27261, + "mbc": 27262, + "pic": 27263, + "skirmish": 27264, + "##bund": 27265, + "##lad": 27266, + "##powered": 27267, + "##yst": 27268, + "hoisted": 27269, + "messina": 27270, + "shatter": 27271, + "##ctum": 27272, + "jedi": 27273, + "vantage": 27274, + "##music": 27275, + "##neil": 27276, + "clemens": 27277, + "mahmoud": 27278, + "corrupted": 27279, + "authentication": 27280, + "lowry": 27281, + "nils": 27282, + "##washed": 27283, + "omnibus": 27284, + "wounding": 27285, + "jillian": 27286, + "##itors": 27287, + "##opped": 27288, + "serialized": 27289, + "narcotics": 27290, + "handheld": 27291, + "##arm": 27292, + "##plicity": 27293, + "intersecting": 27294, + "stimulating": 27295, + "##onis": 27296, + "crate": 27297, + "fellowships": 27298, + "hemingway": 27299, + "casinos": 27300, + "climatic": 27301, + "fordham": 27302, + "copeland": 27303, + "drip": 27304, + "beatty": 27305, + "leaflets": 27306, + "robber": 27307, + "brothel": 27308, + "madeira": 27309, + "##hedral": 27310, + "sphinx": 27311, + "ultrasound": 27312, + "##vana": 27313, + "valor": 27314, + "forbade": 27315, + "leonid": 27316, + "villas": 27317, + "##aldo": 27318, + "duane": 27319, + "marquez": 27320, + "##cytes": 27321, + "disadvantaged": 27322, + "forearms": 27323, + "kawasaki": 27324, + "reacts": 27325, + "consular": 27326, + "lax": 27327, + "uncles": 27328, + "uphold": 27329, + "##hopper": 27330, + "concepcion": 27331, + "dorsey": 27332, + "lass": 27333, + "##izan": 27334, + "arching": 27335, + "passageway": 27336, + "1708": 27337, + "researches": 27338, + "tia": 27339, + "internationals": 27340, + "##graphs": 27341, + "##opers": 27342, + "distinguishes": 27343, + "javanese": 27344, + "divert": 27345, + "##uven": 27346, + "plotted": 27347, + "##listic": 27348, + "##rwin": 27349, + "##erik": 27350, + "##tify": 27351, + "affirmative": 27352, + "signifies": 27353, + "validation": 27354, + "##bson": 27355, + "kari": 27356, + "felicity": 27357, + "georgina": 27358, + "zulu": 27359, + "##eros": 27360, + "##rained": 27361, + "##rath": 27362, + "overcoming": 27363, + "##dot": 27364, + "argyll": 27365, + "##rbin": 27366, + "1734": 27367, + "chiba": 27368, + "ratification": 27369, + "windy": 27370, + "earls": 27371, + "parapet": 27372, + "##marks": 27373, + "hunan": 27374, + "pristine": 27375, + "astrid": 27376, + "punta": 27377, + "##gart": 27378, + "brodie": 27379, + "##kota": 27380, + "##oder": 27381, + "malaga": 27382, + "minerva": 27383, + "rouse": 27384, + "##phonic": 27385, + "bellowed": 27386, + "pagoda": 27387, + "portals": 27388, + "reclamation": 27389, + "##gur": 27390, + "##odies": 27391, + "##⁄₄": 27392, + "parentheses": 27393, + "quoting": 27394, + "allergic": 27395, + "palette": 27396, + "showcases": 27397, + "benefactor": 27398, + "heartland": 27399, + "nonlinear": 27400, + "##tness": 27401, + "bladed": 27402, + "cheerfully": 27403, + "scans": 27404, + "##ety": 27405, + "##hone": 27406, + "1666": 27407, + "girlfriends": 27408, + "pedersen": 27409, + "hiram": 27410, + "sous": 27411, + "##liche": 27412, + "##nator": 27413, + "1683": 27414, + "##nery": 27415, + "##orio": 27416, + "##umen": 27417, + "bobo": 27418, + "primaries": 27419, + "smiley": 27420, + "##cb": 27421, + "unearthed": 27422, + "uniformly": 27423, + "fis": 27424, + "metadata": 27425, + "1635": 27426, + "ind": 27427, + "##oted": 27428, + "recoil": 27429, + "##titles": 27430, + "##tura": 27431, + "##ια": 27432, + "406": 27433, + "hilbert": 27434, + "jamestown": 27435, + "mcmillan": 27436, + "tulane": 27437, + "seychelles": 27438, + "##frid": 27439, + "antics": 27440, + "coli": 27441, + "fated": 27442, + "stucco": 27443, + "##grants": 27444, + "1654": 27445, + "bulky": 27446, + "accolades": 27447, + "arrays": 27448, + "caledonian": 27449, + "carnage": 27450, + "optimism": 27451, + "puebla": 27452, + "##tative": 27453, + "##cave": 27454, + "enforcing": 27455, + "rotherham": 27456, + "seo": 27457, + "dunlop": 27458, + "aeronautics": 27459, + "chimed": 27460, + "incline": 27461, + "zoning": 27462, + "archduke": 27463, + "hellenistic": 27464, + "##oses": 27465, + "##sions": 27466, + "candi": 27467, + "thong": 27468, + "##ople": 27469, + "magnate": 27470, + "rustic": 27471, + "##rsk": 27472, + "projective": 27473, + "slant": 27474, + "##offs": 27475, + "danes": 27476, + "hollis": 27477, + "vocalists": 27478, + "##ammed": 27479, + "congenital": 27480, + "contend": 27481, + "gesellschaft": 27482, + "##ocating": 27483, + "##pressive": 27484, + "douglass": 27485, + "quieter": 27486, + "##cm": 27487, + "##kshi": 27488, + "howled": 27489, + "salim": 27490, + "spontaneously": 27491, + "townsville": 27492, + "buena": 27493, + "southport": 27494, + "##bold": 27495, + "kato": 27496, + "1638": 27497, + "faerie": 27498, + "stiffly": 27499, + "##vus": 27500, + "##rled": 27501, + "297": 27502, + "flawless": 27503, + "realising": 27504, + "taboo": 27505, + "##7th": 27506, + "bytes": 27507, + "straightening": 27508, + "356": 27509, + "jena": 27510, + "##hid": 27511, + "##rmin": 27512, + "cartwright": 27513, + "berber": 27514, + "bertram": 27515, + "soloists": 27516, + "411": 27517, + "noses": 27518, + "417": 27519, + "coping": 27520, + "fission": 27521, + "hardin": 27522, + "inca": 27523, + "##cen": 27524, + "1717": 27525, + "mobilized": 27526, + "vhf": 27527, + "##raf": 27528, + "biscuits": 27529, + "curate": 27530, + "##85": 27531, + "##anial": 27532, + "331": 27533, + "gaunt": 27534, + "neighbourhoods": 27535, + "1540": 27536, + "##abas": 27537, + "blanca": 27538, + "bypassed": 27539, + "sockets": 27540, + "behold": 27541, + "coincidentally": 27542, + "##bane": 27543, + "nara": 27544, + "shave": 27545, + "splinter": 27546, + "terrific": 27547, + "##arion": 27548, + "##erian": 27549, + "commonplace": 27550, + "juris": 27551, + "redwood": 27552, + "waistband": 27553, + "boxed": 27554, + "caitlin": 27555, + "fingerprints": 27556, + "jennie": 27557, + "naturalized": 27558, + "##ired": 27559, + "balfour": 27560, + "craters": 27561, + "jody": 27562, + "bungalow": 27563, + "hugely": 27564, + "quilt": 27565, + "glitter": 27566, + "pigeons": 27567, + "undertaker": 27568, + "bulging": 27569, + "constrained": 27570, + "goo": 27571, + "##sil": 27572, + "##akh": 27573, + "assimilation": 27574, + "reworked": 27575, + "##person": 27576, + "persuasion": 27577, + "##pants": 27578, + "felicia": 27579, + "##cliff": 27580, + "##ulent": 27581, + "1732": 27582, + "explodes": 27583, + "##dun": 27584, + "##inium": 27585, + "##zic": 27586, + "lyman": 27587, + "vulture": 27588, + "hog": 27589, + "overlook": 27590, + "begs": 27591, + "northwards": 27592, + "ow": 27593, + "spoil": 27594, + "##urer": 27595, + "fatima": 27596, + "favorably": 27597, + "accumulate": 27598, + "sargent": 27599, + "sorority": 27600, + "corresponded": 27601, + "dispersal": 27602, + "kochi": 27603, + "toned": 27604, + "##imi": 27605, + "##lita": 27606, + "internacional": 27607, + "newfound": 27608, + "##agger": 27609, + "##lynn": 27610, + "##rigue": 27611, + "booths": 27612, + "peanuts": 27613, + "##eborg": 27614, + "medicare": 27615, + "muriel": 27616, + "nur": 27617, + "##uram": 27618, + "crates": 27619, + "millennia": 27620, + "pajamas": 27621, + "worsened": 27622, + "##breakers": 27623, + "jimi": 27624, + "vanuatu": 27625, + "yawned": 27626, + "##udeau": 27627, + "carousel": 27628, + "##hony": 27629, + "hurdle": 27630, + "##ccus": 27631, + "##mounted": 27632, + "##pod": 27633, + "rv": 27634, + "##eche": 27635, + "airship": 27636, + "ambiguity": 27637, + "compulsion": 27638, + "recapture": 27639, + "##claiming": 27640, + "arthritis": 27641, + "##osomal": 27642, + "1667": 27643, + "asserting": 27644, + "ngc": 27645, + "sniffing": 27646, + "dade": 27647, + "discontent": 27648, + "glendale": 27649, + "ported": 27650, + "##amina": 27651, + "defamation": 27652, + "rammed": 27653, + "##scent": 27654, + "fling": 27655, + "livingstone": 27656, + "##fleet": 27657, + "875": 27658, + "##ppy": 27659, + "apocalyptic": 27660, + "comrade": 27661, + "lcd": 27662, + "##lowe": 27663, + "cessna": 27664, + "eine": 27665, + "persecuted": 27666, + "subsistence": 27667, + "demi": 27668, + "hoop": 27669, + "reliefs": 27670, + "710": 27671, + "coptic": 27672, + "progressing": 27673, + "stemmed": 27674, + "perpetrators": 27675, + "1665": 27676, + "priestess": 27677, + "##nio": 27678, + "dobson": 27679, + "ebony": 27680, + "rooster": 27681, + "itf": 27682, + "tortricidae": 27683, + "##bbon": 27684, + "##jian": 27685, + "cleanup": 27686, + "##jean": 27687, + "##øy": 27688, + "1721": 27689, + "eighties": 27690, + "taxonomic": 27691, + "holiness": 27692, + "##hearted": 27693, + "##spar": 27694, + "antilles": 27695, + "showcasing": 27696, + "stabilized": 27697, + "##nb": 27698, + "gia": 27699, + "mascara": 27700, + "michelangelo": 27701, + "dawned": 27702, + "##uria": 27703, + "##vinsky": 27704, + "extinguished": 27705, + "fitz": 27706, + "grotesque": 27707, + "£100": 27708, + "##fera": 27709, + "##loid": 27710, + "##mous": 27711, + "barges": 27712, + "neue": 27713, + "throbbed": 27714, + "cipher": 27715, + "johnnie": 27716, + "##a1": 27717, + "##mpt": 27718, + "outburst": 27719, + "##swick": 27720, + "spearheaded": 27721, + "administrations": 27722, + "c1": 27723, + "heartbreak": 27724, + "pixels": 27725, + "pleasantly": 27726, + "##enay": 27727, + "lombardy": 27728, + "plush": 27729, + "##nsed": 27730, + "bobbie": 27731, + "##hly": 27732, + "reapers": 27733, + "tremor": 27734, + "xiang": 27735, + "minogue": 27736, + "substantive": 27737, + "hitch": 27738, + "barak": 27739, + "##wyl": 27740, + "kwan": 27741, + "##encia": 27742, + "910": 27743, + "obscene": 27744, + "elegance": 27745, + "indus": 27746, + "surfer": 27747, + "bribery": 27748, + "conserve": 27749, + "##hyllum": 27750, + "##masters": 27751, + "horatio": 27752, + "##fat": 27753, + "apes": 27754, + "rebound": 27755, + "psychotic": 27756, + "##pour": 27757, + "iteration": 27758, + "##mium": 27759, + "##vani": 27760, + "botanic": 27761, + "horribly": 27762, + "antiques": 27763, + "dispose": 27764, + "paxton": 27765, + "##hli": 27766, + "##wg": 27767, + "timeless": 27768, + "1704": 27769, + "disregard": 27770, + "engraver": 27771, + "hounds": 27772, + "##bau": 27773, + "##version": 27774, + "looted": 27775, + "uno": 27776, + "facilitates": 27777, + "groans": 27778, + "masjid": 27779, + "rutland": 27780, + "antibody": 27781, + "disqualification": 27782, + "decatur": 27783, + "footballers": 27784, + "quake": 27785, + "slacks": 27786, + "48th": 27787, + "rein": 27788, + "scribe": 27789, + "stabilize": 27790, + "commits": 27791, + "exemplary": 27792, + "tho": 27793, + "##hort": 27794, + "##chison": 27795, + "pantry": 27796, + "traversed": 27797, + "##hiti": 27798, + "disrepair": 27799, + "identifiable": 27800, + "vibrated": 27801, + "baccalaureate": 27802, + "##nnis": 27803, + "csa": 27804, + "interviewing": 27805, + "##iensis": 27806, + "##raße": 27807, + "greaves": 27808, + "wealthiest": 27809, + "343": 27810, + "classed": 27811, + "jogged": 27812, + "£5": 27813, + "##58": 27814, + "##atal": 27815, + "illuminating": 27816, + "knicks": 27817, + "respecting": 27818, + "##uno": 27819, + "scrubbed": 27820, + "##iji": 27821, + "##dles": 27822, + "kruger": 27823, + "moods": 27824, + "growls": 27825, + "raider": 27826, + "silvia": 27827, + "chefs": 27828, + "kam": 27829, + "vr": 27830, + "cree": 27831, + "percival": 27832, + "##terol": 27833, + "gunter": 27834, + "counterattack": 27835, + "defiant": 27836, + "henan": 27837, + "ze": 27838, + "##rasia": 27839, + "##riety": 27840, + "equivalence": 27841, + "submissions": 27842, + "##fra": 27843, + "##thor": 27844, + "bautista": 27845, + "mechanically": 27846, + "##heater": 27847, + "cornice": 27848, + "herbal": 27849, + "templar": 27850, + "##mering": 27851, + "outputs": 27852, + "ruining": 27853, + "ligand": 27854, + "renumbered": 27855, + "extravagant": 27856, + "mika": 27857, + "blockbuster": 27858, + "eta": 27859, + "insurrection": 27860, + "##ilia": 27861, + "darkening": 27862, + "ferocious": 27863, + "pianos": 27864, + "strife": 27865, + "kinship": 27866, + "##aer": 27867, + "melee": 27868, + "##anor": 27869, + "##iste": 27870, + "##may": 27871, + "##oue": 27872, + "decidedly": 27873, + "weep": 27874, + "##jad": 27875, + "##missive": 27876, + "##ppel": 27877, + "354": 27878, + "puget": 27879, + "unease": 27880, + "##gnant": 27881, + "1629": 27882, + "hammering": 27883, + "kassel": 27884, + "ob": 27885, + "wessex": 27886, + "##lga": 27887, + "bromwich": 27888, + "egan": 27889, + "paranoia": 27890, + "utilization": 27891, + "##atable": 27892, + "##idad": 27893, + "contradictory": 27894, + "provoke": 27895, + "##ols": 27896, + "##ouring": 27897, + "##tangled": 27898, + "knesset": 27899, + "##very": 27900, + "##lette": 27901, + "plumbing": 27902, + "##sden": 27903, + "##¹": 27904, + "greensboro": 27905, + "occult": 27906, + "sniff": 27907, + "338": 27908, + "zev": 27909, + "beaming": 27910, + "gamer": 27911, + "haggard": 27912, + "mahal": 27913, + "##olt": 27914, + "##pins": 27915, + "mendes": 27916, + "utmost": 27917, + "briefing": 27918, + "gunnery": 27919, + "##gut": 27920, + "##pher": 27921, + "##zh": 27922, + "##rok": 27923, + "1679": 27924, + "khalifa": 27925, + "sonya": 27926, + "##boot": 27927, + "principals": 27928, + "urbana": 27929, + "wiring": 27930, + "##liffe": 27931, + "##minating": 27932, + "##rrado": 27933, + "dahl": 27934, + "nyu": 27935, + "skepticism": 27936, + "np": 27937, + "townspeople": 27938, + "ithaca": 27939, + "lobster": 27940, + "somethin": 27941, + "##fur": 27942, + "##arina": 27943, + "##−1": 27944, + "freighter": 27945, + "zimmerman": 27946, + "biceps": 27947, + "contractual": 27948, + "##herton": 27949, + "amend": 27950, + "hurrying": 27951, + "subconscious": 27952, + "##anal": 27953, + "336": 27954, + "meng": 27955, + "clermont": 27956, + "spawning": 27957, + "##eia": 27958, + "##lub": 27959, + "dignitaries": 27960, + "impetus": 27961, + "snacks": 27962, + "spotting": 27963, + "twigs": 27964, + "##bilis": 27965, + "##cz": 27966, + "##ouk": 27967, + "libertadores": 27968, + "nic": 27969, + "skylar": 27970, + "##aina": 27971, + "##firm": 27972, + "gustave": 27973, + "asean": 27974, + "##anum": 27975, + "dieter": 27976, + "legislatures": 27977, + "flirt": 27978, + "bromley": 27979, + "trolls": 27980, + "umar": 27981, + "##bbies": 27982, + "##tyle": 27983, + "blah": 27984, + "parc": 27985, + "bridgeport": 27986, + "crank": 27987, + "negligence": 27988, + "##nction": 27989, + "46th": 27990, + "constantin": 27991, + "molded": 27992, + "bandages": 27993, + "seriousness": 27994, + "00pm": 27995, + "siegel": 27996, + "carpets": 27997, + "compartments": 27998, + "upbeat": 27999, + "statehood": 28000, + "##dner": 28001, + "##edging": 28002, + "marko": 28003, + "730": 28004, + "platt": 28005, + "##hane": 28006, + "paving": 28007, + "##iy": 28008, + "1738": 28009, + "abbess": 28010, + "impatience": 28011, + "limousine": 28012, + "nbl": 28013, + "##talk": 28014, + "441": 28015, + "lucille": 28016, + "mojo": 28017, + "nightfall": 28018, + "robbers": 28019, + "##nais": 28020, + "karel": 28021, + "brisk": 28022, + "calves": 28023, + "replicate": 28024, + "ascribed": 28025, + "telescopes": 28026, + "##olf": 28027, + "intimidated": 28028, + "##reen": 28029, + "ballast": 28030, + "specialization": 28031, + "##sit": 28032, + "aerodynamic": 28033, + "caliphate": 28034, + "rainer": 28035, + "visionary": 28036, + "##arded": 28037, + "epsilon": 28038, + "##aday": 28039, + "##onte": 28040, + "aggregation": 28041, + "auditory": 28042, + "boosted": 28043, + "reunification": 28044, + "kathmandu": 28045, + "loco": 28046, + "robyn": 28047, + "402": 28048, + "acknowledges": 28049, + "appointing": 28050, + "humanoid": 28051, + "newell": 28052, + "redeveloped": 28053, + "restraints": 28054, + "##tained": 28055, + "barbarians": 28056, + "chopper": 28057, + "1609": 28058, + "italiana": 28059, + "##lez": 28060, + "##lho": 28061, + "investigates": 28062, + "wrestlemania": 28063, + "##anies": 28064, + "##bib": 28065, + "690": 28066, + "##falls": 28067, + "creaked": 28068, + "dragoons": 28069, + "gravely": 28070, + "minions": 28071, + "stupidity": 28072, + "volley": 28073, + "##harat": 28074, + "##week": 28075, + "musik": 28076, + "##eries": 28077, + "##uously": 28078, + "fungal": 28079, + "massimo": 28080, + "semantics": 28081, + "malvern": 28082, + "##ahl": 28083, + "##pee": 28084, + "discourage": 28085, + "embryo": 28086, + "imperialism": 28087, + "1910s": 28088, + "profoundly": 28089, + "##ddled": 28090, + "jiangsu": 28091, + "sparkled": 28092, + "stat": 28093, + "##holz": 28094, + "sweatshirt": 28095, + "tobin": 28096, + "##iction": 28097, + "sneered": 28098, + "##cheon": 28099, + "##oit": 28100, + "brit": 28101, + "causal": 28102, + "smyth": 28103, + "##neuve": 28104, + "diffuse": 28105, + "perrin": 28106, + "silvio": 28107, + "##ipes": 28108, + "##recht": 28109, + "detonated": 28110, + "iqbal": 28111, + "selma": 28112, + "##nism": 28113, + "##zumi": 28114, + "roasted": 28115, + "##riders": 28116, + "tay": 28117, + "##ados": 28118, + "##mament": 28119, + "##mut": 28120, + "##rud": 28121, + "840": 28122, + "completes": 28123, + "nipples": 28124, + "cfa": 28125, + "flavour": 28126, + "hirsch": 28127, + "##laus": 28128, + "calderon": 28129, + "sneakers": 28130, + "moravian": 28131, + "##ksha": 28132, + "1622": 28133, + "rq": 28134, + "294": 28135, + "##imeters": 28136, + "bodo": 28137, + "##isance": 28138, + "##pre": 28139, + "##ronia": 28140, + "anatomical": 28141, + "excerpt": 28142, + "##lke": 28143, + "dh": 28144, + "kunst": 28145, + "##tablished": 28146, + "##scoe": 28147, + "biomass": 28148, + "panted": 28149, + "unharmed": 28150, + "gael": 28151, + "housemates": 28152, + "montpellier": 28153, + "##59": 28154, + "coa": 28155, + "rodents": 28156, + "tonic": 28157, + "hickory": 28158, + "singleton": 28159, + "##taro": 28160, + "451": 28161, + "1719": 28162, + "aldo": 28163, + "breaststroke": 28164, + "dempsey": 28165, + "och": 28166, + "rocco": 28167, + "##cuit": 28168, + "merton": 28169, + "dissemination": 28170, + "midsummer": 28171, + "serials": 28172, + "##idi": 28173, + "haji": 28174, + "polynomials": 28175, + "##rdon": 28176, + "gs": 28177, + "enoch": 28178, + "prematurely": 28179, + "shutter": 28180, + "taunton": 28181, + "£3": 28182, + "##grating": 28183, + "##inates": 28184, + "archangel": 28185, + "harassed": 28186, + "##asco": 28187, + "326": 28188, + "archway": 28189, + "dazzling": 28190, + "##ecin": 28191, + "1736": 28192, + "sumo": 28193, + "wat": 28194, + "##kovich": 28195, + "1086": 28196, + "honneur": 28197, + "##ently": 28198, + "##nostic": 28199, + "##ttal": 28200, + "##idon": 28201, + "1605": 28202, + "403": 28203, + "1716": 28204, + "blogger": 28205, + "rents": 28206, + "##gnan": 28207, + "hires": 28208, + "##ikh": 28209, + "##dant": 28210, + "howie": 28211, + "##rons": 28212, + "handler": 28213, + "retracted": 28214, + "shocks": 28215, + "1632": 28216, + "arun": 28217, + "duluth": 28218, + "kepler": 28219, + "trumpeter": 28220, + "##lary": 28221, + "peeking": 28222, + "seasoned": 28223, + "trooper": 28224, + "##mara": 28225, + "laszlo": 28226, + "##iciencies": 28227, + "##rti": 28228, + "heterosexual": 28229, + "##inatory": 28230, + "##ssion": 28231, + "indira": 28232, + "jogging": 28233, + "##inga": 28234, + "##lism": 28235, + "beit": 28236, + "dissatisfaction": 28237, + "malice": 28238, + "##ately": 28239, + "nedra": 28240, + "peeling": 28241, + "##rgeon": 28242, + "47th": 28243, + "stadiums": 28244, + "475": 28245, + "vertigo": 28246, + "##ains": 28247, + "iced": 28248, + "restroom": 28249, + "##plify": 28250, + "##tub": 28251, + "illustrating": 28252, + "pear": 28253, + "##chner": 28254, + "##sibility": 28255, + "inorganic": 28256, + "rappers": 28257, + "receipts": 28258, + "watery": 28259, + "##kura": 28260, + "lucinda": 28261, + "##oulos": 28262, + "reintroduced": 28263, + "##8th": 28264, + "##tched": 28265, + "gracefully": 28266, + "saxons": 28267, + "nutritional": 28268, + "wastewater": 28269, + "rained": 28270, + "favourites": 28271, + "bedrock": 28272, + "fisted": 28273, + "hallways": 28274, + "likeness": 28275, + "upscale": 28276, + "##lateral": 28277, + "1580": 28278, + "blinds": 28279, + "prequel": 28280, + "##pps": 28281, + "##tama": 28282, + "deter": 28283, + "humiliating": 28284, + "restraining": 28285, + "tn": 28286, + "vents": 28287, + "1659": 28288, + "laundering": 28289, + "recess": 28290, + "rosary": 28291, + "tractors": 28292, + "coulter": 28293, + "federer": 28294, + "##ifiers": 28295, + "##plin": 28296, + "persistence": 28297, + "##quitable": 28298, + "geschichte": 28299, + "pendulum": 28300, + "quakers": 28301, + "##beam": 28302, + "bassett": 28303, + "pictorial": 28304, + "buffet": 28305, + "koln": 28306, + "##sitor": 28307, + "drills": 28308, + "reciprocal": 28309, + "shooters": 28310, + "##57": 28311, + "##cton": 28312, + "##tees": 28313, + "converge": 28314, + "pip": 28315, + "dmitri": 28316, + "donnelly": 28317, + "yamamoto": 28318, + "aqua": 28319, + "azores": 28320, + "demographics": 28321, + "hypnotic": 28322, + "spitfire": 28323, + "suspend": 28324, + "wryly": 28325, + "roderick": 28326, + "##rran": 28327, + "sebastien": 28328, + "##asurable": 28329, + "mavericks": 28330, + "##fles": 28331, + "##200": 28332, + "himalayan": 28333, + "prodigy": 28334, + "##iance": 28335, + "transvaal": 28336, + "demonstrators": 28337, + "handcuffs": 28338, + "dodged": 28339, + "mcnamara": 28340, + "sublime": 28341, + "1726": 28342, + "crazed": 28343, + "##efined": 28344, + "##till": 28345, + "ivo": 28346, + "pondered": 28347, + "reconciled": 28348, + "shrill": 28349, + "sava": 28350, + "##duk": 28351, + "bal": 28352, + "cad": 28353, + "heresy": 28354, + "jaipur": 28355, + "goran": 28356, + "##nished": 28357, + "341": 28358, + "lux": 28359, + "shelly": 28360, + "whitehall": 28361, + "##hre": 28362, + "israelis": 28363, + "peacekeeping": 28364, + "##wled": 28365, + "1703": 28366, + "demetrius": 28367, + "ousted": 28368, + "##arians": 28369, + "##zos": 28370, + "beale": 28371, + "anwar": 28372, + "backstroke": 28373, + "raged": 28374, + "shrinking": 28375, + "cremated": 28376, + "##yck": 28377, + "benign": 28378, + "towing": 28379, + "wadi": 28380, + "darmstadt": 28381, + "landfill": 28382, + "parana": 28383, + "soothe": 28384, + "colleen": 28385, + "sidewalks": 28386, + "mayfair": 28387, + "tumble": 28388, + "hepatitis": 28389, + "ferrer": 28390, + "superstructure": 28391, + "##gingly": 28392, + "##urse": 28393, + "##wee": 28394, + "anthropological": 28395, + "translators": 28396, + "##mies": 28397, + "closeness": 28398, + "hooves": 28399, + "##pw": 28400, + "mondays": 28401, + "##roll": 28402, + "##vita": 28403, + "landscaping": 28404, + "##urized": 28405, + "purification": 28406, + "sock": 28407, + "thorns": 28408, + "thwarted": 28409, + "jalan": 28410, + "tiberius": 28411, + "##taka": 28412, + "saline": 28413, + "##rito": 28414, + "confidently": 28415, + "khyber": 28416, + "sculptors": 28417, + "##ij": 28418, + "brahms": 28419, + "hammersmith": 28420, + "inspectors": 28421, + "battista": 28422, + "fivb": 28423, + "fragmentation": 28424, + "hackney": 28425, + "##uls": 28426, + "arresting": 28427, + "exercising": 28428, + "antoinette": 28429, + "bedfordshire": 28430, + "##zily": 28431, + "dyed": 28432, + "##hema": 28433, + "1656": 28434, + "racetrack": 28435, + "variability": 28436, + "##tique": 28437, + "1655": 28438, + "austrians": 28439, + "deteriorating": 28440, + "madman": 28441, + "theorists": 28442, + "aix": 28443, + "lehman": 28444, + "weathered": 28445, + "1731": 28446, + "decreed": 28447, + "eruptions": 28448, + "1729": 28449, + "flaw": 28450, + "quinlan": 28451, + "sorbonne": 28452, + "flutes": 28453, + "nunez": 28454, + "1711": 28455, + "adored": 28456, + "downwards": 28457, + "fable": 28458, + "rasped": 28459, + "1712": 28460, + "moritz": 28461, + "mouthful": 28462, + "renegade": 28463, + "shivers": 28464, + "stunts": 28465, + "dysfunction": 28466, + "restrain": 28467, + "translit": 28468, + "327": 28469, + "pancakes": 28470, + "##avio": 28471, + "##cision": 28472, + "##tray": 28473, + "351": 28474, + "vial": 28475, + "##lden": 28476, + "bain": 28477, + "##maid": 28478, + "##oxide": 28479, + "chihuahua": 28480, + "malacca": 28481, + "vimes": 28482, + "##rba": 28483, + "##rnier": 28484, + "1664": 28485, + "donnie": 28486, + "plaques": 28487, + "##ually": 28488, + "337": 28489, + "bangs": 28490, + "floppy": 28491, + "huntsville": 28492, + "loretta": 28493, + "nikolay": 28494, + "##otte": 28495, + "eater": 28496, + "handgun": 28497, + "ubiquitous": 28498, + "##hett": 28499, + "eras": 28500, + "zodiac": 28501, + "1634": 28502, + "##omorphic": 28503, + "1820s": 28504, + "##zog": 28505, + "cochran": 28506, + "##bula": 28507, + "##lithic": 28508, + "warring": 28509, + "##rada": 28510, + "dalai": 28511, + "excused": 28512, + "blazers": 28513, + "mcconnell": 28514, + "reeling": 28515, + "bot": 28516, + "este": 28517, + "##abi": 28518, + "geese": 28519, + "hoax": 28520, + "taxon": 28521, + "##bla": 28522, + "guitarists": 28523, + "##icon": 28524, + "condemning": 28525, + "hunts": 28526, + "inversion": 28527, + "moffat": 28528, + "taekwondo": 28529, + "##lvis": 28530, + "1624": 28531, + "stammered": 28532, + "##rest": 28533, + "##rzy": 28534, + "sousa": 28535, + "fundraiser": 28536, + "marylebone": 28537, + "navigable": 28538, + "uptown": 28539, + "cabbage": 28540, + "daniela": 28541, + "salman": 28542, + "shitty": 28543, + "whimper": 28544, + "##kian": 28545, + "##utive": 28546, + "programmers": 28547, + "protections": 28548, + "rm": 28549, + "##rmi": 28550, + "##rued": 28551, + "forceful": 28552, + "##enes": 28553, + "fuss": 28554, + "##tao": 28555, + "##wash": 28556, + "brat": 28557, + "oppressive": 28558, + "reykjavik": 28559, + "spartak": 28560, + "ticking": 28561, + "##inkles": 28562, + "##kiewicz": 28563, + "adolph": 28564, + "horst": 28565, + "maui": 28566, + "protege": 28567, + "straighten": 28568, + "cpc": 28569, + "landau": 28570, + "concourse": 28571, + "clements": 28572, + "resultant": 28573, + "##ando": 28574, + "imaginative": 28575, + "joo": 28576, + "reactivated": 28577, + "##rem": 28578, + "##ffled": 28579, + "##uising": 28580, + "consultative": 28581, + "##guide": 28582, + "flop": 28583, + "kaitlyn": 28584, + "mergers": 28585, + "parenting": 28586, + "somber": 28587, + "##vron": 28588, + "supervise": 28589, + "vidhan": 28590, + "##imum": 28591, + "courtship": 28592, + "exemplified": 28593, + "harmonies": 28594, + "medallist": 28595, + "refining": 28596, + "##rrow": 28597, + "##ка": 28598, + "amara": 28599, + "##hum": 28600, + "780": 28601, + "goalscorer": 28602, + "sited": 28603, + "overshadowed": 28604, + "rohan": 28605, + "displeasure": 28606, + "secretive": 28607, + "multiplied": 28608, + "osman": 28609, + "##orth": 28610, + "engravings": 28611, + "padre": 28612, + "##kali": 28613, + "##veda": 28614, + "miniatures": 28615, + "mis": 28616, + "##yala": 28617, + "clap": 28618, + "pali": 28619, + "rook": 28620, + "##cana": 28621, + "1692": 28622, + "57th": 28623, + "antennae": 28624, + "astro": 28625, + "oskar": 28626, + "1628": 28627, + "bulldog": 28628, + "crotch": 28629, + "hackett": 28630, + "yucatan": 28631, + "##sure": 28632, + "amplifiers": 28633, + "brno": 28634, + "ferrara": 28635, + "migrating": 28636, + "##gree": 28637, + "thanking": 28638, + "turing": 28639, + "##eza": 28640, + "mccann": 28641, + "ting": 28642, + "andersson": 28643, + "onslaught": 28644, + "gaines": 28645, + "ganga": 28646, + "incense": 28647, + "standardization": 28648, + "##mation": 28649, + "sentai": 28650, + "scuba": 28651, + "stuffing": 28652, + "turquoise": 28653, + "waivers": 28654, + "alloys": 28655, + "##vitt": 28656, + "regaining": 28657, + "vaults": 28658, + "##clops": 28659, + "##gizing": 28660, + "digger": 28661, + "furry": 28662, + "memorabilia": 28663, + "probing": 28664, + "##iad": 28665, + "payton": 28666, + "rec": 28667, + "deutschland": 28668, + "filippo": 28669, + "opaque": 28670, + "seamen": 28671, + "zenith": 28672, + "afrikaans": 28673, + "##filtration": 28674, + "disciplined": 28675, + "inspirational": 28676, + "##merie": 28677, + "banco": 28678, + "confuse": 28679, + "grafton": 28680, + "tod": 28681, + "##dgets": 28682, + "championed": 28683, + "simi": 28684, + "anomaly": 28685, + "biplane": 28686, + "##ceptive": 28687, + "electrode": 28688, + "##para": 28689, + "1697": 28690, + "cleavage": 28691, + "crossbow": 28692, + "swirl": 28693, + "informant": 28694, + "##lars": 28695, + "##osta": 28696, + "afi": 28697, + "bonfire": 28698, + "spec": 28699, + "##oux": 28700, + "lakeside": 28701, + "slump": 28702, + "##culus": 28703, + "##lais": 28704, + "##qvist": 28705, + "##rrigan": 28706, + "1016": 28707, + "facades": 28708, + "borg": 28709, + "inwardly": 28710, + "cervical": 28711, + "xl": 28712, + "pointedly": 28713, + "050": 28714, + "stabilization": 28715, + "##odon": 28716, + "chests": 28717, + "1699": 28718, + "hacked": 28719, + "ctv": 28720, + "orthogonal": 28721, + "suzy": 28722, + "##lastic": 28723, + "gaulle": 28724, + "jacobite": 28725, + "rearview": 28726, + "##cam": 28727, + "##erted": 28728, + "ashby": 28729, + "##drik": 28730, + "##igate": 28731, + "##mise": 28732, + "##zbek": 28733, + "affectionately": 28734, + "canine": 28735, + "disperse": 28736, + "latham": 28737, + "##istles": 28738, + "##ivar": 28739, + "spielberg": 28740, + "##orin": 28741, + "##idium": 28742, + "ezekiel": 28743, + "cid": 28744, + "##sg": 28745, + "durga": 28746, + "middletown": 28747, + "##cina": 28748, + "customized": 28749, + "frontiers": 28750, + "harden": 28751, + "##etano": 28752, + "##zzy": 28753, + "1604": 28754, + "bolsheviks": 28755, + "##66": 28756, + "coloration": 28757, + "yoko": 28758, + "##bedo": 28759, + "briefs": 28760, + "slabs": 28761, + "debra": 28762, + "liquidation": 28763, + "plumage": 28764, + "##oin": 28765, + "blossoms": 28766, + "dementia": 28767, + "subsidy": 28768, + "1611": 28769, + "proctor": 28770, + "relational": 28771, + "jerseys": 28772, + "parochial": 28773, + "ter": 28774, + "##ici": 28775, + "esa": 28776, + "peshawar": 28777, + "cavalier": 28778, + "loren": 28779, + "cpi": 28780, + "idiots": 28781, + "shamrock": 28782, + "1646": 28783, + "dutton": 28784, + "malabar": 28785, + "mustache": 28786, + "##endez": 28787, + "##ocytes": 28788, + "referencing": 28789, + "terminates": 28790, + "marche": 28791, + "yarmouth": 28792, + "##sop": 28793, + "acton": 28794, + "mated": 28795, + "seton": 28796, + "subtly": 28797, + "baptised": 28798, + "beige": 28799, + "extremes": 28800, + "jolted": 28801, + "kristina": 28802, + "telecast": 28803, + "##actic": 28804, + "safeguard": 28805, + "waldo": 28806, + "##baldi": 28807, + "##bular": 28808, + "endeavors": 28809, + "sloppy": 28810, + "subterranean": 28811, + "##ensburg": 28812, + "##itung": 28813, + "delicately": 28814, + "pigment": 28815, + "tq": 28816, + "##scu": 28817, + "1626": 28818, + "##ound": 28819, + "collisions": 28820, + "coveted": 28821, + "herds": 28822, + "##personal": 28823, + "##meister": 28824, + "##nberger": 28825, + "chopra": 28826, + "##ricting": 28827, + "abnormalities": 28828, + "defective": 28829, + "galician": 28830, + "lucie": 28831, + "##dilly": 28832, + "alligator": 28833, + "likened": 28834, + "##genase": 28835, + "burundi": 28836, + "clears": 28837, + "complexion": 28838, + "derelict": 28839, + "deafening": 28840, + "diablo": 28841, + "fingered": 28842, + "champaign": 28843, + "dogg": 28844, + "enlist": 28845, + "isotope": 28846, + "labeling": 28847, + "mrna": 28848, + "##erre": 28849, + "brilliance": 28850, + "marvelous": 28851, + "##ayo": 28852, + "1652": 28853, + "crawley": 28854, + "ether": 28855, + "footed": 28856, + "dwellers": 28857, + "deserts": 28858, + "hamish": 28859, + "rubs": 28860, + "warlock": 28861, + "skimmed": 28862, + "##lizer": 28863, + "870": 28864, + "buick": 28865, + "embark": 28866, + "heraldic": 28867, + "irregularities": 28868, + "##ajan": 28869, + "kiara": 28870, + "##kulam": 28871, + "##ieg": 28872, + "antigen": 28873, + "kowalski": 28874, + "##lge": 28875, + "oakley": 28876, + "visitation": 28877, + "##mbit": 28878, + "vt": 28879, + "##suit": 28880, + "1570": 28881, + "murderers": 28882, + "##miento": 28883, + "##rites": 28884, + "chimneys": 28885, + "##sling": 28886, + "condemn": 28887, + "custer": 28888, + "exchequer": 28889, + "havre": 28890, + "##ghi": 28891, + "fluctuations": 28892, + "##rations": 28893, + "dfb": 28894, + "hendricks": 28895, + "vaccines": 28896, + "##tarian": 28897, + "nietzsche": 28898, + "biking": 28899, + "juicy": 28900, + "##duced": 28901, + "brooding": 28902, + "scrolling": 28903, + "selangor": 28904, + "##ragan": 28905, + "352": 28906, + "annum": 28907, + "boomed": 28908, + "seminole": 28909, + "sugarcane": 28910, + "##dna": 28911, + "departmental": 28912, + "dismissing": 28913, + "innsbruck": 28914, + "arteries": 28915, + "ashok": 28916, + "batavia": 28917, + "daze": 28918, + "kun": 28919, + "overtook": 28920, + "##rga": 28921, + "##tlan": 28922, + "beheaded": 28923, + "gaddafi": 28924, + "holm": 28925, + "electronically": 28926, + "faulty": 28927, + "galilee": 28928, + "fractures": 28929, + "kobayashi": 28930, + "##lized": 28931, + "gunmen": 28932, + "magma": 28933, + "aramaic": 28934, + "mala": 28935, + "eastenders": 28936, + "inference": 28937, + "messengers": 28938, + "bf": 28939, + "##qu": 28940, + "407": 28941, + "bathrooms": 28942, + "##vere": 28943, + "1658": 28944, + "flashbacks": 28945, + "ideally": 28946, + "misunderstood": 28947, + "##jali": 28948, + "##weather": 28949, + "mendez": 28950, + "##grounds": 28951, + "505": 28952, + "uncanny": 28953, + "##iii": 28954, + "1709": 28955, + "friendships": 28956, + "##nbc": 28957, + "sacrament": 28958, + "accommodated": 28959, + "reiterated": 28960, + "logistical": 28961, + "pebbles": 28962, + "thumped": 28963, + "##escence": 28964, + "administering": 28965, + "decrees": 28966, + "drafts": 28967, + "##flight": 28968, + "##cased": 28969, + "##tula": 28970, + "futuristic": 28971, + "picket": 28972, + "intimidation": 28973, + "winthrop": 28974, + "##fahan": 28975, + "interfered": 28976, + "339": 28977, + "afar": 28978, + "francoise": 28979, + "morally": 28980, + "uta": 28981, + "cochin": 28982, + "croft": 28983, + "dwarfs": 28984, + "##bruck": 28985, + "##dents": 28986, + "##nami": 28987, + "biker": 28988, + "##hner": 28989, + "##meral": 28990, + "nano": 28991, + "##isen": 28992, + "##ometric": 28993, + "##pres": 28994, + "##ан": 28995, + "brightened": 28996, + "meek": 28997, + "parcels": 28998, + "securely": 28999, + "gunners": 29000, + "##jhl": 29001, + "##zko": 29002, + "agile": 29003, + "hysteria": 29004, + "##lten": 29005, + "##rcus": 29006, + "bukit": 29007, + "champs": 29008, + "chevy": 29009, + "cuckoo": 29010, + "leith": 29011, + "sadler": 29012, + "theologians": 29013, + "welded": 29014, + "##section": 29015, + "1663": 29016, + "jj": 29017, + "plurality": 29018, + "xander": 29019, + "##rooms": 29020, + "##formed": 29021, + "shredded": 29022, + "temps": 29023, + "intimately": 29024, + "pau": 29025, + "tormented": 29026, + "##lok": 29027, + "##stellar": 29028, + "1618": 29029, + "charred": 29030, + "ems": 29031, + "essen": 29032, + "##mmel": 29033, + "alarms": 29034, + "spraying": 29035, + "ascot": 29036, + "blooms": 29037, + "twinkle": 29038, + "##abia": 29039, + "##apes": 29040, + "internment": 29041, + "obsidian": 29042, + "##chaft": 29043, + "snoop": 29044, + "##dav": 29045, + "##ooping": 29046, + "malibu": 29047, + "##tension": 29048, + "quiver": 29049, + "##itia": 29050, + "hays": 29051, + "mcintosh": 29052, + "travers": 29053, + "walsall": 29054, + "##ffie": 29055, + "1623": 29056, + "beverley": 29057, + "schwarz": 29058, + "plunging": 29059, + "structurally": 29060, + "m3": 29061, + "rosenthal": 29062, + "vikram": 29063, + "##tsk": 29064, + "770": 29065, + "ghz": 29066, + "##onda": 29067, + "##tiv": 29068, + "chalmers": 29069, + "groningen": 29070, + "pew": 29071, + "reckon": 29072, + "unicef": 29073, + "##rvis": 29074, + "55th": 29075, + "##gni": 29076, + "1651": 29077, + "sulawesi": 29078, + "avila": 29079, + "cai": 29080, + "metaphysical": 29081, + "screwing": 29082, + "turbulence": 29083, + "##mberg": 29084, + "augusto": 29085, + "samba": 29086, + "56th": 29087, + "baffled": 29088, + "momentary": 29089, + "toxin": 29090, + "##urian": 29091, + "##wani": 29092, + "aachen": 29093, + "condoms": 29094, + "dali": 29095, + "steppe": 29096, + "##3d": 29097, + "##app": 29098, + "##oed": 29099, + "##year": 29100, + "adolescence": 29101, + "dauphin": 29102, + "electrically": 29103, + "inaccessible": 29104, + "microscopy": 29105, + "nikita": 29106, + "##ega": 29107, + "atv": 29108, + "##cel": 29109, + "##enter": 29110, + "##oles": 29111, + "##oteric": 29112, + "##ы": 29113, + "accountants": 29114, + "punishments": 29115, + "wrongly": 29116, + "bribes": 29117, + "adventurous": 29118, + "clinch": 29119, + "flinders": 29120, + "southland": 29121, + "##hem": 29122, + "##kata": 29123, + "gough": 29124, + "##ciency": 29125, + "lads": 29126, + "soared": 29127, + "##ה": 29128, + "undergoes": 29129, + "deformation": 29130, + "outlawed": 29131, + "rubbish": 29132, + "##arus": 29133, + "##mussen": 29134, + "##nidae": 29135, + "##rzburg": 29136, + "arcs": 29137, + "##ingdon": 29138, + "##tituted": 29139, + "1695": 29140, + "wheelbase": 29141, + "wheeling": 29142, + "bombardier": 29143, + "campground": 29144, + "zebra": 29145, + "##lices": 29146, + "##oj": 29147, + "##bain": 29148, + "lullaby": 29149, + "##ecure": 29150, + "donetsk": 29151, + "wylie": 29152, + "grenada": 29153, + "##arding": 29154, + "##ης": 29155, + "squinting": 29156, + "eireann": 29157, + "opposes": 29158, + "##andra": 29159, + "maximal": 29160, + "runes": 29161, + "##broken": 29162, + "##cuting": 29163, + "##iface": 29164, + "##ror": 29165, + "##rosis": 29166, + "additive": 29167, + "britney": 29168, + "adultery": 29169, + "triggering": 29170, + "##drome": 29171, + "detrimental": 29172, + "aarhus": 29173, + "containment": 29174, + "jc": 29175, + "swapped": 29176, + "vichy": 29177, + "##ioms": 29178, + "madly": 29179, + "##oric": 29180, + "##rag": 29181, + "brant": 29182, + "##ckey": 29183, + "##trix": 29184, + "1560": 29185, + "1612": 29186, + "broughton": 29187, + "rustling": 29188, + "##stems": 29189, + "##uder": 29190, + "asbestos": 29191, + "mentoring": 29192, + "##nivorous": 29193, + "finley": 29194, + "leaps": 29195, + "##isan": 29196, + "apical": 29197, + "pry": 29198, + "slits": 29199, + "substitutes": 29200, + "##dict": 29201, + "intuitive": 29202, + "fantasia": 29203, + "insistent": 29204, + "unreasonable": 29205, + "##igen": 29206, + "##vna": 29207, + "domed": 29208, + "hannover": 29209, + "margot": 29210, + "ponder": 29211, + "##zziness": 29212, + "impromptu": 29213, + "jian": 29214, + "lc": 29215, + "rampage": 29216, + "stemming": 29217, + "##eft": 29218, + "andrey": 29219, + "gerais": 29220, + "whichever": 29221, + "amnesia": 29222, + "appropriated": 29223, + "anzac": 29224, + "clicks": 29225, + "modifying": 29226, + "ultimatum": 29227, + "cambrian": 29228, + "maids": 29229, + "verve": 29230, + "yellowstone": 29231, + "##mbs": 29232, + "conservatoire": 29233, + "##scribe": 29234, + "adherence": 29235, + "dinners": 29236, + "spectra": 29237, + "imperfect": 29238, + "mysteriously": 29239, + "sidekick": 29240, + "tatar": 29241, + "tuba": 29242, + "##aks": 29243, + "##ifolia": 29244, + "distrust": 29245, + "##athan": 29246, + "##zle": 29247, + "c2": 29248, + "ronin": 29249, + "zac": 29250, + "##pse": 29251, + "celaena": 29252, + "instrumentalist": 29253, + "scents": 29254, + "skopje": 29255, + "##mbling": 29256, + "comical": 29257, + "compensated": 29258, + "vidal": 29259, + "condor": 29260, + "intersect": 29261, + "jingle": 29262, + "wavelengths": 29263, + "##urrent": 29264, + "mcqueen": 29265, + "##izzly": 29266, + "carp": 29267, + "weasel": 29268, + "422": 29269, + "kanye": 29270, + "militias": 29271, + "postdoctoral": 29272, + "eugen": 29273, + "gunslinger": 29274, + "##ɛ": 29275, + "faux": 29276, + "hospice": 29277, + "##for": 29278, + "appalled": 29279, + "derivation": 29280, + "dwarves": 29281, + "##elis": 29282, + "dilapidated": 29283, + "##folk": 29284, + "astoria": 29285, + "philology": 29286, + "##lwyn": 29287, + "##otho": 29288, + "##saka": 29289, + "inducing": 29290, + "philanthropy": 29291, + "##bf": 29292, + "##itative": 29293, + "geek": 29294, + "markedly": 29295, + "sql": 29296, + "##yce": 29297, + "bessie": 29298, + "indices": 29299, + "rn": 29300, + "##flict": 29301, + "495": 29302, + "frowns": 29303, + "resolving": 29304, + "weightlifting": 29305, + "tugs": 29306, + "cleric": 29307, + "contentious": 29308, + "1653": 29309, + "mania": 29310, + "rms": 29311, + "##miya": 29312, + "##reate": 29313, + "##ruck": 29314, + "##tucket": 29315, + "bien": 29316, + "eels": 29317, + "marek": 29318, + "##ayton": 29319, + "##cence": 29320, + "discreet": 29321, + "unofficially": 29322, + "##ife": 29323, + "leaks": 29324, + "##bber": 29325, + "1705": 29326, + "332": 29327, + "dung": 29328, + "compressor": 29329, + "hillsborough": 29330, + "pandit": 29331, + "shillings": 29332, + "distal": 29333, + "##skin": 29334, + "381": 29335, + "##tat": 29336, + "##you": 29337, + "nosed": 29338, + "##nir": 29339, + "mangrove": 29340, + "undeveloped": 29341, + "##idia": 29342, + "textures": 29343, + "##inho": 29344, + "##500": 29345, + "##rise": 29346, + "ae": 29347, + "irritating": 29348, + "nay": 29349, + "amazingly": 29350, + "bancroft": 29351, + "apologetic": 29352, + "compassionate": 29353, + "kata": 29354, + "symphonies": 29355, + "##lovic": 29356, + "airspace": 29357, + "##lch": 29358, + "930": 29359, + "gifford": 29360, + "precautions": 29361, + "fulfillment": 29362, + "sevilla": 29363, + "vulgar": 29364, + "martinique": 29365, + "##urities": 29366, + "looting": 29367, + "piccolo": 29368, + "tidy": 29369, + "##dermott": 29370, + "quadrant": 29371, + "armchair": 29372, + "incomes": 29373, + "mathematicians": 29374, + "stampede": 29375, + "nilsson": 29376, + "##inking": 29377, + "##scan": 29378, + "foo": 29379, + "quarterfinal": 29380, + "##ostal": 29381, + "shang": 29382, + "shouldered": 29383, + "squirrels": 29384, + "##owe": 29385, + "344": 29386, + "vinegar": 29387, + "##bner": 29388, + "##rchy": 29389, + "##systems": 29390, + "delaying": 29391, + "##trics": 29392, + "ars": 29393, + "dwyer": 29394, + "rhapsody": 29395, + "sponsoring": 29396, + "##gration": 29397, + "bipolar": 29398, + "cinder": 29399, + "starters": 29400, + "##olio": 29401, + "##urst": 29402, + "421": 29403, + "signage": 29404, + "##nty": 29405, + "aground": 29406, + "figurative": 29407, + "mons": 29408, + "acquaintances": 29409, + "duets": 29410, + "erroneously": 29411, + "soyuz": 29412, + "elliptic": 29413, + "recreated": 29414, + "##cultural": 29415, + "##quette": 29416, + "##ssed": 29417, + "##tma": 29418, + "##zcz": 29419, + "moderator": 29420, + "scares": 29421, + "##itaire": 29422, + "##stones": 29423, + "##udence": 29424, + "juniper": 29425, + "sighting": 29426, + "##just": 29427, + "##nsen": 29428, + "britten": 29429, + "calabria": 29430, + "ry": 29431, + "bop": 29432, + "cramer": 29433, + "forsyth": 29434, + "stillness": 29435, + "##л": 29436, + "airmen": 29437, + "gathers": 29438, + "unfit": 29439, + "##umber": 29440, + "##upt": 29441, + "taunting": 29442, + "##rip": 29443, + "seeker": 29444, + "streamlined": 29445, + "##bution": 29446, + "holster": 29447, + "schumann": 29448, + "tread": 29449, + "vox": 29450, + "##gano": 29451, + "##onzo": 29452, + "strive": 29453, + "dil": 29454, + "reforming": 29455, + "covent": 29456, + "newbury": 29457, + "predicting": 29458, + "##orro": 29459, + "decorate": 29460, + "tre": 29461, + "##puted": 29462, + "andover": 29463, + "ie": 29464, + "asahi": 29465, + "dept": 29466, + "dunkirk": 29467, + "gills": 29468, + "##tori": 29469, + "buren": 29470, + "huskies": 29471, + "##stis": 29472, + "##stov": 29473, + "abstracts": 29474, + "bets": 29475, + "loosen": 29476, + "##opa": 29477, + "1682": 29478, + "yearning": 29479, + "##glio": 29480, + "##sir": 29481, + "berman": 29482, + "effortlessly": 29483, + "enamel": 29484, + "napoli": 29485, + "persist": 29486, + "##peration": 29487, + "##uez": 29488, + "attache": 29489, + "elisa": 29490, + "b1": 29491, + "invitations": 29492, + "##kic": 29493, + "accelerating": 29494, + "reindeer": 29495, + "boardwalk": 29496, + "clutches": 29497, + "nelly": 29498, + "polka": 29499, + "starbucks": 29500, + "##kei": 29501, + "adamant": 29502, + "huey": 29503, + "lough": 29504, + "unbroken": 29505, + "adventurer": 29506, + "embroidery": 29507, + "inspecting": 29508, + "stanza": 29509, + "##ducted": 29510, + "naia": 29511, + "taluka": 29512, + "##pone": 29513, + "##roids": 29514, + "chases": 29515, + "deprivation": 29516, + "florian": 29517, + "##jing": 29518, + "##ppet": 29519, + "earthly": 29520, + "##lib": 29521, + "##ssee": 29522, + "colossal": 29523, + "foreigner": 29524, + "vet": 29525, + "freaks": 29526, + "patrice": 29527, + "rosewood": 29528, + "triassic": 29529, + "upstate": 29530, + "##pkins": 29531, + "dominates": 29532, + "ata": 29533, + "chants": 29534, + "ks": 29535, + "vo": 29536, + "##400": 29537, + "##bley": 29538, + "##raya": 29539, + "##rmed": 29540, + "555": 29541, + "agra": 29542, + "infiltrate": 29543, + "##ailing": 29544, + "##ilation": 29545, + "##tzer": 29546, + "##uppe": 29547, + "##werk": 29548, + "binoculars": 29549, + "enthusiast": 29550, + "fujian": 29551, + "squeak": 29552, + "##avs": 29553, + "abolitionist": 29554, + "almeida": 29555, + "boredom": 29556, + "hampstead": 29557, + "marsden": 29558, + "rations": 29559, + "##ands": 29560, + "inflated": 29561, + "334": 29562, + "bonuses": 29563, + "rosalie": 29564, + "patna": 29565, + "##rco": 29566, + "329": 29567, + "detachments": 29568, + "penitentiary": 29569, + "54th": 29570, + "flourishing": 29571, + "woolf": 29572, + "##dion": 29573, + "##etched": 29574, + "papyrus": 29575, + "##lster": 29576, + "##nsor": 29577, + "##toy": 29578, + "bobbed": 29579, + "dismounted": 29580, + "endelle": 29581, + "inhuman": 29582, + "motorola": 29583, + "tbs": 29584, + "wince": 29585, + "wreath": 29586, + "##ticus": 29587, + "hideout": 29588, + "inspections": 29589, + "sanjay": 29590, + "disgrace": 29591, + "infused": 29592, + "pudding": 29593, + "stalks": 29594, + "##urbed": 29595, + "arsenic": 29596, + "leases": 29597, + "##hyl": 29598, + "##rrard": 29599, + "collarbone": 29600, + "##waite": 29601, + "##wil": 29602, + "dowry": 29603, + "##bant": 29604, + "##edance": 29605, + "genealogical": 29606, + "nitrate": 29607, + "salamanca": 29608, + "scandals": 29609, + "thyroid": 29610, + "necessitated": 29611, + "##!": 29612, + "##\"": 29613, + "###": 29614, + "##$": 29615, + "##%": 29616, + "##&": 29617, + "##'": 29618, + "##(": 29619, + "##)": 29620, + "##*": 29621, + "##+": 29622, + "##,": 29623, + "##-": 29624, + "##.": 29625, + "##/": 29626, + "##:": 29627, + "##;": 29628, + "##<": 29629, + "##=": 29630, + "##>": 29631, + "##?": 29632, + "##@": 29633, + "##[": 29634, + "##\\": 29635, + "##]": 29636, + "##^": 29637, + "##_": 29638, + "##`": 29639, + "##{": 29640, + "##|": 29641, + "##}": 29642, + "##~": 29643, + "##¡": 29644, + "##¢": 29645, + "##£": 29646, + "##¤": 29647, + "##¥": 29648, + "##¦": 29649, + "##§": 29650, + "##¨": 29651, + "##©": 29652, + "##ª": 29653, + "##«": 29654, + "##¬": 29655, + "##®": 29656, + "##±": 29657, + "##´": 29658, + "##µ": 29659, + "##¶": 29660, + "##·": 29661, + "##º": 29662, + "##»": 29663, + "##¼": 29664, + "##¾": 29665, + "##¿": 29666, + "##æ": 29667, + "##ð": 29668, + "##÷": 29669, + "##þ": 29670, + "##đ": 29671, + "##ħ": 29672, + "##ŋ": 29673, + "##œ": 29674, + "##ƒ": 29675, + "##ɐ": 29676, + "##ɑ": 29677, + "##ɒ": 29678, + "##ɔ": 29679, + "##ɕ": 29680, + "##ə": 29681, + "##ɡ": 29682, + "##ɣ": 29683, + "##ɨ": 29684, + "##ɪ": 29685, + "##ɫ": 29686, + "##ɬ": 29687, + "##ɯ": 29688, + "##ɲ": 29689, + "##ɴ": 29690, + "##ɹ": 29691, + "##ɾ": 29692, + "##ʀ": 29693, + "##ʁ": 29694, + "##ʂ": 29695, + "##ʃ": 29696, + "##ʉ": 29697, + "##ʊ": 29698, + "##ʋ": 29699, + "##ʌ": 29700, + "##ʎ": 29701, + "##ʐ": 29702, + "##ʑ": 29703, + "##ʒ": 29704, + "##ʔ": 29705, + "##ʰ": 29706, + "##ʲ": 29707, + "##ʳ": 29708, + "##ʷ": 29709, + "##ʸ": 29710, + "##ʻ": 29711, + "##ʼ": 29712, + "##ʾ": 29713, + "##ʿ": 29714, + "##ˈ": 29715, + "##ˡ": 29716, + "##ˢ": 29717, + "##ˣ": 29718, + "##ˤ": 29719, + "##β": 29720, + "##γ": 29721, + "##δ": 29722, + "##ε": 29723, + "##ζ": 29724, + "##θ": 29725, + "##κ": 29726, + "##λ": 29727, + "##μ": 29728, + "##ξ": 29729, + "##ο": 29730, + "##π": 29731, + "##ρ": 29732, + "##σ": 29733, + "##τ": 29734, + "##υ": 29735, + "##φ": 29736, + "##χ": 29737, + "##ψ": 29738, + "##ω": 29739, + "##б": 29740, + "##г": 29741, + "##д": 29742, + "##ж": 29743, + "##з": 29744, + "##м": 29745, + "##п": 29746, + "##с": 29747, + "##у": 29748, + "##ф": 29749, + "##х": 29750, + "##ц": 29751, + "##ч": 29752, + "##ш": 29753, + "##щ": 29754, + "##ъ": 29755, + "##э": 29756, + "##ю": 29757, + "##ђ": 29758, + "##є": 29759, + "##і": 29760, + "##ј": 29761, + "##љ": 29762, + "##њ": 29763, + "##ћ": 29764, + "##ӏ": 29765, + "##ա": 29766, + "##բ": 29767, + "##գ": 29768, + "##դ": 29769, + "##ե": 29770, + "##թ": 29771, + "##ի": 29772, + "##լ": 29773, + "##կ": 29774, + "##հ": 29775, + "##մ": 29776, + "##յ": 29777, + "##ն": 29778, + "##ո": 29779, + "##պ": 29780, + "##ս": 29781, + "##վ": 29782, + "##տ": 29783, + "##ր": 29784, + "##ւ": 29785, + "##ք": 29786, + "##־": 29787, + "##א": 29788, + "##ב": 29789, + "##ג": 29790, + "##ד": 29791, + "##ו": 29792, + "##ז": 29793, + "##ח": 29794, + "##ט": 29795, + "##י": 29796, + "##ך": 29797, + "##כ": 29798, + "##ל": 29799, + "##ם": 29800, + "##מ": 29801, + "##ן": 29802, + "##נ": 29803, + "##ס": 29804, + "##ע": 29805, + "##ף": 29806, + "##פ": 29807, + "##ץ": 29808, + "##צ": 29809, + "##ק": 29810, + "##ר": 29811, + "##ש": 29812, + "##ת": 29813, + "##،": 29814, + "##ء": 29815, + "##ب": 29816, + "##ت": 29817, + "##ث": 29818, + "##ج": 29819, + "##ح": 29820, + "##خ": 29821, + "##ذ": 29822, + "##ز": 29823, + "##س": 29824, + "##ش": 29825, + "##ص": 29826, + "##ض": 29827, + "##ط": 29828, + "##ظ": 29829, + "##ع": 29830, + "##غ": 29831, + "##ـ": 29832, + "##ف": 29833, + "##ق": 29834, + "##ك": 29835, + "##و": 29836, + "##ى": 29837, + "##ٹ": 29838, + "##پ": 29839, + "##چ": 29840, + "##ک": 29841, + "##گ": 29842, + "##ں": 29843, + "##ھ": 29844, + "##ہ": 29845, + "##ے": 29846, + "##अ": 29847, + "##आ": 29848, + "##उ": 29849, + "##ए": 29850, + "##क": 29851, + "##ख": 29852, + "##ग": 29853, + "##च": 29854, + "##ज": 29855, + "##ट": 29856, + "##ड": 29857, + "##ण": 29858, + "##त": 29859, + "##थ": 29860, + "##द": 29861, + "##ध": 29862, + "##न": 29863, + "##प": 29864, + "##ब": 29865, + "##भ": 29866, + "##म": 29867, + "##य": 29868, + "##र": 29869, + "##ल": 29870, + "##व": 29871, + "##श": 29872, + "##ष": 29873, + "##स": 29874, + "##ह": 29875, + "##ा": 29876, + "##ि": 29877, + "##ी": 29878, + "##ो": 29879, + "##।": 29880, + "##॥": 29881, + "##ং": 29882, + "##অ": 29883, + "##আ": 29884, + "##ই": 29885, + "##উ": 29886, + "##এ": 29887, + "##ও": 29888, + "##ক": 29889, + "##খ": 29890, + "##গ": 29891, + "##চ": 29892, + "##ছ": 29893, + "##জ": 29894, + "##ট": 29895, + "##ড": 29896, + "##ণ": 29897, + "##ত": 29898, + "##থ": 29899, + "##দ": 29900, + "##ধ": 29901, + "##ন": 29902, + "##প": 29903, + "##ব": 29904, + "##ভ": 29905, + "##ম": 29906, + "##য": 29907, + "##র": 29908, + "##ল": 29909, + "##শ": 29910, + "##ষ": 29911, + "##স": 29912, + "##হ": 29913, + "##া": 29914, + "##ি": 29915, + "##ী": 29916, + "##ে": 29917, + "##க": 29918, + "##ச": 29919, + "##ட": 29920, + "##த": 29921, + "##ந": 29922, + "##ன": 29923, + "##ப": 29924, + "##ம": 29925, + "##ய": 29926, + "##ர": 29927, + "##ல": 29928, + "##ள": 29929, + "##வ": 29930, + "##ா": 29931, + "##ி": 29932, + "##ு": 29933, + "##ே": 29934, + "##ை": 29935, + "##ನ": 29936, + "##ರ": 29937, + "##ಾ": 29938, + "##ක": 29939, + "##ය": 29940, + "##ර": 29941, + "##ල": 29942, + "##ව": 29943, + "##ා": 29944, + "##ก": 29945, + "##ง": 29946, + "##ต": 29947, + "##ท": 29948, + "##น": 29949, + "##พ": 29950, + "##ม": 29951, + "##ย": 29952, + "##ร": 29953, + "##ล": 29954, + "##ว": 29955, + "##ส": 29956, + "##อ": 29957, + "##า": 29958, + "##เ": 29959, + "##་": 29960, + "##།": 29961, + "##ག": 29962, + "##ང": 29963, + "##ད": 29964, + "##ན": 29965, + "##པ": 29966, + "##བ": 29967, + "##མ": 29968, + "##འ": 29969, + "##ར": 29970, + "##ལ": 29971, + "##ས": 29972, + "##မ": 29973, + "##ა": 29974, + "##ბ": 29975, + "##გ": 29976, + "##დ": 29977, + "##ე": 29978, + "##ვ": 29979, + "##თ": 29980, + "##ი": 29981, + "##კ": 29982, + "##ლ": 29983, + "##მ": 29984, + "##ნ": 29985, + "##ო": 29986, + "##რ": 29987, + "##ს": 29988, + "##ტ": 29989, + "##უ": 29990, + "##ᄀ": 29991, + "##ᄂ": 29992, + "##ᄃ": 29993, + "##ᄅ": 29994, + "##ᄆ": 29995, + "##ᄇ": 29996, + "##ᄉ": 29997, + "##ᄊ": 29998, + "##ᄋ": 29999, + "##ᄌ": 30000, + "##ᄎ": 30001, + "##ᄏ": 30002, + "##ᄐ": 30003, + "##ᄑ": 30004, + "##ᄒ": 30005, + "##ᅡ": 30006, + "##ᅢ": 30007, + "##ᅥ": 30008, + "##ᅦ": 30009, + "##ᅧ": 30010, + "##ᅩ": 30011, + "##ᅪ": 30012, + "##ᅭ": 30013, + "##ᅮ": 30014, + "##ᅯ": 30015, + "##ᅲ": 30016, + "##ᅳ": 30017, + "##ᅴ": 30018, + "##ᅵ": 30019, + "##ᆨ": 30020, + "##ᆫ": 30021, + "##ᆯ": 30022, + "##ᆷ": 30023, + "##ᆸ": 30024, + "##ᆼ": 30025, + "##ᴬ": 30026, + "##ᴮ": 30027, + "##ᴰ": 30028, + "##ᴵ": 30029, + "##ᴺ": 30030, + "##ᵀ": 30031, + "##ᵃ": 30032, + "##ᵇ": 30033, + "##ᵈ": 30034, + "##ᵉ": 30035, + "##ᵍ": 30036, + "##ᵏ": 30037, + "##ᵐ": 30038, + "##ᵒ": 30039, + "##ᵖ": 30040, + "##ᵗ": 30041, + "##ᵘ": 30042, + "##ᵣ": 30043, + "##ᵤ": 30044, + "##ᵥ": 30045, + "##ᶜ": 30046, + "##ᶠ": 30047, + "##‐": 30048, + "##‑": 30049, + "##‒": 30050, + "##–": 30051, + "##—": 30052, + "##―": 30053, + "##‖": 30054, + "##‘": 30055, + "##’": 30056, + "##‚": 30057, + "##“": 30058, + "##”": 30059, + "##„": 30060, + "##†": 30061, + "##‡": 30062, + "##•": 30063, + "##…": 30064, + "##‰": 30065, + "##′": 30066, + "##″": 30067, + "##›": 30068, + "##‿": 30069, + "##⁄": 30070, + "##⁰": 30071, + "##ⁱ": 30072, + "##⁴": 30073, + "##⁵": 30074, + "##⁶": 30075, + "##⁷": 30076, + "##⁸": 30077, + "##⁹": 30078, + "##⁻": 30079, + "##ⁿ": 30080, + "##₅": 30081, + "##₆": 30082, + "##₇": 30083, + "##₈": 30084, + "##₉": 30085, + "##₊": 30086, + "##₍": 30087, + "##₎": 30088, + "##ₐ": 30089, + "##ₑ": 30090, + "##ₒ": 30091, + "##ₓ": 30092, + "##ₕ": 30093, + "##ₖ": 30094, + "##ₗ": 30095, + "##ₘ": 30096, + "##ₚ": 30097, + "##ₛ": 30098, + "##ₜ": 30099, + "##₤": 30100, + "##₩": 30101, + "##€": 30102, + "##₱": 30103, + "##₹": 30104, + "##ℓ": 30105, + "##№": 30106, + "##ℝ": 30107, + "##™": 30108, + "##⅓": 30109, + "##⅔": 30110, + "##←": 30111, + "##↑": 30112, + "##→": 30113, + "##↓": 30114, + "##↔": 30115, + "##↦": 30116, + "##⇄": 30117, + "##⇌": 30118, + "##⇒": 30119, + "##∂": 30120, + "##∅": 30121, + "##∆": 30122, + "##∇": 30123, + "##∈": 30124, + "##∗": 30125, + "##∘": 30126, + "##√": 30127, + "##∞": 30128, + "##∧": 30129, + "##∨": 30130, + "##∩": 30131, + "##∪": 30132, + "##≈": 30133, + "##≡": 30134, + "##≤": 30135, + "##≥": 30136, + "##⊂": 30137, + "##⊆": 30138, + "##⊕": 30139, + "##⊗": 30140, + "##⋅": 30141, + "##─": 30142, + "##│": 30143, + "##■": 30144, + "##▪": 30145, + "##●": 30146, + "##★": 30147, + "##☆": 30148, + "##☉": 30149, + "##♠": 30150, + "##♣": 30151, + "##♥": 30152, + "##♦": 30153, + "##♯": 30154, + "##⟨": 30155, + "##⟩": 30156, + "##ⱼ": 30157, + "##⺩": 30158, + "##⺼": 30159, + "##⽥": 30160, + "##、": 30161, + "##。": 30162, + "##〈": 30163, + "##〉": 30164, + "##《": 30165, + "##》": 30166, + "##「": 30167, + "##」": 30168, + "##『": 30169, + "##』": 30170, + "##〜": 30171, + "##あ": 30172, + "##い": 30173, + "##う": 30174, + "##え": 30175, + "##お": 30176, + "##か": 30177, + "##き": 30178, + "##く": 30179, + "##け": 30180, + "##こ": 30181, + "##さ": 30182, + "##し": 30183, + "##す": 30184, + "##せ": 30185, + "##そ": 30186, + "##た": 30187, + "##ち": 30188, + "##っ": 30189, + "##つ": 30190, + "##て": 30191, + "##と": 30192, + "##な": 30193, + "##に": 30194, + "##ぬ": 30195, + "##ね": 30196, + "##の": 30197, + "##は": 30198, + "##ひ": 30199, + "##ふ": 30200, + "##へ": 30201, + "##ほ": 30202, + "##ま": 30203, + "##み": 30204, + "##む": 30205, + "##め": 30206, + "##も": 30207, + "##や": 30208, + "##ゆ": 30209, + "##よ": 30210, + "##ら": 30211, + "##り": 30212, + "##る": 30213, + "##れ": 30214, + "##ろ": 30215, + "##を": 30216, + "##ん": 30217, + "##ァ": 30218, + "##ア": 30219, + "##ィ": 30220, + "##イ": 30221, + "##ウ": 30222, + "##ェ": 30223, + "##エ": 30224, + "##オ": 30225, + "##カ": 30226, + "##キ": 30227, + "##ク": 30228, + "##ケ": 30229, + "##コ": 30230, + "##サ": 30231, + "##シ": 30232, + "##ス": 30233, + "##セ": 30234, + "##タ": 30235, + "##チ": 30236, + "##ッ": 30237, + "##ツ": 30238, + "##テ": 30239, + "##ト": 30240, + "##ナ": 30241, + "##ニ": 30242, + "##ノ": 30243, + "##ハ": 30244, + "##ヒ": 30245, + "##フ": 30246, + "##ヘ": 30247, + "##ホ": 30248, + "##マ": 30249, + "##ミ": 30250, + "##ム": 30251, + "##メ": 30252, + "##モ": 30253, + "##ャ": 30254, + "##ュ": 30255, + "##ョ": 30256, + "##ラ": 30257, + "##リ": 30258, + "##ル": 30259, + "##レ": 30260, + "##ロ": 30261, + "##ワ": 30262, + "##ン": 30263, + "##・": 30264, + "##ー": 30265, + "##一": 30266, + "##三": 30267, + "##上": 30268, + "##下": 30269, + "##不": 30270, + "##世": 30271, + "##中": 30272, + "##主": 30273, + "##久": 30274, + "##之": 30275, + "##也": 30276, + "##事": 30277, + "##二": 30278, + "##五": 30279, + "##井": 30280, + "##京": 30281, + "##人": 30282, + "##亻": 30283, + "##仁": 30284, + "##介": 30285, + "##代": 30286, + "##仮": 30287, + "##伊": 30288, + "##会": 30289, + "##佐": 30290, + "##侍": 30291, + "##保": 30292, + "##信": 30293, + "##健": 30294, + "##元": 30295, + "##光": 30296, + "##八": 30297, + "##公": 30298, + "##内": 30299, + "##出": 30300, + "##分": 30301, + "##前": 30302, + "##劉": 30303, + "##力": 30304, + "##加": 30305, + "##勝": 30306, + "##北": 30307, + "##区": 30308, + "##十": 30309, + "##千": 30310, + "##南": 30311, + "##博": 30312, + "##原": 30313, + "##口": 30314, + "##古": 30315, + "##史": 30316, + "##司": 30317, + "##合": 30318, + "##吉": 30319, + "##同": 30320, + "##名": 30321, + "##和": 30322, + "##囗": 30323, + "##四": 30324, + "##国": 30325, + "##國": 30326, + "##土": 30327, + "##地": 30328, + "##坂": 30329, + "##城": 30330, + "##堂": 30331, + "##場": 30332, + "##士": 30333, + "##夏": 30334, + "##外": 30335, + "##大": 30336, + "##天": 30337, + "##太": 30338, + "##夫": 30339, + "##奈": 30340, + "##女": 30341, + "##子": 30342, + "##学": 30343, + "##宀": 30344, + "##宇": 30345, + "##安": 30346, + "##宗": 30347, + "##定": 30348, + "##宣": 30349, + "##宮": 30350, + "##家": 30351, + "##宿": 30352, + "##寺": 30353, + "##將": 30354, + "##小": 30355, + "##尚": 30356, + "##山": 30357, + "##岡": 30358, + "##島": 30359, + "##崎": 30360, + "##川": 30361, + "##州": 30362, + "##巿": 30363, + "##帝": 30364, + "##平": 30365, + "##年": 30366, + "##幸": 30367, + "##广": 30368, + "##弘": 30369, + "##張": 30370, + "##彳": 30371, + "##後": 30372, + "##御": 30373, + "##德": 30374, + "##心": 30375, + "##忄": 30376, + "##志": 30377, + "##忠": 30378, + "##愛": 30379, + "##成": 30380, + "##我": 30381, + "##戦": 30382, + "##戸": 30383, + "##手": 30384, + "##扌": 30385, + "##政": 30386, + "##文": 30387, + "##新": 30388, + "##方": 30389, + "##日": 30390, + "##明": 30391, + "##星": 30392, + "##春": 30393, + "##昭": 30394, + "##智": 30395, + "##曲": 30396, + "##書": 30397, + "##月": 30398, + "##有": 30399, + "##朝": 30400, + "##木": 30401, + "##本": 30402, + "##李": 30403, + "##村": 30404, + "##東": 30405, + "##松": 30406, + "##林": 30407, + "##森": 30408, + "##楊": 30409, + "##樹": 30410, + "##橋": 30411, + "##歌": 30412, + "##止": 30413, + "##正": 30414, + "##武": 30415, + "##比": 30416, + "##氏": 30417, + "##民": 30418, + "##水": 30419, + "##氵": 30420, + "##氷": 30421, + "##永": 30422, + "##江": 30423, + "##沢": 30424, + "##河": 30425, + "##治": 30426, + "##法": 30427, + "##海": 30428, + "##清": 30429, + "##漢": 30430, + "##瀬": 30431, + "##火": 30432, + "##版": 30433, + "##犬": 30434, + "##王": 30435, + "##生": 30436, + "##田": 30437, + "##男": 30438, + "##疒": 30439, + "##発": 30440, + "##白": 30441, + "##的": 30442, + "##皇": 30443, + "##目": 30444, + "##相": 30445, + "##省": 30446, + "##真": 30447, + "##石": 30448, + "##示": 30449, + "##社": 30450, + "##神": 30451, + "##福": 30452, + "##禾": 30453, + "##秀": 30454, + "##秋": 30455, + "##空": 30456, + "##立": 30457, + "##章": 30458, + "##竹": 30459, + "##糹": 30460, + "##美": 30461, + "##義": 30462, + "##耳": 30463, + "##良": 30464, + "##艹": 30465, + "##花": 30466, + "##英": 30467, + "##華": 30468, + "##葉": 30469, + "##藤": 30470, + "##行": 30471, + "##街": 30472, + "##西": 30473, + "##見": 30474, + "##訁": 30475, + "##語": 30476, + "##谷": 30477, + "##貝": 30478, + "##貴": 30479, + "##車": 30480, + "##軍": 30481, + "##辶": 30482, + "##道": 30483, + "##郎": 30484, + "##郡": 30485, + "##部": 30486, + "##都": 30487, + "##里": 30488, + "##野": 30489, + "##金": 30490, + "##鈴": 30491, + "##镇": 30492, + "##長": 30493, + "##門": 30494, + "##間": 30495, + "##阝": 30496, + "##阿": 30497, + "##陳": 30498, + "##陽": 30499, + "##雄": 30500, + "##青": 30501, + "##面": 30502, + "##風": 30503, + "##食": 30504, + "##香": 30505, + "##馬": 30506, + "##高": 30507, + "##龍": 30508, + "##龸": 30509, + "##fi": 30510, + "##fl": 30511, + "##!": 30512, + "##(": 30513, + "##)": 30514, + "##,": 30515, + "##-": 30516, + "##.": 30517, + "##/": 30518, + "##:": 30519, + "##?": 30520, + "##~": 30521 + } + } +} \ No newline at end of file diff --git a/browser/base/content/assistant/embedding-assets/models/Xenova/all-MiniLM-L6-v2/tokenizer_config.json b/browser/base/content/assistant/embedding-assets/models/Xenova/all-MiniLM-L6-v2/tokenizer_config.json new file mode 100644 index 0000000000000..37fca74771bc7 --- /dev/null +++ b/browser/base/content/assistant/embedding-assets/models/Xenova/all-MiniLM-L6-v2/tokenizer_config.json @@ -0,0 +1,15 @@ +{ + "clean_up_tokenization_spaces": true, + "cls_token": "[CLS]", + "do_basic_tokenize": true, + "do_lower_case": true, + "mask_token": "[MASK]", + "model_max_length": 512, + "never_split": null, + "pad_token": "[PAD]", + "sep_token": "[SEP]", + "strip_accents": null, + "tokenize_chinese_chars": true, + "tokenizer_class": "BertTokenizer", + "unk_token": "[UNK]" +} diff --git a/browser/base/content/assistant/embedding-assets/models/Xenova/all-MiniLM-L6-v2/vocab.txt b/browser/base/content/assistant/embedding-assets/models/Xenova/all-MiniLM-L6-v2/vocab.txt new file mode 100644 index 0000000000000..fb140275c155a --- /dev/null +++ b/browser/base/content/assistant/embedding-assets/models/Xenova/all-MiniLM-L6-v2/vocab.txt @@ -0,0 +1,30522 @@ +[PAD] +[unused0] +[unused1] +[unused2] +[unused3] +[unused4] +[unused5] +[unused6] +[unused7] +[unused8] +[unused9] +[unused10] +[unused11] +[unused12] +[unused13] +[unused14] +[unused15] +[unused16] +[unused17] +[unused18] +[unused19] +[unused20] +[unused21] +[unused22] +[unused23] +[unused24] +[unused25] +[unused26] +[unused27] +[unused28] +[unused29] +[unused30] +[unused31] +[unused32] +[unused33] +[unused34] +[unused35] +[unused36] +[unused37] +[unused38] +[unused39] +[unused40] +[unused41] +[unused42] +[unused43] +[unused44] +[unused45] +[unused46] +[unused47] +[unused48] +[unused49] +[unused50] +[unused51] +[unused52] +[unused53] +[unused54] +[unused55] +[unused56] +[unused57] +[unused58] +[unused59] +[unused60] +[unused61] +[unused62] +[unused63] +[unused64] +[unused65] +[unused66] +[unused67] +[unused68] +[unused69] +[unused70] +[unused71] +[unused72] +[unused73] +[unused74] +[unused75] +[unused76] +[unused77] +[unused78] +[unused79] +[unused80] +[unused81] +[unused82] +[unused83] +[unused84] +[unused85] +[unused86] +[unused87] +[unused88] +[unused89] +[unused90] +[unused91] +[unused92] +[unused93] +[unused94] +[unused95] +[unused96] +[unused97] +[unused98] +[UNK] +[CLS] +[SEP] +[MASK] +[unused99] +[unused100] +[unused101] +[unused102] +[unused103] +[unused104] +[unused105] +[unused106] +[unused107] +[unused108] +[unused109] +[unused110] +[unused111] +[unused112] +[unused113] +[unused114] +[unused115] +[unused116] +[unused117] +[unused118] +[unused119] +[unused120] +[unused121] +[unused122] +[unused123] +[unused124] +[unused125] +[unused126] +[unused127] +[unused128] +[unused129] +[unused130] +[unused131] +[unused132] +[unused133] +[unused134] +[unused135] +[unused136] +[unused137] +[unused138] +[unused139] +[unused140] +[unused141] +[unused142] +[unused143] +[unused144] +[unused145] +[unused146] +[unused147] +[unused148] +[unused149] +[unused150] +[unused151] +[unused152] +[unused153] +[unused154] +[unused155] +[unused156] +[unused157] +[unused158] +[unused159] +[unused160] +[unused161] +[unused162] +[unused163] +[unused164] +[unused165] +[unused166] +[unused167] +[unused168] +[unused169] +[unused170] +[unused171] +[unused172] +[unused173] +[unused174] +[unused175] +[unused176] +[unused177] +[unused178] +[unused179] +[unused180] +[unused181] +[unused182] +[unused183] +[unused184] +[unused185] +[unused186] +[unused187] +[unused188] +[unused189] +[unused190] +[unused191] +[unused192] +[unused193] +[unused194] +[unused195] +[unused196] +[unused197] +[unused198] +[unused199] +[unused200] +[unused201] +[unused202] +[unused203] +[unused204] +[unused205] +[unused206] +[unused207] +[unused208] +[unused209] +[unused210] +[unused211] +[unused212] +[unused213] +[unused214] +[unused215] +[unused216] +[unused217] +[unused218] +[unused219] +[unused220] +[unused221] +[unused222] +[unused223] +[unused224] +[unused225] +[unused226] +[unused227] +[unused228] +[unused229] +[unused230] +[unused231] +[unused232] +[unused233] +[unused234] +[unused235] +[unused236] +[unused237] +[unused238] +[unused239] +[unused240] +[unused241] +[unused242] +[unused243] +[unused244] +[unused245] +[unused246] +[unused247] +[unused248] +[unused249] +[unused250] +[unused251] +[unused252] +[unused253] +[unused254] +[unused255] +[unused256] +[unused257] +[unused258] +[unused259] +[unused260] +[unused261] +[unused262] +[unused263] +[unused264] +[unused265] +[unused266] +[unused267] +[unused268] +[unused269] +[unused270] +[unused271] +[unused272] +[unused273] +[unused274] +[unused275] +[unused276] +[unused277] +[unused278] +[unused279] +[unused280] +[unused281] +[unused282] +[unused283] +[unused284] +[unused285] +[unused286] +[unused287] +[unused288] +[unused289] +[unused290] +[unused291] +[unused292] +[unused293] +[unused294] +[unused295] +[unused296] +[unused297] +[unused298] +[unused299] +[unused300] +[unused301] +[unused302] +[unused303] +[unused304] +[unused305] +[unused306] +[unused307] +[unused308] +[unused309] +[unused310] +[unused311] +[unused312] +[unused313] +[unused314] +[unused315] +[unused316] +[unused317] +[unused318] +[unused319] +[unused320] +[unused321] +[unused322] +[unused323] +[unused324] +[unused325] +[unused326] +[unused327] +[unused328] +[unused329] +[unused330] +[unused331] +[unused332] +[unused333] +[unused334] +[unused335] +[unused336] +[unused337] +[unused338] +[unused339] +[unused340] +[unused341] +[unused342] +[unused343] +[unused344] +[unused345] +[unused346] +[unused347] +[unused348] +[unused349] +[unused350] +[unused351] +[unused352] +[unused353] +[unused354] +[unused355] +[unused356] +[unused357] +[unused358] +[unused359] +[unused360] +[unused361] +[unused362] +[unused363] +[unused364] +[unused365] +[unused366] +[unused367] +[unused368] +[unused369] +[unused370] +[unused371] +[unused372] +[unused373] +[unused374] +[unused375] +[unused376] +[unused377] +[unused378] +[unused379] +[unused380] +[unused381] +[unused382] +[unused383] +[unused384] +[unused385] +[unused386] +[unused387] +[unused388] +[unused389] +[unused390] +[unused391] +[unused392] +[unused393] +[unused394] +[unused395] +[unused396] +[unused397] +[unused398] +[unused399] +[unused400] +[unused401] +[unused402] +[unused403] +[unused404] +[unused405] +[unused406] +[unused407] +[unused408] +[unused409] +[unused410] +[unused411] +[unused412] +[unused413] +[unused414] +[unused415] +[unused416] +[unused417] +[unused418] +[unused419] +[unused420] +[unused421] +[unused422] +[unused423] +[unused424] +[unused425] +[unused426] +[unused427] +[unused428] +[unused429] +[unused430] +[unused431] +[unused432] +[unused433] +[unused434] +[unused435] +[unused436] +[unused437] +[unused438] +[unused439] +[unused440] +[unused441] +[unused442] +[unused443] +[unused444] +[unused445] +[unused446] +[unused447] +[unused448] +[unused449] +[unused450] +[unused451] +[unused452] +[unused453] +[unused454] +[unused455] +[unused456] +[unused457] +[unused458] +[unused459] +[unused460] +[unused461] +[unused462] +[unused463] +[unused464] +[unused465] +[unused466] +[unused467] +[unused468] +[unused469] +[unused470] +[unused471] +[unused472] +[unused473] +[unused474] +[unused475] +[unused476] +[unused477] +[unused478] +[unused479] +[unused480] +[unused481] +[unused482] +[unused483] +[unused484] +[unused485] +[unused486] +[unused487] +[unused488] +[unused489] +[unused490] +[unused491] +[unused492] +[unused493] +[unused494] +[unused495] +[unused496] +[unused497] +[unused498] +[unused499] +[unused500] +[unused501] +[unused502] +[unused503] +[unused504] +[unused505] +[unused506] +[unused507] +[unused508] +[unused509] +[unused510] +[unused511] +[unused512] +[unused513] +[unused514] +[unused515] +[unused516] +[unused517] +[unused518] +[unused519] +[unused520] +[unused521] +[unused522] +[unused523] +[unused524] +[unused525] +[unused526] +[unused527] +[unused528] +[unused529] +[unused530] +[unused531] +[unused532] +[unused533] +[unused534] +[unused535] +[unused536] +[unused537] +[unused538] +[unused539] +[unused540] +[unused541] +[unused542] +[unused543] +[unused544] +[unused545] +[unused546] +[unused547] +[unused548] +[unused549] +[unused550] +[unused551] +[unused552] +[unused553] +[unused554] +[unused555] +[unused556] +[unused557] +[unused558] +[unused559] +[unused560] +[unused561] +[unused562] +[unused563] +[unused564] +[unused565] +[unused566] +[unused567] +[unused568] +[unused569] +[unused570] +[unused571] +[unused572] +[unused573] +[unused574] +[unused575] +[unused576] +[unused577] +[unused578] +[unused579] +[unused580] +[unused581] +[unused582] +[unused583] +[unused584] +[unused585] +[unused586] +[unused587] +[unused588] +[unused589] +[unused590] +[unused591] +[unused592] +[unused593] +[unused594] +[unused595] +[unused596] +[unused597] +[unused598] +[unused599] +[unused600] +[unused601] +[unused602] +[unused603] +[unused604] +[unused605] +[unused606] +[unused607] +[unused608] +[unused609] +[unused610] +[unused611] +[unused612] +[unused613] +[unused614] +[unused615] +[unused616] +[unused617] +[unused618] +[unused619] +[unused620] +[unused621] +[unused622] +[unused623] +[unused624] +[unused625] +[unused626] +[unused627] +[unused628] +[unused629] +[unused630] +[unused631] +[unused632] +[unused633] +[unused634] +[unused635] +[unused636] +[unused637] +[unused638] +[unused639] +[unused640] +[unused641] +[unused642] +[unused643] +[unused644] +[unused645] +[unused646] +[unused647] +[unused648] +[unused649] +[unused650] +[unused651] +[unused652] +[unused653] +[unused654] +[unused655] +[unused656] +[unused657] +[unused658] +[unused659] +[unused660] +[unused661] +[unused662] +[unused663] +[unused664] +[unused665] +[unused666] +[unused667] +[unused668] +[unused669] +[unused670] +[unused671] +[unused672] +[unused673] +[unused674] +[unused675] +[unused676] +[unused677] +[unused678] +[unused679] +[unused680] +[unused681] +[unused682] +[unused683] +[unused684] +[unused685] +[unused686] +[unused687] +[unused688] +[unused689] +[unused690] +[unused691] +[unused692] +[unused693] +[unused694] +[unused695] +[unused696] +[unused697] +[unused698] +[unused699] +[unused700] +[unused701] +[unused702] +[unused703] +[unused704] +[unused705] +[unused706] +[unused707] +[unused708] +[unused709] +[unused710] +[unused711] +[unused712] +[unused713] +[unused714] +[unused715] +[unused716] +[unused717] +[unused718] +[unused719] +[unused720] +[unused721] +[unused722] +[unused723] +[unused724] +[unused725] +[unused726] +[unused727] +[unused728] +[unused729] +[unused730] +[unused731] +[unused732] +[unused733] +[unused734] +[unused735] +[unused736] +[unused737] +[unused738] +[unused739] +[unused740] +[unused741] +[unused742] +[unused743] +[unused744] +[unused745] +[unused746] +[unused747] +[unused748] +[unused749] +[unused750] +[unused751] +[unused752] +[unused753] +[unused754] +[unused755] +[unused756] +[unused757] +[unused758] +[unused759] +[unused760] +[unused761] +[unused762] +[unused763] +[unused764] +[unused765] +[unused766] +[unused767] +[unused768] +[unused769] +[unused770] +[unused771] +[unused772] +[unused773] +[unused774] +[unused775] +[unused776] +[unused777] +[unused778] +[unused779] +[unused780] +[unused781] +[unused782] +[unused783] +[unused784] +[unused785] +[unused786] +[unused787] +[unused788] +[unused789] +[unused790] +[unused791] +[unused792] +[unused793] +[unused794] +[unused795] +[unused796] +[unused797] +[unused798] +[unused799] +[unused800] +[unused801] +[unused802] +[unused803] +[unused804] +[unused805] +[unused806] +[unused807] +[unused808] +[unused809] +[unused810] +[unused811] +[unused812] +[unused813] +[unused814] +[unused815] +[unused816] +[unused817] +[unused818] +[unused819] +[unused820] +[unused821] +[unused822] +[unused823] +[unused824] +[unused825] +[unused826] +[unused827] +[unused828] +[unused829] +[unused830] +[unused831] +[unused832] +[unused833] +[unused834] +[unused835] +[unused836] +[unused837] +[unused838] +[unused839] +[unused840] +[unused841] +[unused842] +[unused843] +[unused844] +[unused845] +[unused846] +[unused847] +[unused848] +[unused849] +[unused850] +[unused851] +[unused852] +[unused853] +[unused854] +[unused855] +[unused856] +[unused857] +[unused858] +[unused859] +[unused860] +[unused861] +[unused862] +[unused863] +[unused864] +[unused865] +[unused866] +[unused867] +[unused868] +[unused869] +[unused870] +[unused871] +[unused872] +[unused873] +[unused874] +[unused875] +[unused876] +[unused877] +[unused878] +[unused879] +[unused880] +[unused881] +[unused882] +[unused883] +[unused884] +[unused885] +[unused886] +[unused887] +[unused888] +[unused889] +[unused890] +[unused891] +[unused892] +[unused893] +[unused894] +[unused895] +[unused896] +[unused897] +[unused898] +[unused899] +[unused900] +[unused901] +[unused902] +[unused903] +[unused904] +[unused905] +[unused906] +[unused907] +[unused908] +[unused909] +[unused910] +[unused911] +[unused912] +[unused913] +[unused914] +[unused915] +[unused916] +[unused917] +[unused918] +[unused919] +[unused920] +[unused921] +[unused922] +[unused923] +[unused924] +[unused925] +[unused926] +[unused927] +[unused928] +[unused929] +[unused930] +[unused931] +[unused932] +[unused933] +[unused934] +[unused935] +[unused936] +[unused937] +[unused938] +[unused939] +[unused940] +[unused941] +[unused942] +[unused943] +[unused944] +[unused945] +[unused946] +[unused947] +[unused948] +[unused949] +[unused950] +[unused951] +[unused952] +[unused953] +[unused954] +[unused955] +[unused956] +[unused957] +[unused958] +[unused959] +[unused960] +[unused961] +[unused962] +[unused963] +[unused964] +[unused965] +[unused966] +[unused967] +[unused968] +[unused969] +[unused970] +[unused971] +[unused972] +[unused973] +[unused974] +[unused975] +[unused976] +[unused977] +[unused978] +[unused979] +[unused980] +[unused981] +[unused982] +[unused983] +[unused984] +[unused985] +[unused986] +[unused987] +[unused988] +[unused989] +[unused990] +[unused991] +[unused992] +[unused993] +! +" +# +$ +% +& +' +( +) +* ++ +, +- +. +/ +0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +: +; +< += +> +? +@ +[ +\ +] +^ +_ +` +a +b +c +d +e +f +g +h +i +j +k +l +m +n +o +p +q +r +s +t +u +v +w +x +y +z +{ +| +} +~ +¡ +¢ +£ +¤ +¥ +¦ +§ +¨ +© +ª +« +¬ +® +° +± +² +³ +´ +µ +¶ +· +¹ +º +» +¼ +½ +¾ +¿ +× +ß +æ +ð +÷ +ø +þ +đ +ħ +ı +ł +ŋ +œ +ƒ +ɐ +ɑ +ɒ +ɔ +ɕ +ə +ɛ +ɡ +ɣ +ɨ +ɪ +ɫ +ɬ +ɯ +ɲ +ɴ +ɹ +ɾ +ʀ +ʁ +ʂ +ʃ +ʉ +ʊ +ʋ +ʌ +ʎ +ʐ +ʑ +ʒ +ʔ +ʰ +ʲ +ʳ +ʷ +ʸ +ʻ +ʼ +ʾ +ʿ +ˈ +ː +ˡ +ˢ +ˣ +ˤ +α +β +γ +δ +ε +ζ +η +θ +ι +κ +λ +μ +ν +ξ +ο +π +ρ +ς +σ +τ +υ +φ +χ +ψ +ω +а +б +в +г +д +е +ж +з +и +к +л +м +н +о +п +р +с +т +у +ф +х +ц +ч +ш +щ +ъ +ы +ь +э +ю +я +ђ +є +і +ј +љ +њ +ћ +ӏ +ա +բ +գ +դ +ե +թ +ի +լ +կ +հ +մ +յ +ն +ո +պ +ս +վ +տ +ր +ւ +ք +־ +א +ב +ג +ד +ה +ו +ז +ח +ט +י +ך +כ +ל +ם +מ +ן +נ +ס +ע +ף +פ +ץ +צ +ק +ר +ש +ת +، +ء +ا +ب +ة +ت +ث +ج +ح +خ +د +ذ +ر +ز +س +ش +ص +ض +ط +ظ +ع +غ +ـ +ف +ق +ك +ل +م +ن +ه +و +ى +ي +ٹ +پ +چ +ک +گ +ں +ھ +ہ +ی +ے +अ +आ +उ +ए +क +ख +ग +च +ज +ट +ड +ण +त +थ +द +ध +न +प +ब +भ +म +य +र +ल +व +श +ष +स +ह +ा +ि +ी +ो +। +॥ +ং +অ +আ +ই +উ +এ +ও +ক +খ +গ +চ +ছ +জ +ট +ড +ণ +ত +থ +দ +ধ +ন +প +ব +ভ +ম +য +র +ল +শ +ষ +স +হ +া +ি +ী +ে +க +ச +ட +த +ந +ன +ப +ம +ய +ர +ல +ள +வ +ா +ி +ு +ே +ை +ನ +ರ +ಾ +ක +ය +ර +ල +ව +ා +ก +ง +ต +ท +น +พ +ม +ย +ร +ล +ว +ส +อ +า +เ +་ +། +ག +ང +ད +ན +པ +བ +མ +འ +ར +ལ +ས +မ +ა +ბ +გ +დ +ე +ვ +თ +ი +კ +ლ +მ +ნ +ო +რ +ს +ტ +უ +ᄀ +ᄂ +ᄃ +ᄅ +ᄆ +ᄇ +ᄉ +ᄊ +ᄋ +ᄌ +ᄎ +ᄏ +ᄐ +ᄑ +ᄒ +ᅡ +ᅢ +ᅥ +ᅦ +ᅧ +ᅩ +ᅪ +ᅭ +ᅮ +ᅯ +ᅲ +ᅳ +ᅴ +ᅵ +ᆨ +ᆫ +ᆯ +ᆷ +ᆸ +ᆼ +ᴬ +ᴮ +ᴰ +ᴵ +ᴺ +ᵀ +ᵃ +ᵇ +ᵈ +ᵉ +ᵍ +ᵏ +ᵐ +ᵒ +ᵖ +ᵗ +ᵘ +ᵢ +ᵣ +ᵤ +ᵥ +ᶜ +ᶠ +‐ +‑ +‒ +– +— +― +‖ +‘ +’ +‚ +“ +” +„ +† +‡ +• +… +‰ +′ +″ +› +‿ +⁄ +⁰ +ⁱ +⁴ +⁵ +⁶ +⁷ +⁸ +⁹ +⁺ +⁻ +ⁿ +₀ +₁ +₂ +₃ +₄ +₅ +₆ +₇ +₈ +₉ +₊ +₍ +₎ +ₐ +ₑ +ₒ +ₓ +ₕ +ₖ +ₗ +ₘ +ₙ +ₚ +ₛ +ₜ +₤ +₩ +€ +₱ +₹ +ℓ +№ +ℝ +™ +⅓ +⅔ +← +↑ +→ +↓ +↔ +↦ +⇄ +⇌ +⇒ +∂ +∅ +∆ +∇ +∈ +− +∗ +∘ +√ +∞ +∧ +∨ +∩ +∪ +≈ +≡ +≤ +≥ +⊂ +⊆ +⊕ +⊗ +⋅ +─ +│ +■ +▪ +● +★ +☆ +☉ +♠ +♣ +♥ +♦ +♭ +♯ +⟨ +⟩ +ⱼ +⺩ +⺼ +⽥ +、 +。 +〈 +〉 +《 +》 +「 +」 +『 +』 +〜 +あ +い +う +え +お +か +き +く +け +こ +さ +し +す +せ +そ +た +ち +っ +つ +て +と +な +に +ぬ +ね +の +は +ひ +ふ +へ +ほ +ま +み +む +め +も +や +ゆ +よ +ら +り +る +れ +ろ +を +ん +ァ +ア +ィ +イ +ウ +ェ +エ +オ +カ +キ +ク +ケ +コ +サ +シ +ス +セ +タ +チ +ッ +ツ +テ +ト +ナ +ニ +ノ +ハ +ヒ +フ +ヘ +ホ +マ +ミ +ム +メ +モ +ャ +ュ +ョ +ラ +リ +ル +レ +ロ +ワ +ン +・ +ー +一 +三 +上 +下 +不 +世 +中 +主 +久 +之 +也 +事 +二 +五 +井 +京 +人 +亻 +仁 +介 +代 +仮 +伊 +会 +佐 +侍 +保 +信 +健 +元 +光 +八 +公 +内 +出 +分 +前 +劉 +力 +加 +勝 +北 +区 +十 +千 +南 +博 +原 +口 +古 +史 +司 +合 +吉 +同 +名 +和 +囗 +四 +国 +國 +土 +地 +坂 +城 +堂 +場 +士 +夏 +外 +大 +天 +太 +夫 +奈 +女 +子 +学 +宀 +宇 +安 +宗 +定 +宣 +宮 +家 +宿 +寺 +將 +小 +尚 +山 +岡 +島 +崎 +川 +州 +巿 +帝 +平 +年 +幸 +广 +弘 +張 +彳 +後 +御 +德 +心 +忄 +志 +忠 +愛 +成 +我 +戦 +戸 +手 +扌 +政 +文 +新 +方 +日 +明 +星 +春 +昭 +智 +曲 +書 +月 +有 +朝 +木 +本 +李 +村 +東 +松 +林 +森 +楊 +樹 +橋 +歌 +止 +正 +武 +比 +氏 +民 +水 +氵 +氷 +永 +江 +沢 +河 +治 +法 +海 +清 +漢 +瀬 +火 +版 +犬 +王 +生 +田 +男 +疒 +発 +白 +的 +皇 +目 +相 +省 +真 +石 +示 +社 +神 +福 +禾 +秀 +秋 +空 +立 +章 +竹 +糹 +美 +義 +耳 +良 +艹 +花 +英 +華 +葉 +藤 +行 +街 +西 +見 +訁 +語 +谷 +貝 +貴 +車 +軍 +辶 +道 +郎 +郡 +部 +都 +里 +野 +金 +鈴 +镇 +長 +門 +間 +阝 +阿 +陳 +陽 +雄 +青 +面 +風 +食 +香 +馬 +高 +龍 +龸 +fi +fl +! +( +) +, +- +. +/ +: +? +~ +the +of +and +in +to +was +he +is +as +for +on +with +that +it +his +by +at +from +her +##s +she +you +had +an +were +but +be +this +are +not +my +they +one +which +or +have +him +me +first +all +also +their +has +up +who +out +been +when +after +there +into +new +two +its +##a +time +would +no +what +about +said +we +over +then +other +so +more +##e +can +if +like +back +them +only +some +could +##i +where +just +##ing +during +before +##n +do +##o +made +school +through +than +now +years +most +world +may +between +down +well +three +##d +year +while +will +##ed +##r +##y +later +##t +city +under +around +did +such +being +used +state +people +part +know +against +your +many +second +university +both +national +##er +these +don +known +off +way +until +re +how +even +get +head +... +didn +##ly +team +american +because +de +##l +born +united +film +since +still +long +work +south +us +became +any +high +again +day +family +see +right +man +eyes +house +season +war +states +including +took +life +north +same +each +called +name +much +place +however +go +four +group +another +found +won +area +here +going +10 +away +series +left +home +music +best +make +hand +number +company +several +never +last +john +000 +very +album +take +end +good +too +following +released +game +played +little +began +district +##m +old +want +those +side +held +own +early +county +ll +league +use +west +##u +face +think +##es +2010 +government +##h +march +came +small +general +town +june +##on +line +based +something +##k +september +thought +looked +along +international +2011 +air +july +club +went +january +october +our +august +april +york +12 +few +2012 +2008 +east +show +member +college +2009 +father +public +##us +come +men +five +set +station +church +##c +next +former +november +room +party +located +december +2013 +age +got +2007 +##g +system +let +love +2006 +though +every +2014 +look +song +water +century +without +body +black +night +within +great +women +single +ve +building +large +population +river +named +band +white +started +##an +once +15 +20 +should +18 +2015 +service +top +built +british +open +death +king +moved +local +times +children +february +book +why +11 +door +need +president +order +final +road +wasn +although +due +major +died +village +third +knew +2016 +asked +turned +st +wanted +say +##p +together +received +main +son +served +different +##en +behind +himself +felt +members +power +football +law +voice +play +##in +near +park +history +30 +having +2005 +16 +##man +saw +mother +##al +army +point +front +help +english +street +art +late +hands +games +award +##ia +young +14 +put +published +country +division +across +told +13 +often +ever +french +london +center +six +red +2017 +led +days +include +light +25 +find +tell +among +species +really +according +central +half +2004 +form +original +gave +office +making +enough +lost +full +opened +must +included +live +given +german +player +run +business +woman +community +cup +might +million +land +2000 +court +development +17 +short +round +ii +km +seen +class +story +always +become +sure +research +almost +director +council +la +##2 +career +things +using +island +##z +couldn +car +##is +24 +close +force +##1 +better +free +support +control +field +students +2003 +education +married +##b +nothing +worked +others +record +big +inside +level +anything +continued +give +james +##3 +military +established +non +returned +feel +does +title +written +thing +feet +william +far +co +association +hard +already +2002 +##ra +championship +human +western +100 +##na +department +hall +role +various +production +21 +19 +heart +2001 +living +fire +version +##ers +##f +television +royal +##4 +produced +working +act +case +society +region +present +radio +period +looking +least +total +keep +england +wife +program +per +brother +mind +special +22 +##le +am +works +soon +##6 +political +george +services +taken +created +##7 +further +able +reached +david +union +joined +upon +done +important +social +information +either +##ic +##x +appeared +position +ground +lead +rock +dark +election +23 +board +france +hair +course +arms +site +police +girl +instead +real +sound +##v +words +moment +##te +someone +##8 +summer +project +announced +san +less +wrote +past +followed +##5 +blue +founded +al +finally +india +taking +records +america +##ne +1999 +design +considered +northern +god +stop +battle +toward +european +outside +described +track +today +playing +language +28 +call +26 +heard +professional +low +australia +miles +california +win +yet +green +##ie +trying +blood +##ton +southern +science +maybe +everything +match +square +27 +mouth +video +race +recorded +leave +above +##9 +daughter +points +space +1998 +museum +change +middle +common +##0 +move +tv +post +##ta +lake +seven +tried +elected +closed +ten +paul +minister +##th +months +start +chief +return +canada +person +sea +release +similar +modern +brought +rest +hit +formed +mr +##la +1997 +floor +event +doing +thomas +1996 +robert +care +killed +training +star +week +needed +turn +finished +railway +rather +news +health +sent +example +ran +term +michael +coming +currently +yes +forces +despite +gold +areas +50 +stage +fact +29 +dead +says +popular +2018 +originally +germany +probably +developed +result +pulled +friend +stood +money +running +mi +signed +word +songs +child +eventually +met +tour +average +teams +minutes +festival +current +deep +kind +1995 +decided +usually +eastern +seemed +##ness +episode +bed +added +table +indian +private +charles +route +available +idea +throughout +centre +addition +appointed +style +1994 +books +eight +construction +press +mean +wall +friends +remained +schools +study +##ch +##um +institute +oh +chinese +sometimes +events +possible +1992 +australian +type +brown +forward +talk +process +food +debut +seat +performance +committee +features +character +arts +herself +else +lot +strong +russian +range +hours +peter +arm +##da +morning +dr +sold +##ry +quickly +directed +1993 +guitar +china +##w +31 +list +##ma +performed +media +uk +players +smile +##rs +myself +40 +placed +coach +province +towards +wouldn +leading +whole +boy +official +designed +grand +census +##el +europe +attack +japanese +henry +1991 +##re +##os +cross +getting +alone +action +lower +network +wide +washington +japan +1990 +hospital +believe +changed +sister +##ar +hold +gone +sir +hadn +ship +##ka +studies +academy +shot +rights +below +base +bad +involved +kept +largest +##ist +bank +future +especially +beginning +mark +movement +section +female +magazine +plan +professor +lord +longer +##ian +sat +walked +hill +actually +civil +energy +model +families +size +thus +aircraft +completed +includes +data +captain +##or +fight +vocals +featured +richard +bridge +fourth +1989 +officer +stone +hear +##ism +means +medical +groups +management +self +lips +competition +entire +lived +technology +leaving +federal +tournament +bit +passed +hot +independent +awards +kingdom +mary +spent +fine +doesn +reported +##ling +jack +fall +raised +itself +stay +true +studio +1988 +sports +replaced +paris +systems +saint +leader +theatre +whose +market +capital +parents +spanish +canadian +earth +##ity +cut +degree +writing +bay +christian +awarded +natural +higher +bill +##as +coast +provided +previous +senior +ft +valley +organization +stopped +onto +countries +parts +conference +queen +security +interest +saying +allowed +master +earlier +phone +matter +smith +winning +try +happened +moving +campaign +los +##ley +breath +nearly +mid +1987 +certain +girls +date +italian +african +standing +fell +artist +##ted +shows +deal +mine +industry +1986 +##ng +everyone +republic +provide +collection +library +student +##ville +primary +owned +older +via +heavy +1st +makes +##able +attention +anyone +africa +##ri +stated +length +ended +fingers +command +staff +skin +foreign +opening +governor +okay +medal +kill +sun +cover +job +1985 +introduced +chest +hell +feeling +##ies +success +meet +reason +standard +meeting +novel +1984 +trade +source +buildings +##land +rose +guy +goal +##ur +chapter +native +husband +previously +unit +limited +entered +weeks +producer +operations +mountain +takes +covered +forced +related +roman +complete +successful +key +texas +cold +##ya +channel +1980 +traditional +films +dance +clear +approximately +500 +nine +van +prince +question +active +tracks +ireland +regional +silver +author +personal +sense +operation +##ine +economic +1983 +holding +twenty +isbn +additional +speed +hour +edition +regular +historic +places +whom +shook +movie +km² +secretary +prior +report +chicago +read +foundation +view +engine +scored +1982 +units +ask +airport +property +ready +immediately +lady +month +listed +contract +##de +manager +themselves +lines +##ki +navy +writer +meant +##ts +runs +##ro +practice +championships +singer +glass +commission +required +forest +starting +culture +generally +giving +access +attended +test +couple +stand +catholic +martin +caught +executive +##less +eye +##ey +thinking +chair +quite +shoulder +1979 +hope +decision +plays +defeated +municipality +whether +structure +offered +slowly +pain +ice +direction +##ion +paper +mission +1981 +mostly +200 +noted +individual +managed +nature +lives +plant +##ha +helped +except +studied +computer +figure +relationship +issue +significant +loss +die +smiled +gun +ago +highest +1972 +##am +male +bring +goals +mexico +problem +distance +commercial +completely +location +annual +famous +drive +1976 +neck +1978 +surface +caused +italy +understand +greek +highway +wrong +hotel +comes +appearance +joseph +double +issues +musical +companies +castle +income +review +assembly +bass +initially +parliament +artists +experience +1974 +particular +walk +foot +engineering +talking +window +dropped +##ter +miss +baby +boys +break +1975 +stars +edge +remember +policy +carried +train +stadium +bar +sex +angeles +evidence +##ge +becoming +assistant +soviet +1977 +upper +step +wing +1970 +youth +financial +reach +##ll +actor +numerous +##se +##st +nodded +arrived +##ation +minute +##nt +believed +sorry +complex +beautiful +victory +associated +temple +1968 +1973 +chance +perhaps +metal +##son +1945 +bishop +##et +lee +launched +particularly +tree +le +retired +subject +prize +contains +yeah +theory +empire +##ce +suddenly +waiting +trust +recording +##to +happy +terms +camp +champion +1971 +religious +pass +zealand +names +2nd +port +ancient +tom +corner +represented +watch +legal +anti +justice +cause +watched +brothers +45 +material +changes +simply +response +louis +fast +##ting +answer +60 +historical +1969 +stories +straight +create +feature +increased +rate +administration +virginia +el +activities +cultural +overall +winner +programs +basketball +legs +guard +beyond +cast +doctor +mm +flight +results +remains +cost +effect +winter +##ble +larger +islands +problems +chairman +grew +commander +isn +1967 +pay +failed +selected +hurt +fort +box +regiment +majority +journal +35 +edward +plans +##ke +##ni +shown +pretty +irish +characters +directly +scene +likely +operated +allow +spring +##j +junior +matches +looks +mike +houses +fellow +##tion +beach +marriage +##ham +##ive +rules +oil +65 +florida +expected +nearby +congress +sam +peace +recent +iii +wait +subsequently +cell +##do +variety +serving +agreed +please +poor +joe +pacific +attempt +wood +democratic +piece +prime +##ca +rural +mile +touch +appears +township +1964 +1966 +soldiers +##men +##ized +1965 +pennsylvania +closer +fighting +claimed +score +jones +physical +editor +##ous +filled +genus +specific +sitting +super +mom +##va +therefore +supported +status +fear +cases +store +meaning +wales +minor +spain +tower +focus +vice +frank +follow +parish +separate +golden +horse +fifth +remaining +branch +32 +presented +stared +##id +uses +secret +forms +##co +baseball +exactly +##ck +choice +note +discovered +travel +composed +truth +russia +ball +color +kiss +dad +wind +continue +ring +referred +numbers +digital +greater +##ns +metres +slightly +direct +increase +1960 +responsible +crew +rule +trees +troops +##no +broke +goes +individuals +hundred +weight +creek +sleep +memory +defense +provides +ordered +code +value +jewish +windows +1944 +safe +judge +whatever +corps +realized +growing +pre +##ga +cities +alexander +gaze +lies +spread +scott +letter +showed +situation +mayor +transport +watching +workers +extended +##li +expression +normal +##ment +chart +multiple +border +##ba +host +##ner +daily +mrs +walls +piano +##ko +heat +cannot +##ate +earned +products +drama +era +authority +seasons +join +grade +##io +sign +difficult +machine +1963 +territory +mainly +##wood +stations +squadron +1962 +stepped +iron +19th +##led +serve +appear +sky +speak +broken +charge +knowledge +kilometres +removed +ships +article +campus +simple +##ty +pushed +britain +##ve +leaves +recently +cd +soft +boston +latter +easy +acquired +poland +##sa +quality +officers +presence +planned +nations +mass +broadcast +jean +share +image +influence +wild +offer +emperor +electric +reading +headed +ability +promoted +yellow +ministry +1942 +throat +smaller +politician +##by +latin +spoke +cars +williams +males +lack +pop +80 +##ier +acting +seeing +consists +##ti +estate +1961 +pressure +johnson +newspaper +jr +chris +olympics +online +conditions +beat +elements +walking +vote +##field +needs +carolina +text +featuring +global +block +shirt +levels +francisco +purpose +females +et +dutch +duke +ahead +gas +twice +safety +serious +turning +highly +lieutenant +firm +maria +amount +mixed +daniel +proposed +perfect +agreement +affairs +3rd +seconds +contemporary +paid +1943 +prison +save +kitchen +label +administrative +intended +constructed +academic +nice +teacher +races +1956 +formerly +corporation +ben +nation +issued +shut +1958 +drums +housing +victoria +seems +opera +1959 +graduated +function +von +mentioned +picked +build +recognized +shortly +protection +picture +notable +exchange +elections +1980s +loved +percent +racing +fish +elizabeth +garden +volume +hockey +1941 +beside +settled +##ford +1940 +competed +replied +drew +1948 +actress +marine +scotland +steel +glanced +farm +steve +1957 +risk +tonight +positive +magic +singles +effects +gray +screen +dog +##ja +residents +bus +sides +none +secondary +literature +polish +destroyed +flying +founder +households +1939 +lay +reserve +usa +gallery +##ler +1946 +industrial +younger +approach +appearances +urban +ones +1950 +finish +avenue +powerful +fully +growth +page +honor +jersey +projects +advanced +revealed +basic +90 +infantry +pair +equipment +visit +33 +evening +search +grant +effort +solo +treatment +buried +republican +primarily +bottom +owner +1970s +israel +gives +jim +dream +bob +remain +spot +70 +notes +produce +champions +contact +ed +soul +accepted +ways +del +##ally +losing +split +price +capacity +basis +trial +questions +##ina +1955 +20th +guess +officially +memorial +naval +initial +##ization +whispered +median +engineer +##ful +sydney +##go +columbia +strength +300 +1952 +tears +senate +00 +card +asian +agent +1947 +software +44 +draw +warm +supposed +com +pro +##il +transferred +leaned +##at +candidate +escape +mountains +asia +potential +activity +entertainment +seem +traffic +jackson +murder +36 +slow +product +orchestra +haven +agency +bbc +taught +website +comedy +unable +storm +planning +albums +rugby +environment +scientific +grabbed +protect +##hi +boat +typically +1954 +1953 +damage +principal +divided +dedicated +mount +ohio +##berg +pick +fought +driver +##der +empty +shoulders +sort +thank +berlin +prominent +account +freedom +necessary +efforts +alex +headquarters +follows +alongside +des +simon +andrew +suggested +operating +learning +steps +1949 +sweet +technical +begin +easily +34 +teeth +speaking +settlement +scale +##sh +renamed +ray +max +enemy +semi +joint +compared +##rd +scottish +leadership +analysis +offers +georgia +pieces +captured +animal +deputy +guest +organized +##lin +tony +combined +method +challenge +1960s +huge +wants +battalion +sons +rise +crime +types +facilities +telling +path +1951 +platform +sit +1990s +##lo +tells +assigned +rich +pull +##ot +commonly +alive +##za +letters +concept +conducted +wearing +happen +bought +becomes +holy +gets +ocean +defeat +languages +purchased +coffee +occurred +titled +##q +declared +applied +sciences +concert +sounds +jazz +brain +##me +painting +fleet +tax +nick +##ius +michigan +count +animals +leaders +episodes +##line +content +##den +birth +##it +clubs +64 +palace +critical +refused +fair +leg +laughed +returning +surrounding +participated +formation +lifted +pointed +connected +rome +medicine +laid +taylor +santa +powers +adam +tall +shared +focused +knowing +yards +entrance +falls +##wa +calling +##ad +sources +chosen +beneath +resources +yard +##ite +nominated +silence +zone +defined +##que +gained +thirty +38 +bodies +moon +##ard +adopted +christmas +widely +register +apart +iran +premier +serves +du +unknown +parties +##les +generation +##ff +continues +quick +fields +brigade +quiet +teaching +clothes +impact +weapons +partner +flat +theater +supreme +1938 +37 +relations +##tor +plants +suffered +1936 +wilson +kids +begins +##age +1918 +seats +armed +internet +models +worth +laws +400 +communities +classes +background +knows +thanks +quarter +reaching +humans +carry +killing +format +kong +hong +setting +75 +architecture +disease +railroad +inc +possibly +wish +arthur +thoughts +harry +doors +density +##di +crowd +illinois +stomach +tone +unique +reports +anyway +##ir +liberal +der +vehicle +thick +dry +drug +faced +largely +facility +theme +holds +creation +strange +colonel +##mi +revolution +bell +politics +turns +silent +rail +relief +independence +combat +shape +write +determined +sales +learned +4th +finger +oxford +providing +1937 +heritage +fiction +situated +designated +allowing +distribution +hosted +##est +sight +interview +estimated +reduced +##ria +toronto +footballer +keeping +guys +damn +claim +motion +sport +sixth +stayed +##ze +en +rear +receive +handed +twelve +dress +audience +granted +brazil +##well +spirit +##ated +noticed +etc +olympic +representative +eric +tight +trouble +reviews +drink +vampire +missing +roles +ranked +newly +household +finals +wave +critics +##ee +phase +massachusetts +pilot +unlike +philadelphia +bright +guns +crown +organizations +roof +42 +respectively +clearly +tongue +marked +circle +fox +korea +bronze +brian +expanded +sexual +supply +yourself +inspired +labour +fc +##ah +reference +vision +draft +connection +brand +reasons +1935 +classic +driving +trip +jesus +cells +entry +1920 +neither +trail +claims +atlantic +orders +labor +nose +afraid +identified +intelligence +calls +cancer +attacked +passing +stephen +positions +imperial +grey +jason +39 +sunday +48 +swedish +avoid +extra +uncle +message +covers +allows +surprise +materials +fame +hunter +##ji +1930 +citizens +figures +davis +environmental +confirmed +shit +titles +di +performing +difference +acts +attacks +##ov +existing +votes +opportunity +nor +shop +entirely +trains +opposite +pakistan +##pa +develop +resulted +representatives +actions +reality +pressed +##ish +barely +wine +conversation +faculty +northwest +ends +documentary +nuclear +stock +grace +sets +eat +alternative +##ps +bag +resulting +creating +surprised +cemetery +1919 +drop +finding +sarah +cricket +streets +tradition +ride +1933 +exhibition +target +ear +explained +rain +composer +injury +apartment +municipal +educational +occupied +netherlands +clean +billion +constitution +learn +1914 +maximum +classical +francis +lose +opposition +jose +ontario +bear +core +hills +rolled +ending +drawn +permanent +fun +##tes +##lla +lewis +sites +chamber +ryan +##way +scoring +height +1934 +##house +lyrics +staring +55 +officials +1917 +snow +oldest +##tic +orange +##ger +qualified +interior +apparently +succeeded +thousand +dinner +lights +existence +fans +heavily +41 +greatest +conservative +send +bowl +plus +enter +catch +##un +economy +duty +1929 +speech +authorities +princess +performances +versions +shall +graduate +pictures +effective +remembered +poetry +desk +crossed +starring +starts +passenger +sharp +##ant +acres +ass +weather +falling +rank +fund +supporting +check +adult +publishing +heads +cm +southeast +lane +##burg +application +bc +##ura +les +condition +transfer +prevent +display +ex +regions +earl +federation +cool +relatively +answered +besides +1928 +obtained +portion +##town +mix +##ding +reaction +liked +dean +express +peak +1932 +##tte +counter +religion +chain +rare +miller +convention +aid +lie +vehicles +mobile +perform +squad +wonder +lying +crazy +sword +##ping +attempted +centuries +weren +philosophy +category +##ize +anna +interested +47 +sweden +wolf +frequently +abandoned +kg +literary +alliance +task +entitled +##ay +threw +promotion +factory +tiny +soccer +visited +matt +fm +achieved +52 +defence +internal +persian +43 +methods +##ging +arrested +otherwise +cambridge +programming +villages +elementary +districts +rooms +criminal +conflict +worry +trained +1931 +attempts +waited +signal +bird +truck +subsequent +programme +##ol +ad +49 +communist +details +faith +sector +patrick +carrying +laugh +##ss +controlled +korean +showing +origin +fuel +evil +1927 +##ent +brief +identity +darkness +address +pool +missed +publication +web +planet +ian +anne +wings +invited +##tt +briefly +standards +kissed +##be +ideas +climate +causing +walter +worse +albert +articles +winners +desire +aged +northeast +dangerous +gate +doubt +1922 +wooden +multi +##ky +poet +rising +funding +46 +communications +communication +violence +copies +prepared +ford +investigation +skills +1924 +pulling +electronic +##ak +##ial +##han +containing +ultimately +offices +singing +understanding +restaurant +tomorrow +fashion +christ +ward +da +pope +stands +5th +flow +studios +aired +commissioned +contained +exist +fresh +americans +##per +wrestling +approved +kid +employed +respect +suit +1925 +angel +asking +increasing +frame +angry +selling +1950s +thin +finds +##nd +temperature +statement +ali +explain +inhabitants +towns +extensive +narrow +51 +jane +flowers +images +promise +somewhere +object +fly +closely +##ls +1912 +bureau +cape +1926 +weekly +presidential +legislative +1921 +##ai +##au +launch +founding +##ny +978 +##ring +artillery +strike +un +institutions +roll +writers +landing +chose +kevin +anymore +pp +##ut +attorney +fit +dan +billboard +receiving +agricultural +breaking +sought +dave +admitted +lands +mexican +##bury +charlie +specifically +hole +iv +howard +credit +moscow +roads +accident +1923 +proved +wear +struck +hey +guards +stuff +slid +expansion +1915 +cat +anthony +##kin +melbourne +opposed +sub +southwest +architect +failure +plane +1916 +##ron +map +camera +tank +listen +regarding +wet +introduction +metropolitan +link +ep +fighter +inch +grown +gene +anger +fixed +buy +dvd +khan +domestic +worldwide +chapel +mill +functions +examples +##head +developing +1910 +turkey +hits +pocket +antonio +papers +grow +unless +circuit +18th +concerned +attached +journalist +selection +journey +converted +provincial +painted +hearing +aren +bands +negative +aside +wondered +knight +lap +survey +ma +##ow +noise +billy +##ium +shooting +guide +bedroom +priest +resistance +motor +homes +sounded +giant +##mer +150 +scenes +equal +comic +patients +hidden +solid +actual +bringing +afternoon +touched +funds +wedding +consisted +marie +canal +sr +kim +treaty +turkish +recognition +residence +cathedral +broad +knees +incident +shaped +fired +norwegian +handle +cheek +contest +represent +##pe +representing +beauty +##sen +birds +advantage +emergency +wrapped +drawing +notice +pink +broadcasting +##ong +somehow +bachelor +seventh +collected +registered +establishment +alan +assumed +chemical +personnel +roger +retirement +jeff +portuguese +wore +tied +device +threat +progress +advance +##ised +banks +hired +manchester +nfl +teachers +structures +forever +##bo +tennis +helping +saturday +sale +applications +junction +hip +incorporated +neighborhood +dressed +ceremony +##ds +influenced +hers +visual +stairs +decades +inner +kansas +hung +hoped +gain +scheduled +downtown +engaged +austria +clock +norway +certainly +pale +protected +1913 +victor +employees +plate +putting +surrounded +##ists +finishing +blues +tropical +##ries +minnesota +consider +philippines +accept +54 +retrieved +1900 +concern +anderson +properties +institution +gordon +successfully +vietnam +##dy +backing +outstanding +muslim +crossing +folk +producing +usual +demand +occurs +observed +lawyer +educated +##ana +kelly +string +pleasure +budget +items +quietly +colorado +philip +typical +##worth +derived +600 +survived +asks +mental +##ide +56 +jake +jews +distinguished +ltd +1911 +sri +extremely +53 +athletic +loud +thousands +worried +shadow +transportation +horses +weapon +arena +importance +users +tim +objects +contributed +dragon +douglas +aware +senator +johnny +jordan +sisters +engines +flag +investment +samuel +shock +capable +clark +row +wheel +refers +session +familiar +biggest +wins +hate +maintained +drove +hamilton +request +expressed +injured +underground +churches +walker +wars +tunnel +passes +stupid +agriculture +softly +cabinet +regarded +joining +indiana +##ea +##ms +push +dates +spend +behavior +woods +protein +gently +chase +morgan +mention +burning +wake +combination +occur +mirror +leads +jimmy +indeed +impossible +singapore +paintings +covering +##nes +soldier +locations +attendance +sell +historian +wisconsin +invasion +argued +painter +diego +changing +egypt +##don +experienced +inches +##ku +missouri +vol +grounds +spoken +switzerland +##gan +reform +rolling +ha +forget +massive +resigned +burned +allen +tennessee +locked +values +improved +##mo +wounded +universe +sick +dating +facing +pack +purchase +user +##pur +moments +##ul +merged +anniversary +1908 +coal +brick +understood +causes +dynasty +queensland +establish +stores +crisis +promote +hoping +views +cards +referee +extension +##si +raise +arizona +improve +colonial +formal +charged +##rt +palm +lucky +hide +rescue +faces +95 +feelings +candidates +juan +##ell +goods +6th +courses +weekend +59 +luke +cash +fallen +##om +delivered +affected +installed +carefully +tries +swiss +hollywood +costs +lincoln +responsibility +##he +shore +file +proper +normally +maryland +assistance +jump +constant +offering +friendly +waters +persons +realize +contain +trophy +800 +partnership +factor +58 +musicians +cry +bound +oregon +indicated +hero +houston +medium +##ure +consisting +somewhat +##ara +57 +cycle +##che +beer +moore +frederick +gotten +eleven +worst +weak +approached +arranged +chin +loan +universal +bond +fifteen +pattern +disappeared +##ney +translated +##zed +lip +arab +capture +interests +insurance +##chi +shifted +cave +prix +warning +sections +courts +coat +plot +smell +feed +golf +favorite +maintain +knife +vs +voted +degrees +finance +quebec +opinion +translation +manner +ruled +operate +productions +choose +musician +discovery +confused +tired +separated +stream +techniques +committed +attend +ranking +kings +throw +passengers +measure +horror +fan +mining +sand +danger +salt +calm +decade +dam +require +runner +##ik +rush +associate +greece +##ker +rivers +consecutive +matthew +##ski +sighed +sq +documents +steam +edited +closing +tie +accused +1905 +##ini +islamic +distributed +directors +organisation +bruce +7th +breathing +mad +lit +arrival +concrete +taste +08 +composition +shaking +faster +amateur +adjacent +stating +1906 +twin +flew +##ran +tokyo +publications +##tone +obviously +ridge +storage +1907 +carl +pages +concluded +desert +driven +universities +ages +terminal +sequence +borough +250 +constituency +creative +cousin +economics +dreams +margaret +notably +reduce +montreal +mode +17th +ears +saved +jan +vocal +##ica +1909 +andy +##jo +riding +roughly +threatened +##ise +meters +meanwhile +landed +compete +repeated +grass +czech +regularly +charges +tea +sudden +appeal +##ung +solution +describes +pierre +classification +glad +parking +##ning +belt +physics +99 +rachel +add +hungarian +participate +expedition +damaged +gift +childhood +85 +fifty +##red +mathematics +jumped +letting +defensive +mph +##ux +##gh +testing +##hip +hundreds +shoot +owners +matters +smoke +israeli +kentucky +dancing +mounted +grandfather +emma +designs +profit +argentina +##gs +truly +li +lawrence +cole +begun +detroit +willing +branches +smiling +decide +miami +enjoyed +recordings +##dale +poverty +ethnic +gay +##bi +gary +arabic +09 +accompanied +##one +##ons +fishing +determine +residential +acid +##ary +alice +returns +starred +mail +##ang +jonathan +strategy +##ue +net +forty +cook +businesses +equivalent +commonwealth +distinct +ill +##cy +seriously +##ors +##ped +shift +harris +replace +rio +imagine +formula +ensure +##ber +additionally +scheme +conservation +occasionally +purposes +feels +favor +##and +##ore +1930s +contrast +hanging +hunt +movies +1904 +instruments +victims +danish +christopher +busy +demon +sugar +earliest +colony +studying +balance +duties +##ks +belgium +slipped +carter +05 +visible +stages +iraq +fifa +##im +commune +forming +zero +07 +continuing +talked +counties +legend +bathroom +option +tail +clay +daughters +afterwards +severe +jaw +visitors +##ded +devices +aviation +russell +kate +##vi +entering +subjects +##ino +temporary +swimming +forth +smooth +ghost +audio +bush +operates +rocks +movements +signs +eddie +##tz +ann +voices +honorary +06 +memories +dallas +pure +measures +racial +promised +66 +harvard +ceo +16th +parliamentary +indicate +benefit +flesh +dublin +louisiana +1902 +1901 +patient +sleeping +1903 +membership +coastal +medieval +wanting +element +scholars +rice +62 +limit +survive +makeup +rating +definitely +collaboration +obvious +##tan +boss +ms +baron +birthday +linked +soil +diocese +##lan +ncaa +##mann +offensive +shell +shouldn +waist +##tus +plain +ross +organ +resolution +manufacturing +adding +relative +kennedy +98 +whilst +moth +marketing +gardens +crash +72 +heading +partners +credited +carlos +moves +cable +##zi +marshall +##out +depending +bottle +represents +rejected +responded +existed +04 +jobs +denmark +lock +##ating +treated +graham +routes +talent +commissioner +drugs +secure +tests +reign +restored +photography +##gi +contributions +oklahoma +designer +disc +grin +seattle +robin +paused +atlanta +unusual +##gate +praised +las +laughing +satellite +hungary +visiting +##sky +interesting +factors +deck +poems +norman +##water +stuck +speaker +rifle +domain +premiered +##her +dc +comics +actors +01 +reputation +eliminated +8th +ceiling +prisoners +script +##nce +leather +austin +mississippi +rapidly +admiral +parallel +charlotte +guilty +tools +gender +divisions +fruit +##bs +laboratory +nelson +fantasy +marry +rapid +aunt +tribe +requirements +aspects +suicide +amongst +adams +bone +ukraine +abc +kick +sees +edinburgh +clothing +column +rough +gods +hunting +broadway +gathered +concerns +##ek +spending +ty +12th +snapped +requires +solar +bones +cavalry +##tta +iowa +drinking +waste +index +franklin +charity +thompson +stewart +tip +flash +landscape +friday +enjoy +singh +poem +listening +##back +eighth +fred +differences +adapted +bomb +ukrainian +surgery +corporate +masters +anywhere +##more +waves +odd +sean +portugal +orleans +dick +debate +kent +eating +puerto +cleared +96 +expect +cinema +97 +guitarist +blocks +electrical +agree +involving +depth +dying +panel +struggle +##ged +peninsula +adults +novels +emerged +vienna +metro +debuted +shoes +tamil +songwriter +meets +prove +beating +instance +heaven +scared +sending +marks +artistic +passage +superior +03 +significantly +shopping +##tive +retained +##izing +malaysia +technique +cheeks +##ola +warren +maintenance +destroy +extreme +allied +120 +appearing +##yn +fill +advice +alabama +qualifying +policies +cleveland +hat +battery +smart +authors +10th +soundtrack +acted +dated +lb +glance +equipped +coalition +funny +outer +ambassador +roy +possibility +couples +campbell +dna +loose +ethan +supplies +1898 +gonna +88 +monster +##res +shake +agents +frequency +springs +dogs +practices +61 +gang +plastic +easier +suggests +gulf +blade +exposed +colors +industries +markets +pan +nervous +electoral +charts +legislation +ownership +##idae +mac +appointment +shield +copy +assault +socialist +abbey +monument +license +throne +employment +jay +93 +replacement +charter +cloud +powered +suffering +accounts +oak +connecticut +strongly +wright +colour +crystal +13th +context +welsh +networks +voiced +gabriel +jerry +##cing +forehead +mp +##ens +manage +schedule +totally +remix +##ii +forests +occupation +print +nicholas +brazilian +strategic +vampires +engineers +76 +roots +seek +correct +instrumental +und +alfred +backed +hop +##des +stanley +robinson +traveled +wayne +welcome +austrian +achieve +67 +exit +rates +1899 +strip +whereas +##cs +sing +deeply +adventure +bobby +rick +jamie +careful +components +cap +useful +personality +knee +##shi +pushing +hosts +02 +protest +ca +ottoman +symphony +##sis +63 +boundary +1890 +processes +considering +considerable +tons +##work +##ft +##nia +cooper +trading +dear +conduct +91 +illegal +apple +revolutionary +holiday +definition +harder +##van +jacob +circumstances +destruction +##lle +popularity +grip +classified +liverpool +donald +baltimore +flows +seeking +honour +approval +92 +mechanical +till +happening +statue +critic +increasingly +immediate +describe +commerce +stare +##ster +indonesia +meat +rounds +boats +baker +orthodox +depression +formally +worn +naked +claire +muttered +sentence +11th +emily +document +77 +criticism +wished +vessel +spiritual +bent +virgin +parker +minimum +murray +lunch +danny +printed +compilation +keyboards +false +blow +belonged +68 +raising +78 +cutting +##board +pittsburgh +##up +9th +shadows +81 +hated +indigenous +jon +15th +barry +scholar +ah +##zer +oliver +##gy +stick +susan +meetings +attracted +spell +romantic +##ver +ye +1895 +photo +demanded +customers +##ac +1896 +logan +revival +keys +modified +commanded +jeans +##ious +upset +raw +phil +detective +hiding +resident +vincent +##bly +experiences +diamond +defeating +coverage +lucas +external +parks +franchise +helen +bible +successor +percussion +celebrated +il +lift +profile +clan +romania +##ied +mills +##su +nobody +achievement +shrugged +fault +1897 +rhythm +initiative +breakfast +carbon +700 +69 +lasted +violent +74 +wound +ken +killer +gradually +filmed +°c +dollars +processing +94 +remove +criticized +guests +sang +chemistry +##vin +legislature +disney +##bridge +uniform +escaped +integrated +proposal +purple +denied +liquid +karl +influential +morris +nights +stones +intense +experimental +twisted +71 +84 +##ld +pace +nazi +mitchell +ny +blind +reporter +newspapers +14th +centers +burn +basin +forgotten +surviving +filed +collections +monastery +losses +manual +couch +description +appropriate +merely +tag +missions +sebastian +restoration +replacing +triple +73 +elder +julia +warriors +benjamin +julian +convinced +stronger +amazing +declined +versus +merchant +happens +output +finland +bare +barbara +absence +ignored +dawn +injuries +##port +producers +##ram +82 +luis +##ities +kw +admit +expensive +electricity +nba +exception +symbol +##ving +ladies +shower +sheriff +characteristics +##je +aimed +button +ratio +effectively +summit +angle +jury +bears +foster +vessels +pants +executed +evans +dozen +advertising +kicked +patrol +1889 +competitions +lifetime +principles +athletics +##logy +birmingham +sponsored +89 +rob +nomination +1893 +acoustic +##sm +creature +longest +##tra +credits +harbor +dust +josh +##so +territories +milk +infrastructure +completion +thailand +indians +leon +archbishop +##sy +assist +pitch +blake +arrangement +girlfriend +serbian +operational +hence +sad +scent +fur +dj +sessions +hp +refer +rarely +##ora +exists +1892 +##ten +scientists +dirty +penalty +burst +portrait +seed +79 +pole +limits +rival +1894 +stable +alpha +grave +constitutional +alcohol +arrest +flower +mystery +devil +architectural +relationships +greatly +habitat +##istic +larry +progressive +remote +cotton +##ics +##ok +preserved +reaches +##ming +cited +86 +vast +scholarship +decisions +cbs +joy +teach +1885 +editions +knocked +eve +searching +partly +participation +gap +animated +fate +excellent +##ett +na +87 +alternate +saints +youngest +##ily +climbed +##ita +##tors +suggest +##ct +discussion +staying +choir +lakes +jacket +revenue +nevertheless +peaked +instrument +wondering +annually +managing +neil +1891 +signing +terry +##ice +apply +clinical +brooklyn +aim +catherine +fuck +farmers +figured +ninth +pride +hugh +evolution +ordinary +involvement +comfortable +shouted +tech +encouraged +taiwan +representation +sharing +##lia +##em +panic +exact +cargo +competing +fat +cried +83 +1920s +occasions +pa +cabin +borders +utah +marcus +##isation +badly +muscles +##ance +victorian +transition +warner +bet +permission +##rin +slave +terrible +similarly +shares +seth +uefa +possession +medals +benefits +colleges +lowered +perfectly +mall +transit +##ye +##kar +publisher +##ened +harrison +deaths +elevation +##ae +asleep +machines +sigh +ash +hardly +argument +occasion +parent +leo +decline +1888 +contribution +##ua +concentration +1000 +opportunities +hispanic +guardian +extent +emotions +hips +mason +volumes +bloody +controversy +diameter +steady +mistake +phoenix +identify +violin +##sk +departure +richmond +spin +funeral +enemies +1864 +gear +literally +connor +random +sergeant +grab +confusion +1865 +transmission +informed +op +leaning +sacred +suspended +thinks +gates +portland +luck +agencies +yours +hull +expert +muscle +layer +practical +sculpture +jerusalem +latest +lloyd +statistics +deeper +recommended +warrior +arkansas +mess +supports +greg +eagle +1880 +recovered +rated +concerts +rushed +##ano +stops +eggs +files +premiere +keith +##vo +delhi +turner +pit +affair +belief +paint +##zing +mate +##ach +##ev +victim +##ology +withdrew +bonus +styles +fled +##ud +glasgow +technologies +funded +nbc +adaptation +##ata +portrayed +cooperation +supporters +judges +bernard +justin +hallway +ralph +##ick +graduating +controversial +distant +continental +spider +bite +##ho +recognize +intention +mixing +##ese +egyptian +bow +tourism +suppose +claiming +tiger +dominated +participants +vi +##ru +nurse +partially +tape +##rum +psychology +##rn +essential +touring +duo +voting +civilian +emotional +channels +##king +apparent +hebrew +1887 +tommy +carrier +intersection +beast +hudson +##gar +##zo +lab +nova +bench +discuss +costa +##ered +detailed +behalf +drivers +unfortunately +obtain +##lis +rocky +##dae +siege +friendship +honey +##rian +1861 +amy +hang +posted +governments +collins +respond +wildlife +preferred +operator +##po +laura +pregnant +videos +dennis +suspected +boots +instantly +weird +automatic +businessman +alleged +placing +throwing +ph +mood +1862 +perry +venue +jet +remainder +##lli +##ci +passion +biological +boyfriend +1863 +dirt +buffalo +ron +segment +fa +abuse +##era +genre +thrown +stroke +colored +stress +exercise +displayed +##gen +struggled +##tti +abroad +dramatic +wonderful +thereafter +madrid +component +widespread +##sed +tale +citizen +todd +monday +1886 +vancouver +overseas +forcing +crying +descent +##ris +discussed +substantial +ranks +regime +1870 +provinces +switch +drum +zane +ted +tribes +proof +lp +cream +researchers +volunteer +manor +silk +milan +donated +allies +venture +principle +delivery +enterprise +##ves +##ans +bars +traditionally +witch +reminded +copper +##uk +pete +inter +links +colin +grinned +elsewhere +competitive +frequent +##oy +scream +##hu +tension +texts +submarine +finnish +defending +defend +pat +detail +1884 +affiliated +stuart +themes +villa +periods +tool +belgian +ruling +crimes +answers +folded +licensed +resort +demolished +hans +lucy +1881 +lion +traded +photographs +writes +craig +##fa +trials +generated +beth +noble +debt +percentage +yorkshire +erected +ss +viewed +grades +confidence +ceased +islam +telephone +retail +##ible +chile +m² +roberts +sixteen +##ich +commented +hampshire +innocent +dual +pounds +checked +regulations +afghanistan +sung +rico +liberty +assets +bigger +options +angels +relegated +tribute +wells +attending +leaf +##yan +butler +romanian +forum +monthly +lisa +patterns +gmina +##tory +madison +hurricane +rev +##ians +bristol +##ula +elite +valuable +disaster +democracy +awareness +germans +freyja +##ins +loop +absolutely +paying +populations +maine +sole +prayer +spencer +releases +doorway +bull +##ani +lover +midnight +conclusion +##sson +thirteen +lily +mediterranean +##lt +nhl +proud +sample +##hill +drummer +guinea +##ova +murphy +climb +##ston +instant +attributed +horn +ain +railways +steven +##ao +autumn +ferry +opponent +root +traveling +secured +corridor +stretched +tales +sheet +trinity +cattle +helps +indicates +manhattan +murdered +fitted +1882 +gentle +grandmother +mines +shocked +vegas +produces +##light +caribbean +##ou +belong +continuous +desperate +drunk +historically +trio +waved +raf +dealing +nathan +bat +murmured +interrupted +residing +scientist +pioneer +harold +aaron +##net +delta +attempting +minority +mini +believes +chorus +tend +lots +eyed +indoor +load +shots +updated +jail +##llo +concerning +connecting +wealth +##ved +slaves +arrive +rangers +sufficient +rebuilt +##wick +cardinal +flood +muhammad +whenever +relation +runners +moral +repair +viewers +arriving +revenge +punk +assisted +bath +fairly +breathe +lists +innings +illustrated +whisper +nearest +voters +clinton +ties +ultimate +screamed +beijing +lions +andre +fictional +gathering +comfort +radar +suitable +dismissed +hms +ban +pine +wrist +atmosphere +voivodeship +bid +timber +##ned +##nan +giants +##ane +cameron +recovery +uss +identical +categories +switched +serbia +laughter +noah +ensemble +therapy +peoples +touching +##off +locally +pearl +platforms +everywhere +ballet +tables +lanka +herbert +outdoor +toured +derek +1883 +spaces +contested +swept +1878 +exclusive +slight +connections +##dra +winds +prisoner +collective +bangladesh +tube +publicly +wealthy +thai +##ys +isolated +select +##ric +insisted +pen +fortune +ticket +spotted +reportedly +animation +enforcement +tanks +110 +decides +wider +lowest +owen +##time +nod +hitting +##hn +gregory +furthermore +magazines +fighters +solutions +##ery +pointing +requested +peru +reed +chancellor +knights +mask +worker +eldest +flames +reduction +1860 +volunteers +##tis +reporting +##hl +wire +advisory +endemic +origins +settlers +pursue +knock +consumer +1876 +eu +compound +creatures +mansion +sentenced +ivan +deployed +guitars +frowned +involves +mechanism +kilometers +perspective +shops +maps +terminus +duncan +alien +fist +bridges +##pers +heroes +fed +derby +swallowed +##ros +patent +sara +illness +characterized +adventures +slide +hawaii +jurisdiction +##op +organised +##side +adelaide +walks +biology +se +##ties +rogers +swing +tightly +boundaries +##rie +prepare +implementation +stolen +##sha +certified +colombia +edwards +garage +##mm +recalled +##ball +rage +harm +nigeria +breast +##ren +furniture +pupils +settle +##lus +cuba +balls +client +alaska +21st +linear +thrust +celebration +latino +genetic +terror +##cia +##ening +lightning +fee +witness +lodge +establishing +skull +##ique +earning +hood +##ei +rebellion +wang +sporting +warned +missile +devoted +activist +porch +worship +fourteen +package +1871 +decorated +##shire +housed +##ock +chess +sailed +doctors +oscar +joan +treat +garcia +harbour +jeremy +##ire +traditions +dominant +jacques +##gon +##wan +relocated +1879 +amendment +sized +companion +simultaneously +volleyball +spun +acre +increases +stopping +loves +belongs +affect +drafted +tossed +scout +battles +1875 +filming +shoved +munich +tenure +vertical +romance +pc +##cher +argue +##ical +craft +ranging +www +opens +honest +tyler +yesterday +virtual +##let +muslims +reveal +snake +immigrants +radical +screaming +speakers +firing +saving +belonging +ease +lighting +prefecture +blame +farmer +hungry +grows +rubbed +beam +sur +subsidiary +##cha +armenian +sao +dropping +conventional +##fer +microsoft +reply +qualify +spots +1867 +sweat +festivals +##ken +immigration +physician +discover +exposure +sandy +explanation +isaac +implemented +##fish +hart +initiated +connect +stakes +presents +heights +householder +pleased +tourist +regardless +slip +closest +##ction +surely +sultan +brings +riley +preparation +aboard +slammed +baptist +experiment +ongoing +interstate +organic +playoffs +##ika +1877 +130 +##tar +hindu +error +tours +tier +plenty +arrangements +talks +trapped +excited +sank +ho +athens +1872 +denver +welfare +suburb +athletes +trick +diverse +belly +exclusively +yelled +1868 +##med +conversion +##ette +1874 +internationally +computers +conductor +abilities +sensitive +hello +dispute +measured +globe +rocket +prices +amsterdam +flights +tigers +inn +municipalities +emotion +references +3d +##mus +explains +airlines +manufactured +pm +archaeological +1873 +interpretation +devon +comment +##ites +settlements +kissing +absolute +improvement +suite +impressed +barcelona +sullivan +jefferson +towers +jesse +julie +##tin +##lu +grandson +hi +gauge +regard +rings +interviews +trace +raymond +thumb +departments +burns +serial +bulgarian +scores +demonstrated +##ix +1866 +kyle +alberta +underneath +romanized +##ward +relieved +acquisition +phrase +cliff +reveals +han +cuts +merger +custom +##dar +nee +gilbert +graduation +##nts +assessment +cafe +difficulty +demands +swung +democrat +jennifer +commons +1940s +grove +##yo +completing +focuses +sum +substitute +bearing +stretch +reception +##py +reflected +essentially +destination +pairs +##ched +survival +resource +##bach +promoting +doubles +messages +tear +##down +##fully +parade +florence +harvey +incumbent +partial +framework +900 +pedro +frozen +procedure +olivia +controls +##mic +shelter +personally +temperatures +##od +brisbane +tested +sits +marble +comprehensive +oxygen +leonard +##kov +inaugural +iranian +referring +quarters +attitude +##ivity +mainstream +lined +mars +dakota +norfolk +unsuccessful +##° +explosion +helicopter +congressional +##sing +inspector +bitch +seal +departed +divine +##ters +coaching +examination +punishment +manufacturer +sink +columns +unincorporated +signals +nevada +squeezed +dylan +dining +photos +martial +manuel +eighteen +elevator +brushed +plates +ministers +ivy +congregation +##len +slept +specialized +taxes +curve +restricted +negotiations +likes +statistical +arnold +inspiration +execution +bold +intermediate +significance +margin +ruler +wheels +gothic +intellectual +dependent +listened +eligible +buses +widow +syria +earn +cincinnati +collapsed +recipient +secrets +accessible +philippine +maritime +goddess +clerk +surrender +breaks +playoff +database +##ified +##lon +ideal +beetle +aspect +soap +regulation +strings +expand +anglo +shorter +crosses +retreat +tough +coins +wallace +directions +pressing +##oon +shipping +locomotives +comparison +topics +nephew +##mes +distinction +honors +travelled +sierra +ibn +##over +fortress +sa +recognised +carved +1869 +clients +##dan +intent +##mar +coaches +describing +bread +##ington +beaten +northwestern +##ona +merit +youtube +collapse +challenges +em +historians +objective +submitted +virus +attacking +drake +assume +##ere +diseases +marc +stem +leeds +##cus +##ab +farming +glasses +##lock +visits +nowhere +fellowship +relevant +carries +restaurants +experiments +101 +constantly +bases +targets +shah +tenth +opponents +verse +territorial +##ira +writings +corruption +##hs +instruction +inherited +reverse +emphasis +##vic +employee +arch +keeps +rabbi +watson +payment +uh +##ala +nancy +##tre +venice +fastest +sexy +banned +adrian +properly +ruth +touchdown +dollar +boards +metre +circles +edges +favour +comments +ok +travels +liberation +scattered +firmly +##ular +holland +permitted +diesel +kenya +den +originated +##ral +demons +resumed +dragged +rider +##rus +servant +blinked +extend +torn +##ias +##sey +input +meal +everybody +cylinder +kinds +camps +##fe +bullet +logic +##wn +croatian +evolved +healthy +fool +chocolate +wise +preserve +pradesh +##ess +respective +1850 +##ew +chicken +artificial +gross +corresponding +convicted +cage +caroline +dialogue +##dor +narrative +stranger +mario +br +christianity +failing +trent +commanding +buddhist +1848 +maurice +focusing +yale +bike +altitude +##ering +mouse +revised +##sley +veteran +##ig +pulls +theology +crashed +campaigns +legion +##ability +drag +excellence +customer +cancelled +intensity +excuse +##lar +liga +participating +contributing +printing +##burn +variable +##rk +curious +bin +legacy +renaissance +##my +symptoms +binding +vocalist +dancer +##nie +grammar +gospel +democrats +ya +enters +sc +diplomatic +hitler +##ser +clouds +mathematical +quit +defended +oriented +##heim +fundamental +hardware +impressive +equally +convince +confederate +guilt +chuck +sliding +##ware +magnetic +narrowed +petersburg +bulgaria +otto +phd +skill +##ama +reader +hopes +pitcher +reservoir +hearts +automatically +expecting +mysterious +bennett +extensively +imagined +seeds +monitor +fix +##ative +journalism +struggling +signature +ranch +encounter +photographer +observation +protests +##pin +influences +##hr +calendar +##all +cruz +croatia +locomotive +hughes +naturally +shakespeare +basement +hook +uncredited +faded +theories +approaches +dare +phillips +filling +fury +obama +##ain +efficient +arc +deliver +min +raid +breeding +inducted +leagues +efficiency +axis +montana +eagles +##ked +supplied +instructions +karen +picking +indicating +trap +anchor +practically +christians +tomb +vary +occasional +electronics +lords +readers +newcastle +faint +innovation +collect +situations +engagement +160 +claude +mixture +##feld +peer +tissue +logo +lean +##ration +°f +floors +##ven +architects +reducing +##our +##ments +rope +1859 +ottawa +##har +samples +banking +declaration +proteins +resignation +francois +saudi +advocate +exhibited +armor +twins +divorce +##ras +abraham +reviewed +jo +temporarily +matrix +physically +pulse +curled +##ena +difficulties +bengal +usage +##ban +annie +riders +certificate +##pi +holes +warsaw +distinctive +jessica +##mon +mutual +1857 +customs +circular +eugene +removal +loaded +mere +vulnerable +depicted +generations +dame +heir +enormous +lightly +climbing +pitched +lessons +pilots +nepal +ram +google +preparing +brad +louise +renowned +##₂ +liam +##ably +plaza +shaw +sophie +brilliant +bills +##bar +##nik +fucking +mainland +server +pleasant +seized +veterans +jerked +fail +beta +brush +radiation +stored +warmth +southeastern +nate +sin +raced +berkeley +joke +athlete +designation +trunk +##low +roland +qualification +archives +heels +artwork +receives +judicial +reserves +##bed +woke +installation +abu +floating +fake +lesser +excitement +interface +concentrated +addressed +characteristic +amanda +saxophone +monk +auto +##bus +releasing +egg +dies +interaction +defender +ce +outbreak +glory +loving +##bert +sequel +consciousness +http +awake +ski +enrolled +##ress +handling +rookie +brow +somebody +biography +warfare +amounts +contracts +presentation +fabric +dissolved +challenged +meter +psychological +lt +elevated +rally +accurate +##tha +hospitals +undergraduate +specialist +venezuela +exhibit +shed +nursing +protestant +fluid +structural +footage +jared +consistent +prey +##ska +succession +reflect +exile +lebanon +wiped +suspect +shanghai +resting +integration +preservation +marvel +variant +pirates +sheep +rounded +capita +sailing +colonies +manuscript +deemed +variations +clarke +functional +emerging +boxing +relaxed +curse +azerbaijan +heavyweight +nickname +editorial +rang +grid +tightened +earthquake +flashed +miguel +rushing +##ches +improvements +boxes +brooks +180 +consumption +molecular +felix +societies +repeatedly +variation +aids +civic +graphics +professionals +realm +autonomous +receiver +delayed +workshop +militia +chairs +trump +canyon +##point +harsh +extending +lovely +happiness +##jan +stake +eyebrows +embassy +wellington +hannah +##ella +sony +corners +bishops +swear +cloth +contents +xi +namely +commenced +1854 +stanford +nashville +courage +graphic +commitment +garrison +##bin +hamlet +clearing +rebels +attraction +literacy +cooking +ruins +temples +jenny +humanity +celebrate +hasn +freight +sixty +rebel +bastard +##art +newton +##ada +deer +##ges +##ching +smiles +delaware +singers +##ets +approaching +assists +flame +##ph +boulevard +barrel +planted +##ome +pursuit +##sia +consequences +posts +shallow +invitation +rode +depot +ernest +kane +rod +concepts +preston +topic +chambers +striking +blast +arrives +descendants +montgomery +ranges +worlds +##lay +##ari +span +chaos +praise +##ag +fewer +1855 +sanctuary +mud +fbi +##ions +programmes +maintaining +unity +harper +bore +handsome +closure +tournaments +thunder +nebraska +linda +facade +puts +satisfied +argentine +dale +cork +dome +panama +##yl +1858 +tasks +experts +##ates +feeding +equation +##las +##ida +##tu +engage +bryan +##ax +um +quartet +melody +disbanded +sheffield +blocked +gasped +delay +kisses +maggie +connects +##non +sts +poured +creator +publishers +##we +guided +ellis +extinct +hug +gaining +##ord +complicated +##bility +poll +clenched +investigate +##use +thereby +quantum +spine +cdp +humor +kills +administered +semifinals +##du +encountered +ignore +##bu +commentary +##maker +bother +roosevelt +140 +plains +halfway +flowing +cultures +crack +imprisoned +neighboring +airline +##ses +##view +##mate +##ec +gather +wolves +marathon +transformed +##ill +cruise +organisations +carol +punch +exhibitions +numbered +alarm +ratings +daddy +silently +##stein +queens +colours +impression +guidance +liu +tactical +##rat +marshal +della +arrow +##ings +rested +feared +tender +owns +bitter +advisor +escort +##ides +spare +farms +grants +##ene +dragons +encourage +colleagues +cameras +##und +sucked +pile +spirits +prague +statements +suspension +landmark +fence +torture +recreation +bags +permanently +survivors +pond +spy +predecessor +bombing +coup +##og +protecting +transformation +glow +##lands +##book +dug +priests +andrea +feat +barn +jumping +##chen +##ologist +##con +casualties +stern +auckland +pipe +serie +revealing +ba +##bel +trevor +mercy +spectrum +yang +consist +governing +collaborated +possessed +epic +comprises +blew +shane +##ack +lopez +honored +magical +sacrifice +judgment +perceived +hammer +mtv +baronet +tune +das +missionary +sheets +350 +neutral +oral +threatening +attractive +shade +aims +seminary +##master +estates +1856 +michel +wounds +refugees +manufacturers +##nic +mercury +syndrome +porter +##iya +##din +hamburg +identification +upstairs +purse +widened +pause +cared +breathed +affiliate +santiago +prevented +celtic +fisher +125 +recruited +byzantine +reconstruction +farther +##mp +diet +sake +au +spite +sensation +##ert +blank +separation +105 +##hon +vladimir +armies +anime +##lie +accommodate +orbit +cult +sofia +archive +##ify +##box +founders +sustained +disorder +honours +northeastern +mia +crops +violet +threats +blanket +fires +canton +followers +southwestern +prototype +voyage +assignment +altered +moderate +protocol +pistol +##eo +questioned +brass +lifting +1852 +math +authored +##ual +doug +dimensional +dynamic +##san +1851 +pronounced +grateful +quest +uncomfortable +boom +presidency +stevens +relating +politicians +chen +barrier +quinn +diana +mosque +tribal +cheese +palmer +portions +sometime +chester +treasure +wu +bend +download +millions +reforms +registration +##osa +consequently +monitoring +ate +preliminary +brandon +invented +ps +eaten +exterior +intervention +ports +documented +log +displays +lecture +sally +favourite +##itz +vermont +lo +invisible +isle +breed +##ator +journalists +relay +speaks +backward +explore +midfielder +actively +stefan +procedures +cannon +blond +kenneth +centered +servants +chains +libraries +malcolm +essex +henri +slavery +##hal +facts +fairy +coached +cassie +cats +washed +cop +##fi +announcement +item +2000s +vinyl +activated +marco +frontier +growled +curriculum +##das +loyal +accomplished +leslie +ritual +kenny +##00 +vii +napoleon +hollow +hybrid +jungle +stationed +friedrich +counted +##ulated +platinum +theatrical +seated +col +rubber +glen +1840 +diversity +healing +extends +id +provisions +administrator +columbus +##oe +tributary +te +assured +org +##uous +prestigious +examined +lectures +grammy +ronald +associations +bailey +allan +essays +flute +believing +consultant +proceedings +travelling +1853 +kit +kerala +yugoslavia +buddy +methodist +##ith +burial +centres +batman +##nda +discontinued +bo +dock +stockholm +lungs +severely +##nk +citing +manga +##ugh +steal +mumbai +iraqi +robot +celebrity +bride +broadcasts +abolished +pot +joel +overhead +franz +packed +reconnaissance +johann +acknowledged +introduce +handled +doctorate +developments +drinks +alley +palestine +##nis +##aki +proceeded +recover +bradley +grain +patch +afford +infection +nationalist +legendary +##ath +interchange +virtually +gen +gravity +exploration +amber +vital +wishes +powell +doctrine +elbow +screenplay +##bird +contribute +indonesian +pet +creates +##com +enzyme +kylie +discipline +drops +manila +hunger +##ien +layers +suffer +fever +bits +monica +keyboard +manages +##hood +searched +appeals +##bad +testament +grande +reid +##war +beliefs +congo +##ification +##dia +si +requiring +##via +casey +1849 +regret +streak +rape +depends +syrian +sprint +pound +tourists +upcoming +pub +##xi +tense +##els +practiced +echo +nationwide +guild +motorcycle +liz +##zar +chiefs +desired +elena +bye +precious +absorbed +relatives +booth +pianist +##mal +citizenship +exhausted +wilhelm +##ceae +##hed +noting +quarterback +urge +hectares +##gue +ace +holly +##tal +blonde +davies +parked +sustainable +stepping +twentieth +airfield +galaxy +nest +chip +##nell +tan +shaft +paulo +requirement +##zy +paradise +tobacco +trans +renewed +vietnamese +##cker +##ju +suggesting +catching +holmes +enjoying +md +trips +colt +holder +butterfly +nerve +reformed +cherry +bowling +trailer +carriage +goodbye +appreciate +toy +joshua +interactive +enabled +involve +##kan +collar +determination +bunch +facebook +recall +shorts +superintendent +episcopal +frustration +giovanni +nineteenth +laser +privately +array +circulation +##ovic +armstrong +deals +painful +permit +discrimination +##wi +aires +retiring +cottage +ni +##sta +horizon +ellen +jamaica +ripped +fernando +chapters +playstation +patron +lecturer +navigation +behaviour +genes +georgian +export +solomon +rivals +swift +seventeen +rodriguez +princeton +independently +sox +1847 +arguing +entity +casting +hank +criteria +oakland +geographic +milwaukee +reflection +expanding +conquest +dubbed +##tv +halt +brave +brunswick +doi +arched +curtis +divorced +predominantly +somerset +streams +ugly +zoo +horrible +curved +buenos +fierce +dictionary +vector +theological +unions +handful +stability +chan +punjab +segments +##lly +altar +ignoring +gesture +monsters +pastor +##stone +thighs +unexpected +operators +abruptly +coin +compiled +associates +improving +migration +pin +##ose +compact +collegiate +reserved +##urs +quarterfinals +roster +restore +assembled +hurry +oval +##cies +1846 +flags +martha +##del +victories +sharply +##rated +argues +deadly +neo +drawings +symbols +performer +##iel +griffin +restrictions +editing +andrews +java +journals +arabia +compositions +dee +pierce +removing +hindi +casino +runway +civilians +minds +nasa +hotels +##zation +refuge +rent +retain +potentially +conferences +suburban +conducting +##tto +##tions +##tle +descended +massacre +##cal +ammunition +terrain +fork +souls +counts +chelsea +durham +drives +cab +##bank +perth +realizing +palestinian +finn +simpson +##dal +betty +##ule +moreover +particles +cardinals +tent +evaluation +extraordinary +##oid +inscription +##works +wednesday +chloe +maintains +panels +ashley +trucks +##nation +cluster +sunlight +strikes +zhang +##wing +dialect +canon +##ap +tucked +##ws +collecting +##mas +##can +##sville +maker +quoted +evan +franco +aria +buying +cleaning +eva +closet +provision +apollo +clinic +rat +##ez +necessarily +ac +##gle +##ising +venues +flipped +cent +spreading +trustees +checking +authorized +##sco +disappointed +##ado +notion +duration +trumpet +hesitated +topped +brussels +rolls +theoretical +hint +define +aggressive +repeat +wash +peaceful +optical +width +allegedly +mcdonald +strict +copyright +##illa +investors +mar +jam +witnesses +sounding +miranda +michelle +privacy +hugo +harmony +##pp +valid +lynn +glared +nina +102 +headquartered +diving +boarding +gibson +##ncy +albanian +marsh +routine +dealt +enhanced +er +intelligent +substance +targeted +enlisted +discovers +spinning +observations +pissed +smoking +rebecca +capitol +visa +varied +costume +seemingly +indies +compensation +surgeon +thursday +arsenal +westminster +suburbs +rid +anglican +##ridge +knots +foods +alumni +lighter +fraser +whoever +portal +scandal +##ray +gavin +advised +instructor +flooding +terrorist +##ale +teenage +interim +senses +duck +teen +thesis +abby +eager +overcome +##ile +newport +glenn +rises +shame +##cc +prompted +priority +forgot +bomber +nicolas +protective +360 +cartoon +katherine +breeze +lonely +trusted +henderson +richardson +relax +banner +candy +palms +remarkable +##rio +legends +cricketer +essay +ordained +edmund +rifles +trigger +##uri +##away +sail +alert +1830 +audiences +penn +sussex +siblings +pursued +indianapolis +resist +rosa +consequence +succeed +avoided +1845 +##ulation +inland +##tie +##nna +counsel +profession +chronicle +hurried +##una +eyebrow +eventual +bleeding +innovative +cure +##dom +committees +accounting +con +scope +hardy +heather +tenor +gut +herald +codes +tore +scales +wagon +##oo +luxury +tin +prefer +fountain +triangle +bonds +darling +convoy +dried +traced +beings +troy +accidentally +slam +findings +smelled +joey +lawyers +outcome +steep +bosnia +configuration +shifting +toll +brook +performers +lobby +philosophical +construct +shrine +aggregate +boot +cox +phenomenon +savage +insane +solely +reynolds +lifestyle +##ima +nationally +holdings +consideration +enable +edgar +mo +mama +##tein +fights +relegation +chances +atomic +hub +conjunction +awkward +reactions +currency +finale +kumar +underwent +steering +elaborate +gifts +comprising +melissa +veins +reasonable +sunshine +chi +solve +trails +inhabited +elimination +ethics +huh +ana +molly +consent +apartments +layout +marines +##ces +hunters +bulk +##oma +hometown +##wall +##mont +cracked +reads +neighbouring +withdrawn +admission +wingspan +damned +anthology +lancashire +brands +batting +forgive +cuban +awful +##lyn +104 +dimensions +imagination +##ade +dante +##ship +tracking +desperately +goalkeeper +##yne +groaned +workshops +confident +burton +gerald +milton +circus +uncertain +slope +copenhagen +sophia +fog +philosopher +portraits +accent +cycling +varying +gripped +larvae +garrett +specified +scotia +mature +luther +kurt +rap +##kes +aerial +750 +ferdinand +heated +es +transported +##shan +safely +nonetheless +##orn +##gal +motors +demanding +##sburg +startled +##brook +ally +generate +caps +ghana +stained +demo +mentions +beds +ap +afterward +diary +##bling +utility +##iro +richards +1837 +conspiracy +conscious +shining +footsteps +observer +cyprus +urged +loyalty +developer +probability +olive +upgraded +gym +miracle +insects +graves +1844 +ourselves +hydrogen +amazon +katie +tickets +poets +##pm +planes +##pan +prevention +witnessed +dense +jin +randy +tang +warehouse +monroe +bang +archived +elderly +investigations +alec +granite +mineral +conflicts +controlling +aboriginal +carlo +##zu +mechanics +stan +stark +rhode +skirt +est +##berry +bombs +respected +##horn +imposed +limestone +deny +nominee +memphis +grabbing +disabled +##als +amusement +aa +frankfurt +corn +referendum +varies +slowed +disk +firms +unconscious +incredible +clue +sue +##zhou +twist +##cio +joins +idaho +chad +developers +computing +destroyer +103 +mortal +tucker +kingston +choices +yu +carson +1800 +os +whitney +geneva +pretend +dimension +staged +plateau +maya +##une +freestyle +##bc +rovers +hiv +##ids +tristan +classroom +prospect +##hus +honestly +diploma +lied +thermal +auxiliary +feast +unlikely +iata +##tel +morocco +pounding +treasury +lithuania +considerably +1841 +dish +1812 +geological +matching +stumbled +destroying +marched +brien +advances +cake +nicole +belle +settling +measuring +directing +##mie +tuesday +bassist +capabilities +stunned +fraud +torpedo +##list +##phone +anton +wisdom +surveillance +ruined +##ulate +lawsuit +healthcare +theorem +halls +trend +aka +horizontal +dozens +acquire +lasting +swim +hawk +gorgeous +fees +vicinity +decrease +adoption +tactics +##ography +pakistani +##ole +draws +##hall +willie +burke +heath +algorithm +integral +powder +elliott +brigadier +jackie +tate +varieties +darker +##cho +lately +cigarette +specimens +adds +##ree +##ensis +##inger +exploded +finalist +cia +murders +wilderness +arguments +nicknamed +acceptance +onwards +manufacture +robertson +jets +tampa +enterprises +blog +loudly +composers +nominations +1838 +ai +malta +inquiry +automobile +hosting +viii +rays +tilted +grief +museums +strategies +furious +euro +equality +cohen +poison +surrey +wireless +governed +ridiculous +moses +##esh +##room +vanished +##ito +barnes +attract +morrison +istanbul +##iness +absent +rotation +petition +janet +##logical +satisfaction +custody +deliberately +observatory +comedian +surfaces +pinyin +novelist +strictly +canterbury +oslo +monks +embrace +ibm +jealous +photograph +continent +dorothy +marina +doc +excess +holden +allegations +explaining +stack +avoiding +lance +storyline +majesty +poorly +spike +dos +bradford +raven +travis +classics +proven +voltage +pillow +fists +butt +1842 +interpreted +##car +1839 +gage +telegraph +lens +promising +expelled +casual +collector +zones +##min +silly +nintendo +##kh +##bra +downstairs +chef +suspicious +afl +flies +vacant +uganda +pregnancy +condemned +lutheran +estimates +cheap +decree +saxon +proximity +stripped +idiot +deposits +contrary +presenter +magnus +glacier +im +offense +edwin +##ori +upright +##long +bolt +##ois +toss +geographical +##izes +environments +delicate +marking +abstract +xavier +nails +windsor +plantation +occurring +equity +saskatchewan +fears +drifted +sequences +vegetation +revolt +##stic +1843 +sooner +fusion +opposing +nato +skating +1836 +secretly +ruin +lease +##oc +edit +##nne +flora +anxiety +ruby +##ological +##mia +tel +bout +taxi +emmy +frost +rainbow +compounds +foundations +rainfall +assassination +nightmare +dominican +##win +achievements +deserve +orlando +intact +armenia +##nte +calgary +valentine +106 +marion +proclaimed +theodore +bells +courtyard +thigh +gonzalez +console +troop +minimal +monte +everyday +##ence +##if +supporter +terrorism +buck +openly +presbyterian +activists +carpet +##iers +rubbing +uprising +##yi +cute +conceived +legally +##cht +millennium +cello +velocity +ji +rescued +cardiff +1835 +rex +concentrate +senators +beard +rendered +glowing +battalions +scouts +competitors +sculptor +catalogue +arctic +ion +raja +bicycle +wow +glancing +lawn +##woman +gentleman +lighthouse +publish +predicted +calculated +##val +variants +##gne +strain +##ui +winston +deceased +##nus +touchdowns +brady +caleb +sinking +echoed +crush +hon +blessed +protagonist +hayes +endangered +magnitude +editors +##tine +estimate +responsibilities +##mel +backup +laying +consumed +sealed +zurich +lovers +frustrated +##eau +ahmed +kicking +mit +treasurer +1832 +biblical +refuse +terrified +pump +agrees +genuine +imprisonment +refuses +plymouth +##hen +lou +##nen +tara +trembling +antarctic +ton +learns +##tas +crap +crucial +faction +atop +##borough +wrap +lancaster +odds +hopkins +erik +lyon +##eon +bros +##ode +snap +locality +tips +empress +crowned +cal +acclaimed +chuckled +##ory +clara +sends +mild +towel +##fl +##day +##а +wishing +assuming +interviewed +##bal +##die +interactions +eden +cups +helena +##lf +indie +beck +##fire +batteries +filipino +wizard +parted +##lam +traces +##born +rows +idol +albany +delegates +##ees +##sar +discussions +##ex +notre +instructed +belgrade +highways +suggestion +lauren +possess +orientation +alexandria +abdul +beats +salary +reunion +ludwig +alright +wagner +intimate +pockets +slovenia +hugged +brighton +merchants +cruel +stole +trek +slopes +repairs +enrollment +politically +underlying +promotional +counting +boeing +##bb +isabella +naming +##и +keen +bacteria +listing +separately +belfast +ussr +450 +lithuanian +anybody +ribs +sphere +martinez +cock +embarrassed +proposals +fragments +nationals +##fs +##wski +premises +fin +1500 +alpine +matched +freely +bounded +jace +sleeve +##af +gaming +pier +populated +evident +##like +frances +flooded +##dle +frightened +pour +trainer +framed +visitor +challenging +pig +wickets +##fold +infected +email +##pes +arose +##aw +reward +ecuador +oblast +vale +ch +shuttle +##usa +bach +rankings +forbidden +cornwall +accordance +salem +consumers +bruno +fantastic +toes +machinery +resolved +julius +remembering +propaganda +iceland +bombardment +tide +contacts +wives +##rah +concerto +macdonald +albania +implement +daisy +tapped +sudan +helmet +angela +mistress +##lic +crop +sunk +finest +##craft +hostile +##ute +##tsu +boxer +fr +paths +adjusted +habit +ballot +supervision +soprano +##zen +bullets +wicked +sunset +regiments +disappear +lamp +performs +app +##gia +##oa +rabbit +digging +incidents +entries +##cion +dishes +##oi +introducing +##ati +##fied +freshman +slot +jill +tackles +baroque +backs +##iest +lone +sponsor +destiny +altogether +convert +##aro +consensus +shapes +demonstration +basically +feminist +auction +artifacts +##bing +strongest +twitter +halifax +2019 +allmusic +mighty +smallest +precise +alexandra +viola +##los +##ille +manuscripts +##illo +dancers +ari +managers +monuments +blades +barracks +springfield +maiden +consolidated +electron +##end +berry +airing +wheat +nobel +inclusion +blair +payments +geography +bee +cc +eleanor +react +##hurst +afc +manitoba +##yu +su +lineup +fitness +recreational +investments +airborne +disappointment +##dis +edmonton +viewing +##row +renovation +##cast +infant +bankruptcy +roses +aftermath +pavilion +##yer +carpenter +withdrawal +ladder +##hy +discussing +popped +reliable +agreements +rochester +##abad +curves +bombers +220 +rao +reverend +decreased +choosing +107 +stiff +consulting +naples +crawford +tracy +ka +ribbon +cops +##lee +crushed +deciding +unified +teenager +accepting +flagship +explorer +poles +sanchez +inspection +revived +skilled +induced +exchanged +flee +locals +tragedy +swallow +loading +hanna +demonstrate +##ela +salvador +flown +contestants +civilization +##ines +wanna +rhodes +fletcher +hector +knocking +considers +##ough +nash +mechanisms +sensed +mentally +walt +unclear +##eus +renovated +madame +##cks +crews +governmental +##hin +undertaken +monkey +##ben +##ato +fatal +armored +copa +caves +governance +grasp +perception +certification +froze +damp +tugged +wyoming +##rg +##ero +newman +##lor +nerves +curiosity +graph +115 +##ami +withdraw +tunnels +dull +meredith +moss +exhibits +neighbors +communicate +accuracy +explored +raiders +republicans +secular +kat +superman +penny +criticised +##tch +freed +update +conviction +wade +ham +likewise +delegation +gotta +doll +promises +technological +myth +nationality +resolve +convent +##mark +sharon +dig +sip +coordinator +entrepreneur +fold +##dine +capability +councillor +synonym +blown +swan +cursed +1815 +jonas +haired +sofa +canvas +keeper +rivalry +##hart +rapper +speedway +swords +postal +maxwell +estonia +potter +recurring +##nn +##ave +errors +##oni +cognitive +1834 +##² +claws +nadu +roberto +bce +wrestler +ellie +##ations +infinite +ink +##tia +presumably +finite +staircase +108 +noel +patricia +nacional +##cation +chill +eternal +tu +preventing +prussia +fossil +limbs +##logist +ernst +frog +perez +rene +##ace +pizza +prussian +##ios +##vy +molecules +regulatory +answering +opinions +sworn +lengths +supposedly +hypothesis +upward +habitats +seating +ancestors +drank +yield +hd +synthesis +researcher +modest +##var +mothers +peered +voluntary +homeland +##the +acclaim +##igan +static +valve +luxembourg +alto +carroll +fe +receptor +norton +ambulance +##tian +johnston +catholics +depicting +jointly +elephant +gloria +mentor +badge +ahmad +distinguish +remarked +councils +precisely +allison +advancing +detection +crowded +##10 +cooperative +ankle +mercedes +dagger +surrendered +pollution +commit +subway +jeffrey +lesson +sculptures +provider +##fication +membrane +timothy +rectangular +fiscal +heating +teammate +basket +particle +anonymous +deployment +##ple +missiles +courthouse +proportion +shoe +sec +##ller +complaints +forbes +blacks +abandon +remind +sizes +overwhelming +autobiography +natalie +##awa +risks +contestant +countryside +babies +scorer +invaded +enclosed +proceed +hurling +disorders +##cu +reflecting +continuously +cruiser +graduates +freeway +investigated +ore +deserved +maid +blocking +phillip +jorge +shakes +dove +mann +variables +lacked +burden +accompanying +que +consistently +organizing +provisional +complained +endless +##rm +tubes +juice +georges +krishna +mick +labels +thriller +##uch +laps +arcade +sage +snail +##table +shannon +fi +laurence +seoul +vacation +presenting +hire +churchill +surprisingly +prohibited +savannah +technically +##oli +170 +##lessly +testimony +suited +speeds +toys +romans +mlb +flowering +measurement +talented +kay +settings +charleston +expectations +shattered +achieving +triumph +ceremonies +portsmouth +lanes +mandatory +loser +stretching +cologne +realizes +seventy +cornell +careers +webb +##ulating +americas +budapest +ava +suspicion +##ison +yo +conrad +##hai +sterling +jessie +rector +##az +1831 +transform +organize +loans +christine +volcanic +warrant +slender +summers +subfamily +newer +danced +dynamics +rhine +proceeds +heinrich +gastropod +commands +sings +facilitate +easter +ra +positioned +responses +expense +fruits +yanked +imported +25th +velvet +vic +primitive +tribune +baldwin +neighbourhood +donna +rip +hay +pr +##uro +1814 +espn +welcomed +##aria +qualifier +glare +highland +timing +##cted +shells +eased +geometry +louder +exciting +slovakia +##sion +##iz +##lot +savings +prairie +##ques +marching +rafael +tonnes +##lled +curtain +preceding +shy +heal +greene +worthy +##pot +detachment +bury +sherman +##eck +reinforced +seeks +bottles +contracted +duchess +outfit +walsh +##sc +mickey +##ase +geoffrey +archer +squeeze +dawson +eliminate +invention +##enberg +neal +##eth +stance +dealer +coral +maple +retire +polo +simplified +##ht +1833 +hid +watts +backwards +jules +##oke +genesis +mt +frames +rebounds +burma +woodland +moist +santos +whispers +drained +subspecies +##aa +streaming +ulster +burnt +correspondence +maternal +gerard +denis +stealing +##load +genius +duchy +##oria +inaugurated +momentum +suits +placement +sovereign +clause +thames +##hara +confederation +reservation +sketch +yankees +lets +rotten +charm +hal +verses +ultra +commercially +dot +salon +citation +adopt +winnipeg +mist +allocated +cairo +##boy +jenkins +interference +objectives +##wind +1820 +portfolio +armoured +sectors +##eh +initiatives +##world +integrity +exercises +robe +tap +ab +gazed +##tones +distracted +rulers +111 +favorable +jerome +tended +cart +factories +##eri +diplomat +valued +gravel +charitable +##try +calvin +exploring +chang +shepherd +terrace +pdf +pupil +##ural +reflects +ups +##rch +governors +shelf +depths +##nberg +trailed +crest +tackle +##nian +##ats +hatred +##kai +clare +makers +ethiopia +longtime +detected +embedded +lacking +slapped +rely +thomson +anticipation +iso +morton +successive +agnes +screenwriter +straightened +philippe +playwright +haunted +licence +iris +intentions +sutton +112 +logical +correctly +##weight +branded +licked +tipped +silva +ricky +narrator +requests +##ents +greeted +supernatural +cow +##wald +lung +refusing +employer +strait +gaelic +liner +##piece +zoe +sabha +##mba +driveway +harvest +prints +bates +reluctantly +threshold +algebra +ira +wherever +coupled +240 +assumption +picks +##air +designers +raids +gentlemen +##ean +roller +blowing +leipzig +locks +screw +dressing +strand +##lings +scar +dwarf +depicts +##nu +nods +##mine +differ +boris +##eur +yuan +flip +##gie +mob +invested +questioning +applying +##ture +shout +##sel +gameplay +blamed +illustrations +bothered +weakness +rehabilitation +##of +##zes +envelope +rumors +miners +leicester +subtle +kerry +##ico +ferguson +##fu +premiership +ne +##cat +bengali +prof +catches +remnants +dana +##rily +shouting +presidents +baltic +ought +ghosts +dances +sailors +shirley +fancy +dominic +##bie +madonna +##rick +bark +buttons +gymnasium +ashes +liver +toby +oath +providence +doyle +evangelical +nixon +cement +carnegie +embarked +hatch +surroundings +guarantee +needing +pirate +essence +##bee +filter +crane +hammond +projected +immune +percy +twelfth +##ult +regent +doctoral +damon +mikhail +##ichi +lu +critically +elect +realised +abortion +acute +screening +mythology +steadily +##fc +frown +nottingham +kirk +wa +minneapolis +##rra +module +algeria +mc +nautical +encounters +surprising +statues +availability +shirts +pie +alma +brows +munster +mack +soup +crater +tornado +sanskrit +cedar +explosive +bordered +dixon +planets +stamp +exam +happily +##bble +carriers +kidnapped +##vis +accommodation +emigrated +##met +knockout +correspondent +violation +profits +peaks +lang +specimen +agenda +ancestry +pottery +spelling +equations +obtaining +ki +linking +1825 +debris +asylum +##20 +buddhism +teddy +##ants +gazette +##nger +##sse +dental +eligibility +utc +fathers +averaged +zimbabwe +francesco +coloured +hissed +translator +lynch +mandate +humanities +mackenzie +uniforms +lin +##iana +##gio +asset +mhz +fitting +samantha +genera +wei +rim +beloved +shark +riot +entities +expressions +indo +carmen +slipping +owing +abbot +neighbor +sidney +##av +rats +recommendations +encouraging +squadrons +anticipated +commanders +conquered +##oto +donations +diagnosed +##mond +divide +##iva +guessed +decoration +vernon +auditorium +revelation +conversations +##kers +##power +herzegovina +dash +alike +protested +lateral +herman +accredited +mg +##gent +freeman +mel +fiji +crow +crimson +##rine +livestock +##pped +humanitarian +bored +oz +whip +##lene +##ali +legitimate +alter +grinning +spelled +anxious +oriental +wesley +##nin +##hole +carnival +controller +detect +##ssa +bowed +educator +kosovo +macedonia +##sin +occupy +mastering +stephanie +janeiro +para +unaware +nurses +noon +135 +cam +hopefully +ranger +combine +sociology +polar +rica +##eer +neill +##sman +holocaust +##ip +doubled +lust +1828 +109 +decent +cooling +unveiled +##card +1829 +nsw +homer +chapman +meyer +##gin +dive +mae +reagan +expertise +##gled +darwin +brooke +sided +prosecution +investigating +comprised +petroleum +genres +reluctant +differently +trilogy +johns +vegetables +corpse +highlighted +lounge +pension +unsuccessfully +elegant +aided +ivory +beatles +amelia +cain +dubai +sunny +immigrant +babe +click +##nder +underwater +pepper +combining +mumbled +atlas +horns +accessed +ballad +physicians +homeless +gestured +rpm +freak +louisville +corporations +patriots +prizes +rational +warn +modes +decorative +overnight +din +troubled +phantom +##ort +monarch +sheer +##dorf +generals +guidelines +organs +addresses +##zon +enhance +curling +parishes +cord +##kie +linux +caesar +deutsche +bavaria +##bia +coleman +cyclone +##eria +bacon +petty +##yama +##old +hampton +diagnosis +1824 +throws +complexity +rita +disputed +##₃ +pablo +##sch +marketed +trafficking +##ulus +examine +plague +formats +##oh +vault +faithful +##bourne +webster +##ox +highlights +##ient +##ann +phones +vacuum +sandwich +modeling +##gated +bolivia +clergy +qualities +isabel +##nas +##ars +wears +screams +reunited +annoyed +bra +##ancy +##rate +differential +transmitter +tattoo +container +poker +##och +excessive +resides +cowboys +##tum +augustus +trash +providers +statute +retreated +balcony +reversed +void +storey +preceded +masses +leap +laughs +neighborhoods +wards +schemes +falcon +santo +battlefield +pad +ronnie +thread +lesbian +venus +##dian +beg +sandstone +daylight +punched +gwen +analog +stroked +wwe +acceptable +measurements +dec +toxic +##kel +adequate +surgical +economist +parameters +varsity +##sberg +quantity +ella +##chy +##rton +countess +generating +precision +diamonds +expressway +ga +##ı +1821 +uruguay +talents +galleries +expenses +scanned +colleague +outlets +ryder +lucien +##ila +paramount +##bon +syracuse +dim +fangs +gown +sweep +##sie +toyota +missionaries +websites +##nsis +sentences +adviser +val +trademark +spells +##plane +patience +starter +slim +##borg +toe +incredibly +shoots +elliot +nobility +##wyn +cowboy +endorsed +gardner +tendency +persuaded +organisms +emissions +kazakhstan +amused +boring +chips +themed +##hand +llc +constantinople +chasing +systematic +guatemala +borrowed +erin +carey +##hard +highlands +struggles +1810 +##ifying +##ced +wong +exceptions +develops +enlarged +kindergarten +castro +##ern +##rina +leigh +zombie +juvenile +##most +consul +##nar +sailor +hyde +clarence +intensive +pinned +nasty +useless +jung +clayton +stuffed +exceptional +ix +apostolic +230 +transactions +##dge +exempt +swinging +cove +religions +##ash +shields +dairy +bypass +190 +pursuing +bug +joyce +bombay +chassis +southampton +chat +interact +redesignated +##pen +nascar +pray +salmon +rigid +regained +malaysian +grim +publicity +constituted +capturing +toilet +delegate +purely +tray +drift +loosely +striker +weakened +trinidad +mitch +itv +defines +transmitted +ming +scarlet +nodding +fitzgerald +fu +narrowly +sp +tooth +standings +virtue +##₁ +##wara +##cting +chateau +gloves +lid +##nel +hurting +conservatory +##pel +sinclair +reopened +sympathy +nigerian +strode +advocated +optional +chronic +discharge +##rc +suck +compatible +laurel +stella +shi +fails +wage +dodge +128 +informal +sorts +levi +buddha +villagers +##aka +chronicles +heavier +summoned +gateway +3000 +eleventh +jewelry +translations +accordingly +seas +##ency +fiber +pyramid +cubic +dragging +##ista +caring +##ops +android +contacted +lunar +##dt +kai +lisbon +patted +1826 +sacramento +theft +madagascar +subtropical +disputes +ta +holidays +piper +willow +mare +cane +itunes +newfoundland +benny +companions +dong +raj +observe +roar +charming +plaque +tibetan +fossils +enacted +manning +bubble +tina +tanzania +##eda +##hir +funk +swamp +deputies +cloak +ufc +scenario +par +scratch +metals +anthem +guru +engaging +specially +##boat +dialects +nineteen +cecil +duet +disability +messenger +unofficial +##lies +defunct +eds +moonlight +drainage +surname +puzzle +honda +switching +conservatives +mammals +knox +broadcaster +sidewalk +cope +##ried +benson +princes +peterson +##sal +bedford +sharks +eli +wreck +alberto +gasp +archaeology +lgbt +teaches +securities +madness +compromise +waving +coordination +davidson +visions +leased +possibilities +eighty +jun +fernandez +enthusiasm +assassin +sponsorship +reviewer +kingdoms +estonian +laboratories +##fy +##nal +applies +verb +celebrations +##zzo +rowing +lightweight +sadness +submit +mvp +balanced +dude +##vas +explicitly +metric +magnificent +mound +brett +mohammad +mistakes +irregular +##hing +##ass +sanders +betrayed +shipped +surge +##enburg +reporters +termed +georg +pity +verbal +bulls +abbreviated +enabling +appealed +##are +##atic +sicily +sting +heel +sweetheart +bart +spacecraft +brutal +monarchy +##tter +aberdeen +cameo +diane +##ub +survivor +clyde +##aries +complaint +##makers +clarinet +delicious +chilean +karnataka +coordinates +1818 +panties +##rst +pretending +ar +dramatically +kiev +bella +tends +distances +113 +catalog +launching +instances +telecommunications +portable +lindsay +vatican +##eim +angles +aliens +marker +stint +screens +bolton +##rne +judy +wool +benedict +plasma +europa +spark +imaging +filmmaker +swiftly +##een +contributor +##nor +opted +stamps +apologize +financing +butter +gideon +sophisticated +alignment +avery +chemicals +yearly +speculation +prominence +professionally +##ils +immortal +institutional +inception +wrists +identifying +tribunal +derives +gains +##wo +papal +preference +linguistic +vince +operative +brewery +##ont +unemployment +boyd +##ured +##outs +albeit +prophet +1813 +bi +##rr +##face +##rad +quarterly +asteroid +cleaned +radius +temper +##llen +telugu +jerk +viscount +menu +##ote +glimpse +##aya +yacht +hawaiian +baden +##rl +laptop +readily +##gu +monetary +offshore +scots +watches +##yang +##arian +upgrade +needle +xbox +lea +encyclopedia +flank +fingertips +##pus +delight +teachings +confirm +roth +beaches +midway +winters +##iah +teasing +daytime +beverly +gambling +bonnie +##backs +regulated +clement +hermann +tricks +knot +##shing +##uring +##vre +detached +ecological +owed +specialty +byron +inventor +bats +stays +screened +unesco +midland +trim +affection +##ander +##rry +jess +thoroughly +feedback +##uma +chennai +strained +heartbeat +wrapping +overtime +pleaded +##sworth +mon +leisure +oclc +##tate +##ele +feathers +angelo +thirds +nuts +surveys +clever +gill +commentator +##dos +darren +rides +gibraltar +##nc +##mu +dissolution +dedication +shin +meals +saddle +elvis +reds +chaired +taller +appreciation +functioning +niece +favored +advocacy +robbie +criminals +suffolk +yugoslav +passport +constable +congressman +hastings +vera +##rov +consecrated +sparks +ecclesiastical +confined +##ovich +muller +floyd +nora +1822 +paved +1827 +cumberland +ned +saga +spiral +##flow +appreciated +yi +collaborative +treating +similarities +feminine +finishes +##ib +jade +import +##nse +##hot +champagne +mice +securing +celebrities +helsinki +attributes +##gos +cousins +phases +ache +lucia +gandhi +submission +vicar +spear +shine +tasmania +biting +detention +constitute +tighter +seasonal +##gus +terrestrial +matthews +##oka +effectiveness +parody +philharmonic +##onic +1816 +strangers +encoded +consortium +guaranteed +regards +shifts +tortured +collision +supervisor +inform +broader +insight +theaters +armour +emeritus +blink +incorporates +mapping +##50 +##ein +handball +flexible +##nta +substantially +generous +thief +##own +carr +loses +1793 +prose +ucla +romeo +generic +metallic +realization +damages +mk +commissioners +zach +default +##ther +helicopters +lengthy +stems +spa +partnered +spectators +rogue +indication +penalties +teresa +1801 +sen +##tric +dalton +##wich +irving +photographic +##vey +dell +deaf +peters +excluded +unsure +##vable +patterson +crawled +##zio +resided +whipped +latvia +slower +ecole +pipes +employers +maharashtra +comparable +va +textile +pageant +##gel +alphabet +binary +irrigation +chartered +choked +antoine +offs +waking +supplement +##wen +quantities +demolition +regain +locate +urdu +folks +alt +114 +##mc +scary +andreas +whites +##ava +classrooms +mw +aesthetic +publishes +valleys +guides +cubs +johannes +bryant +conventions +affecting +##itt +drain +awesome +isolation +prosecutor +ambitious +apology +captive +downs +atmospheric +lorenzo +aisle +beef +foul +##onia +kidding +composite +disturbed +illusion +natives +##ffer +emi +rockets +riverside +wartime +painters +adolf +melted +##ail +uncertainty +simulation +hawks +progressed +meantime +builder +spray +breach +unhappy +regina +russians +##urg +determining +##tation +tram +1806 +##quin +aging +##12 +1823 +garion +rented +mister +diaz +terminated +clip +1817 +depend +nervously +disco +owe +defenders +shiva +notorious +disbelief +shiny +worcester +##gation +##yr +trailing +undertook +islander +belarus +limitations +watershed +fuller +overlooking +utilized +raphael +1819 +synthetic +breakdown +klein +##nate +moaned +memoir +lamb +practicing +##erly +cellular +arrows +exotic +##graphy +witches +117 +charted +rey +hut +hierarchy +subdivision +freshwater +giuseppe +aloud +reyes +qatar +marty +sideways +utterly +sexually +jude +prayers +mccarthy +softball +blend +damien +##gging +##metric +wholly +erupted +lebanese +negro +revenues +tasted +comparative +teamed +transaction +labeled +maori +sovereignty +parkway +trauma +gran +malay +121 +advancement +descendant +2020 +buzz +salvation +inventory +symbolic +##making +antarctica +mps +##gas +##bro +mohammed +myanmar +holt +submarines +tones +##lman +locker +patriarch +bangkok +emerson +remarks +predators +kin +afghan +confession +norwich +rental +emerge +advantages +##zel +rca +##hold +shortened +storms +aidan +##matic +autonomy +compliance +##quet +dudley +atp +##osis +1803 +motto +documentation +summary +professors +spectacular +christina +archdiocese +flashing +innocence +remake +##dell +psychic +reef +scare +employ +rs +sticks +meg +gus +leans +##ude +accompany +bergen +tomas +##iko +doom +wages +pools +##nch +##bes +breasts +scholarly +alison +outline +brittany +breakthrough +willis +realistic +##cut +##boro +competitor +##stan +pike +picnic +icon +designing +commercials +washing +villain +skiing +micro +costumes +auburn +halted +executives +##hat +logistics +cycles +vowel +applicable +barrett +exclaimed +eurovision +eternity +ramon +##umi +##lls +modifications +sweeping +disgust +##uck +torch +aviv +ensuring +rude +dusty +sonic +donovan +outskirts +cu +pathway +##band +##gun +##lines +disciplines +acids +cadet +paired +##40 +sketches +##sive +marriages +##⁺ +folding +peers +slovak +implies +admired +##beck +1880s +leopold +instinct +attained +weston +megan +horace +##ination +dorsal +ingredients +evolutionary +##its +complications +deity +lethal +brushing +levy +deserted +institutes +posthumously +delivering +telescope +coronation +motivated +rapids +luc +flicked +pays +volcano +tanner +weighed +##nica +crowds +frankie +gifted +addressing +granddaughter +winding +##rna +constantine +gomez +##front +landscapes +rudolf +anthropology +slate +werewolf +##lio +astronomy +circa +rouge +dreaming +sack +knelt +drowned +naomi +prolific +tracked +freezing +herb +##dium +agony +randall +twisting +wendy +deposit +touches +vein +wheeler +##bbled +##bor +batted +retaining +tire +presently +compare +specification +daemon +nigel +##grave +merry +recommendation +czechoslovakia +sandra +ng +roma +##sts +lambert +inheritance +sheikh +winchester +cries +examining +##yle +comeback +cuisine +nave +##iv +ko +retrieve +tomatoes +barker +polished +defining +irene +lantern +personalities +begging +tract +swore +1809 +175 +##gic +omaha +brotherhood +##rley +haiti +##ots +exeter +##ete +##zia +steele +dumb +pearson +210 +surveyed +elisabeth +trends +##ef +fritz +##rf +premium +bugs +fraction +calmly +viking +##birds +tug +inserted +unusually +##ield +confronted +distress +crashing +brent +turks +resign +##olo +cambodia +gabe +sauce +##kal +evelyn +116 +extant +clusters +quarry +teenagers +luna +##lers +##ister +affiliation +drill +##ashi +panthers +scenic +libya +anita +strengthen +inscriptions +##cated +lace +sued +judith +riots +##uted +mint +##eta +preparations +midst +dub +challenger +##vich +mock +cf +displaced +wicket +breaths +enables +schmidt +analyst +##lum +ag +highlight +automotive +axe +josef +newark +sufficiently +resembles +50th +##pal +flushed +mum +traits +##ante +commodore +incomplete +warming +titular +ceremonial +ethical +118 +celebrating +eighteenth +cao +lima +medalist +mobility +strips +snakes +##city +miniature +zagreb +barton +escapes +umbrella +automated +doubted +differs +cooled +georgetown +dresden +cooked +fade +wyatt +rna +jacobs +carlton +abundant +stereo +boost +madras +inning +##hia +spur +ip +malayalam +begged +osaka +groan +escaping +charging +dose +vista +##aj +bud +papa +communists +advocates +edged +tri +##cent +resemble +peaking +necklace +fried +montenegro +saxony +goose +glances +stuttgart +curator +recruit +grocery +sympathetic +##tting +##fort +127 +lotus +randolph +ancestor +##rand +succeeding +jupiter +1798 +macedonian +##heads +hiking +1808 +handing +fischer +##itive +garbage +node +##pies +prone +singular +papua +inclined +attractions +italia +pouring +motioned +grandma +garnered +jacksonville +corp +ego +ringing +aluminum +##hausen +ordering +##foot +drawer +traders +synagogue +##play +##kawa +resistant +wandering +fragile +fiona +teased +var +hardcore +soaked +jubilee +decisive +exposition +mercer +poster +valencia +hale +kuwait +1811 +##ises +##wr +##eed +tavern +gamma +122 +johan +##uer +airways +amino +gil +##ury +vocational +domains +torres +##sp +generator +folklore +outcomes +##keeper +canberra +shooter +fl +beams +confrontation +##lling +##gram +feb +aligned +forestry +pipeline +jax +motorway +conception +decay +##tos +coffin +##cott +stalin +1805 +escorted +minded +##nam +sitcom +purchasing +twilight +veronica +additions +passive +tensions +straw +123 +frequencies +1804 +refugee +cultivation +##iate +christie +clary +bulletin +crept +disposal +##rich +##zong +processor +crescent +##rol +bmw +emphasized +whale +nazis +aurora +##eng +dwelling +hauled +sponsors +toledo +mega +ideology +theatres +tessa +cerambycidae +saves +turtle +cone +suspects +kara +rusty +yelling +greeks +mozart +shades +cocked +participant +##tro +shire +spit +freeze +necessity +##cos +inmates +nielsen +councillors +loaned +uncommon +omar +peasants +botanical +offspring +daniels +formations +jokes +1794 +pioneers +sigma +licensing +##sus +wheelchair +polite +1807 +liquor +pratt +trustee +##uta +forewings +balloon +##zz +kilometre +camping +explicit +casually +shawn +foolish +teammates +nm +hassan +carrie +judged +satisfy +vanessa +knives +selective +cnn +flowed +##lice +eclipse +stressed +eliza +mathematician +cease +cultivated +##roy +commissions +browns +##ania +destroyers +sheridan +meadow +##rius +minerals +##cial +downstream +clash +gram +memoirs +ventures +baha +seymour +archie +midlands +edith +fare +flynn +invite +canceled +tiles +stabbed +boulder +incorporate +amended +camden +facial +mollusk +unreleased +descriptions +yoga +grabs +550 +raises +ramp +shiver +##rose +coined +pioneering +tunes +qing +warwick +tops +119 +melanie +giles +##rous +wandered +##inal +annexed +nov +30th +unnamed +##ished +organizational +airplane +normandy +stoke +whistle +blessing +violations +chased +holders +shotgun +##ctic +outlet +reactor +##vik +tires +tearing +shores +fortified +mascot +constituencies +nc +columnist +productive +tibet +##rta +lineage +hooked +oct +tapes +judging +cody +##gger +hansen +kashmir +triggered +##eva +solved +cliffs +##tree +resisted +anatomy +protesters +transparent +implied +##iga +injection +mattress +excluding +##mbo +defenses +helpless +devotion +##elli +growl +liberals +weber +phenomena +atoms +plug +##iff +mortality +apprentice +howe +convincing +aaa +swimmer +barber +leone +promptly +sodium +def +nowadays +arise +##oning +gloucester +corrected +dignity +norm +erie +##ders +elders +evacuated +sylvia +compression +##yar +hartford +pose +backpack +reasoning +accepts +24th +wipe +millimetres +marcel +##oda +dodgers +albion +1790 +overwhelmed +aerospace +oaks +1795 +showcase +acknowledge +recovering +nolan +ashe +hurts +geology +fashioned +disappearance +farewell +swollen +shrug +marquis +wimbledon +124 +rue +1792 +commemorate +reduces +experiencing +inevitable +calcutta +intel +##court +murderer +sticking +fisheries +imagery +bloom +280 +brake +##inus +gustav +hesitation +memorable +po +viral +beans +accidents +tunisia +antenna +spilled +consort +treatments +aye +perimeter +##gard +donation +hostage +migrated +banker +addiction +apex +lil +trout +##ously +conscience +##nova +rams +sands +genome +passionate +troubles +##lets +##set +amid +##ibility +##ret +higgins +exceed +vikings +##vie +payne +##zan +muscular +##ste +defendant +sucking +##wal +ibrahim +fuselage +claudia +vfl +europeans +snails +interval +##garh +preparatory +statewide +tasked +lacrosse +viktor +##lation +angola +##hra +flint +implications +employs +teens +patrons +stall +weekends +barriers +scrambled +nucleus +tehran +jenna +parsons +lifelong +robots +displacement +5000 +##bles +precipitation +##gt +knuckles +clutched +1802 +marrying +ecology +marx +accusations +declare +scars +kolkata +mat +meadows +bermuda +skeleton +finalists +vintage +crawl +coordinate +affects +subjected +orchestral +mistaken +##tc +mirrors +dipped +relied +260 +arches +candle +##nick +incorporating +wildly +fond +basilica +owl +fringe +rituals +whispering +stirred +feud +tertiary +slick +goat +honorable +whereby +skip +ricardo +stripes +parachute +adjoining +submerged +synthesizer +##gren +intend +positively +ninety +phi +beaver +partition +fellows +alexis +prohibition +carlisle +bizarre +fraternity +##bre +doubts +icy +cbc +aquatic +sneak +sonny +combines +airports +crude +supervised +spatial +merge +alfonso +##bic +corrupt +scan +undergo +##ams +disabilities +colombian +comparing +dolphins +perkins +##lish +reprinted +unanimous +bounced +hairs +underworld +midwest +semester +bucket +paperback +miniseries +coventry +demise +##leigh +demonstrations +sensor +rotating +yan +##hler +arrange +soils +##idge +hyderabad +labs +##dr +brakes +grandchildren +##nde +negotiated +rover +ferrari +continuation +directorate +augusta +stevenson +counterpart +gore +##rda +nursery +rican +ave +collectively +broadly +pastoral +repertoire +asserted +discovering +nordic +styled +fiba +cunningham +harley +middlesex +survives +tumor +tempo +zack +aiming +lok +urgent +##rade +##nto +devils +##ement +contractor +turin +##wl +##ool +bliss +repaired +simmons +moan +astronomical +cr +negotiate +lyric +1890s +lara +bred +clad +angus +pbs +##ience +engineered +posed +##lk +hernandez +possessions +elbows +psychiatric +strokes +confluence +electorate +lifts +campuses +lava +alps +##ep +##ution +##date +physicist +woody +##page +##ographic +##itis +juliet +reformation +sparhawk +320 +complement +suppressed +jewel +##½ +floated +##kas +continuity +sadly +##ische +inability +melting +scanning +paula +flour +judaism +safer +vague +##lm +solving +curb +##stown +financially +gable +bees +expired +miserable +cassidy +dominion +1789 +cupped +145 +robbery +facto +amos +warden +resume +tallest +marvin +ing +pounded +usd +declaring +gasoline +##aux +darkened +270 +650 +sophomore +##mere +erection +gossip +televised +risen +dial +##eu +pillars +##link +passages +profound +##tina +arabian +ashton +silicon +nail +##ead +##lated +##wer +##hardt +fleming +firearms +ducked +circuits +blows +waterloo +titans +##lina +atom +fireplace +cheshire +financed +activation +algorithms +##zzi +constituent +catcher +cherokee +partnerships +sexuality +platoon +tragic +vivian +guarded +whiskey +meditation +poetic +##late +##nga +##ake +porto +listeners +dominance +kendra +mona +chandler +factions +22nd +salisbury +attitudes +derivative +##ido +##haus +intake +paced +javier +illustrator +barrels +bias +cockpit +burnett +dreamed +ensuing +##anda +receptors +someday +hawkins +mattered +##lal +slavic +1799 +jesuit +cameroon +wasted +tai +wax +lowering +victorious +freaking +outright +hancock +librarian +sensing +bald +calcium +myers +tablet +announcing +barack +shipyard +pharmaceutical +##uan +greenwich +flush +medley +patches +wolfgang +pt +speeches +acquiring +exams +nikolai +##gg +hayden +kannada +##type +reilly +##pt +waitress +abdomen +devastated +capped +pseudonym +pharmacy +fulfill +paraguay +1796 +clicked +##trom +archipelago +syndicated +##hman +lumber +orgasm +rejection +clifford +lorraine +advent +mafia +rodney +brock +##ght +##used +##elia +cassette +chamberlain +despair +mongolia +sensors +developmental +upstream +##eg +##alis +spanning +165 +trombone +basque +seeded +interred +renewable +rhys +leapt +revision +molecule +##ages +chord +vicious +nord +shivered +23rd +arlington +debts +corpus +sunrise +bays +blackburn +centimetres +##uded +shuddered +gm +strangely +gripping +cartoons +isabelle +orbital +##ppa +seals +proving +##lton +refusal +strengthened +bust +assisting +baghdad +batsman +portrayal +mara +pushes +spears +og +##cock +reside +nathaniel +brennan +1776 +confirmation +caucus +##worthy +markings +yemen +nobles +ku +lazy +viewer +catalan +encompasses +sawyer +##fall +sparked +substances +patents +braves +arranger +evacuation +sergio +persuade +dover +tolerance +penguin +cum +jockey +insufficient +townships +occupying +declining +plural +processed +projection +puppet +flanders +introduces +liability +##yon +gymnastics +antwerp +taipei +hobart +candles +jeep +wes +observers +126 +chaplain +bundle +glorious +##hine +hazel +flung +sol +excavations +dumped +stares +sh +bangalore +triangular +icelandic +intervals +expressing +turbine +##vers +songwriting +crafts +##igo +jasmine +ditch +rite +##ways +entertaining +comply +sorrow +wrestlers +basel +emirates +marian +rivera +helpful +##some +caution +downward +networking +##atory +##tered +darted +genocide +emergence +replies +specializing +spokesman +convenient +unlocked +fading +augustine +concentrations +resemblance +elijah +investigator +andhra +##uda +promotes +bean +##rrell +fleeing +wan +simone +announcer +##ame +##bby +lydia +weaver +132 +residency +modification +##fest +stretches +##ast +alternatively +nat +lowe +lacks +##ented +pam +tile +concealed +inferior +abdullah +residences +tissues +vengeance +##ided +moisture +peculiar +groove +zip +bologna +jennings +ninja +oversaw +zombies +pumping +batch +livingston +emerald +installations +1797 +peel +nitrogen +rama +##fying +##star +schooling +strands +responding +werner +##ost +lime +casa +accurately +targeting +##rod +underway +##uru +hemisphere +lester +##yard +occupies +2d +griffith +angrily +reorganized +##owing +courtney +deposited +##dd +##30 +estadio +##ifies +dunn +exiled +##ying +checks +##combe +##о +##fly +successes +unexpectedly +blu +assessed +##flower +##ه +observing +sacked +spiders +kn +##tail +mu +nodes +prosperity +audrey +divisional +155 +broncos +tangled +adjust +feeds +erosion +paolo +surf +directory +snatched +humid +admiralty +screwed +gt +reddish +##nese +modules +trench +lamps +bind +leah +bucks +competes +##nz +##form +transcription +##uc +isles +violently +clutching +pga +cyclist +inflation +flats +ragged +unnecessary +##hian +stubborn +coordinated +harriet +baba +disqualified +330 +insect +wolfe +##fies +reinforcements +rocked +duel +winked +embraced +bricks +##raj +hiatus +defeats +pending +brightly +jealousy +##xton +##hm +##uki +lena +gdp +colorful +##dley +stein +kidney +##shu +underwear +wanderers +##haw +##icus +guardians +m³ +roared +habits +##wise +permits +gp +uranium +punished +disguise +bundesliga +elise +dundee +erotic +partisan +pi +collectors +float +individually +rendering +behavioral +bucharest +ser +hare +valerie +corporal +nutrition +proportional +##isa +immense +##kis +pavement +##zie +##eld +sutherland +crouched +1775 +##lp +suzuki +trades +endurance +operas +crosby +prayed +priory +rory +socially +##urn +gujarat +##pu +walton +cube +pasha +privilege +lennon +floods +thorne +waterfall +nipple +scouting +approve +##lov +minorities +voter +dwight +extensions +assure +ballroom +slap +dripping +privileges +rejoined +confessed +demonstrating +patriotic +yell +investor +##uth +pagan +slumped +squares +##cle +##kins +confront +bert +embarrassment +##aid +aston +urging +sweater +starr +yuri +brains +williamson +commuter +mortar +structured +selfish +exports +##jon +cds +##him +unfinished +##rre +mortgage +destinations +##nagar +canoe +solitary +buchanan +delays +magistrate +fk +##pling +motivation +##lier +##vier +recruiting +assess +##mouth +malik +antique +1791 +pius +rahman +reich +tub +zhou +smashed +airs +galway +xii +conditioning +honduras +discharged +dexter +##pf +lionel +129 +debates +lemon +tiffany +volunteered +dom +dioxide +procession +devi +sic +tremendous +advertisements +colts +transferring +verdict +hanover +decommissioned +utter +relate +pac +racism +##top +beacon +limp +similarity +terra +occurrence +ant +##how +becky +capt +updates +armament +richie +pal +##graph +halloween +mayo +##ssen +##bone +cara +serena +fcc +dolls +obligations +##dling +violated +lafayette +jakarta +exploitation +##ime +infamous +iconic +##lah +##park +kitty +moody +reginald +dread +spill +crystals +olivier +modeled +bluff +equilibrium +separating +notices +ordnance +extinction +onset +cosmic +attachment +sammy +expose +privy +anchored +##bil +abbott +admits +bending +baritone +emmanuel +policeman +vaughan +winged +climax +dresses +denny +polytechnic +mohamed +burmese +authentic +nikki +genetics +grandparents +homestead +gaza +postponed +metacritic +una +##sby +##bat +unstable +dissertation +##rial +##cian +curls +obscure +uncovered +bronx +praying +disappearing +##hoe +prehistoric +coke +turret +mutations +nonprofit +pits +monaco +##ي +##usion +prominently +dispatched +podium +##mir +uci +##uation +133 +fortifications +birthplace +kendall +##lby +##oll +preacher +rack +goodman +##rman +persistent +##ott +countless +jaime +recorder +lexington +persecution +jumps +renewal +wagons +##11 +crushing +##holder +decorations +##lake +abundance +wrath +laundry +£1 +garde +##rp +jeanne +beetles +peasant +##sl +splitting +caste +sergei +##rer +##ema +scripts +##ively +rub +satellites +##vor +inscribed +verlag +scrapped +gale +packages +chick +potato +slogan +kathleen +arabs +##culture +counterparts +reminiscent +choral +##tead +rand +retains +bushes +dane +accomplish +courtesy +closes +##oth +slaughter +hague +krakow +lawson +tailed +elias +ginger +##ttes +canopy +betrayal +rebuilding +turf +##hof +frowning +allegiance +brigades +kicks +rebuild +polls +alias +nationalism +td +rowan +audition +bowie +fortunately +recognizes +harp +dillon +horrified +##oro +renault +##tics +ropes +##α +presumed +rewarded +infrared +wiping +accelerated +illustration +##rid +presses +practitioners +badminton +##iard +detained +##tera +recognizing +relates +misery +##sies +##tly +reproduction +piercing +potatoes +thornton +esther +manners +hbo +##aan +ours +bullshit +ernie +perennial +sensitivity +illuminated +rupert +##jin +##iss +##ear +rfc +nassau +##dock +staggered +socialism +##haven +appointments +nonsense +prestige +sharma +haul +##tical +solidarity +gps +##ook +##rata +igor +pedestrian +##uit +baxter +tenants +wires +medication +unlimited +guiding +impacts +diabetes +##rama +sasha +pas +clive +extraction +131 +continually +constraints +##bilities +sonata +hunted +sixteenth +chu +planting +quote +mayer +pretended +abs +spat +##hua +ceramic +##cci +curtains +pigs +pitching +##dad +latvian +sore +dayton +##sted +##qi +patrols +slice +playground +##nted +shone +stool +apparatus +inadequate +mates +treason +##ija +desires +##liga +##croft +somalia +laurent +mir +leonardo +oracle +grape +obliged +chevrolet +thirteenth +stunning +enthusiastic +##ede +accounted +concludes +currents +basil +##kovic +drought +##rica +mai +##aire +shove +posting +##shed +pilgrimage +humorous +packing +fry +pencil +wines +smells +144 +marilyn +aching +newest +clung +bon +neighbours +sanctioned +##pie +mug +##stock +drowning +##mma +hydraulic +##vil +hiring +reminder +lilly +investigators +##ncies +sour +##eous +compulsory +packet +##rion +##graphic +##elle +cannes +##inate +depressed +##rit +heroic +importantly +theresa +##tled +conway +saturn +marginal +rae +##xia +corresponds +royce +pact +jasper +explosives +packaging +aluminium +##ttered +denotes +rhythmic +spans +assignments +hereditary +outlined +originating +sundays +lad +reissued +greeting +beatrice +##dic +pillar +marcos +plots +handbook +alcoholic +judiciary +avant +slides +extract +masculine +blur +##eum +##force +homage +trembled +owens +hymn +trey +omega +signaling +socks +accumulated +reacted +attic +theo +lining +angie +distraction +primera +talbot +##key +1200 +ti +creativity +billed +##hey +deacon +eduardo +identifies +proposition +dizzy +gunner +hogan +##yam +##pping +##hol +ja +##chan +jensen +reconstructed +##berger +clearance +darius +##nier +abe +harlem +plea +dei +circled +emotionally +notation +fascist +neville +exceeded +upwards +viable +ducks +##fo +workforce +racer +limiting +shri +##lson +possesses +1600 +kerr +moths +devastating +laden +disturbing +locking +##cture +gal +fearing +accreditation +flavor +aide +1870s +mountainous +##baum +melt +##ures +motel +texture +servers +soda +##mb +herd +##nium +erect +puzzled +hum +peggy +examinations +gould +testified +geoff +ren +devised +sacks +##law +denial +posters +grunted +cesar +tutor +ec +gerry +offerings +byrne +falcons +combinations +ct +incoming +pardon +rocking +26th +avengers +flared +mankind +seller +uttar +loch +nadia +stroking +exposing +##hd +fertile +ancestral +instituted +##has +noises +prophecy +taxation +eminent +vivid +pol +##bol +dart +indirect +multimedia +notebook +upside +displaying +adrenaline +referenced +geometric +##iving +progression +##ddy +blunt +announce +##far +implementing +##lav +aggression +liaison +cooler +cares +headache +plantations +gorge +dots +impulse +thickness +ashamed +averaging +kathy +obligation +precursor +137 +fowler +symmetry +thee +225 +hears +##rai +undergoing +ads +butcher +bowler +##lip +cigarettes +subscription +goodness +##ically +browne +##hos +##tech +kyoto +donor +##erty +damaging +friction +drifting +expeditions +hardened +prostitution +152 +fauna +blankets +claw +tossing +snarled +butterflies +recruits +investigative +coated +healed +138 +communal +hai +xiii +academics +boone +psychologist +restless +lahore +stephens +mba +brendan +foreigners +printer +##pc +ached +explode +27th +deed +scratched +dared +##pole +cardiac +1780 +okinawa +proto +commando +compelled +oddly +electrons +##base +replica +thanksgiving +##rist +sheila +deliberate +stafford +tidal +representations +hercules +ou +##path +##iated +kidnapping +lenses +##tling +deficit +samoa +mouths +consuming +computational +maze +granting +smirk +razor +fixture +ideals +inviting +aiden +nominal +##vs +issuing +julio +pitt +ramsey +docks +##oss +exhaust +##owed +bavarian +draped +anterior +mating +ethiopian +explores +noticing +##nton +discarded +convenience +hoffman +endowment +beasts +cartridge +mormon +paternal +probe +sleeves +interfere +lump +deadline +##rail +jenks +bulldogs +scrap +alternating +justified +reproductive +nam +seize +descending +secretariat +kirby +coupe +grouped +smash +panther +sedan +tapping +##18 +lola +cheer +germanic +unfortunate +##eter +unrelated +##fan +subordinate +##sdale +suzanne +advertisement +##ility +horsepower +##lda +cautiously +discourse +luigi +##mans +##fields +noun +prevalent +mao +schneider +everett +surround +governorate +kira +##avia +westward +##take +misty +rails +sustainability +134 +unused +##rating +packs +toast +unwilling +regulate +thy +suffrage +nile +awe +assam +definitions +travelers +affordable +##rb +conferred +sells +undefeated +beneficial +torso +basal +repeating +remixes +##pass +bahrain +cables +fang +##itated +excavated +numbering +statutory +##rey +deluxe +##lian +forested +ramirez +derbyshire +zeus +slamming +transfers +astronomer +banana +lottery +berg +histories +bamboo +##uchi +resurrection +posterior +bowls +vaguely +##thi +thou +preserving +tensed +offence +##inas +meyrick +callum +ridden +watt +langdon +tying +lowland +snorted +daring +truman +##hale +##girl +aura +overly +filing +weighing +goa +infections +philanthropist +saunders +eponymous +##owski +latitude +perspectives +reviewing +mets +commandant +radial +##kha +flashlight +reliability +koch +vowels +amazed +ada +elaine +supper +##rth +##encies +predator +debated +soviets +cola +##boards +##nah +compartment +crooked +arbitrary +fourteenth +##ctive +havana +majors +steelers +clips +profitable +ambush +exited +packers +##tile +nude +cracks +fungi +##е +limb +trousers +josie +shelby +tens +frederic +##ος +definite +smoothly +constellation +insult +baton +discs +lingering +##nco +conclusions +lent +staging +becker +grandpa +shaky +##tron +einstein +obstacles +sk +adverse +elle +economically +##moto +mccartney +thor +dismissal +motions +readings +nostrils +treatise +##pace +squeezing +evidently +prolonged +1783 +venezuelan +je +marguerite +beirut +takeover +shareholders +##vent +denise +digit +airplay +norse +##bbling +imaginary +pills +hubert +blaze +vacated +eliminating +##ello +vine +mansfield +##tty +retrospective +barrow +borne +clutch +bail +forensic +weaving +##nett +##witz +desktop +citadel +promotions +worrying +dorset +ieee +subdivided +##iating +manned +expeditionary +pickup +synod +chuckle +185 +barney +##rz +##ffin +functionality +karachi +litigation +meanings +uc +lick +turbo +anders +##ffed +execute +curl +oppose +ankles +typhoon +##د +##ache +##asia +linguistics +compassion +pressures +grazing +perfection +##iting +immunity +monopoly +muddy +backgrounds +136 +namibia +francesca +monitors +attracting +stunt +tuition +##ии +vegetable +##mates +##quent +mgm +jen +complexes +forts +##ond +cellar +bites +seventeenth +royals +flemish +failures +mast +charities +##cular +peruvian +capitals +macmillan +ipswich +outward +frigate +postgraduate +folds +employing +##ouse +concurrently +fiery +##tai +contingent +nightmares +monumental +nicaragua +##kowski +lizard +mal +fielding +gig +reject +##pad +harding +##ipe +coastline +##cin +##nos +beethoven +humphrey +innovations +##tam +##nge +norris +doris +solicitor +huang +obey +141 +##lc +niagara +##tton +shelves +aug +bourbon +curry +nightclub +specifications +hilton +##ndo +centennial +dispersed +worm +neglected +briggs +sm +font +kuala +uneasy +plc +##nstein +##bound +##aking +##burgh +awaiting +pronunciation +##bbed +##quest +eh +optimal +zhu +raped +greens +presided +brenda +worries +##life +venetian +marxist +turnout +##lius +refined +braced +sins +grasped +sunderland +nickel +speculated +lowell +cyrillic +communism +fundraising +resembling +colonists +mutant +freddie +usc +##mos +gratitude +##run +mural +##lous +chemist +wi +reminds +28th +steals +tess +pietro +##ingen +promoter +ri +microphone +honoured +rai +sant +##qui +feather +##nson +burlington +kurdish +terrorists +deborah +sickness +##wed +##eet +hazard +irritated +desperation +veil +clarity +##rik +jewels +xv +##gged +##ows +##cup +berkshire +unfair +mysteries +orchid +winced +exhaustion +renovations +stranded +obe +infinity +##nies +adapt +redevelopment +thanked +registry +olga +domingo +noir +tudor +ole +##atus +commenting +behaviors +##ais +crisp +pauline +probable +stirling +wigan +##bian +paralympics +panting +surpassed +##rew +luca +barred +pony +famed +##sters +cassandra +waiter +carolyn +exported +##orted +andres +destructive +deeds +jonah +castles +vacancy +suv +##glass +1788 +orchard +yep +famine +belarusian +sprang +##forth +skinny +##mis +administrators +rotterdam +zambia +zhao +boiler +discoveries +##ride +##physics +lucius +disappointing +outreach +spoon +##frame +qualifications +unanimously +enjoys +regency +##iidae +stade +realism +veterinary +rodgers +dump +alain +chestnut +castile +censorship +rumble +gibbs +##itor +communion +reggae +inactivated +logs +loads +##houses +homosexual +##iano +ale +informs +##cas +phrases +plaster +linebacker +ambrose +kaiser +fascinated +850 +limerick +recruitment +forge +mastered +##nding +leinster +rooted +threaten +##strom +borneo +##hes +suggestions +scholarships +propeller +documentaries +patronage +coats +constructing +invest +neurons +comet +entirety +shouts +identities +annoying +unchanged +wary +##antly +##ogy +neat +oversight +##kos +phillies +replay +constance +##kka +incarnation +humble +skies +minus +##acy +smithsonian +##chel +guerrilla +jar +cadets +##plate +surplus +audit +##aru +cracking +joanna +louisa +pacing +##lights +intentionally +##iri +diner +nwa +imprint +australians +tong +unprecedented +bunker +naive +specialists +ark +nichols +railing +leaked +pedal +##uka +shrub +longing +roofs +v8 +captains +neural +tuned +##ntal +##jet +emission +medina +frantic +codex +definitive +sid +abolition +intensified +stocks +enrique +sustain +genoa +oxide +##written +clues +cha +##gers +tributaries +fragment +venom +##rity +##ente +##sca +muffled +vain +sire +laos +##ingly +##hana +hastily +snapping +surfaced +sentiment +motive +##oft +contests +approximate +mesa +luckily +dinosaur +exchanges +propelled +accord +bourne +relieve +tow +masks +offended +##ues +cynthia +##mmer +rains +bartender +zinc +reviewers +lois +##sai +legged +arrogant +rafe +rosie +comprise +handicap +blockade +inlet +lagoon +copied +drilling +shelley +petals +##inian +mandarin +obsolete +##inated +onward +arguably +productivity +cindy +praising +seldom +busch +discusses +raleigh +shortage +ranged +stanton +encouragement +firstly +conceded +overs +temporal +##uke +cbe +##bos +woo +certainty +pumps +##pton +stalked +##uli +lizzie +periodic +thieves +weaker +##night +gases +shoving +chooses +wc +##chemical +prompting +weights +##kill +robust +flanked +sticky +hu +tuberculosis +##eb +##eal +christchurch +resembled +wallet +reese +inappropriate +pictured +distract +fixing +fiddle +giggled +burger +heirs +hairy +mechanic +torque +apache +obsessed +chiefly +cheng +logging +##tag +extracted +meaningful +numb +##vsky +gloucestershire +reminding +##bay +unite +##lit +breeds +diminished +clown +glove +1860s +##ن +##ug +archibald +focal +freelance +sliced +depiction +##yk +organism +switches +sights +stray +crawling +##ril +lever +leningrad +interpretations +loops +anytime +reel +alicia +delighted +##ech +inhaled +xiv +suitcase +bernie +vega +licenses +northampton +exclusion +induction +monasteries +racecourse +homosexuality +##right +##sfield +##rky +dimitri +michele +alternatives +ions +commentators +genuinely +objected +pork +hospitality +fencing +stephan +warships +peripheral +wit +drunken +wrinkled +quentin +spends +departing +chung +numerical +spokesperson +##zone +johannesburg +caliber +killers +##udge +assumes +neatly +demographic +abigail +bloc +##vel +mounting +##lain +bentley +slightest +xu +recipients +##jk +merlin +##writer +seniors +prisons +blinking +hindwings +flickered +kappa +##hel +80s +strengthening +appealing +brewing +gypsy +mali +lashes +hulk +unpleasant +harassment +bio +treaties +predict +instrumentation +pulp +troupe +boiling +mantle +##ffe +ins +##vn +dividing +handles +verbs +##onal +coconut +senegal +340 +thorough +gum +momentarily +##sto +cocaine +panicked +destined +##turing +teatro +denying +weary +captained +mans +##hawks +##code +wakefield +bollywood +thankfully +##16 +cyril +##wu +amendments +##bahn +consultation +stud +reflections +kindness +1787 +internally +##ovo +tex +mosaic +distribute +paddy +seeming +143 +##hic +piers +##15 +##mura +##verse +popularly +winger +kang +sentinel +mccoy +##anza +covenant +##bag +verge +fireworks +suppress +thrilled +dominate +##jar +swansea +##60 +142 +reconciliation +##ndi +stiffened +cue +dorian +##uf +damascus +amor +ida +foremost +##aga +porsche +unseen +dir +##had +##azi +stony +lexi +melodies +##nko +angular +integer +podcast +ants +inherent +jaws +justify +persona +##olved +josephine +##nr +##ressed +customary +flashes +gala +cyrus +glaring +backyard +ariel +physiology +greenland +html +stir +avon +atletico +finch +methodology +ked +##lent +mas +catholicism +townsend +branding +quincy +fits +containers +1777 +ashore +aragon +##19 +forearm +poisoning +##sd +adopting +conquer +grinding +amnesty +keller +finances +evaluate +forged +lankan +instincts +##uto +guam +bosnian +photographed +workplace +desirable +protector +##dog +allocation +intently +encourages +willy +##sten +bodyguard +electro +brighter +##ν +bihar +##chev +lasts +opener +amphibious +sal +verde +arte +##cope +captivity +vocabulary +yields +##tted +agreeing +desmond +pioneered +##chus +strap +campaigned +railroads +##ович +emblem +##dre +stormed +501 +##ulous +marijuana +northumberland +##gn +##nath +bowen +landmarks +beaumont +##qua +danube +##bler +attorneys +th +ge +flyers +critique +villains +cass +mutation +acc +##0s +colombo +mckay +motif +sampling +concluding +syndicate +##rell +neon +stables +ds +warnings +clint +mourning +wilkinson +##tated +merrill +leopard +evenings +exhaled +emil +sonia +ezra +discrete +stove +farrell +fifteenth +prescribed +superhero +##rier +worms +helm +wren +##duction +##hc +expo +##rator +hq +unfamiliar +antony +prevents +acceleration +fiercely +mari +painfully +calculations +cheaper +ign +clifton +irvine +davenport +mozambique +##np +pierced +##evich +wonders +##wig +##cate +##iling +crusade +ware +##uel +enzymes +reasonably +mls +##coe +mater +ambition +bunny +eliot +kernel +##fin +asphalt +headmaster +torah +aden +lush +pins +waived +##care +##yas +joao +substrate +enforce +##grad +##ules +alvarez +selections +epidemic +tempted +##bit +bremen +translates +ensured +waterfront +29th +forrest +manny +malone +kramer +reigning +cookies +simpler +absorption +205 +engraved +##ffy +evaluated +1778 +haze +146 +comforting +crossover +##abe +thorn +##rift +##imo +##pop +suppression +fatigue +cutter +##tr +201 +wurttemberg +##orf +enforced +hovering +proprietary +gb +samurai +syllable +ascent +lacey +tick +lars +tractor +merchandise +rep +bouncing +defendants +##yre +huntington +##ground +##oko +standardized +##hor +##hima +assassinated +nu +predecessors +rainy +liar +assurance +lyrical +##uga +secondly +flattened +ios +parameter +undercover +##mity +bordeaux +punish +ridges +markers +exodus +inactive +hesitate +debbie +nyc +pledge +savoy +nagar +offset +organist +##tium +hesse +marin +converting +##iver +diagram +propulsion +pu +validity +reverted +supportive +##dc +ministries +clans +responds +proclamation +##inae +##ø +##rea +ein +pleading +patriot +sf +birch +islanders +strauss +hates +##dh +brandenburg +concession +rd +##ob +1900s +killings +textbook +antiquity +cinematography +wharf +embarrassing +setup +creed +farmland +inequality +centred +signatures +fallon +370 +##ingham +##uts +ceylon +gazing +directive +laurie +##tern +globally +##uated +##dent +allah +excavation +threads +##cross +148 +frantically +icc +utilize +determines +respiratory +thoughtful +receptions +##dicate +merging +chandra +seine +147 +builders +builds +diagnostic +dev +visibility +goddamn +analyses +dhaka +cho +proves +chancel +concurrent +curiously +canadians +pumped +restoring +1850s +turtles +jaguar +sinister +spinal +traction +declan +vows +1784 +glowed +capitalism +swirling +install +universidad +##lder +##oat +soloist +##genic +##oor +coincidence +beginnings +nissan +dip +resorts +caucasus +combustion +infectious +##eno +pigeon +serpent +##itating +conclude +masked +salad +jew +##gr +surreal +toni +##wc +harmonica +151 +##gins +##etic +##coat +fishermen +intending +bravery +##wave +klaus +titan +wembley +taiwanese +ransom +40th +incorrect +hussein +eyelids +jp +cooke +dramas +utilities +##etta +##print +eisenhower +principally +granada +lana +##rak +openings +concord +##bl +bethany +connie +morality +sega +##mons +##nard +earnings +##kara +##cine +wii +communes +##rel +coma +composing +softened +severed +grapes +##17 +nguyen +analyzed +warlord +hubbard +heavenly +behave +slovenian +##hit +##ony +hailed +filmmakers +trance +caldwell +skye +unrest +coward +likelihood +##aging +bern +sci +taliban +honolulu +propose +##wang +1700 +browser +imagining +cobra +contributes +dukes +instinctively +conan +violinist +##ores +accessories +gradual +##amp +quotes +sioux +##dating +undertake +intercepted +sparkling +compressed +139 +fungus +tombs +haley +imposing +rests +degradation +lincolnshire +retailers +wetlands +tulsa +distributor +dungeon +nun +greenhouse +convey +atlantis +aft +exits +oman +dresser +lyons +##sti +joking +eddy +judgement +omitted +digits +##cts +##game +juniors +##rae +cents +stricken +une +##ngo +wizards +weir +breton +nan +technician +fibers +liking +royalty +##cca +154 +persia +terribly +magician +##rable +##unt +vance +cafeteria +booker +camille +warmer +##static +consume +cavern +gaps +compass +contemporaries +foyer +soothing +graveyard +maj +plunged +blush +##wear +cascade +demonstrates +ordinance +##nov +boyle +##lana +rockefeller +shaken +banjo +izzy +##ense +breathless +vines +##32 +##eman +alterations +chromosome +dwellings +feudal +mole +153 +catalonia +relics +tenant +mandated +##fm +fridge +hats +honesty +patented +raul +heap +cruisers +accusing +enlightenment +infants +wherein +chatham +contractors +zen +affinity +hc +osborne +piston +156 +traps +maturity +##rana +lagos +##zal +peering +##nay +attendant +dealers +protocols +subset +prospects +biographical +##cre +artery +##zers +insignia +nuns +endured +##eration +recommend +schwartz +serbs +berger +cromwell +crossroads +##ctor +enduring +clasped +grounded +##bine +marseille +twitched +abel +choke +https +catalyst +moldova +italians +##tist +disastrous +wee +##oured +##nti +wwf +nope +##piration +##asa +expresses +thumbs +167 +##nza +coca +1781 +cheating +##ption +skipped +sensory +heidelberg +spies +satan +dangers +semifinal +202 +bohemia +whitish +confusing +shipbuilding +relies +surgeons +landings +ravi +baku +moor +suffix +alejandro +##yana +litre +upheld +##unk +rajasthan +##rek +coaster +insists +posture +scenarios +etienne +favoured +appoint +transgender +elephants +poked +greenwood +defences +fulfilled +militant +somali +1758 +chalk +potent +##ucci +migrants +wink +assistants +nos +restriction +activism +niger +##ario +colon +shaun +##sat +daphne +##erated +swam +congregations +reprise +considerations +magnet +playable +xvi +##р +overthrow +tobias +knob +chavez +coding +##mers +propped +katrina +orient +newcomer +##suke +temperate +##pool +farmhouse +interrogation +##vd +committing +##vert +forthcoming +strawberry +joaquin +macau +ponds +shocking +siberia +##cellular +chant +contributors +##nant +##ologists +sped +absorb +hail +1782 +spared +##hore +barbados +karate +opus +originates +saul +##xie +evergreen +leaped +##rock +correlation +exaggerated +weekday +unification +bump +tracing +brig +afb +pathways +utilizing +##ners +mod +mb +disturbance +kneeling +##stad +##guchi +100th +pune +##thy +decreasing +168 +manipulation +miriam +academia +ecosystem +occupational +rbi +##lem +rift +##14 +rotary +stacked +incorporation +awakening +generators +guerrero +racist +##omy +cyber +derivatives +culminated +allie +annals +panzer +sainte +wikipedia +pops +zu +austro +##vate +algerian +politely +nicholson +mornings +educate +tastes +thrill +dartmouth +##gating +db +##jee +regan +differing +concentrating +choreography +divinity +##media +pledged +alexandre +routing +gregor +madeline +##idal +apocalypse +##hora +gunfire +culminating +elves +fined +liang +lam +programmed +tar +guessing +transparency +gabrielle +##gna +cancellation +flexibility +##lining +accession +shea +stronghold +nets +specializes +##rgan +abused +hasan +sgt +ling +exceeding +##₄ +admiration +supermarket +##ark +photographers +specialised +tilt +resonance +hmm +perfume +380 +sami +threatens +garland +botany +guarding +boiled +greet +puppy +russo +supplier +wilmington +vibrant +vijay +##bius +paralympic +grumbled +paige +faa +licking +margins +hurricanes +##gong +fest +grenade +ripping +##uz +counseling +weigh +##sian +needles +wiltshire +edison +costly +##not +fulton +tramway +redesigned +staffordshire +cache +gasping +watkins +sleepy +candidacy +##group +monkeys +timeline +throbbing +##bid +##sos +berth +uzbekistan +vanderbilt +bothering +overturned +ballots +gem +##iger +sunglasses +subscribers +hooker +compelling +ang +exceptionally +saloon +stab +##rdi +carla +terrifying +rom +##vision +coil +##oids +satisfying +vendors +31st +mackay +deities +overlooked +ambient +bahamas +felipe +olympia +whirled +botanist +advertised +tugging +##dden +disciples +morales +unionist +rites +foley +morse +motives +creepy +##₀ +soo +##sz +bargain +highness +frightening +turnpike +tory +reorganization +##cer +depict +biographer +##walk +unopposed +manifesto +##gles +institut +emile +accidental +kapoor +##dam +kilkenny +cortex +lively +##13 +romanesque +jain +shan +cannons +##ood +##ske +petrol +echoing +amalgamated +disappears +cautious +proposes +sanctions +trenton +##ر +flotilla +aus +contempt +tor +canary +cote +theirs +##hun +conceptual +deleted +fascinating +paso +blazing +elf +honourable +hutchinson +##eiro +##outh +##zin +surveyor +tee +amidst +wooded +reissue +intro +##ono +cobb +shelters +newsletter +hanson +brace +encoding +confiscated +dem +caravan +marino +scroll +melodic +cows +imam +##adi +##aneous +northward +searches +biodiversity +cora +310 +roaring +##bers +connell +theologian +halo +compose +pathetic +unmarried +dynamo +##oot +az +calculation +toulouse +deserves +humour +nr +forgiveness +tam +undergone +martyr +pamela +myths +whore +counselor +hicks +290 +heavens +battleship +electromagnetic +##bbs +stellar +establishments +presley +hopped +##chin +temptation +90s +wills +nas +##yuan +nhs +##nya +seminars +##yev +adaptations +gong +asher +lex +indicator +sikh +tobago +cites +goin +##yte +satirical +##gies +characterised +correspond +bubbles +lure +participates +##vid +eruption +skate +therapeutic +1785 +canals +wholesale +defaulted +sac +460 +petit +##zzled +virgil +leak +ravens +256 +portraying +##yx +ghetto +creators +dams +portray +vicente +##rington +fae +namesake +bounty +##arium +joachim +##ota +##iser +aforementioned +axle +snout +depended +dismantled +reuben +480 +##ibly +gallagher +##lau +##pd +earnest +##ieu +##iary +inflicted +objections +##llar +asa +gritted +##athy +jericho +##sea +##was +flick +underside +ceramics +undead +substituted +195 +eastward +undoubtedly +wheeled +chimney +##iche +guinness +cb +##ager +siding +##bell +traitor +baptiste +disguised +inauguration +149 +tipperary +choreographer +perched +warmed +stationary +eco +##ike +##ntes +bacterial +##aurus +flores +phosphate +##core +attacker +invaders +alvin +intersects +a1 +indirectly +immigrated +businessmen +cornelius +valves +narrated +pill +sober +ul +nationale +monastic +applicants +scenery +##jack +161 +motifs +constitutes +cpu +##osh +jurisdictions +sd +tuning +irritation +woven +##uddin +fertility +gao +##erie +antagonist +impatient +glacial +hides +boarded +denominations +interception +##jas +cookie +nicola +##tee +algebraic +marquess +bahn +parole +buyers +bait +turbines +paperwork +bestowed +natasha +renee +oceans +purchases +157 +vaccine +215 +##tock +fixtures +playhouse +integrate +jai +oswald +intellectuals +##cky +booked +nests +mortimer +##isi +obsession +sept +##gler +##sum +440 +scrutiny +simultaneous +squinted +##shin +collects +oven +shankar +penned +remarkably +##я +slips +luggage +spectral +1786 +collaborations +louie +consolidation +##ailed +##ivating +420 +hoover +blackpool +harness +ignition +vest +tails +belmont +mongol +skinner +##nae +visually +mage +derry +##tism +##unce +stevie +transitional +##rdy +redskins +drying +prep +prospective +##21 +annoyance +oversee +##loaded +fills +##books +##iki +announces +fda +scowled +respects +prasad +mystic +tucson +##vale +revue +springer +bankrupt +1772 +aristotle +salvatore +habsburg +##geny +dal +natal +nut +pod +chewing +darts +moroccan +walkover +rosario +lenin +punjabi +##ße +grossed +scattering +wired +invasive +hui +polynomial +corridors +wakes +gina +portrays +##cratic +arid +retreating +erich +irwin +sniper +##dha +linen +lindsey +maneuver +butch +shutting +socio +bounce +commemorative +postseason +jeremiah +pines +275 +mystical +beads +bp +abbas +furnace +bidding +consulted +assaulted +empirical +rubble +enclosure +sob +weakly +cancel +polly +yielded +##emann +curly +prediction +battered +70s +vhs +jacqueline +render +sails +barked +detailing +grayson +riga +sloane +raging +##yah +herbs +bravo +##athlon +alloy +giggle +imminent +suffers +assumptions +waltz +##itate +accomplishments +##ited +bathing +remixed +deception +prefix +##emia +deepest +##tier +##eis +balkan +frogs +##rong +slab +##pate +philosophers +peterborough +grains +imports +dickinson +rwanda +##atics +1774 +dirk +lan +tablets +##rove +clone +##rice +caretaker +hostilities +mclean +##gre +regimental +treasures +norms +impose +tsar +tango +diplomacy +variously +complain +192 +recognise +arrests +1779 +celestial +pulitzer +##dus +bing +libretto +##moor +adele +splash +##rite +expectation +lds +confronts +##izer +spontaneous +harmful +wedge +entrepreneurs +buyer +##ope +bilingual +translate +rugged +conner +circulated +uae +eaton +##gra +##zzle +lingered +lockheed +vishnu +reelection +alonso +##oom +joints +yankee +headline +cooperate +heinz +laureate +invading +##sford +echoes +scandinavian +##dham +hugging +vitamin +salute +micah +hind +trader +##sper +radioactive +##ndra +militants +poisoned +ratified +remark +campeonato +deprived +wander +prop +##dong +outlook +##tani +##rix +##eye +chiang +darcy +##oping +mandolin +spice +statesman +babylon +182 +walled +forgetting +afro +##cap +158 +giorgio +buffer +##polis +planetary +##gis +overlap +terminals +kinda +centenary +##bir +arising +manipulate +elm +ke +1770 +ak +##tad +chrysler +mapped +moose +pomeranian +quad +macarthur +assemblies +shoreline +recalls +stratford +##rted +noticeable +##evic +imp +##rita +##sque +accustomed +supplying +tents +disgusted +vogue +sipped +filters +khz +reno +selecting +luftwaffe +mcmahon +tyne +masterpiece +carriages +collided +dunes +exercised +flare +remembers +muzzle +##mobile +heck +##rson +burgess +lunged +middleton +boycott +bilateral +##sity +hazardous +lumpur +multiplayer +spotlight +jackets +goldman +liege +porcelain +rag +waterford +benz +attracts +hopeful +battling +ottomans +kensington +baked +hymns +cheyenne +lattice +levine +borrow +polymer +clashes +michaels +monitored +commitments +denounced +##25 +##von +cavity +##oney +hobby +akin +##holders +futures +intricate +cornish +patty +##oned +illegally +dolphin +##lag +barlow +yellowish +maddie +apologized +luton +plagued +##puram +nana +##rds +sway +fanny +łodz +##rino +psi +suspicions +hanged +##eding +initiate +charlton +##por +nak +competent +235 +analytical +annex +wardrobe +reservations +##rma +sect +162 +fairfax +hedge +piled +buckingham +uneven +bauer +simplicity +snyder +interpret +accountability +donors +moderately +byrd +continents +##cite +##max +disciple +hr +jamaican +ping +nominees +##uss +mongolian +diver +attackers +eagerly +ideological +pillows +miracles +apartheid +revolver +sulfur +clinics +moran +163 +##enko +ile +katy +rhetoric +##icated +chronology +recycling +##hrer +elongated +mughal +pascal +profiles +vibration +databases +domination +##fare +##rant +matthias +digest +rehearsal +polling +weiss +initiation +reeves +clinging +flourished +impress +ngo +##hoff +##ume +buckley +symposium +rhythms +weed +emphasize +transforming +##taking +##gence +##yman +accountant +analyze +flicker +foil +priesthood +voluntarily +decreases +##80 +##hya +slater +sv +charting +mcgill +##lde +moreno +##iu +besieged +zur +robes +##phic +admitting +api +deported +turmoil +peyton +earthquakes +##ares +nationalists +beau +clair +brethren +interrupt +welch +curated +galerie +requesting +164 +##ested +impending +steward +viper +##vina +complaining +beautifully +brandy +foam +nl +1660 +##cake +alessandro +punches +laced +explanations +##lim +attribute +clit +reggie +discomfort +##cards +smoothed +whales +##cene +adler +countered +duffy +disciplinary +widening +recipe +reliance +conducts +goats +gradient +preaching +##shaw +matilda +quasi +striped +meridian +cannabis +cordoba +certificates +##agh +##tering +graffiti +hangs +pilgrims +repeats +##ych +revive +urine +etat +##hawk +fueled +belts +fuzzy +susceptible +##hang +mauritius +salle +sincere +beers +hooks +##cki +arbitration +entrusted +advise +sniffed +seminar +junk +donnell +processors +principality +strapped +celia +mendoza +everton +fortunes +prejudice +starving +reassigned +steamer +##lund +tuck +evenly +foreman +##ffen +dans +375 +envisioned +slit +##xy +baseman +liberia +rosemary +##weed +electrified +periodically +potassium +stride +contexts +sperm +slade +mariners +influx +bianca +subcommittee +##rane +spilling +icao +estuary +##nock +delivers +iphone +##ulata +isa +mira +bohemian +dessert +##sbury +welcoming +proudly +slowing +##chs +musee +ascension +russ +##vian +waits +##psy +africans +exploit +##morphic +gov +eccentric +crab +peck +##ull +entrances +formidable +marketplace +groom +bolted +metabolism +patton +robbins +courier +payload +endure +##ifier +andes +refrigerator +##pr +ornate +##uca +ruthless +illegitimate +masonry +strasbourg +bikes +adobe +##³ +apples +quintet +willingly +niche +bakery +corpses +energetic +##cliffe +##sser +##ards +177 +centimeters +centro +fuscous +cretaceous +rancho +##yde +andrei +telecom +tottenham +oasis +ordination +vulnerability +presiding +corey +cp +penguins +sims +##pis +malawi +piss +##48 +correction +##cked +##ffle +##ryn +countdown +detectives +psychiatrist +psychedelic +dinosaurs +blouse +##get +choi +vowed +##oz +randomly +##pol +49ers +scrub +blanche +bruins +dusseldorf +##using +unwanted +##ums +212 +dominique +elevations +headlights +om +laguna +##oga +1750 +famously +ignorance +shrewsbury +##aine +ajax +breuning +che +confederacy +greco +overhaul +##screen +paz +skirts +disagreement +cruelty +jagged +phoebe +shifter +hovered +viruses +##wes +mandy +##lined +##gc +landlord +squirrel +dashed +##ι +ornamental +gag +wally +grange +literal +spurs +undisclosed +proceeding +yin +##text +billie +orphan +spanned +humidity +indy +weighted +presentations +explosions +lucian +##tary +vaughn +hindus +##anga +##hell +psycho +171 +daytona +protects +efficiently +rematch +sly +tandem +##oya +rebranded +impaired +hee +metropolis +peach +godfrey +diaspora +ethnicity +prosperous +gleaming +dar +grossing +playback +##rden +stripe +pistols +##tain +births +labelled +##cating +172 +rudy +alba +##onne +aquarium +hostility +##gb +##tase +shudder +sumatra +hardest +lakers +consonant +creeping +demos +homicide +capsule +zeke +liberties +expulsion +pueblo +##comb +trait +transporting +##ddin +##neck +##yna +depart +gregg +mold +ledge +hangar +oldham +playboy +termination +analysts +gmbh +romero +##itic +insist +cradle +filthy +brightness +slash +shootout +deposed +bordering +##truct +isis +microwave +tumbled +sheltered +cathy +werewolves +messy +andersen +convex +clapped +clinched +satire +wasting +edo +vc +rufus +##jak +mont +##etti +poznan +##keeping +restructuring +transverse +##rland +azerbaijani +slovene +gestures +roommate +choking +shear +##quist +vanguard +oblivious +##hiro +disagreed +baptism +##lich +coliseum +##aceae +salvage +societe +cory +locke +relocation +relying +versailles +ahl +swelling +##elo +cheerful +##word +##edes +gin +sarajevo +obstacle +diverted +##nac +messed +thoroughbred +fluttered +utrecht +chewed +acquaintance +assassins +dispatch +mirza +##wart +nike +salzburg +swell +yen +##gee +idle +ligue +samson +##nds +##igh +playful +spawned +##cise +tease +##case +burgundy +##bot +stirring +skeptical +interceptions +marathi +##dies +bedrooms +aroused +pinch +##lik +preferences +tattoos +buster +digitally +projecting +rust +##ital +kitten +priorities +addison +pseudo +##guard +dusk +icons +sermon +##psis +##iba +bt +##lift +##xt +ju +truce +rink +##dah +##wy +defects +psychiatry +offences +calculate +glucose +##iful +##rized +##unda +francaise +##hari +richest +warwickshire +carly +1763 +purity +redemption +lending +##cious +muse +bruises +cerebral +aero +carving +##name +preface +terminology +invade +monty +##int +anarchist +blurred +##iled +rossi +treats +guts +shu +foothills +ballads +undertaking +premise +cecilia +affiliates +blasted +conditional +wilder +minors +drone +rudolph +buffy +swallowing +horton +attested +##hop +rutherford +howell +primetime +livery +penal +##bis +minimize +hydro +wrecked +wrought +palazzo +##gling +cans +vernacular +friedman +nobleman +shale +walnut +danielle +##ection +##tley +sears +##kumar +chords +lend +flipping +streamed +por +dracula +gallons +sacrifices +gamble +orphanage +##iman +mckenzie +##gible +boxers +daly +##balls +##ان +208 +##ific +##rative +##iq +exploited +slated +##uity +circling +hillary +pinched +goldberg +provost +campaigning +lim +piles +ironically +jong +mohan +successors +usaf +##tem +##ught +autobiographical +haute +preserves +##ending +acquitted +comparisons +203 +hydroelectric +gangs +cypriot +torpedoes +rushes +chrome +derive +bumps +instability +fiat +pets +##mbe +silas +dye +reckless +settler +##itation +info +heats +##writing +176 +canonical +maltese +fins +mushroom +stacy +aspen +avid +##kur +##loading +vickers +gaston +hillside +statutes +wilde +gail +kung +sabine +comfortably +motorcycles +##rgo +169 +pneumonia +fetch +##sonic +axel +faintly +parallels +##oop +mclaren +spouse +compton +interdisciplinary +miner +##eni +181 +clamped +##chal +##llah +separates +versa +##mler +scarborough +labrador +##lity +##osing +rutgers +hurdles +como +166 +burt +divers +##100 +wichita +cade +coincided +##erson +bruised +mla +##pper +vineyard +##ili +##brush +notch +mentioning +jase +hearted +kits +doe +##acle +pomerania +##ady +ronan +seizure +pavel +problematic +##zaki +domenico +##ulin +catering +penelope +dependence +parental +emilio +ministerial +atkinson +##bolic +clarkson +chargers +colby +grill +peeked +arises +summon +##aged +fools +##grapher +faculties +qaeda +##vial +garner +refurbished +##hwa +geelong +disasters +nudged +bs +shareholder +lori +algae +reinstated +rot +##ades +##nous +invites +stainless +183 +inclusive +##itude +diocesan +til +##icz +denomination +##xa +benton +floral +registers +##ider +##erman +##kell +absurd +brunei +guangzhou +hitter +retaliation +##uled +##eve +blanc +nh +consistency +contamination +##eres +##rner +dire +palermo +broadcasters +diaries +inspire +vols +brewer +tightening +ky +mixtape +hormone +##tok +stokes +##color +##dly +##ssi +pg +##ometer +##lington +sanitation +##tility +intercontinental +apps +##adt +¹⁄₂ +cylinders +economies +favourable +unison +croix +gertrude +odyssey +vanity +dangling +##logists +upgrades +dice +middleweight +practitioner +##ight +206 +henrik +parlor +orion +angered +lac +python +blurted +##rri +sensual +intends +swings +angled +##phs +husky +attain +peerage +precinct +textiles +cheltenham +shuffled +dai +confess +tasting +bhutan +##riation +tyrone +segregation +abrupt +ruiz +##rish +smirked +blackwell +confidential +browning +amounted +##put +vase +scarce +fabulous +raided +staple +guyana +unemployed +glider +shay +##tow +carmine +troll +intervene +squash +superstar +##uce +cylindrical +len +roadway +researched +handy +##rium +##jana +meta +lao +declares +##rring +##tadt +##elin +##kova +willem +shrubs +napoleonic +realms +skater +qi +volkswagen +##ł +tad +hara +archaeologist +awkwardly +eerie +##kind +wiley +##heimer +##24 +titus +organizers +cfl +crusaders +lama +usb +vent +enraged +thankful +occupants +maximilian +##gaard +possessing +textbooks +##oran +collaborator +quaker +##ulo +avalanche +mono +silky +straits +isaiah +mustang +surged +resolutions +potomac +descend +cl +kilograms +plato +strains +saturdays +##olin +bernstein +##ype +holstein +ponytail +##watch +belize +conversely +heroine +perpetual +##ylus +charcoal +piedmont +glee +negotiating +backdrop +prologue +##jah +##mmy +pasadena +climbs +ramos +sunni +##holm +##tner +##tri +anand +deficiency +hertfordshire +stout +##avi +aperture +orioles +##irs +doncaster +intrigued +bombed +coating +otis +##mat +cocktail +##jit +##eto +amir +arousal +sar +##proof +##act +##ories +dixie +pots +##bow +whereabouts +159 +##fted +drains +bullying +cottages +scripture +coherent +fore +poe +appetite +##uration +sampled +##ators +##dp +derrick +rotor +jays +peacock +installment +##rro +advisors +##coming +rodeo +scotch +##mot +##db +##fen +##vant +ensued +rodrigo +dictatorship +martyrs +twenties +##н +towed +incidence +marta +rainforest +sai +scaled +##cles +oceanic +qualifiers +symphonic +mcbride +dislike +generalized +aubrey +colonization +##iation +##lion +##ssing +disliked +lublin +salesman +##ulates +spherical +whatsoever +sweating +avalon +contention +punt +severity +alderman +atari +##dina +##grant +##rop +scarf +seville +vertices +annexation +fairfield +fascination +inspiring +launches +palatinate +regretted +##rca +feral +##iom +elk +nap +olsen +reddy +yong +##leader +##iae +garment +transports +feng +gracie +outrage +viceroy +insides +##esis +breakup +grady +organizer +softer +grimaced +222 +murals +galicia +arranging +vectors +##rsten +bas +##sb +##cens +sloan +##eka +bitten +ara +fender +nausea +bumped +kris +banquet +comrades +detector +persisted +##llan +adjustment +endowed +cinemas +##shot +sellers +##uman +peek +epa +kindly +neglect +simpsons +talon +mausoleum +runaway +hangul +lookout +##cic +rewards +coughed +acquainted +chloride +##ald +quicker +accordion +neolithic +##qa +artemis +coefficient +lenny +pandora +tx +##xed +ecstasy +litter +segunda +chairperson +gemma +hiss +rumor +vow +nasal +antioch +compensate +patiently +transformers +##eded +judo +morrow +penis +posthumous +philips +bandits +husbands +denote +flaming +##any +##phones +langley +yorker +1760 +walters +##uo +##kle +gubernatorial +fatty +samsung +leroy +outlaw +##nine +unpublished +poole +jakob +##ᵢ +##ₙ +crete +distorted +superiority +##dhi +intercept +crust +mig +claus +crashes +positioning +188 +stallion +301 +frontal +armistice +##estinal +elton +aj +encompassing +camel +commemorated +malaria +woodward +calf +cigar +penetrate +##oso +willard +##rno +##uche +illustrate +amusing +convergence +noteworthy +##lma +##rva +journeys +realise +manfred +##sable +410 +##vocation +hearings +fiance +##posed +educators +provoked +adjusting +##cturing +modular +stockton +paterson +vlad +rejects +electors +selena +maureen +##tres +uber +##rce +swirled +##num +proportions +nanny +pawn +naturalist +parma +apostles +awoke +ethel +wen +##bey +monsoon +overview +##inating +mccain +rendition +risky +adorned +##ih +equestrian +germain +nj +conspicuous +confirming +##yoshi +shivering +##imeter +milestone +rumours +flinched +bounds +smacked +token +##bei +lectured +automobiles +##shore +impacted +##iable +nouns +nero +##leaf +ismail +prostitute +trams +##lace +bridget +sud +stimulus +impressions +reins +revolves +##oud +##gned +giro +honeymoon +##swell +criterion +##sms +##uil +libyan +prefers +##osition +211 +preview +sucks +accusation +bursts +metaphor +diffusion +tolerate +faye +betting +cinematographer +liturgical +specials +bitterly +humboldt +##ckle +flux +rattled +##itzer +archaeologists +odor +authorised +marshes +discretion +##ов +alarmed +archaic +inverse +##leton +explorers +##pine +drummond +tsunami +woodlands +##minate +##tland +booklet +insanity +owning +insert +crafted +calculus +##tore +receivers +##bt +stung +##eca +##nched +prevailing +travellers +eyeing +lila +graphs +##borne +178 +julien +##won +morale +adaptive +therapist +erica +cw +libertarian +bowman +pitches +vita +##ional +crook +##ads +##entation +caledonia +mutiny +##sible +1840s +automation +##ß +flock +##pia +ironic +pathology +##imus +remarried +##22 +joker +withstand +energies +##att +shropshire +hostages +madeleine +tentatively +conflicting +mateo +recipes +euros +ol +mercenaries +nico +##ndon +albuquerque +augmented +mythical +bel +freud +##child +cough +##lica +365 +freddy +lillian +genetically +nuremberg +calder +209 +bonn +outdoors +paste +suns +urgency +vin +restraint +tyson +##cera +##selle +barrage +bethlehem +kahn +##par +mounts +nippon +barony +happier +ryu +makeshift +sheldon +blushed +castillo +barking +listener +taped +bethel +fluent +headlines +pornography +rum +disclosure +sighing +mace +doubling +gunther +manly +##plex +rt +interventions +physiological +forwards +emerges +##tooth +##gny +compliment +rib +recession +visibly +barge +faults +connector +exquisite +prefect +##rlin +patio +##cured +elevators +brandt +italics +pena +173 +wasp +satin +ea +botswana +graceful +respectable +##jima +##rter +##oic +franciscan +generates +##dl +alfredo +disgusting +##olate +##iously +sherwood +warns +cod +promo +cheryl +sino +##ة +##escu +twitch +##zhi +brownish +thom +ortiz +##dron +densely +##beat +carmel +reinforce +##bana +187 +anastasia +downhill +vertex +contaminated +remembrance +harmonic +homework +##sol +fiancee +gears +olds +angelica +loft +ramsay +quiz +colliery +sevens +##cape +autism +##hil +walkway +##boats +ruben +abnormal +ounce +khmer +##bbe +zachary +bedside +morphology +punching +##olar +sparrow +convinces +##35 +hewitt +queer +remastered +rods +mabel +solemn +notified +lyricist +symmetric +##xide +174 +encore +passports +wildcats +##uni +baja +##pac +mildly +##ease +bleed +commodity +mounds +glossy +orchestras +##omo +damian +prelude +ambitions +##vet +awhile +remotely +##aud +asserts +imply +##iques +distinctly +modelling +remedy +##dded +windshield +dani +xiao +##endra +audible +powerplant +1300 +invalid +elemental +acquisitions +##hala +immaculate +libby +plata +smuggling +ventilation +denoted +minh +##morphism +430 +differed +dion +kelley +lore +mocking +sabbath +spikes +hygiene +drown +runoff +stylized +tally +liberated +aux +interpreter +righteous +aba +siren +reaper +pearce +millie +##cier +##yra +gaius +##iso +captures +##ttering +dorm +claudio +##sic +benches +knighted +blackness +##ored +discount +fumble +oxidation +routed +##ς +novak +perpendicular +spoiled +fracture +splits +##urt +pads +topology +##cats +axes +fortunate +offenders +protestants +esteem +221 +broadband +convened +frankly +hound +prototypes +isil +facilitated +keel +##sher +sahara +awaited +bubba +orb +prosecutors +186 +hem +520 +##xing +relaxing +remnant +romney +sorted +slalom +stefano +ulrich +##active +exemption +folder +pauses +foliage +hitchcock +epithet +204 +criticisms +##aca +ballistic +brody +hinduism +chaotic +youths +equals +##pala +pts +thicker +analogous +capitalist +improvised +overseeing +sinatra +ascended +beverage +##tl +straightforward +##kon +curran +##west +bois +325 +induce +surveying +emperors +sax +unpopular +##kk +cartoonist +fused +##mble +unto +##yuki +localities +##cko +##ln +darlington +slain +academie +lobbying +sediment +puzzles +##grass +defiance +dickens +manifest +tongues +alumnus +arbor +coincide +184 +appalachian +mustafa +examiner +cabaret +traumatic +yves +bracelet +draining +heroin +magnum +baths +odessa +consonants +mitsubishi +##gua +kellan +vaudeville +##fr +joked +null +straps +probation +##ław +ceded +interfaces +##pas +##zawa +blinding +viet +224 +rothschild +museo +640 +huddersfield +##vr +tactic +##storm +brackets +dazed +incorrectly +##vu +reg +glazed +fearful +manifold +benefited +irony +##sun +stumbling +##rte +willingness +balkans +mei +wraps +##aba +injected +##lea +gu +syed +harmless +##hammer +bray +takeoff +poppy +timor +cardboard +astronaut +purdue +weeping +southbound +cursing +stalls +diagonal +##neer +lamar +bryce +comte +weekdays +harrington +##uba +negatively +##see +lays +grouping +##cken +##henko +affirmed +halle +modernist +##lai +hodges +smelling +aristocratic +baptized +dismiss +justification +oilers +##now +coupling +qin +snack +healer +##qing +gardener +layla +battled +formulated +stephenson +gravitational +##gill +##jun +1768 +granny +coordinating +suites +##cd +##ioned +monarchs +##cote +##hips +sep +blended +apr +barrister +deposition +fia +mina +policemen +paranoid +##pressed +churchyard +covert +crumpled +creep +abandoning +tr +transmit +conceal +barr +understands +readiness +spire +##cology +##enia +##erry +610 +startling +unlock +vida +bowled +slots +##nat +##islav +spaced +trusting +admire +rig +##ink +slack +##70 +mv +207 +casualty +##wei +classmates +##odes +##rar +##rked +amherst +furnished +evolve +foundry +menace +mead +##lein +flu +wesleyan +##kled +monterey +webber +##vos +wil +##mith +##на +bartholomew +justices +restrained +##cke +amenities +191 +mediated +sewage +trenches +ml +mainz +##thus +1800s +##cula +##inski +caine +bonding +213 +converts +spheres +superseded +marianne +crypt +sweaty +ensign +historia +##br +spruce +##post +##ask +forks +thoughtfully +yukon +pamphlet +ames +##uter +karma +##yya +bryn +negotiation +sighs +incapable +##mbre +##ntial +actresses +taft +##mill +luce +prevailed +##amine +1773 +motionless +envoy +testify +investing +sculpted +instructors +provence +kali +cullen +horseback +##while +goodwin +##jos +gaa +norte +##ldon +modify +wavelength +abd +214 +skinned +sprinter +forecast +scheduling +marries +squared +tentative +##chman +boer +##isch +bolts +swap +fisherman +assyrian +impatiently +guthrie +martins +murdoch +194 +tanya +nicely +dolly +lacy +med +##45 +syn +decks +fashionable +millionaire +##ust +surfing +##ml +##ision +heaved +tammy +consulate +attendees +routinely +197 +fuse +saxophonist +backseat +malaya +##lord +scowl +tau +##ishly +193 +sighted +steaming +##rks +303 +911 +##holes +##hong +ching +##wife +bless +conserved +jurassic +stacey +unix +zion +chunk +rigorous +blaine +198 +peabody +slayer +dismay +brewers +nz +##jer +det +##glia +glover +postwar +int +penetration +sylvester +imitation +vertically +airlift +heiress +knoxville +viva +##uin +390 +macon +##rim +##fighter +##gonal +janice +##orescence +##wari +marius +belongings +leicestershire +196 +blanco +inverted +preseason +sanity +sobbing +##due +##elt +##dled +collingwood +regeneration +flickering +shortest +##mount +##osi +feminism +##lat +sherlock +cabinets +fumbled +northbound +precedent +snaps +##mme +researching +##akes +guillaume +insights +manipulated +vapor +neighbour +sap +gangster +frey +f1 +stalking +scarcely +callie +barnett +tendencies +audi +doomed +assessing +slung +panchayat +ambiguous +bartlett +##etto +distributing +violating +wolverhampton +##hetic +swami +histoire +##urus +liable +pounder +groin +hussain +larsen +popping +surprises +##atter +vie +curt +##station +mute +relocate +musicals +authorization +richter +##sef +immortality +tna +bombings +##press +deteriorated +yiddish +##acious +robbed +colchester +cs +pmid +ao +verified +balancing +apostle +swayed +recognizable +oxfordshire +retention +nottinghamshire +contender +judd +invitational +shrimp +uhf +##icient +cleaner +longitudinal +tanker +##mur +acronym +broker +koppen +sundance +suppliers +##gil +4000 +clipped +fuels +petite +##anne +landslide +helene +diversion +populous +landowners +auspices +melville +quantitative +##xes +ferries +nicky +##llus +doo +haunting +roche +carver +downed +unavailable +##pathy +approximation +hiroshima +##hue +garfield +valle +comparatively +keyboardist +traveler +##eit +congestion +calculating +subsidiaries +##bate +serb +modernization +fairies +deepened +ville +averages +##lore +inflammatory +tonga +##itch +co₂ +squads +##hea +gigantic +serum +enjoyment +retailer +verona +35th +cis +##phobic +magna +technicians +##vati +arithmetic +##sport +levin +##dation +amtrak +chow +sienna +##eyer +backstage +entrepreneurship +##otic +learnt +tao +##udy +worcestershire +formulation +baggage +hesitant +bali +sabotage +##kari +barren +enhancing +murmur +pl +freshly +putnam +syntax +aces +medicines +resentment +bandwidth +##sier +grins +chili +guido +##sei +framing +implying +gareth +lissa +genevieve +pertaining +admissions +geo +thorpe +proliferation +sato +bela +analyzing +parting +##gor +awakened +##isman +huddled +secrecy +##kling +hush +gentry +540 +dungeons +##ego +coasts +##utz +sacrificed +##chule +landowner +mutually +prevalence +programmer +adolescent +disrupted +seaside +gee +trusts +vamp +georgie +##nesian +##iol +schedules +sindh +##market +etched +hm +sparse +bey +beaux +scratching +gliding +unidentified +216 +collaborating +gems +jesuits +oro +accumulation +shaping +mbe +anal +##xin +231 +enthusiasts +newscast +##egan +janata +dewey +parkinson +179 +ankara +biennial +towering +dd +inconsistent +950 +##chet +thriving +terminate +cabins +furiously +eats +advocating +donkey +marley +muster +phyllis +leiden +##user +grassland +glittering +iucn +loneliness +217 +memorandum +armenians +##ddle +popularized +rhodesia +60s +lame +##illon +sans +bikini +header +orbits +##xx +##finger +##ulator +sharif +spines +biotechnology +strolled +naughty +yates +##wire +fremantle +milo +##mour +abducted +removes +##atin +humming +wonderland +##chrome +##ester +hume +pivotal +##rates +armand +grams +believers +elector +rte +apron +bis +scraped +##yria +endorsement +initials +##llation +eps +dotted +hints +buzzing +emigration +nearer +##tom +indicators +##ulu +coarse +neutron +protectorate +##uze +directional +exploits +pains +loire +1830s +proponents +guggenheim +rabbits +ritchie +305 +hectare +inputs +hutton +##raz +verify +##ako +boilers +longitude +##lev +skeletal +yer +emilia +citrus +compromised +##gau +pokemon +prescription +paragraph +eduard +cadillac +attire +categorized +kenyan +weddings +charley +##bourg +entertain +monmouth +##lles +nutrients +davey +mesh +incentive +practised +ecosystems +kemp +subdued +overheard +##rya +bodily +maxim +##nius +apprenticeship +ursula +##fight +lodged +rug +silesian +unconstitutional +patel +inspected +coyote +unbeaten +##hak +34th +disruption +convict +parcel +##cl +##nham +collier +implicated +mallory +##iac +##lab +susannah +winkler +##rber +shia +phelps +sediments +graphical +robotic +##sner +adulthood +mart +smoked +##isto +kathryn +clarified +##aran +divides +convictions +oppression +pausing +burying +##mt +federico +mathias +eileen +##tana +kite +hunched +##acies +189 +##atz +disadvantage +liza +kinetic +greedy +paradox +yokohama +dowager +trunks +ventured +##gement +gupta +vilnius +olaf +##thest +crimean +hopper +##ej +progressively +arturo +mouthed +arrondissement +##fusion +rubin +simulcast +oceania +##orum +##stra +##rred +busiest +intensely +navigator +cary +##vine +##hini +##bies +fife +rowe +rowland +posing +insurgents +shafts +lawsuits +activate +conor +inward +culturally +garlic +265 +##eering +eclectic +##hui +##kee +##nl +furrowed +vargas +meteorological +rendezvous +##aus +culinary +commencement +##dition +quota +##notes +mommy +salaries +overlapping +mule +##iology +##mology +sums +wentworth +##isk +##zione +mainline +subgroup +##illy +hack +plaintiff +verdi +bulb +differentiation +engagements +multinational +supplemented +bertrand +caller +regis +##naire +##sler +##arts +##imated +blossom +propagation +kilometer +viaduct +vineyards +##uate +beckett +optimization +golfer +songwriters +seminal +semitic +thud +volatile +evolving +ridley +##wley +trivial +distributions +scandinavia +jiang +##ject +wrestled +insistence +##dio +emphasizes +napkin +##ods +adjunct +rhyme +##ricted +##eti +hopeless +surrounds +tremble +32nd +smoky +##ntly +oils +medicinal +padded +steer +wilkes +219 +255 +concessions +hue +uniquely +blinded +landon +yahoo +##lane +hendrix +commemorating +dex +specify +chicks +##ggio +intercity +1400 +morley +##torm +highlighting +##oting +pang +oblique +stalled +##liner +flirting +newborn +1769 +bishopric +shaved +232 +currie +##ush +dharma +spartan +##ooped +favorites +smug +novella +sirens +abusive +creations +espana +##lage +paradigm +semiconductor +sheen +##rdo +##yen +##zak +nrl +renew +##pose +##tur +adjutant +marches +norma +##enity +ineffective +weimar +grunt +##gat +lordship +plotting +expenditure +infringement +lbs +refrain +av +mimi +mistakenly +postmaster +1771 +##bara +ras +motorsports +tito +199 +subjective +##zza +bully +stew +##kaya +prescott +1a +##raphic +##zam +bids +styling +paranormal +reeve +sneaking +exploding +katz +akbar +migrant +syllables +indefinitely +##ogical +destroys +replaces +applause +##phine +pest +##fide +218 +articulated +bertie +##thing +##cars +##ptic +courtroom +crowley +aesthetics +cummings +tehsil +hormones +titanic +dangerously +##ibe +stadion +jaenelle +auguste +ciudad +##chu +mysore +partisans +##sio +lucan +philipp +##aly +debating +henley +interiors +##rano +##tious +homecoming +beyonce +usher +henrietta +prepares +weeds +##oman +ely +plucked +##pire +##dable +luxurious +##aq +artifact +password +pasture +juno +maddy +minsk +##dder +##ologies +##rone +assessments +martian +royalist +1765 +examines +##mani +##rge +nino +223 +parry +scooped +relativity +##eli +##uting +##cao +congregational +noisy +traverse +##agawa +strikeouts +nickelodeon +obituary +transylvania +binds +depictions +polk +trolley +##yed +##lard +breeders +##under +dryly +hokkaido +1762 +strengths +stacks +bonaparte +connectivity +neared +prostitutes +stamped +anaheim +gutierrez +sinai +##zzling +bram +fresno +madhya +##86 +proton +##lena +##llum +##phon +reelected +wanda +##anus +##lb +ample +distinguishing +##yler +grasping +sermons +tomato +bland +stimulation +avenues +##eux +spreads +scarlett +fern +pentagon +assert +baird +chesapeake +ir +calmed +distortion +fatalities +##olis +correctional +pricing +##astic +##gina +prom +dammit +ying +collaborate +##chia +welterweight +33rd +pointer +substitution +bonded +umpire +communicating +multitude +paddle +##obe +federally +intimacy +##insky +betray +ssr +##lett +##lean +##lves +##therapy +airbus +##tery +functioned +ud +bearer +biomedical +netflix +##hire +##nca +condom +brink +ik +##nical +macy +##bet +flap +gma +experimented +jelly +lavender +##icles +##ulia +munro +##mian +##tial +rye +##rle +60th +gigs +hottest +rotated +predictions +fuji +bu +##erence +##omi +barangay +##fulness +##sas +clocks +##rwood +##liness +cereal +roe +wight +decker +uttered +babu +onion +xml +forcibly +##df +petra +sarcasm +hartley +peeled +storytelling +##42 +##xley +##ysis +##ffa +fibre +kiel +auditor +fig +harald +greenville +##berries +geographically +nell +quartz +##athic +cemeteries +##lr +crossings +nah +holloway +reptiles +chun +sichuan +snowy +660 +corrections +##ivo +zheng +ambassadors +blacksmith +fielded +fluids +hardcover +turnover +medications +melvin +academies +##erton +ro +roach +absorbing +spaniards +colton +##founded +outsider +espionage +kelsey +245 +edible +##ulf +dora +establishes +##sham +##tries +contracting +##tania +cinematic +costello +nesting +##uron +connolly +duff +##nology +mma +##mata +fergus +sexes +gi +optics +spectator +woodstock +banning +##hee +##fle +differentiate +outfielder +refinery +226 +312 +gerhard +horde +lair +drastically +##udi +landfall +##cheng +motorsport +odi +##achi +predominant +quay +skins +##ental +edna +harshly +complementary +murdering +##aves +wreckage +##90 +ono +outstretched +lennox +munitions +galen +reconcile +470 +scalp +bicycles +gillespie +questionable +rosenberg +guillermo +hostel +jarvis +kabul +volvo +opium +yd +##twined +abuses +decca +outpost +##cino +sensible +neutrality +##64 +ponce +anchorage +atkins +turrets +inadvertently +disagree +libre +vodka +reassuring +weighs +##yal +glide +jumper +ceilings +repertory +outs +stain +##bial +envy +##ucible +smashing +heightened +policing +hyun +mixes +lai +prima +##ples +celeste +##bina +lucrative +intervened +kc +manually +##rned +stature +staffed +bun +bastards +nairobi +priced +##auer +thatcher +##kia +tripped +comune +##ogan +##pled +brasil +incentives +emanuel +hereford +musica +##kim +benedictine +biennale +##lani +eureka +gardiner +rb +knocks +sha +##ael +##elled +##onate +efficacy +ventura +masonic +sanford +maize +leverage +##feit +capacities +santana +##aur +novelty +vanilla +##cter +##tour +benin +##oir +##rain +neptune +drafting +tallinn +##cable +humiliation +##boarding +schleswig +fabian +bernardo +liturgy +spectacle +sweeney +pont +routledge +##tment +cosmos +ut +hilt +sleek +universally +##eville +##gawa +typed +##dry +favors +allegheny +glaciers +##rly +recalling +aziz +##log +parasite +requiem +auf +##berto +##llin +illumination +##breaker +##issa +festivities +bows +govern +vibe +vp +333 +sprawled +larson +pilgrim +bwf +leaping +##rts +##ssel +alexei +greyhound +hoarse +##dler +##oration +seneca +##cule +gaping +##ulously +##pura +cinnamon +##gens +##rricular +craven +fantasies +houghton +engined +reigned +dictator +supervising +##oris +bogota +commentaries +unnatural +fingernails +spirituality +tighten +##tm +canadiens +protesting +intentional +cheers +sparta +##ytic +##iere +##zine +widen +belgarath +controllers +dodd +iaaf +navarre +##ication +defect +squire +steiner +whisky +##mins +560 +inevitably +tome +##gold +chew +##uid +##lid +elastic +##aby +streaked +alliances +jailed +regal +##ined +##phy +czechoslovak +narration +absently +##uld +bluegrass +guangdong +quran +criticizing +hose +hari +##liest +##owa +skier +streaks +deploy +##lom +raft +bose +dialed +huff +##eira +haifa +simplest +bursting +endings +ib +sultanate +##titled +franks +whitman +ensures +sven +##ggs +collaborators +forster +organising +ui +banished +napier +injustice +teller +layered +thump +##otti +roc +battleships +evidenced +fugitive +sadie +robotics +##roud +equatorial +geologist +##iza +yielding +##bron +##sr +internationale +mecca +##diment +sbs +skyline +toad +uploaded +reflective +undrafted +lal +leafs +bayern +##dai +lakshmi +shortlisted +##stick +##wicz +camouflage +donate +af +christi +lau +##acio +disclosed +nemesis +1761 +assemble +straining +northamptonshire +tal +##asi +bernardino +premature +heidi +42nd +coefficients +galactic +reproduce +buzzed +sensations +zionist +monsieur +myrtle +##eme +archery +strangled +musically +viewpoint +antiquities +bei +trailers +seahawks +cured +pee +preferring +tasmanian +lange +sul +##mail +##working +colder +overland +lucivar +massey +gatherings +haitian +##smith +disapproval +flaws +##cco +##enbach +1766 +npr +##icular +boroughs +creole +forums +techno +1755 +dent +abdominal +streetcar +##eson +##stream +procurement +gemini +predictable +##tya +acheron +christoph +feeder +fronts +vendor +bernhard +jammu +tumors +slang +##uber +goaltender +twists +curving +manson +vuelta +mer +peanut +confessions +pouch +unpredictable +allowance +theodor +vascular +##factory +bala +authenticity +metabolic +coughing +nanjing +##cea +pembroke +##bard +splendid +36th +ff +hourly +##ahu +elmer +handel +##ivate +awarding +thrusting +dl +experimentation +##hesion +##46 +caressed +entertained +steak +##rangle +biologist +orphans +baroness +oyster +stepfather +##dridge +mirage +reefs +speeding +##31 +barons +1764 +227 +inhabit +preached +repealed +##tral +honoring +boogie +captives +administer +johanna +##imate +gel +suspiciously +1767 +sobs +##dington +backbone +hayward +garry +##folding +##nesia +maxi +##oof +##ppe +ellison +galileo +##stand +crimea +frenzy +amour +bumper +matrices +natalia +baking +garth +palestinians +##grove +smack +conveyed +ensembles +gardening +##manship +##rup +##stituting +1640 +harvesting +topography +jing +shifters +dormitory +##carriage +##lston +ist +skulls +##stadt +dolores +jewellery +sarawak +##wai +##zier +fences +christy +confinement +tumbling +credibility +fir +stench +##bria +##plication +##nged +##sam +virtues +##belt +marjorie +pba +##eem +##made +celebrates +schooner +agitated +barley +fulfilling +anthropologist +##pro +restrict +novi +regulating +##nent +padres +##rani +##hesive +loyola +tabitha +milky +olson +proprietor +crambidae +guarantees +intercollegiate +ljubljana +hilda +##sko +ignorant +hooded +##lts +sardinia +##lidae +##vation +frontman +privileged +witchcraft +##gp +jammed +laude +poking +##than +bracket +amazement +yunnan +##erus +maharaja +linnaeus +264 +commissioning +milano +peacefully +##logies +akira +rani +regulator +##36 +grasses +##rance +luzon +crows +compiler +gretchen +seaman +edouard +tab +buccaneers +ellington +hamlets +whig +socialists +##anto +directorial +easton +mythological +##kr +##vary +rhineland +semantic +taut +dune +inventions +succeeds +##iter +replication +branched +##pired +jul +prosecuted +kangaroo +penetrated +##avian +middlesbrough +doses +bleak +madam +predatory +relentless +##vili +reluctance +##vir +hailey +crore +silvery +1759 +monstrous +swimmers +transmissions +hawthorn +informing +##eral +toilets +caracas +crouch +kb +##sett +295 +cartel +hadley +##aling +alexia +yvonne +##biology +cinderella +eton +superb +blizzard +stabbing +industrialist +maximus +##gm +##orus +groves +maud +clade +oversized +comedic +##bella +rosen +nomadic +fulham +montane +beverages +galaxies +redundant +swarm +##rot +##folia +##llis +buckinghamshire +fen +bearings +bahadur +##rom +gilles +phased +dynamite +faber +benoit +vip +##ount +##wd +booking +fractured +tailored +anya +spices +westwood +cairns +auditions +inflammation +steamed +##rocity +##acion +##urne +skyla +thereof +watford +torment +archdeacon +transforms +lulu +demeanor +fucked +serge +##sor +mckenna +minas +entertainer +##icide +caress +originate +residue +##sty +1740 +##ilised +##org +beech +##wana +subsidies +##ghton +emptied +gladstone +ru +firefighters +voodoo +##rcle +het +nightingale +tamara +edmond +ingredient +weaknesses +silhouette +285 +compatibility +withdrawing +hampson +##mona +anguish +giggling +##mber +bookstore +##jiang +southernmost +tilting +##vance +bai +economical +rf +briefcase +dreadful +hinted +projections +shattering +totaling +##rogate +analogue +indicted +periodical +fullback +##dman +haynes +##tenberg +##ffs +##ishment +1745 +thirst +stumble +penang +vigorous +##ddling +##kor +##lium +octave +##ove +##enstein +##inen +##ones +siberian +##uti +cbn +repeal +swaying +##vington +khalid +tanaka +unicorn +otago +plastered +lobe +riddle +##rella +perch +##ishing +croydon +filtered +graeme +tripoli +##ossa +crocodile +##chers +sufi +mined +##tung +inferno +lsu +##phi +swelled +utilizes +£2 +cale +periodicals +styx +hike +informally +coop +lund +##tidae +ala +hen +qui +transformations +disposed +sheath +chickens +##cade +fitzroy +sas +silesia +unacceptable +odisha +1650 +sabrina +pe +spokane +ratios +athena +massage +shen +dilemma +##drum +##riz +##hul +corona +doubtful +niall +##pha +##bino +fines +cite +acknowledging +bangor +ballard +bathurst +##resh +huron +mustered +alzheimer +garments +kinase +tyre +warship +##cp +flashback +pulmonary +braun +cheat +kamal +cyclists +constructions +grenades +ndp +traveller +excuses +stomped +signalling +trimmed +futsal +mosques +relevance +##wine +wta +##23 +##vah +##lter +hoc +##riding +optimistic +##´s +deco +sim +interacting +rejecting +moniker +waterways +##ieri +##oku +mayors +gdansk +outnumbered +pearls +##ended +##hampton +fairs +totals +dominating +262 +notions +stairway +compiling +pursed +commodities +grease +yeast +##jong +carthage +griffiths +residual +amc +contraction +laird +sapphire +##marine +##ivated +amalgamation +dissolve +inclination +lyle +packaged +altitudes +suez +canons +graded +lurched +narrowing +boasts +guise +wed +enrico +##ovsky +rower +scarred +bree +cub +iberian +protagonists +bargaining +proposing +trainers +voyages +vans +fishes +##aea +##ivist +##verance +encryption +artworks +kazan +sabre +cleopatra +hepburn +rotting +supremacy +mecklenburg +##brate +burrows +hazards +outgoing +flair +organizes +##ctions +scorpion +##usions +boo +234 +chevalier +dunedin +slapping +##34 +ineligible +pensions +##38 +##omic +manufactures +emails +bismarck +238 +weakening +blackish +ding +mcgee +quo +##rling +northernmost +xx +manpower +greed +sampson +clicking +##ange +##horpe +##inations +##roving +torre +##eptive +##moral +symbolism +38th +asshole +meritorious +outfits +splashed +biographies +sprung +astros +##tale +302 +737 +filly +raoul +nw +tokugawa +linden +clubhouse +##apa +tracts +romano +##pio +putin +tags +##note +chained +dickson +gunshot +moe +gunn +rashid +##tails +zipper +##bas +##nea +contrasted +##ply +##udes +plum +pharaoh +##pile +aw +comedies +ingrid +sandwiches +subdivisions +1100 +mariana +nokia +kamen +hz +delaney +veto +herring +##words +possessive +outlines +##roup +siemens +stairwell +rc +gallantry +messiah +palais +yells +233 +zeppelin +##dm +bolivar +##cede +smackdown +mckinley +##mora +##yt +muted +geologic +finely +unitary +avatar +hamas +maynard +rees +bog +contrasting +##rut +liv +chico +disposition +pixel +##erate +becca +dmitry +yeshiva +narratives +##lva +##ulton +mercenary +sharpe +tempered +navigate +stealth +amassed +keynes +##lini +untouched +##rrie +havoc +lithium +##fighting +abyss +graf +southward +wolverine +balloons +implements +ngos +transitions +##icum +ambushed +concacaf +dormant +economists +##dim +costing +csi +rana +universite +boulders +verity +##llon +collin +mellon +misses +cypress +fluorescent +lifeless +spence +##ulla +crewe +shepard +pak +revelations +##م +jolly +gibbons +paw +##dro +##quel +freeing +##test +shack +fries +palatine +##51 +##hiko +accompaniment +cruising +recycled +##aver +erwin +sorting +synthesizers +dyke +realities +sg +strides +enslaved +wetland +##ghan +competence +gunpowder +grassy +maroon +reactors +objection +##oms +carlson +gearbox +macintosh +radios +shelton +##sho +clergyman +prakash +254 +mongols +trophies +oricon +228 +stimuli +twenty20 +cantonese +cortes +mirrored +##saurus +bhp +cristina +melancholy +##lating +enjoyable +nuevo +##wny +downfall +schumacher +##ind +banging +lausanne +rumbled +paramilitary +reflex +ax +amplitude +migratory +##gall +##ups +midi +barnard +lastly +sherry +##hp +##nall +keystone +##kra +carleton +slippery +##53 +coloring +foe +socket +otter +##rgos +mats +##tose +consultants +bafta +bison +topping +##km +490 +primal +abandonment +transplant +atoll +hideous +mort +pained +reproduced +tae +howling +##turn +unlawful +billionaire +hotter +poised +lansing +##chang +dinamo +retro +messing +nfc +domesday +##mina +blitz +timed +##athing +##kley +ascending +gesturing +##izations +signaled +tis +chinatown +mermaid +savanna +jameson +##aint +catalina +##pet +##hers +cochrane +cy +chatting +##kus +alerted +computation +mused +noelle +majestic +mohawk +campo +octagonal +##sant +##hend +241 +aspiring +##mart +comprehend +iona +paralyzed +shimmering +swindon +rhone +##eley +reputed +configurations +pitchfork +agitation +francais +gillian +lipstick +##ilo +outsiders +pontifical +resisting +bitterness +sewer +rockies +##edd +##ucher +misleading +1756 +exiting +galloway +##nging +risked +##heart +246 +commemoration +schultz +##rka +integrating +##rsa +poses +shrieked +##weiler +guineas +gladys +jerking +owls +goldsmith +nightly +penetrating +##unced +lia +##33 +ignited +betsy +##aring +##thorpe +follower +vigorously +##rave +coded +kiran +knit +zoology +tbilisi +##28 +##bered +repository +govt +deciduous +dino +growling +##bba +enhancement +unleashed +chanting +pussy +biochemistry +##eric +kettle +repression +toxicity +nrhp +##arth +##kko +##bush +ernesto +commended +outspoken +242 +mca +parchment +sms +kristen +##aton +bisexual +raked +glamour +navajo +a2 +conditioned +showcased +##hma +spacious +youthful +##esa +usl +appliances +junta +brest +layne +conglomerate +enchanted +chao +loosened +picasso +circulating +inspect +montevideo +##centric +##kti +piazza +spurred +##aith +bari +freedoms +poultry +stamford +lieu +##ect +indigo +sarcastic +bahia +stump +attach +dvds +frankenstein +lille +approx +scriptures +pollen +##script +nmi +overseen +##ivism +tides +proponent +newmarket +inherit +milling +##erland +centralized +##rou +distributors +credentials +drawers +abbreviation +##lco +##xon +downing +uncomfortably +ripe +##oes +erase +franchises +##ever +populace +##bery +##khar +decomposition +pleas +##tet +daryl +sabah +##stle +##wide +fearless +genie +lesions +annette +##ogist +oboe +appendix +nair +dripped +petitioned +maclean +mosquito +parrot +rpg +hampered +1648 +operatic +reservoirs +##tham +irrelevant +jolt +summarized +##fp +medallion +##taff +##− +clawed +harlow +narrower +goddard +marcia +bodied +fremont +suarez +altering +tempest +mussolini +porn +##isms +sweetly +oversees +walkers +solitude +grimly +shrines +hk +ich +supervisors +hostess +dietrich +legitimacy +brushes +expressive +##yp +dissipated +##rse +localized +systemic +##nikov +gettysburg +##js +##uaries +dialogues +muttering +251 +housekeeper +sicilian +discouraged +##frey +beamed +kaladin +halftime +kidnap +##amo +##llet +1754 +synonymous +depleted +instituto +insulin +reprised +##opsis +clashed +##ctric +interrupting +radcliffe +insisting +medici +1715 +ejected +playfully +turbulent +##47 +starvation +##rini +shipment +rebellious +petersen +verification +merits +##rified +cakes +##charged +1757 +milford +shortages +spying +fidelity +##aker +emitted +storylines +harvested +seismic +##iform +cheung +kilda +theoretically +barbie +lynx +##rgy +##tius +goblin +mata +poisonous +##nburg +reactive +residues +obedience +##евич +conjecture +##rac +401 +hating +sixties +kicker +moaning +motown +##bha +emancipation +neoclassical +##hering +consoles +ebert +professorship +##tures +sustaining +assaults +obeyed +affluent +incurred +tornadoes +##eber +##zow +emphasizing +highlanders +cheated +helmets +##ctus +internship +terence +bony +executions +legislators +berries +peninsular +tinged +##aco +1689 +amplifier +corvette +ribbons +lavish +pennant +##lander +worthless +##chfield +##forms +mariano +pyrenees +expenditures +##icides +chesterfield +mandir +tailor +39th +sergey +nestled +willed +aristocracy +devotees +goodnight +raaf +rumored +weaponry +remy +appropriations +harcourt +burr +riaa +##lence +limitation +unnoticed +guo +soaking +swamps +##tica +collapsing +tatiana +descriptive +brigham +psalm +##chment +maddox +##lization +patti +caliph +##aja +akron +injuring +serra +##ganj +basins +##sari +astonished +launcher +##church +hilary +wilkins +sewing +##sf +stinging +##fia +##ncia +underwood +startup +##ition +compilations +vibrations +embankment +jurist +##nity +bard +juventus +groundwater +kern +palaces +helium +boca +cramped +marissa +soto +##worm +jae +princely +##ggy +faso +bazaar +warmly +##voking +229 +pairing +##lite +##grate +##nets +wien +freaked +ulysses +rebirth +##alia +##rent +mummy +guzman +jimenez +stilled +##nitz +trajectory +tha +woken +archival +professions +##pts +##pta +hilly +shadowy +shrink +##bolt +norwood +glued +migrate +stereotypes +devoid +##pheus +625 +evacuate +horrors +infancy +gotham +knowles +optic +downloaded +sachs +kingsley +parramatta +darryl +mor +##onale +shady +commence +confesses +kan +##meter +##placed +marlborough +roundabout +regents +frigates +io +##imating +gothenburg +revoked +carvings +clockwise +convertible +intruder +##sche +banged +##ogo +vicky +bourgeois +##mony +dupont +footing +##gum +pd +##real +buckle +yun +penthouse +sane +720 +serviced +stakeholders +neumann +bb +##eers +comb +##gam +catchment +pinning +rallies +typing +##elles +forefront +freiburg +sweetie +giacomo +widowed +goodwill +worshipped +aspirations +midday +##vat +fishery +##trick +bournemouth +turk +243 +hearth +ethanol +guadalajara +murmurs +sl +##uge +afforded +scripted +##hta +wah +##jn +coroner +translucent +252 +memorials +puck +progresses +clumsy +##race +315 +candace +recounted +##27 +##slin +##uve +filtering +##mac +howl +strata +heron +leveled +##ays +dubious +##oja +##т +##wheel +citations +exhibiting +##laya +##mics +##pods +turkic +##lberg +injunction +##ennial +##mit +antibodies +##44 +organise +##rigues +cardiovascular +cushion +inverness +##zquez +dia +cocoa +sibling +##tman +##roid +expanse +feasible +tunisian +algiers +##relli +rus +bloomberg +dso +westphalia +bro +tacoma +281 +downloads +##ours +konrad +duran +##hdi +continuum +jett +compares +legislator +secession +##nable +##gues +##zuka +translating +reacher +##gley +##ła +aleppo +##agi +tc +orchards +trapping +linguist +versatile +drumming +postage +calhoun +superiors +##mx +barefoot +leary +##cis +ignacio +alfa +kaplan +##rogen +bratislava +mori +##vot +disturb +haas +313 +cartridges +gilmore +radiated +salford +tunic +hades +##ulsive +archeological +delilah +magistrates +auditioned +brewster +charters +empowerment +blogs +cappella +dynasties +iroquois +whipping +##krishna +raceway +truths +myra +weaken +judah +mcgregor +##horse +mic +refueling +37th +burnley +bosses +markus +premio +query +##gga +dunbar +##economic +darkest +lyndon +sealing +commendation +reappeared +##mun +addicted +ezio +slaughtered +satisfactory +shuffle +##eves +##thic +##uj +fortification +warrington +##otto +resurrected +fargo +mane +##utable +##lei +##space +foreword +ox +##aris +##vern +abrams +hua +##mento +sakura +##alo +uv +sentimental +##skaya +midfield +##eses +sturdy +scrolls +macleod +##kyu +entropy +##lance +mitochondrial +cicero +excelled +thinner +convoys +perceive +##oslav +##urable +systematically +grind +burkina +287 +##tagram +ops +##aman +guantanamo +##cloth +##tite +forcefully +wavy +##jou +pointless +##linger +##tze +layton +portico +superficial +clerical +outlaws +##hism +burials +muir +##inn +creditors +hauling +rattle +##leg +calais +monde +archers +reclaimed +dwell +wexford +hellenic +falsely +remorse +##tek +dough +furnishings +##uttered +gabon +neurological +novice +##igraphy +contemplated +pulpit +nightstand +saratoga +##istan +documenting +pulsing +taluk +##firmed +busted +marital +##rien +disagreements +wasps +##yes +hodge +mcdonnell +mimic +fran +pendant +dhabi +musa +##nington +congratulations +argent +darrell +concussion +losers +regrets +thessaloniki +reversal +donaldson +hardwood +thence +achilles +ritter +##eran +demonic +jurgen +prophets +goethe +eki +classmate +buff +##cking +yank +irrational +##inging +perished +seductive +qur +sourced +##crat +##typic +mustard +ravine +barre +horizontally +characterization +phylogenetic +boise +##dit +##runner +##tower +brutally +intercourse +seduce +##bbing +fay +ferris +ogden +amar +nik +unarmed +##inator +evaluating +kyrgyzstan +sweetness +##lford +##oki +mccormick +meiji +notoriety +stimulate +disrupt +figuring +instructional +mcgrath +##zoo +groundbreaking +##lto +flinch +khorasan +agrarian +bengals +mixer +radiating +##sov +ingram +pitchers +nad +tariff +##cript +tata +##codes +##emi +##ungen +appellate +lehigh +##bled +##giri +brawl +duct +texans +##ciation +##ropolis +skipper +speculative +vomit +doctrines +stresses +253 +davy +graders +whitehead +jozef +timely +cumulative +haryana +paints +appropriately +boon +cactus +##ales +##pid +dow +legions +##pit +perceptions +1730 +picturesque +##yse +periphery +rune +wr +##aha +celtics +sentencing +whoa +##erin +confirms +variance +425 +moines +mathews +spade +rave +m1 +fronted +fx +blending +alleging +reared +##gl +237 +##paper +grassroots +eroded +##free +##physical +directs +ordeal +##sław +accelerate +hacker +rooftop +##inia +lev +buys +cebu +devote +##lce +specialising +##ulsion +choreographed +repetition +warehouses +##ryl +paisley +tuscany +analogy +sorcerer +hash +huts +shards +descends +exclude +nix +chaplin +gaga +ito +vane +##drich +causeway +misconduct +limo +orchestrated +glands +jana +##kot +u2 +##mple +##sons +branching +contrasts +scoop +longed +##virus +chattanooga +##75 +syrup +cornerstone +##tized +##mind +##iaceae +careless +precedence +frescoes +##uet +chilled +consult +modelled +snatch +peat +##thermal +caucasian +humane +relaxation +spins +temperance +##lbert +occupations +lambda +hybrids +moons +mp3 +##oese +247 +rolf +societal +yerevan +ness +##ssler +befriended +mechanized +nominate +trough +boasted +cues +seater +##hom +bends +##tangle +conductors +emptiness +##lmer +eurasian +adriatic +tian +##cie +anxiously +lark +propellers +chichester +jock +ev +2a +##holding +credible +recounts +tori +loyalist +abduction +##hoot +##redo +nepali +##mite +ventral +tempting +##ango +##crats +steered +##wice +javelin +dipping +laborers +prentice +looming +titanium +##ː +badges +emir +tensor +##ntation +egyptians +rash +denies +hawthorne +lombard +showers +wehrmacht +dietary +trojan +##reus +welles +executing +horseshoe +lifeboat +##lak +elsa +infirmary +nearing +roberta +boyer +mutter +trillion +joanne +##fine +##oked +sinks +vortex +uruguayan +clasp +sirius +##block +accelerator +prohibit +sunken +byu +chronological +diplomats +ochreous +510 +symmetrical +1644 +maia +##tology +salts +reigns +atrocities +##ия +hess +bared +issn +##vyn +cater +saturated +##cycle +##isse +sable +voyager +dyer +yusuf +##inge +fountains +wolff +##39 +##nni +engraving +rollins +atheist +ominous +##ault +herr +chariot +martina +strung +##fell +##farlane +horrific +sahib +gazes +saetan +erased +ptolemy +##olic +flushing +lauderdale +analytic +##ices +530 +navarro +beak +gorilla +herrera +broom +guadalupe +raiding +sykes +311 +bsc +deliveries +1720 +invasions +carmichael +tajikistan +thematic +ecumenical +sentiments +onstage +##rians +##brand +##sume +catastrophic +flanks +molten +##arns +waller +aimee +terminating +##icing +alternately +##oche +nehru +printers +outraged +##eving +empires +template +banners +repetitive +za +##oise +vegetarian +##tell +guiana +opt +cavendish +lucknow +synthesized +##hani +##mada +finalized +##ctable +fictitious +mayoral +unreliable +##enham +embracing +peppers +rbis +##chio +##neo +inhibition +slashed +togo +orderly +embroidered +safari +salty +236 +barron +benito +totaled +##dak +pubs +simulated +caden +devin +tolkien +momma +welding +sesame +##ept +gottingen +hardness +630 +shaman +temeraire +620 +adequately +pediatric +##kit +ck +assertion +radicals +composure +cadence +seafood +beaufort +lazarus +mani +warily +cunning +kurdistan +249 +cantata +##kir +ares +##41 +##clusive +nape +townland +geared +insulted +flutter +boating +violate +draper +dumping +malmo +##hh +##romatic +firearm +alta +bono +obscured +##clave +exceeds +panorama +unbelievable +##train +preschool +##essed +disconnected +installing +rescuing +secretaries +accessibility +##castle +##drive +##ifice +##film +bouts +slug +waterway +mindanao +##buro +##ratic +halves +##ل +calming +liter +maternity +adorable +bragg +electrification +mcc +##dote +roxy +schizophrenia +##body +munoz +kaye +whaling +239 +mil +tingling +tolerant +##ago +unconventional +volcanoes +##finder +deportivo +##llie +robson +kaufman +neuroscience +wai +deportation +masovian +scraping +converse +##bh +hacking +bulge +##oun +administratively +yao +580 +amp +mammoth +booster +claremont +hooper +nomenclature +pursuits +mclaughlin +melinda +##sul +catfish +barclay +substrates +taxa +zee +originals +kimberly +packets +padma +##ality +borrowing +ostensibly +solvent +##bri +##genesis +##mist +lukas +shreveport +veracruz +##ь +##lou +##wives +cheney +tt +anatolia +hobbs +##zyn +cyclic +radiant +alistair +greenish +siena +dat +independents +##bation +conform +pieter +hyper +applicant +bradshaw +spores +telangana +vinci +inexpensive +nuclei +322 +jang +nme +soho +spd +##ign +cradled +receptionist +pow +##43 +##rika +fascism +##ifer +experimenting +##ading +##iec +##region +345 +jocelyn +maris +stair +nocturnal +toro +constabulary +elgin +##kker +msc +##giving +##schen +##rase +doherty +doping +sarcastically +batter +maneuvers +##cano +##apple +##gai +##git +intrinsic +##nst +##stor +1753 +showtime +cafes +gasps +lviv +ushered +##thed +fours +restart +astonishment +transmitting +flyer +shrugs +##sau +intriguing +cones +dictated +mushrooms +medial +##kovsky +##elman +escorting +gaped +##26 +godfather +##door +##sell +djs +recaptured +timetable +vila +1710 +3a +aerodrome +mortals +scientology +##orne +angelina +mag +convection +unpaid +insertion +intermittent +lego +##nated +endeavor +kota +pereira +##lz +304 +bwv +glamorgan +insults +agatha +fey +##cend +fleetwood +mahogany +protruding +steamship +zeta +##arty +mcguire +suspense +##sphere +advising +urges +##wala +hurriedly +meteor +gilded +inline +arroyo +stalker +##oge +excitedly +revered +##cure +earle +introductory +##break +##ilde +mutants +puff +pulses +reinforcement +##haling +curses +lizards +stalk +correlated +##fixed +fallout +macquarie +##unas +bearded +denton +heaving +802 +##ocation +winery +assign +dortmund +##lkirk +everest +invariant +charismatic +susie +##elling +bled +lesley +telegram +sumner +bk +##ogen +##к +wilcox +needy +colbert +duval +##iferous +##mbled +allotted +attends +imperative +##hita +replacements +hawker +##inda +insurgency +##zee +##eke +casts +##yla +680 +ives +transitioned +##pack +##powering +authoritative +baylor +flex +cringed +plaintiffs +woodrow +##skie +drastic +ape +aroma +unfolded +commotion +nt +preoccupied +theta +routines +lasers +privatization +wand +domino +ek +clenching +nsa +strategically +showered +bile +handkerchief +pere +storing +christophe +insulting +316 +nakamura +romani +asiatic +magdalena +palma +cruises +stripping +405 +konstantin +soaring +##berman +colloquially +forerunner +havilland +incarcerated +parasites +sincerity +##utus +disks +plank +saigon +##ining +corbin +homo +ornaments +powerhouse +##tlement +chong +fastened +feasibility +idf +morphological +usable +##nish +##zuki +aqueduct +jaguars +keepers +##flies +aleksandr +faust +assigns +ewing +bacterium +hurled +tricky +hungarians +integers +wallis +321 +yamaha +##isha +hushed +oblivion +aviator +evangelist +friars +##eller +monograph +ode +##nary +airplanes +labourers +charms +##nee +1661 +hagen +tnt +rudder +fiesta +transcript +dorothea +ska +inhibitor +maccabi +retorted +raining +encompassed +clauses +menacing +1642 +lineman +##gist +vamps +##ape +##dick +gloom +##rera +dealings +easing +seekers +##nut +##pment +helens +unmanned +##anu +##isson +basics +##amy +##ckman +adjustments +1688 +brutality +horne +##zell +sui +##55 +##mable +aggregator +##thal +rhino +##drick +##vira +counters +zoom +##01 +##rting +mn +montenegrin +packard +##unciation +##♭ +##kki +reclaim +scholastic +thugs +pulsed +##icia +syriac +quan +saddam +banda +kobe +blaming +buddies +dissent +##lusion +##usia +corbett +jaya +delle +erratic +lexie +##hesis +435 +amiga +hermes +##pressing +##leen +chapels +gospels +jamal +##uating +compute +revolving +warp +##sso +##thes +armory +##eras +##gol +antrim +loki +##kow +##asian +##good +##zano +braid +handwriting +subdistrict +funky +pantheon +##iculate +concurrency +estimation +improper +juliana +##his +newcomers +johnstone +staten +communicated +##oco +##alle +sausage +stormy +##stered +##tters +superfamily +##grade +acidic +collateral +tabloid +##oped +##rza +bladder +austen +##ellant +mcgraw +##hay +hannibal +mein +aquino +lucifer +wo +badger +boar +cher +christensen +greenberg +interruption +##kken +jem +244 +mocked +bottoms +cambridgeshire +##lide +sprawling +##bbly +eastwood +ghent +synth +##buck +advisers +##bah +nominally +hapoel +qu +daggers +estranged +fabricated +towels +vinnie +wcw +misunderstanding +anglia +nothin +unmistakable +##dust +##lova +chilly +marquette +truss +##edge +##erine +reece +##lty +##chemist +##connected +272 +308 +41st +bash +raion +waterfalls +##ump +##main +labyrinth +queue +theorist +##istle +bharatiya +flexed +soundtracks +rooney +leftist +patrolling +wharton +plainly +alleviate +eastman +schuster +topographic +engages +immensely +unbearable +fairchild +1620 +dona +lurking +parisian +oliveira +ia +indictment +hahn +bangladeshi +##aster +vivo +##uming +##ential +antonia +expects +indoors +kildare +harlan +##logue +##ogenic +##sities +forgiven +##wat +childish +tavi +##mide +##orra +plausible +grimm +successively +scooted +##bola +##dget +##rith +spartans +emery +flatly +azure +epilogue +##wark +flourish +##iny +##tracted +##overs +##oshi +bestseller +distressed +receipt +spitting +hermit +topological +##cot +drilled +subunit +francs +##layer +eel +##fk +##itas +octopus +footprint +petitions +ufo +##say +##foil +interfering +leaking +palo +##metry +thistle +valiant +##pic +narayan +mcpherson +##fast +gonzales +##ym +##enne +dustin +novgorod +solos +##zman +doin +##raph +##patient +##meyer +soluble +ashland +cuffs +carole +pendleton +whistling +vassal +##river +deviation +revisited +constituents +rallied +rotate +loomed +##eil +##nting +amateurs +augsburg +auschwitz +crowns +skeletons +##cona +bonnet +257 +dummy +globalization +simeon +sleeper +mandal +differentiated +##crow +##mare +milne +bundled +exasperated +talmud +owes +segregated +##feng +##uary +dentist +piracy +props +##rang +devlin +##torium +malicious +paws +##laid +dependency +##ergy +##fers +##enna +258 +pistons +rourke +jed +grammatical +tres +maha +wig +512 +ghostly +jayne +##achal +##creen +##ilis +##lins +##rence +designate +##with +arrogance +cambodian +clones +showdown +throttle +twain +##ception +lobes +metz +nagoya +335 +braking +##furt +385 +roaming +##minster +amin +crippled +##37 +##llary +indifferent +hoffmann +idols +intimidating +1751 +261 +influenza +memo +onions +1748 +bandage +consciously +##landa +##rage +clandestine +observes +swiped +tangle +##ener +##jected +##trum +##bill +##lta +hugs +congresses +josiah +spirited +##dek +humanist +managerial +filmmaking +inmate +rhymes +debuting +grimsby +ur +##laze +duplicate +vigor +##tf +republished +bolshevik +refurbishment +antibiotics +martini +methane +newscasts +royale +horizons +levant +iain +visas +##ischen +paler +##around +manifestation +snuck +alf +chop +futile +pedestal +rehab +##kat +bmg +kerman +res +fairbanks +jarrett +abstraction +saharan +##zek +1746 +procedural +clearer +kincaid +sash +luciano +##ffey +crunch +helmut +##vara +revolutionaries +##tute +creamy +leach +##mmon +1747 +permitting +nes +plight +wendell +##lese +contra +ts +clancy +ipa +mach +staples +autopsy +disturbances +nueva +karin +pontiac +##uding +proxy +venerable +haunt +leto +bergman +expands +##helm +wal +##pipe +canning +celine +cords +obesity +##enary +intrusion +planner +##phate +reasoned +sequencing +307 +harrow +##chon +##dora +marred +mcintyre +repay +tarzan +darting +248 +harrisburg +margarita +repulsed +##hur +##lding +belinda +hamburger +novo +compliant +runways +bingham +registrar +skyscraper +ic +cuthbert +improvisation +livelihood +##corp +##elial +admiring +##dened +sporadic +believer +casablanca +popcorn +##29 +asha +shovel +##bek +##dice +coiled +tangible +##dez +casper +elsie +resin +tenderness +rectory +##ivision +avail +sonar +##mori +boutique +##dier +guerre +bathed +upbringing +vaulted +sandals +blessings +##naut +##utnant +1680 +306 +foxes +pia +corrosion +hesitantly +confederates +crystalline +footprints +shapiro +tirana +valentin +drones +45th +microscope +shipments +texted +inquisition +wry +guernsey +unauthorized +resigning +760 +ripple +schubert +stu +reassure +felony +##ardo +brittle +koreans +##havan +##ives +dun +implicit +tyres +##aldi +##lth +magnolia +##ehan +##puri +##poulos +aggressively +fei +gr +familiarity +##poo +indicative +##trust +fundamentally +jimmie +overrun +395 +anchors +moans +##opus +britannia +armagh +##ggle +purposely +seizing +##vao +bewildered +mundane +avoidance +cosmopolitan +geometridae +quartermaster +caf +415 +chatter +engulfed +gleam +purge +##icate +juliette +jurisprudence +guerra +revisions +##bn +casimir +brew +##jm +1749 +clapton +cloudy +conde +hermitage +278 +simulations +torches +vincenzo +matteo +##rill +hidalgo +booming +westbound +accomplishment +tentacles +unaffected +##sius +annabelle +flopped +sloping +##litz +dreamer +interceptor +vu +##loh +consecration +copying +messaging +breaker +climates +hospitalized +1752 +torino +afternoons +winfield +witnessing +##teacher +breakers +choirs +sawmill +coldly +##ege +sipping +haste +uninhabited +conical +bibliography +pamphlets +severn +edict +##oca +deux +illnesses +grips +##pl +rehearsals +sis +thinkers +tame +##keepers +1690 +acacia +reformer +##osed +##rys +shuffling +##iring +##shima +eastbound +ionic +rhea +flees +littered +##oum +rocker +vomiting +groaning +champ +overwhelmingly +civilizations +paces +sloop +adoptive +##tish +skaters +##vres +aiding +mango +##joy +nikola +shriek +##ignon +pharmaceuticals +##mg +tuna +calvert +gustavo +stocked +yearbook +##urai +##mana +computed +subsp +riff +hanoi +kelvin +hamid +moors +pastures +summons +jihad +nectar +##ctors +bayou +untitled +pleasing +vastly +republics +intellect +##η +##ulio +##tou +crumbling +stylistic +sb +##ی +consolation +frequented +h₂o +walden +widows +##iens +404 +##ignment +chunks +improves +288 +grit +recited +##dev +snarl +sociological +##arte +##gul +inquired +##held +bruise +clube +consultancy +homogeneous +hornets +multiplication +pasta +prick +savior +##grin +##kou +##phile +yoon +##gara +grimes +vanishing +cheering +reacting +bn +distillery +##quisite +##vity +coe +dockyard +massif +##jord +escorts +voss +##valent +byte +chopped +hawke +illusions +workings +floats +##koto +##vac +kv +annapolis +madden +##onus +alvaro +noctuidae +##cum +##scopic +avenge +steamboat +forte +illustrates +erika +##trip +570 +dew +nationalities +bran +manifested +thirsty +diversified +muscled +reborn +##standing +arson +##lessness +##dran +##logram +##boys +##kushima +##vious +willoughby +##phobia +286 +alsace +dashboard +yuki +##chai +granville +myspace +publicized +tricked +##gang +adjective +##ater +relic +reorganisation +enthusiastically +indications +saxe +##lassified +consolidate +iec +padua +helplessly +ramps +renaming +regulars +pedestrians +accents +convicts +inaccurate +lowers +mana +##pati +barrie +bjp +outta +someplace +berwick +flanking +invoked +marrow +sparsely +excerpts +clothed +rei +##ginal +wept +##straße +##vish +alexa +excel +##ptive +membranes +aquitaine +creeks +cutler +sheppard +implementations +ns +##dur +fragrance +budge +concordia +magnesium +marcelo +##antes +gladly +vibrating +##rral +##ggles +montrose +##omba +lew +seamus +1630 +cocky +##ament +##uen +bjorn +##rrick +fielder +fluttering +##lase +methyl +kimberley +mcdowell +reductions +barbed +##jic +##tonic +aeronautical +condensed +distracting +##promising +huffed +##cala +##sle +claudius +invincible +missy +pious +balthazar +ci +##lang +butte +combo +orson +##dication +myriad +1707 +silenced +##fed +##rh +coco +netball +yourselves +##oza +clarify +heller +peg +durban +etudes +offender +roast +blackmail +curvature +##woods +vile +309 +illicit +suriname +##linson +overture +1685 +bubbling +gymnast +tucking +##mming +##ouin +maldives +##bala +gurney +##dda +##eased +##oides +backside +pinto +jars +racehorse +tending +##rdial +baronetcy +wiener +duly +##rke +barbarian +cupping +flawed +##thesis +bertha +pleistocene +puddle +swearing +##nob +##tically +fleeting +prostate +amulet +educating +##mined +##iti +##tler +75th +jens +respondents +analytics +cavaliers +papacy +raju +##iente +##ulum +##tip +funnel +271 +disneyland +##lley +sociologist +##iam +2500 +faulkner +louvre +menon +##dson +276 +##ower +afterlife +mannheim +peptide +referees +comedians +meaningless +##anger +##laise +fabrics +hurley +renal +sleeps +##bour +##icle +breakout +kristin +roadside +animator +clover +disdain +unsafe +redesign +##urity +firth +barnsley +portage +reset +narrows +268 +commandos +expansive +speechless +tubular +##lux +essendon +eyelashes +smashwords +##yad +##bang +##claim +craved +sprinted +chet +somme +astor +wrocław +orton +266 +bane +##erving +##uing +mischief +##amps +##sund +scaling +terre +##xious +impairment +offenses +undermine +moi +soy +contiguous +arcadia +inuit +seam +##tops +macbeth +rebelled +##icative +##iot +590 +elaborated +frs +uniformed +##dberg +259 +powerless +priscilla +stimulated +980 +qc +arboretum +frustrating +trieste +bullock +##nified +enriched +glistening +intern +##adia +locus +nouvelle +ollie +ike +lash +starboard +ee +tapestry +headlined +hove +rigged +##vite +pollock +##yme +thrive +clustered +cas +roi +gleamed +olympiad +##lino +pressured +regimes +##hosis +##lick +ripley +##ophone +kickoff +gallon +rockwell +##arable +crusader +glue +revolutions +scrambling +1714 +grover +##jure +englishman +aztec +263 +contemplating +coven +ipad +preach +triumphant +tufts +##esian +rotational +##phus +328 +falkland +##brates +strewn +clarissa +rejoin +environmentally +glint +banded +drenched +moat +albanians +johor +rr +maestro +malley +nouveau +shaded +taxonomy +v6 +adhere +bunk +airfields +##ritan +1741 +encompass +remington +tran +##erative +amelie +mazda +friar +morals +passions +##zai +breadth +vis +##hae +argus +burnham +caressing +insider +rudd +##imov +##mini +##rso +italianate +murderous +textual +wainwright +armada +bam +weave +timer +##taken +##nh +fra +##crest +ardent +salazar +taps +tunis +##ntino +allegro +gland +philanthropic +##chester +implication +##optera +esq +judas +noticeably +wynn +##dara +inched +indexed +crises +villiers +bandit +royalties +patterned +cupboard +interspersed +accessory +isla +kendrick +entourage +stitches +##esthesia +headwaters +##ior +interlude +distraught +draught +1727 +##basket +biased +sy +transient +triad +subgenus +adapting +kidd +shortstop +##umatic +dimly +spiked +mcleod +reprint +nellie +pretoria +windmill +##cek +singled +##mps +273 +reunite +##orous +747 +bankers +outlying +##omp +##ports +##tream +apologies +cosmetics +patsy +##deh +##ocks +##yson +bender +nantes +serene +##nad +lucha +mmm +323 +##cius +##gli +cmll +coinage +nestor +juarez +##rook +smeared +sprayed +twitching +sterile +irina +embodied +juveniles +enveloped +miscellaneous +cancers +dq +gulped +luisa +crested +swat +donegal +ref +##anov +##acker +hearst +mercantile +##lika +doorbell +ua +vicki +##alla +##som +bilbao +psychologists +stryker +sw +horsemen +turkmenistan +wits +##national +anson +mathew +screenings +##umb +rihanna +##agne +##nessy +aisles +##iani +##osphere +hines +kenton +saskatoon +tasha +truncated +##champ +##itan +mildred +advises +fredrik +interpreting +inhibitors +##athi +spectroscopy +##hab +##kong +karim +panda +##oia +##nail +##vc +conqueror +kgb +leukemia +##dity +arrivals +cheered +pisa +phosphorus +shielded +##riated +mammal +unitarian +urgently +chopin +sanitary +##mission +spicy +drugged +hinges +##tort +tipping +trier +impoverished +westchester +##caster +267 +epoch +nonstop +##gman +##khov +aromatic +centrally +cerro +##tively +##vio +billions +modulation +sedimentary +283 +facilitating +outrageous +goldstein +##eak +##kt +ld +maitland +penultimate +pollard +##dance +fleets +spaceship +vertebrae +##nig +alcoholism +als +recital +##bham +##ference +##omics +m2 +##bm +trois +##tropical +##в +commemorates +##meric +marge +##raction +1643 +670 +cosmetic +ravaged +##ige +catastrophe +eng +##shida +albrecht +arterial +bellamy +decor +harmon +##rde +bulbs +synchronized +vito +easiest +shetland +shielding +wnba +##glers +##ssar +##riam +brianna +cumbria +##aceous +##rard +cores +thayer +##nsk +brood +hilltop +luminous +carts +keynote +larkin +logos +##cta +##ا +##mund +##quay +lilith +tinted +277 +wrestle +mobilization +##uses +sequential +siam +bloomfield +takahashi +274 +##ieving +presenters +ringo +blazed +witty +##oven +##ignant +devastation +haydn +harmed +newt +therese +##peed +gershwin +molina +rabbis +sudanese +001 +innate +restarted +##sack +##fus +slices +wb +##shah +enroll +hypothetical +hysterical +1743 +fabio +indefinite +warped +##hg +exchanging +525 +unsuitable +##sboro +gallo +1603 +bret +cobalt +homemade +##hunter +mx +operatives +##dhar +terraces +durable +latch +pens +whorls +##ctuated +##eaux +billing +ligament +succumbed +##gly +regulators +spawn +##brick +##stead +filmfare +rochelle +##nzo +1725 +circumstance +saber +supplements +##nsky +##tson +crowe +wellesley +carrot +##9th +##movable +primate +drury +sincerely +topical +##mad +##rao +callahan +kyiv +smarter +tits +undo +##yeh +announcements +anthologies +barrio +nebula +##islaus +##shaft +##tyn +bodyguards +2021 +assassinate +barns +emmett +scully +##mah +##yd +##eland +##tino +##itarian +demoted +gorman +lashed +prized +adventist +writ +##gui +alla +invertebrates +##ausen +1641 +amman +1742 +align +healy +redistribution +##gf +##rize +insulation +##drop +adherents +hezbollah +vitro +ferns +yanking +269 +php +registering +uppsala +cheerleading +confines +mischievous +tully +##ross +49th +docked +roam +stipulated +pumpkin +##bry +prompt +##ezer +blindly +shuddering +craftsmen +frail +scented +katharine +scramble +shaggy +sponge +helix +zaragoza +279 +##52 +43rd +backlash +fontaine +seizures +posse +cowan +nonfiction +telenovela +wwii +hammered +undone +##gpur +encircled +irs +##ivation +artefacts +oneself +searing +smallpox +##belle +##osaurus +shandong +breached +upland +blushing +rankin +infinitely +psyche +tolerated +docking +evicted +##col +unmarked +##lving +gnome +lettering +litres +musique +##oint +benevolent +##jal +blackened +##anna +mccall +racers +tingle +##ocene +##orestation +introductions +radically +292 +##hiff +##باد +1610 +1739 +munchen +plead +##nka +condo +scissors +##sight +##tens +apprehension +##cey +##yin +hallmark +watering +formulas +sequels +##llas +aggravated +bae +commencing +##building +enfield +prohibits +marne +vedic +civilized +euclidean +jagger +beforehand +blasts +dumont +##arney +##nem +740 +conversions +hierarchical +rios +simulator +##dya +##lellan +hedges +oleg +thrusts +shadowed +darby +maximize +1744 +gregorian +##nded +##routed +sham +unspecified +##hog +emory +factual +##smo +##tp +fooled +##rger +ortega +wellness +marlon +##oton +##urance +casket +keating +ley +enclave +##ayan +char +influencing +jia +##chenko +412 +ammonia +erebidae +incompatible +violins +cornered +##arat +grooves +astronauts +columbian +rampant +fabrication +kyushu +mahmud +vanish +##dern +mesopotamia +##lete +ict +##rgen +caspian +kenji +pitted +##vered +999 +grimace +roanoke +tchaikovsky +twinned +##analysis +##awan +xinjiang +arias +clemson +kazakh +sizable +1662 +##khand +##vard +plunge +tatum +vittorio +##nden +cholera +##dana +##oper +bracing +indifference +projectile +superliga +##chee +realises +upgrading +299 +porte +retribution +##vies +nk +stil +##resses +ama +bureaucracy +blackberry +bosch +testosterone +collapses +greer +##pathic +ioc +fifties +malls +##erved +bao +baskets +adolescents +siegfried +##osity +##tosis +mantra +detecting +existent +fledgling +##cchi +dissatisfied +gan +telecommunication +mingled +sobbed +6000 +controversies +outdated +taxis +##raus +fright +slams +##lham +##fect +##tten +detectors +fetal +tanned +##uw +fray +goth +olympian +skipping +mandates +scratches +sheng +unspoken +hyundai +tracey +hotspur +restrictive +##buch +americana +mundo +##bari +burroughs +diva +vulcan +##6th +distinctions +thumping +##ngen +mikey +sheds +fide +rescues +springsteen +vested +valuation +##ece +##ely +pinnacle +rake +sylvie +##edo +almond +quivering +##irus +alteration +faltered +##wad +51st +hydra +ticked +##kato +recommends +##dicated +antigua +arjun +stagecoach +wilfred +trickle +pronouns +##pon +aryan +nighttime +##anian +gall +pea +stitch +##hei +leung +milos +##dini +eritrea +nexus +starved +snowfall +kant +parasitic +cot +discus +hana +strikers +appleton +kitchens +##erina +##partisan +##itha +##vius +disclose +metis +##channel +1701 +tesla +##vera +fitch +1735 +blooded +##tila +decimal +##tang +##bai +cyclones +eun +bottled +peas +pensacola +basha +bolivian +crabs +boil +lanterns +partridge +roofed +1645 +necks +##phila +opined +patting +##kla +##lland +chuckles +volta +whereupon +##nche +devout +euroleague +suicidal +##dee +inherently +involuntary +knitting +nasser +##hide +puppets +colourful +courageous +southend +stills +miraculous +hodgson +richer +rochdale +ethernet +greta +uniting +prism +umm +##haya +##itical +##utation +deterioration +pointe +prowess +##ropriation +lids +scranton +billings +subcontinent +##koff +##scope +brute +kellogg +psalms +degraded +##vez +stanisław +##ructured +ferreira +pun +astonishing +gunnar +##yat +arya +prc +gottfried +##tight +excursion +##ographer +dina +##quil +##nare +huffington +illustrious +wilbur +gundam +verandah +##zard +naacp +##odle +constructive +fjord +kade +##naud +generosity +thrilling +baseline +cayman +frankish +plastics +accommodations +zoological +##fting +cedric +qb +motorized +##dome +##otted +squealed +tackled +canucks +budgets +situ +asthma +dail +gabled +grasslands +whimpered +writhing +judgments +##65 +minnie +pv +##carbon +bananas +grille +domes +monique +odin +maguire +markham +tierney +##estra +##chua +libel +poke +speedy +atrium +laval +notwithstanding +##edly +fai +kala +##sur +robb +##sma +listings +luz +supplementary +tianjin +##acing +enzo +jd +ric +scanner +croats +transcribed +##49 +arden +cv +##hair +##raphy +##lver +##uy +357 +seventies +staggering +alam +horticultural +hs +regression +timbers +blasting +##ounded +montagu +manipulating +##cit +catalytic +1550 +troopers +##meo +condemnation +fitzpatrick +##oire +##roved +inexperienced +1670 +castes +##lative +outing +314 +dubois +flicking +quarrel +ste +learners +1625 +iq +whistled +##class +282 +classify +tariffs +temperament +355 +folly +liszt +##yles +immersed +jordanian +ceasefire +apparel +extras +maru +fished +##bio +harta +stockport +assortment +craftsman +paralysis +transmitters +##cola +blindness +##wk +fatally +proficiency +solemnly +##orno +repairing +amore +groceries +ultraviolet +##chase +schoolhouse +##tua +resurgence +nailed +##otype +##× +ruse +saliva +diagrams +##tructing +albans +rann +thirties +1b +antennas +hilarious +cougars +paddington +stats +##eger +breakaway +ipod +reza +authorship +prohibiting +scoffed +##etz +##ttle +conscription +defected +trondheim +##fires +ivanov +keenan +##adan +##ciful +##fb +##slow +locating +##ials +##tford +cadiz +basalt +blankly +interned +rags +rattling +##tick +carpathian +reassured +sync +bum +guildford +iss +staunch +##onga +astronomers +sera +sofie +emergencies +susquehanna +##heard +duc +mastery +vh1 +williamsburg +bayer +buckled +craving +##khan +##rdes +bloomington +##write +alton +barbecue +##bians +justine +##hri +##ndt +delightful +smartphone +newtown +photon +retrieval +peugeot +hissing +##monium +##orough +flavors +lighted +relaunched +tainted +##games +##lysis +anarchy +microscopic +hopping +adept +evade +evie +##beau +inhibit +sinn +adjustable +hurst +intuition +wilton +cisco +44th +lawful +lowlands +stockings +thierry +##dalen +##hila +##nai +fates +prank +tb +maison +lobbied +provocative +1724 +4a +utopia +##qual +carbonate +gujarati +purcell +##rford +curtiss +##mei +overgrown +arenas +mediation +swallows +##rnik +respectful +turnbull +##hedron +##hope +alyssa +ozone +##ʻi +ami +gestapo +johansson +snooker +canteen +cuff +declines +empathy +stigma +##ags +##iner +##raine +taxpayers +gui +volga +##wright +##copic +lifespan +overcame +tattooed +enactment +giggles +##ador +##camp +barrington +bribe +obligatory +orbiting +peng +##enas +elusive +sucker +##vating +cong +hardship +empowered +anticipating +estrada +cryptic +greasy +detainees +planck +sudbury +plaid +dod +marriott +kayla +##ears +##vb +##zd +mortally +##hein +cognition +radha +319 +liechtenstein +meade +richly +argyle +harpsichord +liberalism +trumpets +lauded +tyrant +salsa +tiled +lear +promoters +reused +slicing +trident +##chuk +##gami +##lka +cantor +checkpoint +##points +gaul +leger +mammalian +##tov +##aar +##schaft +doha +frenchman +nirvana +##vino +delgado +headlining +##eron +##iography +jug +tko +1649 +naga +intersections +##jia +benfica +nawab +##suka +ashford +gulp +##deck +##vill +##rug +brentford +frazier +pleasures +dunne +potsdam +shenzhen +dentistry +##tec +flanagan +##dorff +##hear +chorale +dinah +prem +quezon +##rogated +relinquished +sutra +terri +##pani +flaps +##rissa +poly +##rnet +homme +aback +##eki +linger +womb +##kson +##lewood +doorstep +orthodoxy +threaded +westfield +##rval +dioceses +fridays +subsided +##gata +loyalists +##biotic +##ettes +letterman +lunatic +prelate +tenderly +invariably +souza +thug +winslow +##otide +furlongs +gogh +jeopardy +##runa +pegasus +##umble +humiliated +standalone +tagged +##roller +freshmen +klan +##bright +attaining +initiating +transatlantic +logged +viz +##uance +1723 +combatants +intervening +stephane +chieftain +despised +grazed +317 +cdc +galveston +godzilla +macro +simulate +##planes +parades +##esses +960 +##ductive +##unes +equator +overdose +##cans +##hosh +##lifting +joshi +epstein +sonora +treacherous +aquatics +manchu +responsive +##sation +supervisory +##christ +##llins +##ibar +##balance +##uso +kimball +karlsruhe +mab +##emy +ignores +phonetic +reuters +spaghetti +820 +almighty +danzig +rumbling +tombstone +designations +lured +outset +##felt +supermarkets +##wt +grupo +kei +kraft +susanna +##blood +comprehension +genealogy +##aghan +##verted +redding +##ythe +1722 +bowing +##pore +##roi +lest +sharpened +fulbright +valkyrie +sikhs +##unds +swans +bouquet +merritt +##tage +##venting +commuted +redhead +clerks +leasing +cesare +dea +hazy +##vances +fledged +greenfield +servicemen +##gical +armando +blackout +dt +sagged +downloadable +intra +potion +pods +##4th +##mism +xp +attendants +gambia +stale +##ntine +plump +asteroids +rediscovered +buds +flea +hive +##neas +1737 +classifications +debuts +##eles +olympus +scala +##eurs +##gno +##mute +hummed +sigismund +visuals +wiggled +await +pilasters +clench +sulfate +##ances +bellevue +enigma +trainee +snort +##sw +clouded +denim +##rank +##rder +churning +hartman +lodges +riches +sima +##missible +accountable +socrates +regulates +mueller +##cr +1702 +avoids +solids +himalayas +nutrient +pup +##jevic +squat +fades +nec +##lates +##pina +##rona +##ου +privateer +tequila +##gative +##mpton +apt +hornet +immortals +##dou +asturias +cleansing +dario +##rries +##anta +etymology +servicing +zhejiang +##venor +##nx +horned +erasmus +rayon +relocating +£10 +##bags +escalated +promenade +stubble +2010s +artisans +axial +liquids +mora +sho +yoo +##tsky +bundles +oldies +##nally +notification +bastion +##ths +sparkle +##lved +1728 +leash +pathogen +highs +##hmi +immature +880 +gonzaga +ignatius +mansions +monterrey +sweets +bryson +##loe +polled +regatta +brightest +pei +rosy +squid +hatfield +payroll +addict +meath +cornerback +heaviest +lodging +##mage +capcom +rippled +##sily +barnet +mayhem +ymca +snuggled +rousseau +##cute +blanchard +284 +fragmented +leighton +chromosomes +risking +##md +##strel +##utter +corinne +coyotes +cynical +hiroshi +yeomanry +##ractive +ebook +grading +mandela +plume +agustin +magdalene +##rkin +bea +femme +trafford +##coll +##lun +##tance +52nd +fourier +upton +##mental +camilla +gust +iihf +islamabad +longevity +##kala +feldman +netting +##rization +endeavour +foraging +mfa +orr +##open +greyish +contradiction +graz +##ruff +handicapped +marlene +tweed +oaxaca +spp +campos +miocene +pri +configured +cooks +pluto +cozy +pornographic +##entes +70th +fairness +glided +jonny +lynne +rounding +sired +##emon +##nist +remade +uncover +##mack +complied +lei +newsweek +##jured +##parts +##enting +##pg +293 +finer +guerrillas +athenian +deng +disused +stepmother +accuse +gingerly +seduction +521 +confronting +##walker +##going +gora +nostalgia +sabres +virginity +wrenched +##minated +syndication +wielding +eyre +##56 +##gnon +##igny +behaved +taxpayer +sweeps +##growth +childless +gallant +##ywood +amplified +geraldine +scrape +##ffi +babylonian +fresco +##rdan +##kney +##position +1718 +restricting +tack +fukuoka +osborn +selector +partnering +##dlow +318 +gnu +kia +tak +whitley +gables +##54 +##mania +mri +softness +immersion +##bots +##evsky +1713 +chilling +insignificant +pcs +##uis +elites +lina +purported +supplemental +teaming +##americana +##dding +##inton +proficient +rouen +##nage +##rret +niccolo +selects +##bread +fluffy +1621 +gruff +knotted +mukherjee +polgara +thrash +nicholls +secluded +smoothing +thru +corsica +loaf +whitaker +inquiries +##rrier +##kam +indochina +289 +marlins +myles +peking +##tea +extracts +pastry +superhuman +connacht +vogel +##ditional +##het +##udged +##lash +gloss +quarries +refit +teaser +##alic +##gaon +20s +materialized +sling +camped +pickering +tung +tracker +pursuant +##cide +cranes +soc +##cini +##typical +##viere +anhalt +overboard +workout +chores +fares +orphaned +stains +##logie +fenton +surpassing +joyah +triggers +##itte +grandmaster +##lass +##lists +clapping +fraudulent +ledger +nagasaki +##cor +##nosis +##tsa +eucalyptus +tun +##icio +##rney +##tara +dax +heroism +ina +wrexham +onboard +unsigned +##dates +moshe +galley +winnie +droplets +exiles +praises +watered +noodles +##aia +fein +adi +leland +multicultural +stink +bingo +comets +erskine +modernized +canned +constraint +domestically +chemotherapy +featherweight +stifled +##mum +darkly +irresistible +refreshing +hasty +isolate +##oys +kitchener +planners +##wehr +cages +yarn +implant +toulon +elects +childbirth +yue +##lind +##lone +cn +rightful +sportsman +junctions +remodeled +specifies +##rgh +291 +##oons +complimented +##urgent +lister +ot +##logic +bequeathed +cheekbones +fontana +gabby +##dial +amadeus +corrugated +maverick +resented +triangles +##hered +##usly +nazareth +tyrol +1675 +assent +poorer +sectional +aegean +##cous +296 +nylon +ghanaian +##egorical +##weig +cushions +forbid +fusiliers +obstruction +somerville +##scia +dime +earrings +elliptical +leyte +oder +polymers +timmy +atm +midtown +piloted +settles +continual +externally +mayfield +##uh +enrichment +henson +keane +persians +1733 +benji +braden +pep +324 +##efe +contenders +pepsi +valet +##isches +298 +##asse +##earing +goofy +stroll +##amen +authoritarian +occurrences +adversary +ahmedabad +tangent +toppled +dorchester +1672 +modernism +marxism +islamist +charlemagne +exponential +racks +unicode +brunette +mbc +pic +skirmish +##bund +##lad +##powered +##yst +hoisted +messina +shatter +##ctum +jedi +vantage +##music +##neil +clemens +mahmoud +corrupted +authentication +lowry +nils +##washed +omnibus +wounding +jillian +##itors +##opped +serialized +narcotics +handheld +##arm +##plicity +intersecting +stimulating +##onis +crate +fellowships +hemingway +casinos +climatic +fordham +copeland +drip +beatty +leaflets +robber +brothel +madeira +##hedral +sphinx +ultrasound +##vana +valor +forbade +leonid +villas +##aldo +duane +marquez +##cytes +disadvantaged +forearms +kawasaki +reacts +consular +lax +uncles +uphold +##hopper +concepcion +dorsey +lass +##izan +arching +passageway +1708 +researches +tia +internationals +##graphs +##opers +distinguishes +javanese +divert +##uven +plotted +##listic +##rwin +##erik +##tify +affirmative +signifies +validation +##bson +kari +felicity +georgina +zulu +##eros +##rained +##rath +overcoming +##dot +argyll +##rbin +1734 +chiba +ratification +windy +earls +parapet +##marks +hunan +pristine +astrid +punta +##gart +brodie +##kota +##oder +malaga +minerva +rouse +##phonic +bellowed +pagoda +portals +reclamation +##gur +##odies +##⁄₄ +parentheses +quoting +allergic +palette +showcases +benefactor +heartland +nonlinear +##tness +bladed +cheerfully +scans +##ety +##hone +1666 +girlfriends +pedersen +hiram +sous +##liche +##nator +1683 +##nery +##orio +##umen +bobo +primaries +smiley +##cb +unearthed +uniformly +fis +metadata +1635 +ind +##oted +recoil +##titles +##tura +##ια +406 +hilbert +jamestown +mcmillan +tulane +seychelles +##frid +antics +coli +fated +stucco +##grants +1654 +bulky +accolades +arrays +caledonian +carnage +optimism +puebla +##tative +##cave +enforcing +rotherham +seo +dunlop +aeronautics +chimed +incline +zoning +archduke +hellenistic +##oses +##sions +candi +thong +##ople +magnate +rustic +##rsk +projective +slant +##offs +danes +hollis +vocalists +##ammed +congenital +contend +gesellschaft +##ocating +##pressive +douglass +quieter +##cm +##kshi +howled +salim +spontaneously +townsville +buena +southport +##bold +kato +1638 +faerie +stiffly +##vus +##rled +297 +flawless +realising +taboo +##7th +bytes +straightening +356 +jena +##hid +##rmin +cartwright +berber +bertram +soloists +411 +noses +417 +coping +fission +hardin +inca +##cen +1717 +mobilized +vhf +##raf +biscuits +curate +##85 +##anial +331 +gaunt +neighbourhoods +1540 +##abas +blanca +bypassed +sockets +behold +coincidentally +##bane +nara +shave +splinter +terrific +##arion +##erian +commonplace +juris +redwood +waistband +boxed +caitlin +fingerprints +jennie +naturalized +##ired +balfour +craters +jody +bungalow +hugely +quilt +glitter +pigeons +undertaker +bulging +constrained +goo +##sil +##akh +assimilation +reworked +##person +persuasion +##pants +felicia +##cliff +##ulent +1732 +explodes +##dun +##inium +##zic +lyman +vulture +hog +overlook +begs +northwards +ow +spoil +##urer +fatima +favorably +accumulate +sargent +sorority +corresponded +dispersal +kochi +toned +##imi +##lita +internacional +newfound +##agger +##lynn +##rigue +booths +peanuts +##eborg +medicare +muriel +nur +##uram +crates +millennia +pajamas +worsened +##breakers +jimi +vanuatu +yawned +##udeau +carousel +##hony +hurdle +##ccus +##mounted +##pod +rv +##eche +airship +ambiguity +compulsion +recapture +##claiming +arthritis +##osomal +1667 +asserting +ngc +sniffing +dade +discontent +glendale +ported +##amina +defamation +rammed +##scent +fling +livingstone +##fleet +875 +##ppy +apocalyptic +comrade +lcd +##lowe +cessna +eine +persecuted +subsistence +demi +hoop +reliefs +710 +coptic +progressing +stemmed +perpetrators +1665 +priestess +##nio +dobson +ebony +rooster +itf +tortricidae +##bbon +##jian +cleanup +##jean +##øy +1721 +eighties +taxonomic +holiness +##hearted +##spar +antilles +showcasing +stabilized +##nb +gia +mascara +michelangelo +dawned +##uria +##vinsky +extinguished +fitz +grotesque +£100 +##fera +##loid +##mous +barges +neue +throbbed +cipher +johnnie +##a1 +##mpt +outburst +##swick +spearheaded +administrations +c1 +heartbreak +pixels +pleasantly +##enay +lombardy +plush +##nsed +bobbie +##hly +reapers +tremor +xiang +minogue +substantive +hitch +barak +##wyl +kwan +##encia +910 +obscene +elegance +indus +surfer +bribery +conserve +##hyllum +##masters +horatio +##fat +apes +rebound +psychotic +##pour +iteration +##mium +##vani +botanic +horribly +antiques +dispose +paxton +##hli +##wg +timeless +1704 +disregard +engraver +hounds +##bau +##version +looted +uno +facilitates +groans +masjid +rutland +antibody +disqualification +decatur +footballers +quake +slacks +48th +rein +scribe +stabilize +commits +exemplary +tho +##hort +##chison +pantry +traversed +##hiti +disrepair +identifiable +vibrated +baccalaureate +##nnis +csa +interviewing +##iensis +##raße +greaves +wealthiest +343 +classed +jogged +£5 +##58 +##atal +illuminating +knicks +respecting +##uno +scrubbed +##iji +##dles +kruger +moods +growls +raider +silvia +chefs +kam +vr +cree +percival +##terol +gunter +counterattack +defiant +henan +ze +##rasia +##riety +equivalence +submissions +##fra +##thor +bautista +mechanically +##heater +cornice +herbal +templar +##mering +outputs +ruining +ligand +renumbered +extravagant +mika +blockbuster +eta +insurrection +##ilia +darkening +ferocious +pianos +strife +kinship +##aer +melee +##anor +##iste +##may +##oue +decidedly +weep +##jad +##missive +##ppel +354 +puget +unease +##gnant +1629 +hammering +kassel +ob +wessex +##lga +bromwich +egan +paranoia +utilization +##atable +##idad +contradictory +provoke +##ols +##ouring +##tangled +knesset +##very +##lette +plumbing +##sden +##¹ +greensboro +occult +sniff +338 +zev +beaming +gamer +haggard +mahal +##olt +##pins +mendes +utmost +briefing +gunnery +##gut +##pher +##zh +##rok +1679 +khalifa +sonya +##boot +principals +urbana +wiring +##liffe +##minating +##rrado +dahl +nyu +skepticism +np +townspeople +ithaca +lobster +somethin +##fur +##arina +##−1 +freighter +zimmerman +biceps +contractual +##herton +amend +hurrying +subconscious +##anal +336 +meng +clermont +spawning +##eia +##lub +dignitaries +impetus +snacks +spotting +twigs +##bilis +##cz +##ouk +libertadores +nic +skylar +##aina +##firm +gustave +asean +##anum +dieter +legislatures +flirt +bromley +trolls +umar +##bbies +##tyle +blah +parc +bridgeport +crank +negligence +##nction +46th +constantin +molded +bandages +seriousness +00pm +siegel +carpets +compartments +upbeat +statehood +##dner +##edging +marko +730 +platt +##hane +paving +##iy +1738 +abbess +impatience +limousine +nbl +##talk +441 +lucille +mojo +nightfall +robbers +##nais +karel +brisk +calves +replicate +ascribed +telescopes +##olf +intimidated +##reen +ballast +specialization +##sit +aerodynamic +caliphate +rainer +visionary +##arded +epsilon +##aday +##onte +aggregation +auditory +boosted +reunification +kathmandu +loco +robyn +402 +acknowledges +appointing +humanoid +newell +redeveloped +restraints +##tained +barbarians +chopper +1609 +italiana +##lez +##lho +investigates +wrestlemania +##anies +##bib +690 +##falls +creaked +dragoons +gravely +minions +stupidity +volley +##harat +##week +musik +##eries +##uously +fungal +massimo +semantics +malvern +##ahl +##pee +discourage +embryo +imperialism +1910s +profoundly +##ddled +jiangsu +sparkled +stat +##holz +sweatshirt +tobin +##iction +sneered +##cheon +##oit +brit +causal +smyth +##neuve +diffuse +perrin +silvio +##ipes +##recht +detonated +iqbal +selma +##nism +##zumi +roasted +##riders +tay +##ados +##mament +##mut +##rud +840 +completes +nipples +cfa +flavour +hirsch +##laus +calderon +sneakers +moravian +##ksha +1622 +rq +294 +##imeters +bodo +##isance +##pre +##ronia +anatomical +excerpt +##lke +dh +kunst +##tablished +##scoe +biomass +panted +unharmed +gael +housemates +montpellier +##59 +coa +rodents +tonic +hickory +singleton +##taro +451 +1719 +aldo +breaststroke +dempsey +och +rocco +##cuit +merton +dissemination +midsummer +serials +##idi +haji +polynomials +##rdon +gs +enoch +prematurely +shutter +taunton +£3 +##grating +##inates +archangel +harassed +##asco +326 +archway +dazzling +##ecin +1736 +sumo +wat +##kovich +1086 +honneur +##ently +##nostic +##ttal +##idon +1605 +403 +1716 +blogger +rents +##gnan +hires +##ikh +##dant +howie +##rons +handler +retracted +shocks +1632 +arun +duluth +kepler +trumpeter +##lary +peeking +seasoned +trooper +##mara +laszlo +##iciencies +##rti +heterosexual +##inatory +##ssion +indira +jogging +##inga +##lism +beit +dissatisfaction +malice +##ately +nedra +peeling +##rgeon +47th +stadiums +475 +vertigo +##ains +iced +restroom +##plify +##tub +illustrating +pear +##chner +##sibility +inorganic +rappers +receipts +watery +##kura +lucinda +##oulos +reintroduced +##8th +##tched +gracefully +saxons +nutritional +wastewater +rained +favourites +bedrock +fisted +hallways +likeness +upscale +##lateral +1580 +blinds +prequel +##pps +##tama +deter +humiliating +restraining +tn +vents +1659 +laundering +recess +rosary +tractors +coulter +federer +##ifiers +##plin +persistence +##quitable +geschichte +pendulum +quakers +##beam +bassett +pictorial +buffet +koln +##sitor +drills +reciprocal +shooters +##57 +##cton +##tees +converge +pip +dmitri +donnelly +yamamoto +aqua +azores +demographics +hypnotic +spitfire +suspend +wryly +roderick +##rran +sebastien +##asurable +mavericks +##fles +##200 +himalayan +prodigy +##iance +transvaal +demonstrators +handcuffs +dodged +mcnamara +sublime +1726 +crazed +##efined +##till +ivo +pondered +reconciled +shrill +sava +##duk +bal +cad +heresy +jaipur +goran +##nished +341 +lux +shelly +whitehall +##hre +israelis +peacekeeping +##wled +1703 +demetrius +ousted +##arians +##zos +beale +anwar +backstroke +raged +shrinking +cremated +##yck +benign +towing +wadi +darmstadt +landfill +parana +soothe +colleen +sidewalks +mayfair +tumble +hepatitis +ferrer +superstructure +##gingly +##urse +##wee +anthropological +translators +##mies +closeness +hooves +##pw +mondays +##roll +##vita +landscaping +##urized +purification +sock +thorns +thwarted +jalan +tiberius +##taka +saline +##rito +confidently +khyber +sculptors +##ij +brahms +hammersmith +inspectors +battista +fivb +fragmentation +hackney +##uls +arresting +exercising +antoinette +bedfordshire +##zily +dyed +##hema +1656 +racetrack +variability +##tique +1655 +austrians +deteriorating +madman +theorists +aix +lehman +weathered +1731 +decreed +eruptions +1729 +flaw +quinlan +sorbonne +flutes +nunez +1711 +adored +downwards +fable +rasped +1712 +moritz +mouthful +renegade +shivers +stunts +dysfunction +restrain +translit +327 +pancakes +##avio +##cision +##tray +351 +vial +##lden +bain +##maid +##oxide +chihuahua +malacca +vimes +##rba +##rnier +1664 +donnie +plaques +##ually +337 +bangs +floppy +huntsville +loretta +nikolay +##otte +eater +handgun +ubiquitous +##hett +eras +zodiac +1634 +##omorphic +1820s +##zog +cochran +##bula +##lithic +warring +##rada +dalai +excused +blazers +mcconnell +reeling +bot +este +##abi +geese +hoax +taxon +##bla +guitarists +##icon +condemning +hunts +inversion +moffat +taekwondo +##lvis +1624 +stammered +##rest +##rzy +sousa +fundraiser +marylebone +navigable +uptown +cabbage +daniela +salman +shitty +whimper +##kian +##utive +programmers +protections +rm +##rmi +##rued +forceful +##enes +fuss +##tao +##wash +brat +oppressive +reykjavik +spartak +ticking +##inkles +##kiewicz +adolph +horst +maui +protege +straighten +cpc +landau +concourse +clements +resultant +##ando +imaginative +joo +reactivated +##rem +##ffled +##uising +consultative +##guide +flop +kaitlyn +mergers +parenting +somber +##vron +supervise +vidhan +##imum +courtship +exemplified +harmonies +medallist +refining +##rrow +##ка +amara +##hum +780 +goalscorer +sited +overshadowed +rohan +displeasure +secretive +multiplied +osman +##orth +engravings +padre +##kali +##veda +miniatures +mis +##yala +clap +pali +rook +##cana +1692 +57th +antennae +astro +oskar +1628 +bulldog +crotch +hackett +yucatan +##sure +amplifiers +brno +ferrara +migrating +##gree +thanking +turing +##eza +mccann +ting +andersson +onslaught +gaines +ganga +incense +standardization +##mation +sentai +scuba +stuffing +turquoise +waivers +alloys +##vitt +regaining +vaults +##clops +##gizing +digger +furry +memorabilia +probing +##iad +payton +rec +deutschland +filippo +opaque +seamen +zenith +afrikaans +##filtration +disciplined +inspirational +##merie +banco +confuse +grafton +tod +##dgets +championed +simi +anomaly +biplane +##ceptive +electrode +##para +1697 +cleavage +crossbow +swirl +informant +##lars +##osta +afi +bonfire +spec +##oux +lakeside +slump +##culus +##lais +##qvist +##rrigan +1016 +facades +borg +inwardly +cervical +xl +pointedly +050 +stabilization +##odon +chests +1699 +hacked +ctv +orthogonal +suzy +##lastic +gaulle +jacobite +rearview +##cam +##erted +ashby +##drik +##igate +##mise +##zbek +affectionately +canine +disperse +latham +##istles +##ivar +spielberg +##orin +##idium +ezekiel +cid +##sg +durga +middletown +##cina +customized +frontiers +harden +##etano +##zzy +1604 +bolsheviks +##66 +coloration +yoko +##bedo +briefs +slabs +debra +liquidation +plumage +##oin +blossoms +dementia +subsidy +1611 +proctor +relational +jerseys +parochial +ter +##ici +esa +peshawar +cavalier +loren +cpi +idiots +shamrock +1646 +dutton +malabar +mustache +##endez +##ocytes +referencing +terminates +marche +yarmouth +##sop +acton +mated +seton +subtly +baptised +beige +extremes +jolted +kristina +telecast +##actic +safeguard +waldo +##baldi +##bular +endeavors +sloppy +subterranean +##ensburg +##itung +delicately +pigment +tq +##scu +1626 +##ound +collisions +coveted +herds +##personal +##meister +##nberger +chopra +##ricting +abnormalities +defective +galician +lucie +##dilly +alligator +likened +##genase +burundi +clears +complexion +derelict +deafening +diablo +fingered +champaign +dogg +enlist +isotope +labeling +mrna +##erre +brilliance +marvelous +##ayo +1652 +crawley +ether +footed +dwellers +deserts +hamish +rubs +warlock +skimmed +##lizer +870 +buick +embark +heraldic +irregularities +##ajan +kiara +##kulam +##ieg +antigen +kowalski +##lge +oakley +visitation +##mbit +vt +##suit +1570 +murderers +##miento +##rites +chimneys +##sling +condemn +custer +exchequer +havre +##ghi +fluctuations +##rations +dfb +hendricks +vaccines +##tarian +nietzsche +biking +juicy +##duced +brooding +scrolling +selangor +##ragan +352 +annum +boomed +seminole +sugarcane +##dna +departmental +dismissing +innsbruck +arteries +ashok +batavia +daze +kun +overtook +##rga +##tlan +beheaded +gaddafi +holm +electronically +faulty +galilee +fractures +kobayashi +##lized +gunmen +magma +aramaic +mala +eastenders +inference +messengers +bf +##qu +407 +bathrooms +##vere +1658 +flashbacks +ideally +misunderstood +##jali +##weather +mendez +##grounds +505 +uncanny +##iii +1709 +friendships +##nbc +sacrament +accommodated +reiterated +logistical +pebbles +thumped +##escence +administering +decrees +drafts +##flight +##cased +##tula +futuristic +picket +intimidation +winthrop +##fahan +interfered +339 +afar +francoise +morally +uta +cochin +croft +dwarfs +##bruck +##dents +##nami +biker +##hner +##meral +nano +##isen +##ometric +##pres +##ан +brightened +meek +parcels +securely +gunners +##jhl +##zko +agile +hysteria +##lten +##rcus +bukit +champs +chevy +cuckoo +leith +sadler +theologians +welded +##section +1663 +jj +plurality +xander +##rooms +##formed +shredded +temps +intimately +pau +tormented +##lok +##stellar +1618 +charred +ems +essen +##mmel +alarms +spraying +ascot +blooms +twinkle +##abia +##apes +internment +obsidian +##chaft +snoop +##dav +##ooping +malibu +##tension +quiver +##itia +hays +mcintosh +travers +walsall +##ffie +1623 +beverley +schwarz +plunging +structurally +m3 +rosenthal +vikram +##tsk +770 +ghz +##onda +##tiv +chalmers +groningen +pew +reckon +unicef +##rvis +55th +##gni +1651 +sulawesi +avila +cai +metaphysical +screwing +turbulence +##mberg +augusto +samba +56th +baffled +momentary +toxin +##urian +##wani +aachen +condoms +dali +steppe +##3d +##app +##oed +##year +adolescence +dauphin +electrically +inaccessible +microscopy +nikita +##ega +atv +##cel +##enter +##oles +##oteric +##ы +accountants +punishments +wrongly +bribes +adventurous +clinch +flinders +southland +##hem +##kata +gough +##ciency +lads +soared +##ה +undergoes +deformation +outlawed +rubbish +##arus +##mussen +##nidae +##rzburg +arcs +##ingdon +##tituted +1695 +wheelbase +wheeling +bombardier +campground +zebra +##lices +##oj +##bain +lullaby +##ecure +donetsk +wylie +grenada +##arding +##ης +squinting +eireann +opposes +##andra +maximal +runes +##broken +##cuting +##iface +##ror +##rosis +additive +britney +adultery +triggering +##drome +detrimental +aarhus +containment +jc +swapped +vichy +##ioms +madly +##oric +##rag +brant +##ckey +##trix +1560 +1612 +broughton +rustling +##stems +##uder +asbestos +mentoring +##nivorous +finley +leaps +##isan +apical +pry +slits +substitutes +##dict +intuitive +fantasia +insistent +unreasonable +##igen +##vna +domed +hannover +margot +ponder +##zziness +impromptu +jian +lc +rampage +stemming +##eft +andrey +gerais +whichever +amnesia +appropriated +anzac +clicks +modifying +ultimatum +cambrian +maids +verve +yellowstone +##mbs +conservatoire +##scribe +adherence +dinners +spectra +imperfect +mysteriously +sidekick +tatar +tuba +##aks +##ifolia +distrust +##athan +##zle +c2 +ronin +zac +##pse +celaena +instrumentalist +scents +skopje +##mbling +comical +compensated +vidal +condor +intersect +jingle +wavelengths +##urrent +mcqueen +##izzly +carp +weasel +422 +kanye +militias +postdoctoral +eugen +gunslinger +##ɛ +faux +hospice +##for +appalled +derivation +dwarves +##elis +dilapidated +##folk +astoria +philology +##lwyn +##otho +##saka +inducing +philanthropy +##bf +##itative +geek +markedly +sql +##yce +bessie +indices +rn +##flict +495 +frowns +resolving +weightlifting +tugs +cleric +contentious +1653 +mania +rms +##miya +##reate +##ruck +##tucket +bien +eels +marek +##ayton +##cence +discreet +unofficially +##ife +leaks +##bber +1705 +332 +dung +compressor +hillsborough +pandit +shillings +distal +##skin +381 +##tat +##you +nosed +##nir +mangrove +undeveloped +##idia +textures +##inho +##500 +##rise +ae +irritating +nay +amazingly +bancroft +apologetic +compassionate +kata +symphonies +##lovic +airspace +##lch +930 +gifford +precautions +fulfillment +sevilla +vulgar +martinique +##urities +looting +piccolo +tidy +##dermott +quadrant +armchair +incomes +mathematicians +stampede +nilsson +##inking +##scan +foo +quarterfinal +##ostal +shang +shouldered +squirrels +##owe +344 +vinegar +##bner +##rchy +##systems +delaying +##trics +ars +dwyer +rhapsody +sponsoring +##gration +bipolar +cinder +starters +##olio +##urst +421 +signage +##nty +aground +figurative +mons +acquaintances +duets +erroneously +soyuz +elliptic +recreated +##cultural +##quette +##ssed +##tma +##zcz +moderator +scares +##itaire +##stones +##udence +juniper +sighting +##just +##nsen +britten +calabria +ry +bop +cramer +forsyth +stillness +##л +airmen +gathers +unfit +##umber +##upt +taunting +##rip +seeker +streamlined +##bution +holster +schumann +tread +vox +##gano +##onzo +strive +dil +reforming +covent +newbury +predicting +##orro +decorate +tre +##puted +andover +ie +asahi +dept +dunkirk +gills +##tori +buren +huskies +##stis +##stov +abstracts +bets +loosen +##opa +1682 +yearning +##glio +##sir +berman +effortlessly +enamel +napoli +persist +##peration +##uez +attache +elisa +b1 +invitations +##kic +accelerating +reindeer +boardwalk +clutches +nelly +polka +starbucks +##kei +adamant +huey +lough +unbroken +adventurer +embroidery +inspecting +stanza +##ducted +naia +taluka +##pone +##roids +chases +deprivation +florian +##jing +##ppet +earthly +##lib +##ssee +colossal +foreigner +vet +freaks +patrice +rosewood +triassic +upstate +##pkins +dominates +ata +chants +ks +vo +##400 +##bley +##raya +##rmed +555 +agra +infiltrate +##ailing +##ilation +##tzer +##uppe +##werk +binoculars +enthusiast +fujian +squeak +##avs +abolitionist +almeida +boredom +hampstead +marsden +rations +##ands +inflated +334 +bonuses +rosalie +patna +##rco +329 +detachments +penitentiary +54th +flourishing +woolf +##dion +##etched +papyrus +##lster +##nsor +##toy +bobbed +dismounted +endelle +inhuman +motorola +tbs +wince +wreath +##ticus +hideout +inspections +sanjay +disgrace +infused +pudding +stalks +##urbed +arsenic +leases +##hyl +##rrard +collarbone +##waite +##wil +dowry +##bant +##edance +genealogical +nitrate +salamanca +scandals +thyroid +necessitated +##! +##" +### +##$ +##% +##& +##' +##( +##) +##* +##+ +##, +##- +##. +##/ +##: +##; +##< +##= +##> +##? +##@ +##[ +##\ +##] +##^ +##_ +##` +##{ +##| +##} +##~ +##¡ +##¢ +##£ +##¤ +##¥ +##¦ +##§ +##¨ +##© +##ª +##« +##¬ +##® +##± +##´ +##µ +##¶ +##· +##º +##» +##¼ +##¾ +##¿ +##æ +##ð +##÷ +##þ +##đ +##ħ +##ŋ +##œ +##ƒ +##ɐ +##ɑ +##ɒ +##ɔ +##ɕ +##ə +##ɡ +##ɣ +##ɨ +##ɪ +##ɫ +##ɬ +##ɯ +##ɲ +##ɴ +##ɹ +##ɾ +##ʀ +##ʁ +##ʂ +##ʃ +##ʉ +##ʊ +##ʋ +##ʌ +##ʎ +##ʐ +##ʑ +##ʒ +##ʔ +##ʰ +##ʲ +##ʳ +##ʷ +##ʸ +##ʻ +##ʼ +##ʾ +##ʿ +##ˈ +##ˡ +##ˢ +##ˣ +##ˤ +##β +##γ +##δ +##ε +##ζ +##θ +##κ +##λ +##μ +##ξ +##ο +##π +##ρ +##σ +##τ +##υ +##φ +##χ +##ψ +##ω +##б +##г +##д +##ж +##з +##м +##п +##с +##у +##ф +##х +##ц +##ч +##ш +##щ +##ъ +##э +##ю +##ђ +##є +##і +##ј +##љ +##њ +##ћ +##ӏ +##ա +##բ +##գ +##դ +##ե +##թ +##ի +##լ +##կ +##հ +##մ +##յ +##ն +##ո +##պ +##ս +##վ +##տ +##ր +##ւ +##ք +##־ +##א +##ב +##ג +##ד +##ו +##ז +##ח +##ט +##י +##ך +##כ +##ל +##ם +##מ +##ן +##נ +##ס +##ע +##ף +##פ +##ץ +##צ +##ק +##ר +##ש +##ת +##، +##ء +##ب +##ت +##ث +##ج +##ح +##خ +##ذ +##ز +##س +##ش +##ص +##ض +##ط +##ظ +##ع +##غ +##ـ +##ف +##ق +##ك +##و +##ى +##ٹ +##پ +##چ +##ک +##گ +##ں +##ھ +##ہ +##ے +##अ +##आ +##उ +##ए +##क +##ख +##ग +##च +##ज +##ट +##ड +##ण +##त +##थ +##द +##ध +##न +##प +##ब +##भ +##म +##य +##र +##ल +##व +##श +##ष +##स +##ह +##ा +##ि +##ी +##ो +##। +##॥ +##ং +##অ +##আ +##ই +##উ +##এ +##ও +##ক +##খ +##গ +##চ +##ছ +##জ +##ট +##ড +##ণ +##ত +##থ +##দ +##ধ +##ন +##প +##ব +##ভ +##ম +##য +##র +##ল +##শ +##ষ +##স +##হ +##া +##ি +##ী +##ে +##க +##ச +##ட +##த +##ந +##ன +##ப +##ம +##ய +##ர +##ல +##ள +##வ +##ா +##ி +##ு +##ே +##ை +##ನ +##ರ +##ಾ +##ක +##ය +##ර +##ල +##ව +##ා +##ก +##ง +##ต +##ท +##น +##พ +##ม +##ย +##ร +##ล +##ว +##ส +##อ +##า +##เ +##་ +##། +##ག +##ང +##ད +##ན +##པ +##བ +##མ +##འ +##ར +##ལ +##ས +##မ +##ა +##ბ +##გ +##დ +##ე +##ვ +##თ +##ი +##კ +##ლ +##მ +##ნ +##ო +##რ +##ს +##ტ +##უ +##ᄀ +##ᄂ +##ᄃ +##ᄅ +##ᄆ +##ᄇ +##ᄉ +##ᄊ +##ᄋ +##ᄌ +##ᄎ +##ᄏ +##ᄐ +##ᄑ +##ᄒ +##ᅡ +##ᅢ +##ᅥ +##ᅦ +##ᅧ +##ᅩ +##ᅪ +##ᅭ +##ᅮ +##ᅯ +##ᅲ +##ᅳ +##ᅴ +##ᅵ +##ᆨ +##ᆫ +##ᆯ +##ᆷ +##ᆸ +##ᆼ +##ᴬ +##ᴮ +##ᴰ +##ᴵ +##ᴺ +##ᵀ +##ᵃ +##ᵇ +##ᵈ +##ᵉ +##ᵍ +##ᵏ +##ᵐ +##ᵒ +##ᵖ +##ᵗ +##ᵘ +##ᵣ +##ᵤ +##ᵥ +##ᶜ +##ᶠ +##‐ +##‑ +##‒ +##– +##— +##― +##‖ +##‘ +##’ +##‚ +##“ +##” +##„ +##† +##‡ +##• +##… +##‰ +##′ +##″ +##› +##‿ +##⁄ +##⁰ +##ⁱ +##⁴ +##⁵ +##⁶ +##⁷ +##⁸ +##⁹ +##⁻ +##ⁿ +##₅ +##₆ +##₇ +##₈ +##₉ +##₊ +##₍ +##₎ +##ₐ +##ₑ +##ₒ +##ₓ +##ₕ +##ₖ +##ₗ +##ₘ +##ₚ +##ₛ +##ₜ +##₤ +##₩ +##€ +##₱ +##₹ +##ℓ +##№ +##ℝ +##™ +##⅓ +##⅔ +##← +##↑ +##→ +##↓ +##↔ +##↦ +##⇄ +##⇌ +##⇒ +##∂ +##∅ +##∆ +##∇ +##∈ +##∗ +##∘ +##√ +##∞ +##∧ +##∨ +##∩ +##∪ +##≈ +##≡ +##≤ +##≥ +##⊂ +##⊆ +##⊕ +##⊗ +##⋅ +##─ +##│ +##■ +##▪ +##● +##★ +##☆ +##☉ +##♠ +##♣ +##♥ +##♦ +##♯ +##⟨ +##⟩ +##ⱼ +##⺩ +##⺼ +##⽥ +##、 +##。 +##〈 +##〉 +##《 +##》 +##「 +##」 +##『 +##』 +##〜 +##あ +##い +##う +##え +##お +##か +##き +##く +##け +##こ +##さ +##し +##す +##せ +##そ +##た +##ち +##っ +##つ +##て +##と +##な +##に +##ぬ +##ね +##の +##は +##ひ +##ふ +##へ +##ほ +##ま +##み +##む +##め +##も +##や +##ゆ +##よ +##ら +##り +##る +##れ +##ろ +##を +##ん +##ァ +##ア +##ィ +##イ +##ウ +##ェ +##エ +##オ +##カ +##キ +##ク +##ケ +##コ +##サ +##シ +##ス +##セ +##タ +##チ +##ッ +##ツ +##テ +##ト +##ナ +##ニ +##ノ +##ハ +##ヒ +##フ +##ヘ +##ホ +##マ +##ミ +##ム +##メ +##モ +##ャ +##ュ +##ョ +##ラ +##リ +##ル +##レ +##ロ +##ワ +##ン +##・ +##ー +##一 +##三 +##上 +##下 +##不 +##世 +##中 +##主 +##久 +##之 +##也 +##事 +##二 +##五 +##井 +##京 +##人 +##亻 +##仁 +##介 +##代 +##仮 +##伊 +##会 +##佐 +##侍 +##保 +##信 +##健 +##元 +##光 +##八 +##公 +##内 +##出 +##分 +##前 +##劉 +##力 +##加 +##勝 +##北 +##区 +##十 +##千 +##南 +##博 +##原 +##口 +##古 +##史 +##司 +##合 +##吉 +##同 +##名 +##和 +##囗 +##四 +##国 +##國 +##土 +##地 +##坂 +##城 +##堂 +##場 +##士 +##夏 +##外 +##大 +##天 +##太 +##夫 +##奈 +##女 +##子 +##学 +##宀 +##宇 +##安 +##宗 +##定 +##宣 +##宮 +##家 +##宿 +##寺 +##將 +##小 +##尚 +##山 +##岡 +##島 +##崎 +##川 +##州 +##巿 +##帝 +##平 +##年 +##幸 +##广 +##弘 +##張 +##彳 +##後 +##御 +##德 +##心 +##忄 +##志 +##忠 +##愛 +##成 +##我 +##戦 +##戸 +##手 +##扌 +##政 +##文 +##新 +##方 +##日 +##明 +##星 +##春 +##昭 +##智 +##曲 +##書 +##月 +##有 +##朝 +##木 +##本 +##李 +##村 +##東 +##松 +##林 +##森 +##楊 +##樹 +##橋 +##歌 +##止 +##正 +##武 +##比 +##氏 +##民 +##水 +##氵 +##氷 +##永 +##江 +##沢 +##河 +##治 +##法 +##海 +##清 +##漢 +##瀬 +##火 +##版 +##犬 +##王 +##生 +##田 +##男 +##疒 +##発 +##白 +##的 +##皇 +##目 +##相 +##省 +##真 +##石 +##示 +##社 +##神 +##福 +##禾 +##秀 +##秋 +##空 +##立 +##章 +##竹 +##糹 +##美 +##義 +##耳 +##良 +##艹 +##花 +##英 +##華 +##葉 +##藤 +##行 +##街 +##西 +##見 +##訁 +##語 +##谷 +##貝 +##貴 +##車 +##軍 +##辶 +##道 +##郎 +##郡 +##部 +##都 +##里 +##野 +##金 +##鈴 +##镇 +##長 +##門 +##間 +##阝 +##阿 +##陳 +##陽 +##雄 +##青 +##面 +##風 +##食 +##香 +##馬 +##高 +##龍 +##龸 +##fi +##fl +##! +##( +##) +##, +##- +##. +##/ +##: +##? +##~ diff --git a/browser/base/content/assistant/embedding-assets/ort/ort-wasm-simd-threaded.jsep.mjs b/browser/base/content/assistant/embedding-assets/ort/ort-wasm-simd-threaded.jsep.mjs new file mode 100644 index 0000000000000..fd68c6339d617 --- /dev/null +++ b/browser/base/content/assistant/embedding-assets/ort/ort-wasm-simd-threaded.jsep.mjs @@ -0,0 +1,125 @@ +var ortWasmThreaded = (() => { + var _scriptName = import.meta.url; + + return ( +async function(moduleArg = {}) { + var moduleRtn; + +var e=moduleArg,aa,ca,da=new Promise((a,b)=>{aa=a;ca=b}),ea="object"==typeof window,k="undefined"!=typeof WorkerGlobalScope,n="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node&&"renderer"!=process.type,q=k&&self.name?.startsWith("em-pthread");if(n){const {createRequire:a}=await import("module");var require=a(import.meta.url),fa=require("worker_threads");global.Worker=fa.Worker;q=(k=!fa.oc)&&"em-pthread"==fa.workerData} +e.mountExternalData=(a,b)=>{a.startsWith("./")&&(a=a.substring(2));(e.Eb||(e.Eb=new Map)).set(a,b)};e.unmountExternalData=()=>{delete e.Eb};var SharedArrayBuffer=globalThis.SharedArrayBuffer??(new WebAssembly.Memory({initial:0,maximum:0,pc:!0})).buffer.constructor; +const ha=a=>async(...b)=>{try{if(e.Fb)throw Error("Session already started");const c=e.Fb={dc:b[0],errors:[]},d=await a(...b);if(e.Fb!==c)throw Error("Session mismatch");e.Jb?.flush();const f=c.errors;if(0h);if(0{if("webgpu"===a){[e.Jb,e.Ub,e.Yb,e.Kb,e.Xb,e.jb,e.Zb,e.ac,e.Vb,e.Wb,e.$b]=b;const c=e.Jb;e.jsepRegisterBuffer=(d,f,g,h)=>c.registerBuffer(d,f,g,h);e.jsepGetBuffer=d=>c.getBuffer(d);e.jsepCreateDownloader=(d,f,g)=>c.createDownloader(d,f,g);e.jsepOnCreateSession=d=>{c.onCreateSession(d)};e.jsepOnReleaseSession=d=>{c.onReleaseSession(d)};e.jsepOnRunStart=d=>c.onRunStart(d);e.bc=(d,f)=>{c.upload(d,f)}}else if("webnn"===a){const c=b[0];[e.nc,e.Nb,e.webnnEnsureTensor,e.Ob,e.webnnDownloadTensor]= +b.slice(1);e.webnnReleaseTensorId=e.Nb;e.webnnUploadTensor=e.Ob;e.webnnOnRunStart=d=>c.onRunStart(d);e.webnnOnRunEnd=c.onRunEnd.bind(c);e.webnnRegisterMLContext=(d,f)=>{c.registerMLContext(d,f)};e.webnnOnReleaseSession=d=>{c.onReleaseSession(d)};e.webnnCreateMLTensorDownloader=(d,f)=>c.createMLTensorDownloader(d,f);e.webnnRegisterMLTensor=(d,f,g,h)=>c.registerMLTensor(d,f,g,h);e.webnnCreateMLContext=d=>c.createMLContext(d);e.webnnRegisterMLConstant=(d,f,g,h,l,m)=>c.registerMLConstant(d,f,g,h,l,e.Eb, +m);e.webnnRegisterGraphInput=c.registerGraphInput.bind(c);e.webnnIsGraphInput=c.isGraphInput.bind(c);e.webnnCreateTemporaryTensor=c.createTemporaryTensor.bind(c);e.webnnIsInt64Supported=c.isInt64Supported.bind(c)}}; +let ja=()=>{const a=(b,c,d)=>(...f)=>{const g=t,h=c?.();f=b(...f);const l=c?.();h!==l&&(b=l,d(h),c=d=null);return t!=g?ia():f};(b=>{for(const c of b)e[c]=a(e[c],()=>e[c],d=>e[c]=d)})(["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"]);"undefined"!==typeof ha&&(e._OrtRun=ha(e._OrtRun),e._OrtRunWithBinding=ha(e._OrtRunWithBinding));ja=void 0};e.asyncInit=()=>{ja?.()};var ka=Object.assign({},e),la="./this.program",ma=(a,b)=>{throw b;},v="",na,oa; +if(n){var fs=require("fs"),pa=require("path");import.meta.url.startsWith("data:")||(v=pa.dirname(require("url").fileURLToPath(import.meta.url))+"/");oa=a=>{a=qa(a)?new URL(a):a;return fs.readFileSync(a)};na=async a=>{a=qa(a)?new URL(a):a;return fs.readFileSync(a,void 0)};!e.thisProgram&&1{process.exitCode=a;throw b;}}else if(ea||k)k?v=self.location.href:"undefined"!=typeof document&& +document.currentScript&&(v=document.currentScript.src),_scriptName&&(v=_scriptName),v.startsWith("blob:")?v="":v=v.slice(0,v.replace(/[?#].*/,"").lastIndexOf("/")+1),n||(k&&(oa=a=>{var b=new XMLHttpRequest;b.open("GET",a,!1);b.responseType="arraybuffer";b.send(null);return new Uint8Array(b.response)}),na=async a=>{if(qa(a))return new Promise((c,d)=>{var f=new XMLHttpRequest;f.open("GET",a,!0);f.responseType="arraybuffer";f.onload=()=>{200==f.status||0==f.status&&f.response?c(f.response):d(f.status)}; +f.onerror=d;f.send(null)});var b=await fetch(a,{credentials:"same-origin"});if(b.ok)return b.arrayBuffer();throw Error(b.status+" : "+b.url);});var ra=console.log.bind(console),sa=console.error.bind(console);n&&(ra=(...a)=>fs.writeSync(1,a.join(" ")+"\n"),sa=(...a)=>fs.writeSync(2,a.join(" ")+"\n"));var ta=ra,x=sa;Object.assign(e,ka);ka=null;var ua=e.wasmBinary,z,va,A=!1,wa,B,xa,ya,za,Aa,Ba,Ca,C,Da,Ea,qa=a=>a.startsWith("file://");function D(){z.buffer!=B.buffer&&E();return B} +function F(){z.buffer!=B.buffer&&E();return xa}function G(){z.buffer!=B.buffer&&E();return ya}function Fa(){z.buffer!=B.buffer&&E();return za}function H(){z.buffer!=B.buffer&&E();return Aa}function I(){z.buffer!=B.buffer&&E();return Ba}function Ga(){z.buffer!=B.buffer&&E();return Ca}function J(){z.buffer!=B.buffer&&E();return Ea} +if(q){var Ha;if(n){var Ia=fa.parentPort;Ia.on("message",b=>onmessage({data:b}));Object.assign(globalThis,{self:global,postMessage:b=>Ia.postMessage(b)})}var Ja=!1;x=function(...b){b=b.join(" ");n?fs.writeSync(2,b+"\n"):console.error(b)};self.alert=function(...b){postMessage({Bb:"alert",text:b.join(" "),ic:Ka()})};self.onunhandledrejection=b=>{throw b.reason||b;};function a(b){try{var c=b.data,d=c.Bb;if("load"===d){let f=[];self.onmessage=g=>f.push(g);self.startWorker=()=>{postMessage({Bb:"loaded"}); +for(let g of f)a(g);self.onmessage=a};for(const g of c.Rb)if(!e[g]||e[g].proxy)e[g]=(...h)=>{postMessage({Bb:"callHandler",Qb:g,args:h})},"print"==g&&(ta=e[g]),"printErr"==g&&(x=e[g]);z=c.kc;E();Ha(c.lc)}else if("run"===d){La(c.Ab);Ma(c.Ab,0,0,1,0,0);Na();Oa(c.Ab);Ja||(Pa(),Ja=!0);try{Qa(c.fc,c.Hb)}catch(f){if("unwind"!=f)throw f;}}else"setimmediate"!==c.target&&("checkMailbox"===d?Ja&&Ra():d&&(x(`worker: received unknown command ${d}`),x(c)))}catch(f){throw Sa(),f;}}self.onmessage=a} +function E(){var a=z.buffer;e.HEAP8=B=new Int8Array(a);e.HEAP16=ya=new Int16Array(a);e.HEAPU8=xa=new Uint8Array(a);e.HEAPU16=za=new Uint16Array(a);e.HEAP32=Aa=new Int32Array(a);e.HEAPU32=Ba=new Uint32Array(a);e.HEAPF32=Ca=new Float32Array(a);e.HEAPF64=Ea=new Float64Array(a);e.HEAP64=C=new BigInt64Array(a);e.HEAPU64=Da=new BigUint64Array(a)}q||(z=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),E());function Ta(){q?startWorker(e):K.Ca()}var Ua=0,Va=null; +function Wa(){Ua--;if(0==Ua&&Va){var a=Va;Va=null;a()}}function L(a){a="Aborted("+a+")";x(a);A=!0;a=new WebAssembly.RuntimeError(a+". Build with -sASSERTIONS for more info.");ca(a);throw a;}var Xa;async function Ya(a){if(!ua)try{var b=await na(a);return new Uint8Array(b)}catch{}if(a==Xa&&ua)a=new Uint8Array(ua);else if(oa)a=oa(a);else throw"both async and sync fetching of the wasm failed";return a} +async function Za(a,b){try{var c=await Ya(a);return await WebAssembly.instantiate(c,b)}catch(d){x(`failed to asynchronously prepare wasm: ${d}`),L(d)}}async function $a(a){var b=Xa;if(!ua&&"function"==typeof WebAssembly.instantiateStreaming&&!qa(b)&&!n)try{var c=fetch(b,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(c,a)}catch(d){x(`wasm streaming compile failed: ${d}`),x("falling back to ArrayBuffer instantiation")}return Za(b,a)} +function ab(){bb={L:cb,Aa:db,b:eb,$:fb,A:gb,pa:hb,X:ib,Z:jb,qa:kb,na:lb,ga:mb,ma:nb,J:ob,Y:pb,V:qb,oa:rb,W:sb,va:tb,E:ub,Q:vb,O:wb,D:xb,u:yb,r:zb,P:Ab,z:Bb,R:Cb,ja:Db,T:Eb,aa:Fb,M:Gb,F:Hb,ia:Oa,sa:Ib,t:Jb,Ba:Kb,w:Lb,o:Mb,l:Nb,c:Ob,n:Pb,j:Qb,v:Rb,p:Sb,f:Tb,s:Ub,m:Vb,e:Wb,k:Xb,i:Yb,g:Zb,d:$b,da:ac,ea:bc,fa:cc,ba:dc,ca:ec,N:fc,xa:gc,ua:hc,h:ic,C:jc,G:kc,ta:lc,x:mc,ra:nc,U:oc,q:pc,y:qc,K:rc,S:sc,za:tc,ya:uc,ka:vc,la:wc,_:xc,B:yc,I:zc,ha:Ac,H:Bc,a:z,wa:Cc};return{a:bb}} +var Dc={829644:(a,b,c,d,f)=>{if("undefined"==typeof e||!e.Eb)return 1;a=M(Number(a>>>0));a.startsWith("./")&&(a=a.substring(2));a=e.Eb.get(a);if(!a)return 2;b=Number(b>>>0);c=Number(c>>>0);d=Number(d>>>0);if(b+c>a.byteLength)return 3;try{const g=a.subarray(b,b+c);switch(f){case 0:F().set(g,d>>>0);break;case 1:e.mc?e.mc(d,g):e.bc(d,g);break;default:return 4}return 0}catch{return 4}},830468:(a,b,c)=>{e.Ob(a,F().subarray(b>>>0,b+c>>>0))},830532:()=>e.nc(),830574:a=>{e.Nb(a)},830611:()=>{e.Vb()},830642:()=> +{e.Wb()},830671:()=>{e.$b()},830696:a=>e.Ub(a),830729:a=>e.Yb(a),830761:(a,b,c)=>{e.Kb(Number(a),Number(b),Number(c),!0)},830824:(a,b,c)=>{e.Kb(Number(a),Number(b),Number(c))},830881:()=>"undefined"!==typeof wasmOffsetConverter,830938:a=>{e.jb("Abs",a,void 0)},830989:a=>{e.jb("Neg",a,void 0)},831040:a=>{e.jb("Floor",a,void 0)},831093:a=>{e.jb("Ceil",a,void 0)},831145:a=>{e.jb("Reciprocal",a,void 0)},831203:a=>{e.jb("Sqrt",a,void 0)},831255:a=>{e.jb("Exp",a,void 0)},831306:a=>{e.jb("Erf",a,void 0)}, +831357:a=>{e.jb("Sigmoid",a,void 0)},831412:(a,b,c)=>{e.jb("HardSigmoid",a,{alpha:b,beta:c})},831491:a=>{e.jb("Log",a,void 0)},831542:a=>{e.jb("Sin",a,void 0)},831593:a=>{e.jb("Cos",a,void 0)},831644:a=>{e.jb("Tan",a,void 0)},831695:a=>{e.jb("Asin",a,void 0)},831747:a=>{e.jb("Acos",a,void 0)},831799:a=>{e.jb("Atan",a,void 0)},831851:a=>{e.jb("Sinh",a,void 0)},831903:a=>{e.jb("Cosh",a,void 0)},831955:a=>{e.jb("Asinh",a,void 0)},832008:a=>{e.jb("Acosh",a,void 0)},832061:a=>{e.jb("Atanh",a,void 0)}, +832114:a=>{e.jb("Tanh",a,void 0)},832166:a=>{e.jb("Not",a,void 0)},832217:(a,b,c)=>{e.jb("Clip",a,{min:b,max:c})},832286:a=>{e.jb("Clip",a,void 0)},832338:(a,b)=>{e.jb("Elu",a,{alpha:b})},832396:a=>{e.jb("Gelu",a,void 0)},832448:a=>{e.jb("Relu",a,void 0)},832500:(a,b)=>{e.jb("LeakyRelu",a,{alpha:b})},832564:(a,b)=>{e.jb("ThresholdedRelu",a,{alpha:b})},832634:(a,b)=>{e.jb("Cast",a,{to:b})},832692:a=>{e.jb("Add",a,void 0)},832743:a=>{e.jb("Sub",a,void 0)},832794:a=>{e.jb("Mul",a,void 0)},832845:a=> +{e.jb("Div",a,void 0)},832896:a=>{e.jb("Pow",a,void 0)},832947:a=>{e.jb("Equal",a,void 0)},833E3:a=>{e.jb("Greater",a,void 0)},833055:a=>{e.jb("GreaterOrEqual",a,void 0)},833117:a=>{e.jb("Less",a,void 0)},833169:a=>{e.jb("LessOrEqual",a,void 0)},833228:(a,b,c,d,f)=>{e.jb("ReduceMean",a,{keepDims:!!b,noopWithEmptyAxes:!!c,axes:d?Array.from(H().subarray(Number(d)>>>0,Number(f)>>>0)):[]})},833403:(a,b,c,d,f)=>{e.jb("ReduceMax",a,{keepDims:!!b,noopWithEmptyAxes:!!c,axes:d?Array.from(H().subarray(Number(d)>>> +0,Number(f)>>>0)):[]})},833577:(a,b,c,d,f)=>{e.jb("ReduceMin",a,{keepDims:!!b,noopWithEmptyAxes:!!c,axes:d?Array.from(H().subarray(Number(d)>>>0,Number(f)>>>0)):[]})},833751:(a,b,c,d,f)=>{e.jb("ReduceProd",a,{keepDims:!!b,noopWithEmptyAxes:!!c,axes:d?Array.from(H().subarray(Number(d)>>>0,Number(f)>>>0)):[]})},833926:(a,b,c,d,f)=>{e.jb("ReduceSum",a,{keepDims:!!b,noopWithEmptyAxes:!!c,axes:d?Array.from(H().subarray(Number(d)>>>0,Number(f)>>>0)):[]})},834100:(a,b,c,d,f)=>{e.jb("ReduceL1",a,{keepDims:!!b, +noopWithEmptyAxes:!!c,axes:d?Array.from(H().subarray(Number(d)>>>0,Number(f)>>>0)):[]})},834273:(a,b,c,d,f)=>{e.jb("ReduceL2",a,{keepDims:!!b,noopWithEmptyAxes:!!c,axes:d?Array.from(H().subarray(Number(d)>>>0,Number(f)>>>0)):[]})},834446:(a,b,c,d,f)=>{e.jb("ReduceLogSum",a,{keepDims:!!b,noopWithEmptyAxes:!!c,axes:d?Array.from(H().subarray(Number(d)>>>0,Number(f)>>>0)):[]})},834623:(a,b,c,d,f)=>{e.jb("ReduceSumSquare",a,{keepDims:!!b,noopWithEmptyAxes:!!c,axes:d?Array.from(H().subarray(Number(d)>>> +0,Number(f)>>>0)):[]})},834803:(a,b,c,d,f)=>{e.jb("ReduceLogSumExp",a,{keepDims:!!b,noopWithEmptyAxes:!!c,axes:d?Array.from(H().subarray(Number(d)>>>0,Number(f)>>>0)):[]})},834983:a=>{e.jb("Where",a,void 0)},835036:(a,b,c)=>{e.jb("Transpose",a,{perm:b?Array.from(H().subarray(Number(b)>>>0,Number(c)>>>0)):[]})},835160:(a,b,c,d)=>{e.jb("DepthToSpace",a,{blocksize:b,mode:M(c),format:d?"NHWC":"NCHW"})},835293:(a,b,c,d)=>{e.jb("DepthToSpace",a,{blocksize:b,mode:M(c),format:d?"NHWC":"NCHW"})},835426:(a, +b,c,d,f,g,h,l,m,p,r,u,w,y,ba)=>{e.jb("ConvTranspose",a,{format:m?"NHWC":"NCHW",autoPad:b,dilations:[c],group:d,kernelShape:[f],pads:[g,h],strides:[l],wIsConst:()=>!!D()[p>>>0],outputPadding:r?Array.from(H().subarray(Number(r)>>>0,Number(u)>>>0)):[],outputShape:w?Array.from(H().subarray(Number(w)>>>0,Number(y)>>>0)):[],activation:M(ba)})},835859:(a,b,c,d,f,g,h,l,m,p,r,u,w,y)=>{e.jb("ConvTranspose",a,{format:l?"NHWC":"NCHW",autoPad:b,dilations:Array.from(H().subarray(Number(c)>>>0,(Number(c)>>>0)+2>>> +0)),group:d,kernelShape:Array.from(H().subarray(Number(f)>>>0,(Number(f)>>>0)+2>>>0)),pads:Array.from(H().subarray(Number(g)>>>0,(Number(g)>>>0)+4>>>0)),strides:Array.from(H().subarray(Number(h)>>>0,(Number(h)>>>0)+2>>>0)),wIsConst:()=>!!D()[m>>>0],outputPadding:p?Array.from(H().subarray(Number(p)>>>0,Number(r)>>>0)):[],outputShape:u?Array.from(H().subarray(Number(u)>>>0,Number(w)>>>0)):[],activation:M(y)})},836520:(a,b,c,d,f,g,h,l,m,p,r,u,w,y,ba)=>{e.jb("ConvTranspose",a,{format:m?"NHWC":"NCHW", +autoPad:b,dilations:[c],group:d,kernelShape:[f],pads:[g,h],strides:[l],wIsConst:()=>!!D()[p>>>0],outputPadding:r?Array.from(H().subarray(Number(r)>>>0,Number(u)>>>0)):[],outputShape:w?Array.from(H().subarray(Number(w)>>>0,Number(y)>>>0)):[],activation:M(ba)})},836953:(a,b,c,d,f,g,h,l,m,p,r,u,w,y)=>{e.jb("ConvTranspose",a,{format:l?"NHWC":"NCHW",autoPad:b,dilations:Array.from(H().subarray(Number(c)>>>0,(Number(c)>>>0)+2>>>0)),group:d,kernelShape:Array.from(H().subarray(Number(f)>>>0,(Number(f)>>>0)+ +2>>>0)),pads:Array.from(H().subarray(Number(g)>>>0,(Number(g)>>>0)+4>>>0)),strides:Array.from(H().subarray(Number(h)>>>0,(Number(h)>>>0)+2>>>0)),wIsConst:()=>!!D()[m>>>0],outputPadding:p?Array.from(H().subarray(Number(p)>>>0,Number(r)>>>0)):[],outputShape:u?Array.from(H().subarray(Number(u)>>>0,Number(w)>>>0)):[],activation:M(y)})},837614:(a,b)=>{e.jb("GlobalAveragePool",a,{format:b?"NHWC":"NCHW"})},837705:(a,b,c,d,f,g,h,l,m,p,r,u,w,y)=>{e.jb("AveragePool",a,{format:y?"NHWC":"NCHW",auto_pad:b,ceil_mode:c, +count_include_pad:d,storage_order:f,dilations:g?Array.from(H().subarray(Number(g)>>>0,Number(h)>>>0)):[],kernel_shape:l?Array.from(H().subarray(Number(l)>>>0,Number(m)>>>0)):[],pads:p?Array.from(H().subarray(Number(p)>>>0,Number(r)>>>0)):[],strides:u?Array.from(H().subarray(Number(u)>>>0,Number(w)>>>0)):[]})},838184:(a,b)=>{e.jb("GlobalAveragePool",a,{format:b?"NHWC":"NCHW"})},838275:(a,b,c,d,f,g,h,l,m,p,r,u,w,y)=>{e.jb("AveragePool",a,{format:y?"NHWC":"NCHW",auto_pad:b,ceil_mode:c,count_include_pad:d, +storage_order:f,dilations:g?Array.from(H().subarray(Number(g)>>>0,Number(h)>>>0)):[],kernel_shape:l?Array.from(H().subarray(Number(l)>>>0,Number(m)>>>0)):[],pads:p?Array.from(H().subarray(Number(p)>>>0,Number(r)>>>0)):[],strides:u?Array.from(H().subarray(Number(u)>>>0,Number(w)>>>0)):[]})},838754:(a,b)=>{e.jb("GlobalMaxPool",a,{format:b?"NHWC":"NCHW"})},838841:(a,b,c,d,f,g,h,l,m,p,r,u,w,y)=>{e.jb("MaxPool",a,{format:y?"NHWC":"NCHW",auto_pad:b,ceil_mode:c,count_include_pad:d,storage_order:f,dilations:g? +Array.from(H().subarray(Number(g)>>>0,Number(h)>>>0)):[],kernel_shape:l?Array.from(H().subarray(Number(l)>>>0,Number(m)>>>0)):[],pads:p?Array.from(H().subarray(Number(p)>>>0,Number(r)>>>0)):[],strides:u?Array.from(H().subarray(Number(u)>>>0,Number(w)>>>0)):[]})},839316:(a,b)=>{e.jb("GlobalMaxPool",a,{format:b?"NHWC":"NCHW"})},839403:(a,b,c,d,f,g,h,l,m,p,r,u,w,y)=>{e.jb("MaxPool",a,{format:y?"NHWC":"NCHW",auto_pad:b,ceil_mode:c,count_include_pad:d,storage_order:f,dilations:g?Array.from(H().subarray(Number(g)>>> +0,Number(h)>>>0)):[],kernel_shape:l?Array.from(H().subarray(Number(l)>>>0,Number(m)>>>0)):[],pads:p?Array.from(H().subarray(Number(p)>>>0,Number(r)>>>0)):[],strides:u?Array.from(H().subarray(Number(u)>>>0,Number(w)>>>0)):[]})},839878:(a,b,c,d,f)=>{e.jb("Gemm",a,{alpha:b,beta:c,transA:d,transB:f})},839982:a=>{e.jb("MatMul",a,void 0)},840036:(a,b,c,d)=>{e.jb("ArgMax",a,{keepDims:!!b,selectLastIndex:!!c,axis:d})},840144:(a,b,c,d)=>{e.jb("ArgMin",a,{keepDims:!!b,selectLastIndex:!!c,axis:d})},840252:(a, +b)=>{e.jb("Softmax",a,{axis:b})},840315:(a,b)=>{e.jb("Concat",a,{axis:b})},840375:(a,b,c,d,f)=>{e.jb("Split",a,{axis:b,numOutputs:c,splitSizes:d?Array.from(H().subarray(Number(d)>>>0,Number(f)>>>0)):[]})},840531:a=>{e.jb("Expand",a,void 0)},840585:(a,b)=>{e.jb("Gather",a,{axis:Number(b)})},840656:(a,b)=>{e.jb("GatherElements",a,{axis:Number(b)})},840735:(a,b)=>{e.jb("GatherND",a,{batch_dims:Number(b)})},840814:(a,b,c,d,f,g,h,l,m,p,r)=>{e.jb("Resize",a,{antialias:b,axes:c?Array.from(H().subarray(Number(c)>>> +0,Number(d)>>>0)):[],coordinateTransformMode:M(f),cubicCoeffA:g,excludeOutside:h,extrapolationValue:l,keepAspectRatioPolicy:M(m),mode:M(p),nearestMode:M(r)})},841176:(a,b,c,d,f,g,h)=>{e.jb("Slice",a,{starts:b?Array.from(H().subarray(Number(b)>>>0,Number(c)>>>0)):[],ends:d?Array.from(H().subarray(Number(d)>>>0,Number(f)>>>0)):[],axes:g?Array.from(H().subarray(Number(g)>>>0,Number(h)>>>0)):[]})},841440:a=>{e.jb("Tile",a,void 0)},841492:(a,b,c)=>{e.jb("InstanceNormalization",a,{epsilon:b,format:c?"NHWC": +"NCHW"})},841606:(a,b,c)=>{e.jb("InstanceNormalization",a,{epsilon:b,format:c?"NHWC":"NCHW"})},841720:a=>{e.jb("Range",a,void 0)},841773:(a,b)=>{e.jb("Einsum",a,{equation:M(b)})},841854:(a,b,c,d,f)=>{e.jb("Pad",a,{mode:b,value:c,pads:d?Array.from(H().subarray(Number(d)>>>0,Number(f)>>>0)):[]})},841997:(a,b,c,d,f,g)=>{e.jb("BatchNormalization",a,{epsilon:b,momentum:c,spatial:!!f,trainingMode:!!d,format:g?"NHWC":"NCHW"})},842166:(a,b,c,d,f,g)=>{e.jb("BatchNormalization",a,{epsilon:b,momentum:c,spatial:!!f, +trainingMode:!!d,format:g?"NHWC":"NCHW"})},842335:(a,b,c)=>{e.jb("CumSum",a,{exclusive:Number(b),reverse:Number(c)})},842432:(a,b,c)=>{e.jb("DequantizeLinear",a,{axis:b,blockSize:c})},842522:(a,b,c,d,f)=>{e.jb("GridSample",a,{align_corners:b,mode:M(c),padding_mode:M(d),format:f?"NHWC":"NCHW"})},842692:(a,b,c,d,f)=>{e.jb("GridSample",a,{align_corners:b,mode:M(c),padding_mode:M(d),format:f?"NHWC":"NCHW"})},842862:(a,b)=>{e.jb("ScatterND",a,{reduction:M(b)})},842947:(a,b,c,d,f,g,h,l,m)=>{e.jb("Attention", +a,{numHeads:b,isUnidirectional:c,maskFilterValue:d,scale:f,doRotary:g,qkvHiddenSizes:h?Array.from(H().subarray(Number(l)>>>0,Number(l)+h>>>0)):[],pastPresentShareBuffer:!!m})},843219:a=>{e.jb("BiasAdd",a,void 0)},843274:a=>{e.jb("BiasSplitGelu",a,void 0)},843335:a=>{e.jb("FastGelu",a,void 0)},843391:(a,b,c,d,f,g,h,l,m,p,r,u,w,y,ba,Vd)=>{e.jb("Conv",a,{format:u?"NHWC":"NCHW",auto_pad:b,dilations:c?Array.from(H().subarray(Number(c)>>>0,Number(d)>>>0)):[],group:f,kernel_shape:g?Array.from(H().subarray(Number(g)>>> +0,Number(h)>>>0)):[],pads:l?Array.from(H().subarray(Number(l)>>>0,Number(m)>>>0)):[],strides:p?Array.from(H().subarray(Number(p)>>>0,Number(r)>>>0)):[],w_is_const:()=>!!D()[Number(w)>>>0],activation:M(y),activation_params:ba?Array.from(Ga().subarray(Number(ba)>>>0,Number(Vd)>>>0)):[]})},843975:a=>{e.jb("Gelu",a,void 0)},844027:(a,b,c,d,f,g,h,l,m)=>{e.jb("GroupQueryAttention",a,{numHeads:b,kvNumHeads:c,scale:d,softcap:f,doRotary:g,rotaryInterleaved:h,smoothSoftmax:l,localWindowSize:m})},844244:(a, +b,c,d)=>{e.jb("LayerNormalization",a,{axis:b,epsilon:c,simplified:!!d})},844355:(a,b,c,d)=>{e.jb("LayerNormalization",a,{axis:b,epsilon:c,simplified:!!d})},844466:(a,b,c,d,f,g)=>{e.jb("MatMulNBits",a,{k:b,n:c,accuracyLevel:d,bits:f,blockSize:g})},844593:(a,b,c,d,f,g)=>{e.jb("MultiHeadAttention",a,{numHeads:b,isUnidirectional:c,maskFilterValue:d,scale:f,doRotary:g})},844752:(a,b)=>{e.jb("QuickGelu",a,{alpha:b})},844816:(a,b,c,d,f)=>{e.jb("RotaryEmbedding",a,{interleaved:!!b,numHeads:c,rotaryEmbeddingDim:d, +scale:f})},844955:(a,b,c)=>{e.jb("SkipLayerNormalization",a,{epsilon:b,simplified:!!c})},845057:(a,b,c)=>{e.jb("SkipLayerNormalization",a,{epsilon:b,simplified:!!c})},845159:(a,b,c,d)=>{e.jb("GatherBlockQuantized",a,{gatherAxis:b,quantizeAxis:c,blockSize:d})},845280:a=>{e.Zb(a)},845314:(a,b)=>e.ac(Number(a),Number(b),e.Fb.dc,e.Fb.errors)};function db(a,b,c){return Ec(async()=>{await e.Xb(Number(a),Number(b),Number(c))})}function cb(){return"undefined"!==typeof wasmOffsetConverter} +class Fc{name="ExitStatus";constructor(a){this.message=`Program terminated with exit(${a})`;this.status=a}} +var Gc=a=>{a.terminate();a.onmessage=()=>{}},Hc=[],Lc=a=>{0==N.length&&(Ic(),Jc(N[0]));var b=N.pop();if(!b)return 6;Kc.push(b);O[a.Ab]=b;b.Ab=a.Ab;var c={Bb:"run",fc:a.ec,Hb:a.Hb,Ab:a.Ab};n&&b.unref();b.postMessage(c,a.Mb);return 0},P=0,Q=(a,b,...c)=>{for(var d=2*c.length,f=Mc(),g=Nc(8*d),h=g>>>3,l=0;l>>0]=m)}a=Oc(a,0,d,g,b);Pc(f);return a}; +function Cc(a){if(q)return Q(0,1,a);wa=a;if(!(0{wa=a;if(q)throw Qc(a),"unwind";Cc(a)},N=[],Kc=[],Rc=[],O={};function Sc(){for(var a=e.numThreads-1;a--;)Ic();Hc.unshift(()=>{Ua++;Tc(()=>Wa())})}var Vc=a=>{var b=a.Ab;delete O[b];N.push(a);Kc.splice(Kc.indexOf(a),1);a.Ab=0;Uc(b)};function Na(){Rc.forEach(a=>a())} +var Jc=a=>new Promise(b=>{a.onmessage=g=>{g=g.data;var h=g.Bb;if(g.Gb&&g.Gb!=Ka()){var l=O[g.Gb];l?l.postMessage(g,g.Mb):x(`Internal error! Worker sent a message "${h}" to target pthread ${g.Gb}, but that thread no longer exists!`)}else if("checkMailbox"===h)Ra();else if("spawnThread"===h)Lc(g);else if("cleanupThread"===h)Vc(O[g.hc]);else if("loaded"===h)a.loaded=!0,n&&!a.Ab&&a.unref(),b(a);else if("alert"===h)alert(`Thread ${g.ic}: ${g.text}`);else if("setimmediate"===g.target)a.postMessage(g);else if("callHandler"=== +h)e[g.Qb](...g.args);else h&&x(`worker sent an unknown command ${h}`)};a.onerror=g=>{x(`${"worker sent an error!"} ${g.filename}:${g.lineno}: ${g.message}`);throw g;};n&&(a.on("message",g=>a.onmessage({data:g})),a.on("error",g=>a.onerror(g)));var c=[],d=[],f;for(f of d)e.propertyIsEnumerable(f)&&c.push(f);a.postMessage({Bb:"load",Rb:c,kc:z,lc:va})});function Tc(a){q?a():Promise.all(N.map(Jc)).then(a)} +function Ic(){var a=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});N.push(a)}var La=a=>{E();var b=I()[a+52>>>2>>>0];a=I()[a+56>>>2>>>0];Wc(b,b-a);Pc(b)},Qa=(a,b)=>{P=0;a=Xc(a,b);0>>=0;var d=new Zc(a);b>>>=0;c>>>=0;I()[d.Ib+16>>>2>>>0]=0;I()[d.Ib+4>>>2>>>0]=b;I()[d.Ib+8>>>2>>>0]=c;$c=a;ad++;throw $c;} +function bd(a,b,c,d){return q?Q(2,1,a,b,c,d):fb(a,b,c,d)}function fb(a,b,c,d){a>>>=0;b>>>=0;c>>>=0;d>>>=0;if("undefined"==typeof SharedArrayBuffer)return 6;var f=[];if(q&&0===f.length)return bd(a,b,c,d);a={ec:c,Ab:a,Hb:d,Mb:f};return q?(a.Bb="spawnThread",postMessage(a,f),0):Lc(a)} +var cd="undefined"!=typeof TextDecoder?new TextDecoder:void 0,dd=(a,b=0,c=NaN)=>{b>>>=0;var d=b+c;for(c=b;a[c]&&!(c>=d);)++c;if(16f?d+=String.fromCharCode(f):(f-=65536,d+=String.fromCharCode(55296|f>>10,56320| +f&1023))}}else d+=String.fromCharCode(f)}return d},M=(a,b)=>(a>>>=0)?dd(F(),a,b):"";function gb(a,b,c){return q?Q(3,1,a,b,c):0}function hb(a,b){if(q)return Q(4,1,a,b)} +var ed=a=>{for(var b=0,c=0;c=d?b++:2047>=d?b+=2:55296<=d&&57343>=d?(b+=4,++c):b+=3}return b},fd=(a,b,c)=>{var d=F();b>>>=0;if(0=h){var l=a.charCodeAt(++g);h=65536+((h&1023)<<10)|l&1023}if(127>=h){if(b>=c)break;d[b++>>>0]=h}else{if(2047>=h){if(b+1>=c)break;d[b++>>>0]=192|h>>6}else{if(65535>=h){if(b+2>=c)break;d[b++>>>0]=224|h>>12}else{if(b+3>=c)break;d[b++>>>0]=240|h>>18; +d[b++>>>0]=128|h>>12&63}d[b++>>>0]=128|h>>6&63}d[b++>>>0]=128|h&63}}d[b>>>0]=0;a=b-f}else a=0;return a};function ib(a,b){if(q)return Q(5,1,a,b)}function jb(a,b,c){if(q)return Q(6,1,a,b,c)}function kb(a,b,c){return q?Q(7,1,a,b,c):0}function lb(a,b){if(q)return Q(8,1,a,b)}function mb(a,b,c){if(q)return Q(9,1,a,b,c)}function nb(a,b,c,d){if(q)return Q(10,1,a,b,c,d)}function ob(a,b,c,d){if(q)return Q(11,1,a,b,c,d)}function pb(a,b,c,d){if(q)return Q(12,1,a,b,c,d)}function qb(a){if(q)return Q(13,1,a)} +function rb(a,b){if(q)return Q(14,1,a,b)}function sb(a,b,c){if(q)return Q(15,1,a,b,c)}var tb=()=>L(""),gd,R=a=>{for(var b="";F()[a>>>0];)b+=gd[F()[a++>>>0]];return b},hd={},jd={},kd={},S;function ld(a,b,c={}){var d=b.name;if(!a)throw new S(`type "${d}" must have a positive integer typeid pointer`);if(jd.hasOwnProperty(a)){if(c.Sb)return;throw new S(`Cannot register type '${d}' twice`);}jd[a]=b;delete kd[a];hd.hasOwnProperty(a)&&(b=hd[a],delete hd[a],b.forEach(f=>f()))} +function T(a,b,c={}){return ld(a,b,c)}var md=(a,b,c)=>{switch(b){case 1:return c?d=>D()[d>>>0]:d=>F()[d>>>0];case 2:return c?d=>G()[d>>>1>>>0]:d=>Fa()[d>>>1>>>0];case 4:return c?d=>H()[d>>>2>>>0]:d=>I()[d>>>2>>>0];case 8:return c?d=>C[d>>>3]:d=>Da[d>>>3];default:throw new TypeError(`invalid integer width (${b}): ${a}`);}}; +function ub(a,b,c){a>>>=0;c>>>=0;b=R(b>>>0);T(a,{name:b,fromWireType:d=>d,toWireType:function(d,f){if("bigint"!=typeof f&&"number"!=typeof f)throw null===f?f="null":(d=typeof f,f="object"===d||"array"===d||"function"===d?f.toString():""+f),new TypeError(`Cannot convert "${f}" to ${this.name}`);"number"==typeof f&&(f=BigInt(f));return f},Cb:U,readValueFromPointer:md(b,c,-1==b.indexOf("u")),Db:null})}var U=8; +function vb(a,b,c,d){a>>>=0;b=R(b>>>0);T(a,{name:b,fromWireType:function(f){return!!f},toWireType:function(f,g){return g?c:d},Cb:U,readValueFromPointer:function(f){return this.fromWireType(F()[f>>>0])},Db:null})}var nd=[],V=[];function Ob(a){a>>>=0;9{if(!a)throw new S("Cannot use deleted val. handle = "+a);return V[a]},X=a=>{switch(a){case void 0:return 2;case null:return 4;case !0:return 6;case !1:return 8;default:const b=nd.pop()||V.length;V[b]=a;V[b+1]=1;return b}};function od(a){return this.fromWireType(I()[a>>>2>>>0])}var pd={name:"emscripten::val",fromWireType:a=>{var b=W(a);Ob(a);return b},toWireType:(a,b)=>X(b),Cb:U,readValueFromPointer:od,Db:null};function wb(a){return T(a>>>0,pd)} +var qd=(a,b)=>{switch(b){case 4:return function(c){return this.fromWireType(Ga()[c>>>2>>>0])};case 8:return function(c){return this.fromWireType(J()[c>>>3>>>0])};default:throw new TypeError(`invalid float width (${b}): ${a}`);}};function xb(a,b,c){a>>>=0;c>>>=0;b=R(b>>>0);T(a,{name:b,fromWireType:d=>d,toWireType:(d,f)=>f,Cb:U,readValueFromPointer:qd(b,c),Db:null})} +function yb(a,b,c,d,f){a>>>=0;c>>>=0;b=R(b>>>0);-1===f&&(f=4294967295);f=l=>l;if(0===d){var g=32-8*c;f=l=>l<>>g}var h=b.includes("unsigned")?function(l,m){return m>>>0}:function(l,m){return m};T(a,{name:b,fromWireType:f,toWireType:h,Cb:U,readValueFromPointer:md(b,c,0!==d),Db:null})} +function zb(a,b,c){function d(g){var h=I()[g>>>2>>>0];g=I()[g+4>>>2>>>0];return new f(D().buffer,g,h)}a>>>=0;var f=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][b];c=R(c>>>0);T(a,{name:c,fromWireType:d,Cb:U,readValueFromPointer:d},{Sb:!0})} +function Ab(a,b){a>>>=0;b=R(b>>>0);T(a,{name:b,fromWireType:function(c){for(var d=I()[c>>>2>>>0],f=c+4,g,h=f,l=0;l<=d;++l){var m=f+l;if(l==d||0==F()[m>>>0])h=M(h,m-h),void 0===g?g=h:(g+=String.fromCharCode(0),g+=h),h=m+1}Y(c);return g},toWireType:function(c,d){d instanceof ArrayBuffer&&(d=new Uint8Array(d));var f="string"==typeof d;if(!(f||d instanceof Uint8Array||d instanceof Uint8ClampedArray||d instanceof Int8Array))throw new S("Cannot pass non-string to std::string");var g=f?ed(d):d.length;var h= +rd(4+g+1),l=h+4;I()[h>>>2>>>0]=g;if(f)fd(d,l,g+1);else if(f)for(f=0;f>>0]=m}else for(f=0;f>>0]=d[f];null!==c&&c.push(Y,h);return h},Cb:U,readValueFromPointer:od,Db(c){Y(c)}})} +var sd="undefined"!=typeof TextDecoder?new TextDecoder("utf-16le"):void 0,td=(a,b)=>{var c=a>>1;for(var d=c+b/2;!(c>=d)&&Fa()[c>>>0];)++c;c<<=1;if(32=b/2);++d){var f=G()[a+2*d>>>1>>>0];if(0==f)break;c+=String.fromCharCode(f)}return c},ud=(a,b,c)=>{c??=2147483647;if(2>c)return 0;c-=2;var d=b;c=c<2*a.length?c/2:a.length;for(var f=0;f>>1>>>0]=g;b+=2}G()[b>>>1>>>0]=0;return b-d},vd=a=>2*a.length,wd=(a,b)=>{for(var c= +0,d="";!(c>=b/4);){var f=H()[a+4*c>>>2>>>0];if(0==f)break;++c;65536<=f?(f-=65536,d+=String.fromCharCode(55296|f>>10,56320|f&1023)):d+=String.fromCharCode(f)}return d},xd=(a,b,c)=>{b>>>=0;c??=2147483647;if(4>c)return 0;var d=b;c=d+c-4;for(var f=0;f=g){var h=a.charCodeAt(++f);g=65536+((g&1023)<<10)|h&1023}H()[b>>>2>>>0]=g;b+=4;if(b+4>c)break}H()[b>>>2>>>0]=0;return b-d},yd=a=>{for(var b=0,c=0;c= +d&&++c;b+=4}return b}; +function Bb(a,b,c){a>>>=0;b>>>=0;c>>>=0;c=R(c);if(2===b){var d=td;var f=ud;var g=vd;var h=l=>Fa()[l>>>1>>>0]}else 4===b&&(d=wd,f=xd,g=yd,h=l=>I()[l>>>2>>>0]);T(a,{name:c,fromWireType:l=>{for(var m=I()[l>>>2>>>0],p,r=l+4,u=0;u<=m;++u){var w=l+4+u*b;if(u==m||0==h(w))r=d(r,w-r),void 0===p?p=r:(p+=String.fromCharCode(0),p+=r),r=w+b}Y(l);return p},toWireType:(l,m)=>{if("string"!=typeof m)throw new S(`Cannot pass non-string to C++ string type ${c}`);var p=g(m),r=rd(4+p+b);I()[r>>>2>>>0]=p/b;f(m,r+4,p+b); +null!==l&&l.push(Y,r);return r},Cb:U,readValueFromPointer:od,Db(l){Y(l)}})}function Cb(a,b){a>>>=0;b=R(b>>>0);T(a,{Tb:!0,name:b,Cb:0,fromWireType:()=>{},toWireType:()=>{}})}function Db(a){Ma(a>>>0,!k,1,!ea,131072,!1);Na()}var zd=a=>{if(!A)try{if(a(),!(0>>=0;"function"===typeof Atomics.jc&&(Atomics.jc(H(),a>>>2,a).value.then(Ra),a+=128,Atomics.store(H(),a>>>2,1))}var Ra=()=>{var a=Ka();a&&(Oa(a),zd(Ad))};function Eb(a,b){a>>>=0;a==b>>>0?setTimeout(Ra):q?postMessage({Gb:a,Bb:"checkMailbox"}):(a=O[a])&&a.postMessage({Bb:"checkMailbox"})}var Bd=[];function Fb(a,b,c,d,f){b>>>=0;d/=2;Bd.length=d;c=f>>>0>>>3;for(f=0;f>>0];return(b?Dc[b]:Cd[a])(...Bd)}var Gb=()=>{P=0}; +function Hb(a){a>>>=0;q?postMessage({Bb:"cleanupThread",hc:a}):Vc(O[a])}function Ib(a){n&&O[a>>>0].ref()}var Ed=(a,b)=>{var c=jd[a];if(void 0===c)throw a=Dd(a),c=R(a),Y(a),new S(`${b} has unknown type ${c}`);return c},Fd=(a,b,c)=>{var d=[];a=a.toWireType(d,c);d.length&&(I()[b>>>2>>>0]=X(d));return a};function Jb(a,b,c){b>>>=0;c>>>=0;a=W(a>>>0);b=Ed(b,"emval::as");return Fd(b,c,a)}function Kb(a,b){b>>>=0;a=W(a>>>0);b=Ed(b,"emval::as");return b.toWireType(null,a)}var Gd=a=>{try{a()}catch(b){L(b)}}; +function Hd(){var a=K,b={};for(let [c,d]of Object.entries(a))b[c]="function"==typeof d?(...f)=>{Id.push(c);try{return d(...f)}finally{A||(Id.pop(),t&&1===Z&&0===Id.length&&(Z=0,P+=1,Gd(Jd),"undefined"!=typeof Fibers&&Fibers.rc()))}}:d;return b}var Z=0,t=null,Kd=0,Id=[],Ld={},Md={},Nd=0,Od=null,Pd=[];function ia(){return new Promise((a,b)=>{Od={resolve:a,reject:b}})} +function Qd(){var a=rd(65548),b=a+12;I()[a>>>2>>>0]=b;I()[a+4>>>2>>>0]=b+65536;b=Id[0];var c=Ld[b];void 0===c&&(c=Nd++,Ld[b]=c,Md[c]=b);b=c;H()[a+8>>>2>>>0]=b;return a}function Rd(){var a=H()[t+8>>>2>>>0];a=K[Md[a]];--P;return a()} +function Sd(a){if(!A){if(0===Z){var b=!1,c=!1;a((d=0)=>{if(!A&&(Kd=d,b=!0,c)){Z=2;Gd(()=>Td(t));"undefined"!=typeof MainLoop&&MainLoop.Pb&&MainLoop.resume();d=!1;try{var f=Rd()}catch(l){f=l,d=!0}var g=!1;if(!t){var h=Od;h&&(Od=null,(d?h.reject:h.resolve)(f),g=!0)}if(d&&!g)throw f;}});c=!0;b||(Z=1,t=Qd(),"undefined"!=typeof MainLoop&&MainLoop.Pb&&MainLoop.pause(),Gd(()=>Ud(t)))}else 2===Z?(Z=0,Gd(Wd),Y(t),t=null,Pd.forEach(zd)):L(`invalid state: ${Z}`);return Kd}} +function Ec(a){return Sd(b=>{a().then(b)})}function Lb(a){a>>>=0;return Ec(async()=>{var b=await W(a);return X(b)})}var Xd=[];function Mb(a,b,c,d){c>>>=0;d>>>=0;a=Xd[a>>>0];b=W(b>>>0);return a(null,b,c,d)}var Yd={},Zd=a=>{var b=Yd[a];return void 0===b?R(a):b};function Nb(a,b,c,d,f){c>>>=0;d>>>=0;f>>>=0;a=Xd[a>>>0];b=W(b>>>0);c=Zd(c);return a(b,b[c],d,f)}var $d=()=>"object"==typeof globalThis?globalThis:Function("return this")(); +function Pb(a){a>>>=0;if(0===a)return X($d());a=Zd(a);return X($d()[a])}var ae=a=>{var b=Xd.length;Xd.push(a);return b},be=(a,b)=>{for(var c=Array(a),d=0;d>>2>>>0],"parameter "+d);return c},ce=(a,b)=>Object.defineProperty(b,"name",{value:a}); +function de(a){var b=Function;if(!(b instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof b} which is not a function`);var c=ce(b.name||"unknownFunctionName",function(){});c.prototype=b.prototype;c=new c;a=b.apply(c,a);return a instanceof Object?a:c} +function Qb(a,b,c){b=be(a,b>>>0);var d=b.shift();a--;var f="return function (obj, func, destructorsRef, args) {\n",g=0,h=[];0===c&&h.push("obj");for(var l=["retType"],m=[d],p=0;pr.name).join(", ")}) => ${d.name}>`;return ae(ce(c,a))}function Rb(a){a=Zd(a>>>0);return X(e[a])}function Sb(a,b){b>>>=0;a=W(a>>>0);b=W(b);return X(a[b])}function Tb(a){a>>>=0;9>>0);for(var b=Array(a.length),c=0;c>>0))}function Xb(){return X({})} +function Yb(a){a>>>=0;for(var b=W(a);b.length;){var c=b.pop();b.pop()(c)}Ob(a)}function Zb(a,b,c){b>>>=0;c>>>=0;a=W(a>>>0);b=W(b);c=W(c);a[b]=c}function $b(a,b){b>>>=0;a=Ed(a>>>0,"_emval_take_value");a=a.readValueFromPointer(b);return X(a)} +function ac(a,b){a=-9007199254740992>a||9007199254740992>>=0;a=new Date(1E3*a);H()[b>>>2>>>0]=a.getUTCSeconds();H()[b+4>>>2>>>0]=a.getUTCMinutes();H()[b+8>>>2>>>0]=a.getUTCHours();H()[b+12>>>2>>>0]=a.getUTCDate();H()[b+16>>>2>>>0]=a.getUTCMonth();H()[b+20>>>2>>>0]=a.getUTCFullYear()-1900;H()[b+24>>>2>>>0]=a.getUTCDay();a=(a.getTime()-Date.UTC(a.getUTCFullYear(),0,1,0,0,0,0))/864E5|0;H()[b+28>>>2>>>0]=a} +var ee=a=>0===a%4&&(0!==a%100||0===a%400),fe=[0,31,60,91,121,152,182,213,244,274,305,335],ge=[0,31,59,90,120,151,181,212,243,273,304,334]; +function bc(a,b){a=-9007199254740992>a||9007199254740992>>=0;a=new Date(1E3*a);H()[b>>>2>>>0]=a.getSeconds();H()[b+4>>>2>>>0]=a.getMinutes();H()[b+8>>>2>>>0]=a.getHours();H()[b+12>>>2>>>0]=a.getDate();H()[b+16>>>2>>>0]=a.getMonth();H()[b+20>>>2>>>0]=a.getFullYear()-1900;H()[b+24>>>2>>>0]=a.getDay();var c=(ee(a.getFullYear())?fe:ge)[a.getMonth()]+a.getDate()-1|0;H()[b+28>>>2>>>0]=c;H()[b+36>>>2>>>0]=-(60*a.getTimezoneOffset());c=(new Date(a.getFullYear(),6,1)).getTimezoneOffset(); +var d=(new Date(a.getFullYear(),0,1)).getTimezoneOffset();a=(c!=d&&a.getTimezoneOffset()==Math.min(d,c))|0;H()[b+32>>>2>>>0]=a} +function cc(a){a>>>=0;var b=new Date(H()[a+20>>>2>>>0]+1900,H()[a+16>>>2>>>0],H()[a+12>>>2>>>0],H()[a+8>>>2>>>0],H()[a+4>>>2>>>0],H()[a>>>2>>>0],0),c=H()[a+32>>>2>>>0],d=b.getTimezoneOffset(),f=(new Date(b.getFullYear(),6,1)).getTimezoneOffset(),g=(new Date(b.getFullYear(),0,1)).getTimezoneOffset(),h=Math.min(g,f);0>c?H()[a+32>>>2>>>0]=Number(f!=g&&h==d):0>>2>>>0]=b.getDay();c=(ee(b.getFullYear())?fe:ge)[b.getMonth()]+ +b.getDate()-1|0;H()[a+28>>>2>>>0]=c;H()[a>>>2>>>0]=b.getSeconds();H()[a+4>>>2>>>0]=b.getMinutes();H()[a+8>>>2>>>0]=b.getHours();H()[a+12>>>2>>>0]=b.getDate();H()[a+16>>>2>>>0]=b.getMonth();H()[a+20>>>2>>>0]=b.getYear();a=b.getTime();return BigInt(isNaN(a)?-1:a/1E3)}function dc(a,b,c,d,f,g,h){return q?Q(16,1,a,b,c,d,f,g,h):-52}function ec(a,b,c,d,f,g){if(q)return Q(17,1,a,b,c,d,f,g)}var he={},pc=()=>performance.timeOrigin+performance.now(); +function fc(a,b){if(q)return Q(18,1,a,b);he[a]&&(clearTimeout(he[a].id),delete he[a]);if(!b)return 0;var c=setTimeout(()=>{delete he[a];zd(()=>ie(a,performance.timeOrigin+performance.now()))},b);he[a]={id:c,qc:b};return 0} +function gc(a,b,c,d){a>>>=0;b>>>=0;c>>>=0;d>>>=0;var f=(new Date).getFullYear(),g=(new Date(f,0,1)).getTimezoneOffset();f=(new Date(f,6,1)).getTimezoneOffset();var h=Math.max(g,f);I()[a>>>2>>>0]=60*h;H()[b>>>2>>>0]=Number(g!=f);b=l=>{var m=Math.abs(l);return`UTC${0<=l?"-":"+"}${String(Math.floor(m/60)).padStart(2,"0")}${String(m%60).padStart(2,"0")}`};a=b(g);b=b(f);fDate.now(),je=1; +function hc(a,b,c){if(!(0<=a&&3>=a))return 28;if(0===a)a=Date.now();else if(je)a=performance.timeOrigin+performance.now();else return 52;C[c>>>0>>>3]=BigInt(Math.round(1E6*a));return 0}var ke=[],le=(a,b)=>{ke.length=0;for(var c;c=F()[a++>>>0];){var d=105!=c;d&=112!=c;b+=d&&b%8?4:0;ke.push(112==c?I()[b>>>2>>>0]:106==c?C[b>>>3]:105==c?H()[b>>>2>>>0]:J()[b>>>3>>>0]);b+=d?8:4}return ke};function ic(a,b,c){a>>>=0;b=le(b>>>0,c>>>0);return Dc[a](...b)} +function jc(a,b,c){a>>>=0;b=le(b>>>0,c>>>0);return Dc[a](...b)}var kc=()=>{};function mc(a,b){return x(M(a>>>0,b>>>0))}var nc=()=>{P+=1;throw"unwind";};function oc(){return 4294901760}var qc=()=>n?require("os").cpus().length:navigator.hardwareConcurrency;function rc(){L("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER");return 0} +function sc(a){a>>>=0;var b=F().length;if(a<=b||4294901760=c;c*=2){var d=b*(1+.2/c);d=Math.min(d,a+100663296);a:{d=(Math.min(4294901760,65536*Math.ceil(Math.max(a,d)/65536))-z.buffer.byteLength+65535)/65536|0;try{z.grow(d);E();var f=1;break a}catch(g){}f=void 0}if(f)return!0}return!1}var me=()=>{L("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER");return 0},ne={},oe=a=>{a.forEach(b=>{var c=me();c&&(ne[c]=b)})}; +function tc(){var a=Error().stack.toString().split("\n");"Error"==a[0]&&a.shift();oe(a);ne.Lb=me();ne.cc=a;return ne.Lb}function uc(a,b,c){a>>>=0;b>>>=0;if(ne.Lb==a)var d=ne.cc;else d=Error().stack.toString().split("\n"),"Error"==d[0]&&d.shift(),oe(d);for(var f=3;d[f]&&me()!=a;)++f;for(a=0;a>>2>>>0]=me();return a} +var pe={},re=()=>{if(!qe){var a={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:la||"./this.program"},b;for(b in pe)void 0===pe[b]?delete a[b]:a[b]=pe[b];var c=[];for(b in a)c.push(`${b}=${a[b]}`);qe=c}return qe},qe; +function vc(a,b){if(q)return Q(19,1,a,b);a>>>=0;b>>>=0;var c=0;re().forEach((d,f)=>{var g=b+c;f=I()[a+4*f>>>2>>>0]=g;for(g=0;g>>0]=d.charCodeAt(g);D()[f>>>0]=0;c+=d.length+1});return 0}function wc(a,b){if(q)return Q(20,1,a,b);a>>>=0;b>>>=0;var c=re();I()[a>>>2>>>0]=c.length;var d=0;c.forEach(f=>d+=f.length+1);I()[b>>>2>>>0]=d;return 0}function yc(a){return q?Q(21,1,a):52}function zc(a,b,c,d){return q?Q(22,1,a,b,c,d):52}function Ac(a,b,c,d){return q?Q(23,1,a,b,c,d):70} +var se=[null,[],[]];function Bc(a,b,c,d){if(q)return Q(24,1,a,b,c,d);b>>>=0;c>>>=0;d>>>=0;for(var f=0,g=0;g>>2>>>0],l=I()[b+4>>>2>>>0];b+=8;for(var m=0;m>>0],r=se[a];0===p||10===p?((1===a?ta:x)(dd(r)),r.length=0):r.push(p)}f+=l}I()[d>>>2>>>0]=f;return 0}q||Sc();for(var te=Array(256),ue=0;256>ue;++ue)te[ue]=String.fromCharCode(ue);gd=te;S=e.BindingError=class extends Error{constructor(a){super(a);this.name="BindingError"}}; +e.InternalError=class extends Error{constructor(a){super(a);this.name="InternalError"}};V.push(0,1,void 0,1,null,1,!0,1,!1,1);e.count_emval_handles=()=>V.length/2-5-nd.length;var Cd=[Cc,Qc,bd,gb,hb,ib,jb,kb,lb,mb,nb,ob,pb,qb,rb,sb,dc,ec,fc,vc,wc,yc,zc,Ac,Bc],bb,K; +(async function(){function a(d,f){K=d.exports;K=Hd();K=ve();Rc.push(K.ib);va=f;Wa();return K}Ua++;var b=ab();if(e.instantiateWasm)return new Promise(d=>{e.instantiateWasm(b,(f,g)=>{a(f,g);d(f.exports)})});if(q)return new Promise(d=>{Ha=f=>{var g=new WebAssembly.Instance(f,ab());d(a(g,f))}});Xa??=e.locateFile?e.locateFile?e.locateFile("ort-wasm-simd-threaded.jsep.wasm",v):v+"ort-wasm-simd-threaded.jsep.wasm":(new URL("ort-wasm-simd-threaded.jsep.wasm",import.meta.url)).href;try{var c=await $a(b); +return a(c.instance,c.module)}catch(d){return ca(d),Promise.reject(d)}})();var Dd=a=>(Dd=K.Da)(a),Pa=()=>(Pa=K.Ea)();e._OrtInit=(a,b)=>(e._OrtInit=K.Fa)(a,b);e._OrtGetLastError=(a,b)=>(e._OrtGetLastError=K.Ga)(a,b);e._OrtCreateSessionOptions=(a,b,c,d,f,g,h,l,m,p)=>(e._OrtCreateSessionOptions=K.Ha)(a,b,c,d,f,g,h,l,m,p);e._OrtAppendExecutionProvider=(a,b,c,d,f)=>(e._OrtAppendExecutionProvider=K.Ia)(a,b,c,d,f);e._OrtAddFreeDimensionOverride=(a,b,c)=>(e._OrtAddFreeDimensionOverride=K.Ja)(a,b,c); +e._OrtAddSessionConfigEntry=(a,b,c)=>(e._OrtAddSessionConfigEntry=K.Ka)(a,b,c);e._OrtReleaseSessionOptions=a=>(e._OrtReleaseSessionOptions=K.La)(a);e._OrtCreateSession=(a,b,c)=>(e._OrtCreateSession=K.Ma)(a,b,c);e._OrtReleaseSession=a=>(e._OrtReleaseSession=K.Na)(a);e._OrtGetInputOutputCount=(a,b,c)=>(e._OrtGetInputOutputCount=K.Oa)(a,b,c);e._OrtGetInputOutputMetadata=(a,b,c,d)=>(e._OrtGetInputOutputMetadata=K.Pa)(a,b,c,d);e._OrtFree=a=>(e._OrtFree=K.Qa)(a); +e._OrtCreateTensor=(a,b,c,d,f,g)=>(e._OrtCreateTensor=K.Ra)(a,b,c,d,f,g);e._OrtGetTensorData=(a,b,c,d,f)=>(e._OrtGetTensorData=K.Sa)(a,b,c,d,f);e._OrtReleaseTensor=a=>(e._OrtReleaseTensor=K.Ta)(a);e._OrtCreateRunOptions=(a,b,c,d)=>(e._OrtCreateRunOptions=K.Ua)(a,b,c,d);e._OrtAddRunConfigEntry=(a,b,c)=>(e._OrtAddRunConfigEntry=K.Va)(a,b,c);e._OrtReleaseRunOptions=a=>(e._OrtReleaseRunOptions=K.Wa)(a);e._OrtCreateBinding=a=>(e._OrtCreateBinding=K.Xa)(a); +e._OrtBindInput=(a,b,c)=>(e._OrtBindInput=K.Ya)(a,b,c);e._OrtBindOutput=(a,b,c,d)=>(e._OrtBindOutput=K.Za)(a,b,c,d);e._OrtClearBoundOutputs=a=>(e._OrtClearBoundOutputs=K._a)(a);e._OrtReleaseBinding=a=>(e._OrtReleaseBinding=K.$a)(a);e._OrtRunWithBinding=(a,b,c,d,f)=>(e._OrtRunWithBinding=K.ab)(a,b,c,d,f);e._OrtRun=(a,b,c,d,f,g,h,l)=>(e._OrtRun=K.bb)(a,b,c,d,f,g,h,l);e._OrtEndProfiling=a=>(e._OrtEndProfiling=K.cb)(a);e._JsepOutput=(a,b,c)=>(e._JsepOutput=K.db)(a,b,c); +e._JsepGetNodeName=a=>(e._JsepGetNodeName=K.eb)(a); +var Ka=()=>(Ka=K.fb)(),Y=e._free=a=>(Y=e._free=K.gb)(a),rd=e._malloc=a=>(rd=e._malloc=K.hb)(a),Ma=(a,b,c,d,f,g)=>(Ma=K.kb)(a,b,c,d,f,g),Sa=()=>(Sa=K.lb)(),Oc=(a,b,c,d,f)=>(Oc=K.mb)(a,b,c,d,f),Uc=a=>(Uc=K.nb)(a),Yc=a=>(Yc=K.ob)(a),ie=(a,b)=>(ie=K.pb)(a,b),Ad=()=>(Ad=K.qb)(),Wc=(a,b)=>(Wc=K.rb)(a,b),Pc=a=>(Pc=K.sb)(a),Nc=a=>(Nc=K.tb)(a),Mc=()=>(Mc=K.ub)(),Xc=e.dynCall_ii=(a,b)=>(Xc=e.dynCall_ii=K.vb)(a,b),Ud=a=>(Ud=K.wb)(a),Jd=()=>(Jd=K.xb)(),Td=a=>(Td=K.yb)(a),Wd=()=>(Wd=K.zb)(); +function ve(){var a=K;a=Object.assign({},a);var b=d=>f=>d(f)>>>0,c=d=>()=>d()>>>0;a.Da=b(a.Da);a.fb=c(a.fb);a.hb=b(a.hb);a.tb=b(a.tb);a.ub=c(a.ub);a.__cxa_get_exception_ptr=b(a.__cxa_get_exception_ptr);return a}e.stackSave=()=>Mc();e.stackRestore=a=>Pc(a);e.stackAlloc=a=>Nc(a); +e.setValue=function(a,b,c="i8"){c.endsWith("*")&&(c="*");switch(c){case "i1":D()[a>>>0]=b;break;case "i8":D()[a>>>0]=b;break;case "i16":G()[a>>>1>>>0]=b;break;case "i32":H()[a>>>2>>>0]=b;break;case "i64":C[a>>>3]=BigInt(b);break;case "float":Ga()[a>>>2>>>0]=b;break;case "double":J()[a>>>3>>>0]=b;break;case "*":I()[a>>>2>>>0]=b;break;default:L(`invalid type for setValue: ${c}`)}}; +e.getValue=function(a,b="i8"){b.endsWith("*")&&(b="*");switch(b){case "i1":return D()[a>>>0];case "i8":return D()[a>>>0];case "i16":return G()[a>>>1>>>0];case "i32":return H()[a>>>2>>>0];case "i64":return C[a>>>3];case "float":return Ga()[a>>>2>>>0];case "double":return J()[a>>>3>>>0];case "*":return I()[a>>>2>>>0];default:L(`invalid type for getValue: ${b}`)}};e.UTF8ToString=M;e.stringToUTF8=fd;e.lengthBytesUTF8=ed; +function we(){if(0 that + * navigates to chrome://browser/content/assistant/embedding-worker.html. + * The page loads embedding-worker.bundle.js (packaged; no CDN). This script + * relays CustomEvents between the page and chrome (messageManager). + */ + +/* eslint-env mozilla/frame-script */ + +console.log("[EmbedFrameScript] Frame script loaded, readyState:", content.document.readyState); + +let embedListenersAttached = false; + +function setupPageListeners() { + if (embedListenersAttached) { + return; + } + embedListenersAttached = true; + console.log("[EmbedFrameScript] Setting up page listeners"); + + content.document.addEventListener( + "embed-result", + function (event) { + var detail = event.detail; + console.log("[EmbedFrameScript] Got embed-result, id:", detail.id); + sendAsyncMessage("EmbedResponse", { + id: detail.id, + embedding: detail.embedding, + }); + }, + false, + true + ); + + content.document.addEventListener( + "embed-error", + function (event) { + var detail = event.detail; + console.log("[EmbedFrameScript] Got embed-error, id:", detail.id); + sendAsyncMessage("EmbedResponse", { + id: detail.id, + error: detail.error, + }); + }, + false, + true + ); + + content.document.addEventListener( + "embed-ready", + function () { + console.log("[EmbedFrameScript] Got embed-ready from page!"); + sendAsyncMessage("EmbedWorkerReady", {}); + }, + false, + true + ); + + content.document.addEventListener( + "embed-model-loaded", + function () { + console.log("[EmbedFrameScript] Got embed-model-loaded"); + sendAsyncMessage("EmbedModelLoaded", {}); + }, + false, + true + ); +} + +addMessageListener("EmbedRequest", function (msg) { + console.log("[EmbedFrameScript] Relaying EmbedRequest, id:", msg.data.id); + var event = new content.CustomEvent("embed-request", { + detail: Cu.cloneInto( + { id: msg.data.id, text: msg.data.text }, + content + ), + }); + content.document.dispatchEvent(event); +}); + +function init() { + console.log("[EmbedFrameScript] Initializing..."); + setupPageListeners(); +} + +if ( + content.document.readyState === "complete" || + content.document.readyState === "interactive" +) { + init(); +} else { + addEventListener( + "DOMContentLoaded", + function () { + console.log("[EmbedFrameScript] DOMContentLoaded fired"); + init(); + }, + { once: true } + ); +} diff --git a/browser/base/content/assistant/embedding-worker.bundle.js b/browser/base/content/assistant/embedding-worker.bundle.js new file mode 100644 index 0000000000000..5eec7d244a9d2 --- /dev/null +++ b/browser/base/content/assistant/embedding-worker.bundle.js @@ -0,0 +1,48096 @@ +"use strict"; +(() => { + var __defProp = Object.defineProperty; + var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { + get: (a, b) => (typeof require !== "undefined" ? require : a)[b] + }) : x)(function(x) { + if (typeof require !== "undefined") return require.apply(this, arguments); + throw Error('Dynamic require of "' + x + '" is not supported'); + }); + var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); + }; + + // node_modules/onnxruntime-common/dist/esm/index.js + var esm_exports = {}; + __export(esm_exports, { + InferenceSession: () => InferenceSession2, + TRACE: () => TRACE, + TRACE_FUNC_BEGIN: () => TRACE_FUNC_BEGIN, + TRACE_FUNC_END: () => TRACE_FUNC_END, + Tensor: () => Tensor2, + env: () => env2, + registerBackend: () => registerBackend + }); + + // node_modules/onnxruntime-common/dist/esm/backend-impl.js + var backends = /* @__PURE__ */ new Map(); + var backendsSortedByPriority = []; + var registerBackend = (name, backend, priority) => { + if (backend && typeof backend.init === "function" && typeof backend.createInferenceSessionHandler === "function") { + const currentBackend = backends.get(name); + if (currentBackend === void 0) { + backends.set(name, { backend, priority }); + } else if (currentBackend.priority > priority) { + return; + } else if (currentBackend.priority === priority) { + if (currentBackend.backend !== backend) { + throw new Error(`cannot register backend "${name}" using priority ${priority}`); + } + } + if (priority >= 0) { + const i = backendsSortedByPriority.indexOf(name); + if (i !== -1) { + backendsSortedByPriority.splice(i, 1); + } + for (let i2 = 0; i2 < backendsSortedByPriority.length; i2++) { + if (backends.get(backendsSortedByPriority[i2]).priority <= priority) { + backendsSortedByPriority.splice(i2, 0, name); + return; + } + } + backendsSortedByPriority.push(name); + } + return; + } + throw new TypeError("not a valid backend"); + }; + var tryResolveAndInitializeBackend = async (backendName) => { + const backendInfo = backends.get(backendName); + if (!backendInfo) { + return "backend not found."; + } + if (backendInfo.initialized) { + return backendInfo.backend; + } else if (backendInfo.aborted) { + return backendInfo.error; + } else { + const isInitializing = !!backendInfo.initPromise; + try { + if (!isInitializing) { + backendInfo.initPromise = backendInfo.backend.init(backendName); + } + await backendInfo.initPromise; + backendInfo.initialized = true; + return backendInfo.backend; + } catch (e) { + if (!isInitializing) { + backendInfo.error = `${e}`; + backendInfo.aborted = true; + } + return backendInfo.error; + } finally { + delete backendInfo.initPromise; + } + } + }; + var resolveBackendAndExecutionProviders = async (options) => { + const eps = options.executionProviders || []; + const backendHints = eps.map((i) => typeof i === "string" ? i : i.name); + const backendNames = backendHints.length === 0 ? backendsSortedByPriority : backendHints; + let backend; + const errors = []; + const availableBackendNames = /* @__PURE__ */ new Set(); + for (const backendName of backendNames) { + const resolveResult = await tryResolveAndInitializeBackend(backendName); + if (typeof resolveResult === "string") { + errors.push({ name: backendName, err: resolveResult }); + } else { + if (!backend) { + backend = resolveResult; + } + if (backend === resolveResult) { + availableBackendNames.add(backendName); + } + } + } + if (!backend) { + throw new Error(`no available backend found. ERR: ${errors.map((e) => `[${e.name}] ${e.err}`).join(", ")}`); + } + for (const { name, err } of errors) { + if (backendHints.includes(name)) { + console.warn(`removing requested execution provider "${name}" from session options because it is not available: ${err}`); + } + } + const filteredEps = eps.filter((i) => availableBackendNames.has(typeof i === "string" ? i : i.name)); + return [ + backend, + new Proxy(options, { + get: (target, prop) => { + if (prop === "executionProviders") { + return filteredEps; + } + return Reflect.get(target, prop); + } + }) + ]; + }; + + // node_modules/onnxruntime-common/dist/esm/version.js + var version = "1.21.0"; + + // node_modules/onnxruntime-common/dist/esm/env-impl.js + var logLevelValue = "warning"; + var env = { + wasm: {}, + webgl: {}, + webgpu: {}, + versions: { common: version }, + set logLevel(value) { + if (value === void 0) { + return; + } + if (typeof value !== "string" || ["verbose", "info", "warning", "error", "fatal"].indexOf(value) === -1) { + throw new Error(`Unsupported logging level: ${value}`); + } + logLevelValue = value; + }, + get logLevel() { + return logLevelValue; + } + }; + Object.defineProperty(env, "logLevel", { enumerable: true }); + + // node_modules/onnxruntime-common/dist/esm/env.js + var env2 = env; + + // node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js + var tensorToDataURL = (tensor, options) => { + const canvas = typeof document !== "undefined" ? document.createElement("canvas") : new OffscreenCanvas(1, 1); + canvas.width = tensor.dims[3]; + canvas.height = tensor.dims[2]; + const pixels2DContext = canvas.getContext("2d"); + if (pixels2DContext != null) { + let width; + let height; + if (options?.tensorLayout !== void 0 && options.tensorLayout === "NHWC") { + width = tensor.dims[2]; + height = tensor.dims[3]; + } else { + width = tensor.dims[3]; + height = tensor.dims[2]; + } + const inputformat = options?.format !== void 0 ? options.format : "RGB"; + const norm = options?.norm; + let normMean; + let normBias; + if (norm === void 0 || norm.mean === void 0) { + normMean = [255, 255, 255, 255]; + } else { + if (typeof norm.mean === "number") { + normMean = [norm.mean, norm.mean, norm.mean, norm.mean]; + } else { + normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 0]; + if (norm.mean[3] !== void 0) { + normMean[3] = norm.mean[3]; + } + } + } + if (norm === void 0 || norm.bias === void 0) { + normBias = [0, 0, 0, 0]; + } else { + if (typeof norm.bias === "number") { + normBias = [norm.bias, norm.bias, norm.bias, norm.bias]; + } else { + normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0]; + if (norm.bias[3] !== void 0) { + normBias[3] = norm.bias[3]; + } + } + } + const stride = height * width; + let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1; + if (inputformat === "RGBA") { + rTensorPointer = 0; + gTensorPointer = stride; + bTensorPointer = stride * 2; + aTensorPointer = stride * 3; + } else if (inputformat === "RGB") { + rTensorPointer = 0; + gTensorPointer = stride; + bTensorPointer = stride * 2; + } else if (inputformat === "RBG") { + rTensorPointer = 0; + bTensorPointer = stride; + gTensorPointer = stride * 2; + } + for (let i = 0; i < height; i++) { + for (let j = 0; j < width; j++) { + const R = (tensor.data[rTensorPointer++] - normBias[0]) * normMean[0]; + const G = (tensor.data[gTensorPointer++] - normBias[1]) * normMean[1]; + const B = (tensor.data[bTensorPointer++] - normBias[2]) * normMean[2]; + const A = aTensorPointer === -1 ? 255 : (tensor.data[aTensorPointer++] - normBias[3]) * normMean[3]; + pixels2DContext.fillStyle = "rgba(" + R + "," + G + "," + B + "," + A + ")"; + pixels2DContext.fillRect(j, i, 1, 1); + } + } + if ("toDataURL" in canvas) { + return canvas.toDataURL(); + } else { + throw new Error("toDataURL is not supported"); + } + } else { + throw new Error("Can not access image data"); + } + }; + var tensorToImageData = (tensor, options) => { + const pixels2DContext = typeof document !== "undefined" ? document.createElement("canvas").getContext("2d") : new OffscreenCanvas(1, 1).getContext("2d"); + let image; + if (pixels2DContext != null) { + let width; + let height; + let channels; + if (options?.tensorLayout !== void 0 && options.tensorLayout === "NHWC") { + width = tensor.dims[2]; + height = tensor.dims[1]; + channels = tensor.dims[3]; + } else { + width = tensor.dims[3]; + height = tensor.dims[2]; + channels = tensor.dims[1]; + } + const inputformat = options !== void 0 ? options.format !== void 0 ? options.format : "RGB" : "RGB"; + const norm = options?.norm; + let normMean; + let normBias; + if (norm === void 0 || norm.mean === void 0) { + normMean = [255, 255, 255, 255]; + } else { + if (typeof norm.mean === "number") { + normMean = [norm.mean, norm.mean, norm.mean, norm.mean]; + } else { + normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 255]; + if (norm.mean[3] !== void 0) { + normMean[3] = norm.mean[3]; + } + } + } + if (norm === void 0 || norm.bias === void 0) { + normBias = [0, 0, 0, 0]; + } else { + if (typeof norm.bias === "number") { + normBias = [norm.bias, norm.bias, norm.bias, norm.bias]; + } else { + normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0]; + if (norm.bias[3] !== void 0) { + normBias[3] = norm.bias[3]; + } + } + } + const stride = height * width; + if (options !== void 0) { + if (options.format !== void 0 && channels === 4 && options.format !== "RGBA" || channels === 3 && options.format !== "RGB" && options.format !== "BGR") { + throw new Error("Tensor format doesn't match input tensor dims"); + } + } + const step = 4; + let rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3; + let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1; + if (inputformat === "RGBA") { + rTensorPointer = 0; + gTensorPointer = stride; + bTensorPointer = stride * 2; + aTensorPointer = stride * 3; + } else if (inputformat === "RGB") { + rTensorPointer = 0; + gTensorPointer = stride; + bTensorPointer = stride * 2; + } else if (inputformat === "RBG") { + rTensorPointer = 0; + bTensorPointer = stride; + gTensorPointer = stride * 2; + } + image = pixels2DContext.createImageData(width, height); + for (let i = 0; i < height * width; rImagePointer += step, gImagePointer += step, bImagePointer += step, aImagePointer += step, i++) { + image.data[rImagePointer] = (tensor.data[rTensorPointer++] - normBias[0]) * normMean[0]; + image.data[gImagePointer] = (tensor.data[gTensorPointer++] - normBias[1]) * normMean[1]; + image.data[bImagePointer] = (tensor.data[bTensorPointer++] - normBias[2]) * normMean[2]; + image.data[aImagePointer] = aTensorPointer === -1 ? 255 : (tensor.data[aTensorPointer++] - normBias[3]) * normMean[3]; + } + } else { + throw new Error("Can not access image data"); + } + return image; + }; + + // node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js + var bufferToTensor = (buffer, options) => { + if (buffer === void 0) { + throw new Error("Image buffer must be defined"); + } + if (options.height === void 0 || options.width === void 0) { + throw new Error("Image height and width must be defined"); + } + if (options.tensorLayout === "NHWC") { + throw new Error("NHWC Tensor layout is not supported yet"); + } + const { height, width } = options; + const norm = options.norm ?? { mean: 255, bias: 0 }; + let normMean; + let normBias; + if (typeof norm.mean === "number") { + normMean = [norm.mean, norm.mean, norm.mean, norm.mean]; + } else { + normMean = [norm.mean[0], norm.mean[1], norm.mean[2], norm.mean[3] ?? 255]; + } + if (typeof norm.bias === "number") { + normBias = [norm.bias, norm.bias, norm.bias, norm.bias]; + } else { + normBias = [norm.bias[0], norm.bias[1], norm.bias[2], norm.bias[3] ?? 0]; + } + const inputformat = options.format !== void 0 ? options.format : "RGBA"; + const outputformat = options.tensorFormat !== void 0 ? options.tensorFormat !== void 0 ? options.tensorFormat : "RGB" : "RGB"; + const stride = height * width; + const float32Data = outputformat === "RGBA" ? new Float32Array(stride * 4) : new Float32Array(stride * 3); + let step = 4, rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3; + let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1; + if (inputformat === "RGB") { + step = 3; + rImagePointer = 0; + gImagePointer = 1; + bImagePointer = 2; + aImagePointer = -1; + } + if (outputformat === "RGBA") { + aTensorPointer = stride * 3; + } else if (outputformat === "RBG") { + rTensorPointer = 0; + bTensorPointer = stride; + gTensorPointer = stride * 2; + } else if (outputformat === "BGR") { + bTensorPointer = 0; + gTensorPointer = stride; + rTensorPointer = stride * 2; + } + for (let i = 0; i < stride; i++, rImagePointer += step, bImagePointer += step, gImagePointer += step, aImagePointer += step) { + float32Data[rTensorPointer++] = (buffer[rImagePointer] + normBias[0]) / normMean[0]; + float32Data[gTensorPointer++] = (buffer[gImagePointer] + normBias[1]) / normMean[1]; + float32Data[bTensorPointer++] = (buffer[bImagePointer] + normBias[2]) / normMean[2]; + if (aTensorPointer !== -1 && aImagePointer !== -1) { + float32Data[aTensorPointer++] = (buffer[aImagePointer] + normBias[3]) / normMean[3]; + } + } + const outputTensor = outputformat === "RGBA" ? new Tensor("float32", float32Data, [1, 4, height, width]) : new Tensor("float32", float32Data, [1, 3, height, width]); + return outputTensor; + }; + var tensorFromImage = async (image, options) => { + const isHTMLImageEle = typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement; + const isImageDataEle = typeof ImageData !== "undefined" && image instanceof ImageData; + const isImageBitmap = typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap; + const isString = typeof image === "string"; + let data; + let bufferToTensorOptions = options ?? {}; + const createCanvas = () => { + if (typeof document !== "undefined") { + return document.createElement("canvas"); + } else if (typeof OffscreenCanvas !== "undefined") { + return new OffscreenCanvas(1, 1); + } else { + throw new Error("Canvas is not supported"); + } + }; + const createCanvasContext = (canvas) => { + if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) { + return canvas.getContext("2d"); + } else if (canvas instanceof OffscreenCanvas) { + return canvas.getContext("2d"); + } else { + return null; + } + }; + if (isHTMLImageEle) { + const canvas = createCanvas(); + canvas.width = image.width; + canvas.height = image.height; + const pixels2DContext = createCanvasContext(canvas); + if (pixels2DContext != null) { + let height = image.height; + let width = image.width; + if (options !== void 0 && options.resizedHeight !== void 0 && options.resizedWidth !== void 0) { + height = options.resizedHeight; + width = options.resizedWidth; + } + if (options !== void 0) { + bufferToTensorOptions = options; + if (options.tensorFormat !== void 0) { + throw new Error("Image input config format must be RGBA for HTMLImageElement"); + } else { + bufferToTensorOptions.tensorFormat = "RGBA"; + } + bufferToTensorOptions.height = height; + bufferToTensorOptions.width = width; + } else { + bufferToTensorOptions.tensorFormat = "RGBA"; + bufferToTensorOptions.height = height; + bufferToTensorOptions.width = width; + } + pixels2DContext.drawImage(image, 0, 0); + data = pixels2DContext.getImageData(0, 0, width, height).data; + } else { + throw new Error("Can not access image data"); + } + } else if (isImageDataEle) { + let height; + let width; + if (options !== void 0 && options.resizedWidth !== void 0 && options.resizedHeight !== void 0) { + height = options.resizedHeight; + width = options.resizedWidth; + } else { + height = image.height; + width = image.width; + } + if (options !== void 0) { + bufferToTensorOptions = options; + } + bufferToTensorOptions.format = "RGBA"; + bufferToTensorOptions.height = height; + bufferToTensorOptions.width = width; + if (options !== void 0) { + const tempCanvas = createCanvas(); + tempCanvas.width = width; + tempCanvas.height = height; + const pixels2DContext = createCanvasContext(tempCanvas); + if (pixels2DContext != null) { + pixels2DContext.putImageData(image, 0, 0); + data = pixels2DContext.getImageData(0, 0, width, height).data; + } else { + throw new Error("Can not access image data"); + } + } else { + data = image.data; + } + } else if (isImageBitmap) { + if (options === void 0) { + throw new Error("Please provide image config with format for Imagebitmap"); + } + const canvas = createCanvas(); + canvas.width = image.width; + canvas.height = image.height; + const pixels2DContext = createCanvasContext(canvas); + if (pixels2DContext != null) { + const height = image.height; + const width = image.width; + pixels2DContext.drawImage(image, 0, 0, width, height); + data = pixels2DContext.getImageData(0, 0, width, height).data; + bufferToTensorOptions.height = height; + bufferToTensorOptions.width = width; + return bufferToTensor(data, bufferToTensorOptions); + } else { + throw new Error("Can not access image data"); + } + } else if (isString) { + return new Promise((resolve, reject) => { + const canvas = createCanvas(); + const context = createCanvasContext(canvas); + if (!image || !context) { + return reject(); + } + const newImage = new Image(); + newImage.crossOrigin = "Anonymous"; + newImage.src = image; + newImage.onload = () => { + canvas.width = newImage.width; + canvas.height = newImage.height; + context.drawImage(newImage, 0, 0, canvas.width, canvas.height); + const img = context.getImageData(0, 0, canvas.width, canvas.height); + bufferToTensorOptions.height = canvas.height; + bufferToTensorOptions.width = canvas.width; + resolve(bufferToTensor(img.data, bufferToTensorOptions)); + }; + }); + } else { + throw new Error("Input data provided is not supported - aborted tensor creation"); + } + if (data !== void 0) { + return bufferToTensor(data, bufferToTensorOptions); + } else { + throw new Error("Input data provided is not supported - aborted tensor creation"); + } + }; + var tensorFromTexture = (texture, options) => { + const { width, height, download, dispose } = options; + const dims = [1, height, width, 4]; + return new Tensor({ location: "texture", type: "float32", texture, dims, download, dispose }); + }; + var tensorFromGpuBuffer = (gpuBuffer, options) => { + const { dataType, dims, download, dispose } = options; + return new Tensor({ location: "gpu-buffer", type: dataType ?? "float32", gpuBuffer, dims, download, dispose }); + }; + var tensorFromMLTensor = (mlTensor, options) => { + const { dataType, dims, download, dispose } = options; + return new Tensor({ location: "ml-tensor", type: dataType ?? "float32", mlTensor, dims, download, dispose }); + }; + var tensorFromPinnedBuffer = (type, buffer, dims) => new Tensor({ location: "cpu-pinned", type, data: buffer, dims: dims ?? [buffer.length] }); + + // node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js + var NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP = /* @__PURE__ */ new Map([ + ["float32", Float32Array], + ["uint8", Uint8Array], + ["int8", Int8Array], + ["uint16", Uint16Array], + ["int16", Int16Array], + ["int32", Int32Array], + ["bool", Uint8Array], + ["float64", Float64Array], + ["uint32", Uint32Array], + ["int4", Uint8Array], + ["uint4", Uint8Array] + ]); + var NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP = /* @__PURE__ */ new Map([ + [Float32Array, "float32"], + [Uint8Array, "uint8"], + [Int8Array, "int8"], + [Uint16Array, "uint16"], + [Int16Array, "int16"], + [Int32Array, "int32"], + [Float64Array, "float64"], + [Uint32Array, "uint32"] + ]); + var isTypedArrayChecked = false; + var checkTypedArray = () => { + if (!isTypedArrayChecked) { + isTypedArrayChecked = true; + const isBigInt64ArrayAvailable = typeof BigInt64Array !== "undefined" && BigInt64Array.from; + const isBigUint64ArrayAvailable = typeof BigUint64Array !== "undefined" && BigUint64Array.from; + const Float16Array2 = globalThis.Float16Array; + const isFloat16ArrayAvailable = typeof Float16Array2 !== "undefined" && Float16Array2.from; + if (isBigInt64ArrayAvailable) { + NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("int64", BigInt64Array); + NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array, "int64"); + } + if (isBigUint64ArrayAvailable) { + NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("uint64", BigUint64Array); + NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array, "uint64"); + } + if (isFloat16ArrayAvailable) { + NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("float16", Float16Array2); + NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(Float16Array2, "float16"); + } else { + NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("float16", Uint16Array); + } + } + }; + + // node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js + var calculateSize = (dims) => { + let size = 1; + for (let i = 0; i < dims.length; i++) { + const dim = dims[i]; + if (typeof dim !== "number" || !Number.isSafeInteger(dim)) { + throw new TypeError(`dims[${i}] must be an integer, got: ${dim}`); + } + if (dim < 0) { + throw new RangeError(`dims[${i}] must be a non-negative integer, got: ${dim}`); + } + size *= dim; + } + return size; + }; + var tensorReshape = (tensor, dims) => { + switch (tensor.location) { + case "cpu": + return new Tensor(tensor.type, tensor.data, dims); + case "cpu-pinned": + return new Tensor({ + location: "cpu-pinned", + data: tensor.data, + type: tensor.type, + dims + }); + case "texture": + return new Tensor({ + location: "texture", + texture: tensor.texture, + type: tensor.type, + dims + }); + case "gpu-buffer": + return new Tensor({ + location: "gpu-buffer", + gpuBuffer: tensor.gpuBuffer, + type: tensor.type, + dims + }); + case "ml-tensor": + return new Tensor({ + location: "ml-tensor", + mlTensor: tensor.mlTensor, + type: tensor.type, + dims + }); + default: + throw new Error(`tensorReshape: tensor location ${tensor.location} is not supported`); + } + }; + + // node_modules/onnxruntime-common/dist/esm/tensor-impl.js + var Tensor = class { + /** + * implementation. + */ + constructor(arg0, arg1, arg2) { + checkTypedArray(); + let type; + let dims; + if (typeof arg0 === "object" && "location" in arg0) { + this.dataLocation = arg0.location; + type = arg0.type; + dims = arg0.dims; + switch (arg0.location) { + case "cpu-pinned": { + const expectedTypedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(type); + if (!expectedTypedArrayConstructor) { + throw new TypeError(`unsupported type "${type}" to create tensor from pinned buffer`); + } + if (!(arg0.data instanceof expectedTypedArrayConstructor)) { + throw new TypeError(`buffer should be of type ${expectedTypedArrayConstructor.name}`); + } + this.cpuData = arg0.data; + break; + } + case "texture": { + if (type !== "float32") { + throw new TypeError(`unsupported type "${type}" to create tensor from texture`); + } + this.gpuTextureData = arg0.texture; + this.downloader = arg0.download; + this.disposer = arg0.dispose; + break; + } + case "gpu-buffer": { + if (type !== "float32" && type !== "float16" && type !== "int32" && type !== "int64" && type !== "uint32" && type !== "uint8" && type !== "bool" && type !== "uint4" && type !== "int4") { + throw new TypeError(`unsupported type "${type}" to create tensor from gpu buffer`); + } + this.gpuBufferData = arg0.gpuBuffer; + this.downloader = arg0.download; + this.disposer = arg0.dispose; + break; + } + case "ml-tensor": { + if (type !== "float32" && type !== "float16" && type !== "int32" && type !== "int64" && type !== "uint32" && type !== "uint64" && type !== "int8" && type !== "uint8" && type !== "bool" && type !== "uint4" && type !== "int4") { + throw new TypeError(`unsupported type "${type}" to create tensor from MLTensor`); + } + this.mlTensorData = arg0.mlTensor; + this.downloader = arg0.download; + this.disposer = arg0.dispose; + break; + } + default: + throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`); + } + } else { + let data; + let maybeDims; + if (typeof arg0 === "string") { + type = arg0; + maybeDims = arg2; + if (arg0 === "string") { + if (!Array.isArray(arg1)) { + throw new TypeError("A string tensor's data must be a string array."); + } + data = arg1; + } else { + const typedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(arg0); + if (typedArrayConstructor === void 0) { + throw new TypeError(`Unsupported tensor type: ${arg0}.`); + } + if (Array.isArray(arg1)) { + if (arg0 === "float16" && typedArrayConstructor === Uint16Array || arg0 === "uint4" || arg0 === "int4") { + throw new TypeError(`Creating a ${arg0} tensor from number array is not supported. Please use ${typedArrayConstructor.name} as data.`); + } else if (arg0 === "uint64" || arg0 === "int64") { + data = typedArrayConstructor.from(arg1, BigInt); + } else { + data = typedArrayConstructor.from(arg1); + } + } else if (arg1 instanceof typedArrayConstructor) { + data = arg1; + } else if (arg1 instanceof Uint8ClampedArray) { + if (arg0 === "uint8") { + data = Uint8Array.from(arg1); + } else { + throw new TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`); + } + } else if (arg0 === "float16" && arg1 instanceof Uint16Array && typedArrayConstructor !== Uint16Array) { + data = new globalThis.Float16Array(arg1.buffer, arg1.byteOffset, arg1.length); + } else { + throw new TypeError(`A ${type} tensor's data must be type of ${typedArrayConstructor}`); + } + } + } else { + maybeDims = arg1; + if (Array.isArray(arg0)) { + if (arg0.length === 0) { + throw new TypeError("Tensor type cannot be inferred from an empty array."); + } + const firstElementType = typeof arg0[0]; + if (firstElementType === "string") { + type = "string"; + data = arg0; + } else if (firstElementType === "boolean") { + type = "bool"; + data = Uint8Array.from(arg0); + } else { + throw new TypeError(`Invalid element type of data array: ${firstElementType}.`); + } + } else if (arg0 instanceof Uint8ClampedArray) { + type = "uint8"; + data = Uint8Array.from(arg0); + } else { + const mappedType = NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(arg0.constructor); + if (mappedType === void 0) { + throw new TypeError(`Unsupported type for tensor data: ${arg0.constructor}.`); + } + type = mappedType; + data = arg0; + } + } + if (maybeDims === void 0) { + maybeDims = [data.length]; + } else if (!Array.isArray(maybeDims)) { + throw new TypeError("A tensor's dims must be a number array"); + } + dims = maybeDims; + this.cpuData = data; + this.dataLocation = "cpu"; + } + const size = calculateSize(dims); + if (this.cpuData && size !== this.cpuData.length) { + if ((type === "uint4" || type === "int4") && Math.ceil(size / 2) === this.cpuData.length) { + } else { + throw new Error(`Tensor's size(${size}) does not match data length(${this.cpuData.length}).`); + } + } + this.type = type; + this.dims = dims; + this.size = size; + } + // #endregion + // #region factory + static async fromImage(image, options) { + return tensorFromImage(image, options); + } + static fromTexture(texture, options) { + return tensorFromTexture(texture, options); + } + static fromGpuBuffer(gpuBuffer, options) { + return tensorFromGpuBuffer(gpuBuffer, options); + } + static fromMLTensor(mlTensor, options) { + return tensorFromMLTensor(mlTensor, options); + } + static fromPinnedBuffer(type, buffer, dims) { + return tensorFromPinnedBuffer(type, buffer, dims); + } + // #endregion + // #region conversions + toDataURL(options) { + return tensorToDataURL(this, options); + } + toImageData(options) { + return tensorToImageData(this, options); + } + // #endregion + // #region properties + get data() { + this.ensureValid(); + if (!this.cpuData) { + throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly."); + } + return this.cpuData; + } + get location() { + return this.dataLocation; + } + get texture() { + this.ensureValid(); + if (!this.gpuTextureData) { + throw new Error("The data is not stored as a WebGL texture."); + } + return this.gpuTextureData; + } + get gpuBuffer() { + this.ensureValid(); + if (!this.gpuBufferData) { + throw new Error("The data is not stored as a WebGPU buffer."); + } + return this.gpuBufferData; + } + get mlTensor() { + this.ensureValid(); + if (!this.mlTensorData) { + throw new Error("The data is not stored as a WebNN MLTensor."); + } + return this.mlTensorData; + } + // #endregion + // #region methods + async getData(releaseData) { + this.ensureValid(); + switch (this.dataLocation) { + case "cpu": + case "cpu-pinned": + return this.data; + case "texture": + case "gpu-buffer": + case "ml-tensor": { + if (!this.downloader) { + throw new Error("The current tensor is not created with a specified data downloader."); + } + if (this.isDownloading) { + throw new Error("The current tensor is being downloaded."); + } + try { + this.isDownloading = true; + const data = await this.downloader(); + this.downloader = void 0; + this.dataLocation = "cpu"; + this.cpuData = data; + if (releaseData && this.disposer) { + this.disposer(); + this.disposer = void 0; + } + return data; + } finally { + this.isDownloading = false; + } + } + default: + throw new Error(`cannot get data from location: ${this.dataLocation}`); + } + } + dispose() { + if (this.isDownloading) { + throw new Error("The current tensor is being downloaded."); + } + if (this.disposer) { + this.disposer(); + this.disposer = void 0; + } + this.cpuData = void 0; + this.gpuTextureData = void 0; + this.gpuBufferData = void 0; + this.mlTensorData = void 0; + this.downloader = void 0; + this.isDownloading = void 0; + this.dataLocation = "none"; + } + // #endregion + // #region tensor utilities + ensureValid() { + if (this.dataLocation === "none") { + throw new Error("The tensor is disposed."); + } + } + reshape(dims) { + this.ensureValid(); + if (this.downloader || this.disposer) { + throw new Error("Cannot reshape a tensor that owns GPU resource."); + } + return tensorReshape(this, dims); + } + }; + + // node_modules/onnxruntime-common/dist/esm/tensor.js + var Tensor2 = Tensor; + + // node_modules/onnxruntime-common/dist/esm/trace.js + var TRACE = (deviceType, label) => { + if (typeof env.trace === "undefined" ? !env.wasm.trace : !env.trace) { + return; + } + console.timeStamp(`${deviceType}::ORT::${label}`); + }; + var TRACE_FUNC = (msg, extraMsg) => { + const stack = new Error().stack?.split(/\r\n|\r|\n/g) || []; + let hasTraceFunc = false; + for (let i = 0; i < stack.length; i++) { + if (hasTraceFunc && !stack[i].includes("TRACE_FUNC")) { + let label = `FUNC_${msg}::${stack[i].trim().split(" ")[1]}`; + if (extraMsg) { + label += `::${extraMsg}`; + } + TRACE("CPU", label); + return; + } + if (stack[i].includes("TRACE_FUNC")) { + hasTraceFunc = true; + } + } + }; + var TRACE_FUNC_BEGIN = (extraMsg) => { + if (typeof env.trace === "undefined" ? !env.wasm.trace : !env.trace) { + return; + } + TRACE_FUNC("BEGIN", extraMsg); + }; + var TRACE_FUNC_END = (extraMsg) => { + if (typeof env.trace === "undefined" ? !env.wasm.trace : !env.trace) { + return; + } + TRACE_FUNC("END", extraMsg); + }; + + // node_modules/onnxruntime-common/dist/esm/inference-session-impl.js + var InferenceSession = class _InferenceSession { + constructor(handler) { + this.handler = handler; + } + async run(feeds, arg1, arg2) { + TRACE_FUNC_BEGIN(); + const fetches = {}; + let options = {}; + if (typeof feeds !== "object" || feeds === null || feeds instanceof Tensor2 || Array.isArray(feeds)) { + throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values."); + } + let isFetchesEmpty = true; + if (typeof arg1 === "object") { + if (arg1 === null) { + throw new TypeError("Unexpected argument[1]: cannot be null."); + } + if (arg1 instanceof Tensor2) { + throw new TypeError("'fetches' cannot be a Tensor"); + } + if (Array.isArray(arg1)) { + if (arg1.length === 0) { + throw new TypeError("'fetches' cannot be an empty array."); + } + isFetchesEmpty = false; + for (const name of arg1) { + if (typeof name !== "string") { + throw new TypeError("'fetches' must be a string array or an object."); + } + if (this.outputNames.indexOf(name) === -1) { + throw new RangeError(`'fetches' contains invalid output name: ${name}.`); + } + fetches[name] = null; + } + if (typeof arg2 === "object" && arg2 !== null) { + options = arg2; + } else if (typeof arg2 !== "undefined") { + throw new TypeError("'options' must be an object."); + } + } else { + let isFetches = false; + const arg1Keys = Object.getOwnPropertyNames(arg1); + for (const name of this.outputNames) { + if (arg1Keys.indexOf(name) !== -1) { + const v = arg1[name]; + if (v === null || v instanceof Tensor2) { + isFetches = true; + isFetchesEmpty = false; + fetches[name] = v; + } + } + } + if (isFetches) { + if (typeof arg2 === "object" && arg2 !== null) { + options = arg2; + } else if (typeof arg2 !== "undefined") { + throw new TypeError("'options' must be an object."); + } + } else { + options = arg1; + } + } + } else if (typeof arg1 !== "undefined") { + throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'."); + } + for (const name of this.inputNames) { + if (typeof feeds[name] === "undefined") { + throw new Error(`input '${name}' is missing in 'feeds'.`); + } + } + if (isFetchesEmpty) { + for (const name of this.outputNames) { + fetches[name] = null; + } + } + const results = await this.handler.run(feeds, fetches, options); + const returnValue = {}; + for (const key in results) { + if (Object.hasOwnProperty.call(results, key)) { + const result = results[key]; + if (result instanceof Tensor2) { + returnValue[key] = result; + } else { + returnValue[key] = new Tensor2(result.type, result.data, result.dims); + } + } + } + TRACE_FUNC_END(); + return returnValue; + } + async release() { + return this.handler.dispose(); + } + static async create(arg0, arg1, arg2, arg3) { + TRACE_FUNC_BEGIN(); + let filePathOrUint8Array; + let options = {}; + if (typeof arg0 === "string") { + filePathOrUint8Array = arg0; + if (typeof arg1 === "object" && arg1 !== null) { + options = arg1; + } else if (typeof arg1 !== "undefined") { + throw new TypeError("'options' must be an object."); + } + } else if (arg0 instanceof Uint8Array) { + filePathOrUint8Array = arg0; + if (typeof arg1 === "object" && arg1 !== null) { + options = arg1; + } else if (typeof arg1 !== "undefined") { + throw new TypeError("'options' must be an object."); + } + } else if (arg0 instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && arg0 instanceof SharedArrayBuffer) { + const buffer = arg0; + let byteOffset = 0; + let byteLength = arg0.byteLength; + if (typeof arg1 === "object" && arg1 !== null) { + options = arg1; + } else if (typeof arg1 === "number") { + byteOffset = arg1; + if (!Number.isSafeInteger(byteOffset)) { + throw new RangeError("'byteOffset' must be an integer."); + } + if (byteOffset < 0 || byteOffset >= buffer.byteLength) { + throw new RangeError(`'byteOffset' is out of range [0, ${buffer.byteLength}).`); + } + byteLength = arg0.byteLength - byteOffset; + if (typeof arg2 === "number") { + byteLength = arg2; + if (!Number.isSafeInteger(byteLength)) { + throw new RangeError("'byteLength' must be an integer."); + } + if (byteLength <= 0 || byteOffset + byteLength > buffer.byteLength) { + throw new RangeError(`'byteLength' is out of range (0, ${buffer.byteLength - byteOffset}].`); + } + if (typeof arg3 === "object" && arg3 !== null) { + options = arg3; + } else if (typeof arg3 !== "undefined") { + throw new TypeError("'options' must be an object."); + } + } else if (typeof arg2 !== "undefined") { + throw new TypeError("'byteLength' must be a number."); + } + } else if (typeof arg1 !== "undefined") { + throw new TypeError("'options' must be an object."); + } + filePathOrUint8Array = new Uint8Array(buffer, byteOffset, byteLength); + } else { + throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'."); + } + const [backend, optionsWithValidatedEPs] = await resolveBackendAndExecutionProviders(options); + const handler = await backend.createInferenceSessionHandler(filePathOrUint8Array, optionsWithValidatedEPs); + TRACE_FUNC_END(); + return new _InferenceSession(handler); + } + startProfiling() { + this.handler.startProfiling(); + } + endProfiling() { + this.handler.endProfiling(); + } + get inputNames() { + return this.handler.inputNames; + } + get outputNames() { + return this.handler.outputNames; + } + }; + + // node_modules/onnxruntime-common/dist/esm/inference-session.js + var InferenceSession2 = InferenceSession; + + // node_modules/onnxruntime-web/dist/ort.bundle.min.mjs + var ort_bundle_min_exports = {}; + __export(ort_bundle_min_exports, { + InferenceSession: () => Gp, + TRACE: () => gr, + TRACE_FUNC_BEGIN: () => Re, + TRACE_FUNC_END: () => Oe, + Tensor: () => Ge, + default: () => IS, + env: () => ge, + registerBackend: () => $t + }); + var import_meta = {}; + var zn = Object.defineProperty; + var Up = Object.getOwnPropertyDescriptor; + var Np = Object.getOwnPropertyNames; + var Vp = Object.prototype.hasOwnProperty; + var On = ((e) => typeof __require < "u" ? __require : typeof Proxy < "u" ? new Proxy(e, { get: (t, r) => (typeof __require < "u" ? __require : t)[r] }) : e)(function(e) { + if (typeof __require < "u") return __require.apply(this, arguments); + throw Error('Dynamic require of "' + e + '" is not supported'); + }); + var U = (e, t) => () => (e && (t = e(e = 0)), t); + var Dt = (e, t) => { + for (var r in t) zn(e, r, { get: t[r], enumerable: true }); + }; + var Wp = (e, t, r, n) => { + if (t && typeof t == "object" || typeof t == "function") for (let o of Np(t)) !Vp.call(e, o) && o !== r && zn(e, o, { get: () => t[o], enumerable: !(n = Up(t, o)) || n.enumerable }); + return e; + }; + var Ft = (e) => Wp(zn({}, "__esModule", { value: true }), e); + var fr; + var vt; + var $t; + var Lp; + var Fi; + var Bn = U(() => { + "use strict"; + fr = /* @__PURE__ */ new Map(), vt = [], $t = (e, t, r) => { + if (t && typeof t.init == "function" && typeof t.createInferenceSessionHandler == "function") { + let n = fr.get(e); + if (n === void 0) fr.set(e, { backend: t, priority: r }); + else { + if (n.priority > r) return; + if (n.priority === r && n.backend !== t) throw new Error(`cannot register backend "${e}" using priority ${r}`); + } + if (r >= 0) { + let o = vt.indexOf(e); + o !== -1 && vt.splice(o, 1); + for (let i = 0; i < vt.length; i++) if (fr.get(vt[i]).priority <= r) { + vt.splice(i, 0, e); + return; + } + vt.push(e); + } + return; + } + throw new TypeError("not a valid backend"); + }, Lp = async (e) => { + let t = fr.get(e); + if (!t) return "backend not found."; + if (t.initialized) return t.backend; + if (t.aborted) return t.error; + { + let r = !!t.initPromise; + try { + return r || (t.initPromise = t.backend.init(e)), await t.initPromise, t.initialized = true, t.backend; + } catch (n) { + return r || (t.error = `${n}`, t.aborted = true), t.error; + } finally { + delete t.initPromise; + } + } + }, Fi = async (e) => { + let t = e.executionProviders || [], r = t.map((d) => typeof d == "string" ? d : d.name), n = r.length === 0 ? vt : r, o, i = [], a = /* @__PURE__ */ new Set(); + for (let d of n) { + let c = await Lp(d); + typeof c == "string" ? i.push({ name: d, err: c }) : (o || (o = c), o === c && a.add(d)); + } + if (!o) throw new Error(`no available backend found. ERR: ${i.map((d) => `[${d.name}] ${d.err}`).join(", ")}`); + for (let { name: d, err: c } of i) r.includes(d) && console.warn(`removing requested execution provider "${d}" from session options because it is not available: ${c}`); + let u = t.filter((d) => a.has(typeof d == "string" ? d : d.name)); + return [o, new Proxy(e, { get: (d, c) => c === "executionProviders" ? u : Reflect.get(d, c) })]; + }; + }); + var qi = U(() => { + "use strict"; + Bn(); + }); + var ji; + var Ki = U(() => { + "use strict"; + ji = "1.22.0-dev.20250409-89f8206ba4"; + }); + var Zi; + var Me; + var Dn = U(() => { + "use strict"; + Ki(); + Zi = "warning", Me = { wasm: {}, webgl: {}, webgpu: {}, versions: { common: ji }, set logLevel(e) { + if (e !== void 0) { + if (typeof e != "string" || ["verbose", "info", "warning", "error", "fatal"].indexOf(e) === -1) throw new Error(`Unsupported logging level: ${e}`); + Zi = e; + } + }, get logLevel() { + return Zi; + } }; + Object.defineProperty(Me, "logLevel", { enumerable: true }); + }); + var ge; + var Qi = U(() => { + "use strict"; + Dn(); + ge = Me; + }); + var Yi; + var Xi; + var Ji = U(() => { + "use strict"; + Yi = (e, t) => { + let r = typeof document < "u" ? document.createElement("canvas") : new OffscreenCanvas(1, 1); + r.width = e.dims[3], r.height = e.dims[2]; + let n = r.getContext("2d"); + if (n != null) { + let o, i; + t?.tensorLayout !== void 0 && t.tensorLayout === "NHWC" ? (o = e.dims[2], i = e.dims[3]) : (o = e.dims[3], i = e.dims[2]); + let a = t?.format !== void 0 ? t.format : "RGB", u = t?.norm, d, c; + u === void 0 || u.mean === void 0 ? d = [255, 255, 255, 255] : typeof u.mean == "number" ? d = [u.mean, u.mean, u.mean, u.mean] : (d = [u.mean[0], u.mean[1], u.mean[2], 0], u.mean[3] !== void 0 && (d[3] = u.mean[3])), u === void 0 || u.bias === void 0 ? c = [0, 0, 0, 0] : typeof u.bias == "number" ? c = [u.bias, u.bias, u.bias, u.bias] : (c = [u.bias[0], u.bias[1], u.bias[2], 0], u.bias[3] !== void 0 && (c[3] = u.bias[3])); + let p = i * o, m = 0, f = p, b = p * 2, g = -1; + a === "RGBA" ? (m = 0, f = p, b = p * 2, g = p * 3) : a === "RGB" ? (m = 0, f = p, b = p * 2) : a === "RBG" && (m = 0, b = p, f = p * 2); + for (let _ = 0; _ < i; _++) for (let S = 0; S < o; S++) { + let $ = (e.data[m++] - c[0]) * d[0], v = (e.data[f++] - c[1]) * d[1], x = (e.data[b++] - c[2]) * d[2], T = g === -1 ? 255 : (e.data[g++] - c[3]) * d[3]; + n.fillStyle = "rgba(" + $ + "," + v + "," + x + "," + T + ")", n.fillRect(S, _, 1, 1); + } + if ("toDataURL" in r) return r.toDataURL(); + throw new Error("toDataURL is not supported"); + } else throw new Error("Can not access image data"); + }, Xi = (e, t) => { + let r = typeof document < "u" ? document.createElement("canvas").getContext("2d") : new OffscreenCanvas(1, 1).getContext("2d"), n; + if (r != null) { + let o, i, a; + t?.tensorLayout !== void 0 && t.tensorLayout === "NHWC" ? (o = e.dims[2], i = e.dims[1], a = e.dims[3]) : (o = e.dims[3], i = e.dims[2], a = e.dims[1]); + let u = t !== void 0 && t.format !== void 0 ? t.format : "RGB", d = t?.norm, c, p; + d === void 0 || d.mean === void 0 ? c = [255, 255, 255, 255] : typeof d.mean == "number" ? c = [d.mean, d.mean, d.mean, d.mean] : (c = [d.mean[0], d.mean[1], d.mean[2], 255], d.mean[3] !== void 0 && (c[3] = d.mean[3])), d === void 0 || d.bias === void 0 ? p = [0, 0, 0, 0] : typeof d.bias == "number" ? p = [d.bias, d.bias, d.bias, d.bias] : (p = [d.bias[0], d.bias[1], d.bias[2], 0], d.bias[3] !== void 0 && (p[3] = d.bias[3])); + let m = i * o; + if (t !== void 0 && (t.format !== void 0 && a === 4 && t.format !== "RGBA" || a === 3 && t.format !== "RGB" && t.format !== "BGR")) throw new Error("Tensor format doesn't match input tensor dims"); + let f = 4, b = 0, g = 1, _ = 2, S = 3, $ = 0, v = m, x = m * 2, T = -1; + u === "RGBA" ? ($ = 0, v = m, x = m * 2, T = m * 3) : u === "RGB" ? ($ = 0, v = m, x = m * 2) : u === "RBG" && ($ = 0, x = m, v = m * 2), n = r.createImageData(o, i); + for (let E = 0; E < i * o; b += f, g += f, _ += f, S += f, E++) n.data[b] = (e.data[$++] - p[0]) * c[0], n.data[g] = (e.data[v++] - p[1]) * c[1], n.data[_] = (e.data[x++] - p[2]) * c[2], n.data[S] = T === -1 ? 255 : (e.data[T++] - p[3]) * c[3]; + } else throw new Error("Can not access image data"); + return n; + }; + }); + var Mn; + var ea; + var ta; + var ra; + var na; + var oa; + var ia = U(() => { + "use strict"; + hr(); + Mn = (e, t) => { + if (e === void 0) throw new Error("Image buffer must be defined"); + if (t.height === void 0 || t.width === void 0) throw new Error("Image height and width must be defined"); + if (t.tensorLayout === "NHWC") throw new Error("NHWC Tensor layout is not supported yet"); + let { height: r, width: n } = t, o = t.norm ?? { mean: 255, bias: 0 }, i, a; + typeof o.mean == "number" ? i = [o.mean, o.mean, o.mean, o.mean] : i = [o.mean[0], o.mean[1], o.mean[2], o.mean[3] ?? 255], typeof o.bias == "number" ? a = [o.bias, o.bias, o.bias, o.bias] : a = [o.bias[0], o.bias[1], o.bias[2], o.bias[3] ?? 0]; + let u = t.format !== void 0 ? t.format : "RGBA", d = t.tensorFormat !== void 0 && t.tensorFormat !== void 0 ? t.tensorFormat : "RGB", c = r * n, p = d === "RGBA" ? new Float32Array(c * 4) : new Float32Array(c * 3), m = 4, f = 0, b = 1, g = 2, _ = 3, S = 0, $ = c, v = c * 2, x = -1; + u === "RGB" && (m = 3, f = 0, b = 1, g = 2, _ = -1), d === "RGBA" ? x = c * 3 : d === "RBG" ? (S = 0, v = c, $ = c * 2) : d === "BGR" && (v = 0, $ = c, S = c * 2); + for (let E = 0; E < c; E++, f += m, g += m, b += m, _ += m) p[S++] = (e[f] + a[0]) / i[0], p[$++] = (e[b] + a[1]) / i[1], p[v++] = (e[g] + a[2]) / i[2], x !== -1 && _ !== -1 && (p[x++] = (e[_] + a[3]) / i[3]); + return d === "RGBA" ? new Pe("float32", p, [1, 4, r, n]) : new Pe("float32", p, [1, 3, r, n]); + }, ea = async (e, t) => { + let r = typeof HTMLImageElement < "u" && e instanceof HTMLImageElement, n = typeof ImageData < "u" && e instanceof ImageData, o = typeof ImageBitmap < "u" && e instanceof ImageBitmap, i = typeof e == "string", a, u = t ?? {}, d = () => { + if (typeof document < "u") return document.createElement("canvas"); + if (typeof OffscreenCanvas < "u") return new OffscreenCanvas(1, 1); + throw new Error("Canvas is not supported"); + }, c = (p) => typeof HTMLCanvasElement < "u" && p instanceof HTMLCanvasElement || p instanceof OffscreenCanvas ? p.getContext("2d") : null; + if (r) { + let p = d(); + p.width = e.width, p.height = e.height; + let m = c(p); + if (m != null) { + let f = e.height, b = e.width; + if (t !== void 0 && t.resizedHeight !== void 0 && t.resizedWidth !== void 0 && (f = t.resizedHeight, b = t.resizedWidth), t !== void 0) { + if (u = t, t.tensorFormat !== void 0) throw new Error("Image input config format must be RGBA for HTMLImageElement"); + u.tensorFormat = "RGBA", u.height = f, u.width = b; + } else u.tensorFormat = "RGBA", u.height = f, u.width = b; + m.drawImage(e, 0, 0), a = m.getImageData(0, 0, b, f).data; + } else throw new Error("Can not access image data"); + } else if (n) { + let p, m; + if (t !== void 0 && t.resizedWidth !== void 0 && t.resizedHeight !== void 0 ? (p = t.resizedHeight, m = t.resizedWidth) : (p = e.height, m = e.width), t !== void 0 && (u = t), u.format = "RGBA", u.height = p, u.width = m, t !== void 0) { + let f = d(); + f.width = m, f.height = p; + let b = c(f); + if (b != null) b.putImageData(e, 0, 0), a = b.getImageData(0, 0, m, p).data; + else throw new Error("Can not access image data"); + } else a = e.data; + } else if (o) { + if (t === void 0) throw new Error("Please provide image config with format for Imagebitmap"); + let p = d(); + p.width = e.width, p.height = e.height; + let m = c(p); + if (m != null) { + let f = e.height, b = e.width; + return m.drawImage(e, 0, 0, b, f), a = m.getImageData(0, 0, b, f).data, u.height = f, u.width = b, Mn(a, u); + } else throw new Error("Can not access image data"); + } else { + if (i) return new Promise((p, m) => { + let f = d(), b = c(f); + if (!e || !b) return m(); + let g = new Image(); + g.crossOrigin = "Anonymous", g.src = e, g.onload = () => { + f.width = g.width, f.height = g.height, b.drawImage(g, 0, 0, f.width, f.height); + let _ = b.getImageData(0, 0, f.width, f.height); + u.height = f.height, u.width = f.width, p(Mn(_.data, u)); + }; + }); + throw new Error("Input data provided is not supported - aborted tensor creation"); + } + if (a !== void 0) return Mn(a, u); + throw new Error("Input data provided is not supported - aborted tensor creation"); + }, ta = (e, t) => { + let { width: r, height: n, download: o, dispose: i } = t, a = [1, n, r, 4]; + return new Pe({ location: "texture", type: "float32", texture: e, dims: a, download: o, dispose: i }); + }, ra = (e, t) => { + let { dataType: r, dims: n, download: o, dispose: i } = t; + return new Pe({ location: "gpu-buffer", type: r ?? "float32", gpuBuffer: e, dims: n, download: o, dispose: i }); + }, na = (e, t) => { + let { dataType: r, dims: n, download: o, dispose: i } = t; + return new Pe({ location: "ml-tensor", type: r ?? "float32", mlTensor: e, dims: n, download: o, dispose: i }); + }, oa = (e, t, r) => new Pe({ location: "cpu-pinned", type: e, data: t, dims: r ?? [t.length] }); + }); + var xt; + var qt; + var aa; + var sa; + var ua = U(() => { + "use strict"; + xt = /* @__PURE__ */ new Map([["float32", Float32Array], ["uint8", Uint8Array], ["int8", Int8Array], ["uint16", Uint16Array], ["int16", Int16Array], ["int32", Int32Array], ["bool", Uint8Array], ["float64", Float64Array], ["uint32", Uint32Array], ["int4", Uint8Array], ["uint4", Uint8Array]]), qt = /* @__PURE__ */ new Map([[Float32Array, "float32"], [Uint8Array, "uint8"], [Int8Array, "int8"], [Uint16Array, "uint16"], [Int16Array, "int16"], [Int32Array, "int32"], [Float64Array, "float64"], [Uint32Array, "uint32"]]), aa = false, sa = () => { + if (!aa) { + aa = true; + let e = typeof BigInt64Array < "u" && BigInt64Array.from, t = typeof BigUint64Array < "u" && BigUint64Array.from, r = globalThis.Float16Array, n = typeof r < "u" && r.from; + e && (xt.set("int64", BigInt64Array), qt.set(BigInt64Array, "int64")), t && (xt.set("uint64", BigUint64Array), qt.set(BigUint64Array, "uint64")), n ? (xt.set("float16", r), qt.set(r, "float16")) : xt.set("float16", Uint16Array); + } + }; + }); + var da; + var la; + var ca = U(() => { + "use strict"; + hr(); + da = (e) => { + let t = 1; + for (let r = 0; r < e.length; r++) { + let n = e[r]; + if (typeof n != "number" || !Number.isSafeInteger(n)) throw new TypeError(`dims[${r}] must be an integer, got: ${n}`); + if (n < 0) throw new RangeError(`dims[${r}] must be a non-negative integer, got: ${n}`); + t *= n; + } + return t; + }, la = (e, t) => { + switch (e.location) { + case "cpu": + return new Pe(e.type, e.data, t); + case "cpu-pinned": + return new Pe({ location: "cpu-pinned", data: e.data, type: e.type, dims: t }); + case "texture": + return new Pe({ location: "texture", texture: e.texture, type: e.type, dims: t }); + case "gpu-buffer": + return new Pe({ location: "gpu-buffer", gpuBuffer: e.gpuBuffer, type: e.type, dims: t }); + case "ml-tensor": + return new Pe({ location: "ml-tensor", mlTensor: e.mlTensor, type: e.type, dims: t }); + default: + throw new Error(`tensorReshape: tensor location ${e.location} is not supported`); + } + }; + }); + var Pe; + var hr = U(() => { + "use strict"; + Ji(); + ia(); + ua(); + ca(); + Pe = class { + constructor(t, r, n) { + sa(); + let o, i; + if (typeof t == "object" && "location" in t) switch (this.dataLocation = t.location, o = t.type, i = t.dims, t.location) { + case "cpu-pinned": { + let u = xt.get(o); + if (!u) throw new TypeError(`unsupported type "${o}" to create tensor from pinned buffer`); + if (!(t.data instanceof u)) throw new TypeError(`buffer should be of type ${u.name}`); + this.cpuData = t.data; + break; + } + case "texture": { + if (o !== "float32") throw new TypeError(`unsupported type "${o}" to create tensor from texture`); + this.gpuTextureData = t.texture, this.downloader = t.download, this.disposer = t.dispose; + break; + } + case "gpu-buffer": { + if (o !== "float32" && o !== "float16" && o !== "int32" && o !== "int64" && o !== "uint32" && o !== "uint8" && o !== "bool" && o !== "uint4" && o !== "int4") throw new TypeError(`unsupported type "${o}" to create tensor from gpu buffer`); + this.gpuBufferData = t.gpuBuffer, this.downloader = t.download, this.disposer = t.dispose; + break; + } + case "ml-tensor": { + if (o !== "float32" && o !== "float16" && o !== "int32" && o !== "int64" && o !== "uint32" && o !== "uint64" && o !== "int8" && o !== "uint8" && o !== "bool" && o !== "uint4" && o !== "int4") throw new TypeError(`unsupported type "${o}" to create tensor from MLTensor`); + this.mlTensorData = t.mlTensor, this.downloader = t.download, this.disposer = t.dispose; + break; + } + default: + throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`); + } + else { + let u, d; + if (typeof t == "string") if (o = t, d = n, t === "string") { + if (!Array.isArray(r)) throw new TypeError("A string tensor's data must be a string array."); + u = r; + } else { + let c = xt.get(t); + if (c === void 0) throw new TypeError(`Unsupported tensor type: ${t}.`); + if (Array.isArray(r)) { + if (t === "float16" && c === Uint16Array || t === "uint4" || t === "int4") throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${c.name} as data.`); + t === "uint64" || t === "int64" ? u = c.from(r, BigInt) : u = c.from(r); + } else if (r instanceof c) u = r; + else if (r instanceof Uint8ClampedArray) if (t === "uint8") u = Uint8Array.from(r); + else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8"); + else if (t === "float16" && r instanceof Uint16Array && c !== Uint16Array) u = new globalThis.Float16Array(r.buffer, r.byteOffset, r.length); + else throw new TypeError(`A ${o} tensor's data must be type of ${c}`); + } + else if (d = r, Array.isArray(t)) { + if (t.length === 0) throw new TypeError("Tensor type cannot be inferred from an empty array."); + let c = typeof t[0]; + if (c === "string") o = "string", u = t; + else if (c === "boolean") o = "bool", u = Uint8Array.from(t); + else throw new TypeError(`Invalid element type of data array: ${c}.`); + } else if (t instanceof Uint8ClampedArray) o = "uint8", u = Uint8Array.from(t); + else { + let c = qt.get(t.constructor); + if (c === void 0) throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`); + o = c, u = t; + } + if (d === void 0) d = [u.length]; + else if (!Array.isArray(d)) throw new TypeError("A tensor's dims must be a number array"); + i = d, this.cpuData = u, this.dataLocation = "cpu"; + } + let a = da(i); + if (this.cpuData && a !== this.cpuData.length && !((o === "uint4" || o === "int4") && Math.ceil(a / 2) === this.cpuData.length)) throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`); + this.type = o, this.dims = i, this.size = a; + } + static async fromImage(t, r) { + return ea(t, r); + } + static fromTexture(t, r) { + return ta(t, r); + } + static fromGpuBuffer(t, r) { + return ra(t, r); + } + static fromMLTensor(t, r) { + return na(t, r); + } + static fromPinnedBuffer(t, r, n) { + return oa(t, r, n); + } + toDataURL(t) { + return Yi(this, t); + } + toImageData(t) { + return Xi(this, t); + } + get data() { + if (this.ensureValid(), !this.cpuData) throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly."); + return this.cpuData; + } + get location() { + return this.dataLocation; + } + get texture() { + if (this.ensureValid(), !this.gpuTextureData) throw new Error("The data is not stored as a WebGL texture."); + return this.gpuTextureData; + } + get gpuBuffer() { + if (this.ensureValid(), !this.gpuBufferData) throw new Error("The data is not stored as a WebGPU buffer."); + return this.gpuBufferData; + } + get mlTensor() { + if (this.ensureValid(), !this.mlTensorData) throw new Error("The data is not stored as a WebNN MLTensor."); + return this.mlTensorData; + } + async getData(t) { + switch (this.ensureValid(), this.dataLocation) { + case "cpu": + case "cpu-pinned": + return this.data; + case "texture": + case "gpu-buffer": + case "ml-tensor": { + if (!this.downloader) throw new Error("The current tensor is not created with a specified data downloader."); + if (this.isDownloading) throw new Error("The current tensor is being downloaded."); + try { + this.isDownloading = true; + let r = await this.downloader(); + return this.downloader = void 0, this.dataLocation = "cpu", this.cpuData = r, t && this.disposer && (this.disposer(), this.disposer = void 0), r; + } finally { + this.isDownloading = false; + } + } + default: + throw new Error(`cannot get data from location: ${this.dataLocation}`); + } + } + dispose() { + if (this.isDownloading) throw new Error("The current tensor is being downloaded."); + this.disposer && (this.disposer(), this.disposer = void 0), this.cpuData = void 0, this.gpuTextureData = void 0, this.gpuBufferData = void 0, this.mlTensorData = void 0, this.downloader = void 0, this.isDownloading = void 0, this.dataLocation = "none"; + } + ensureValid() { + if (this.dataLocation === "none") throw new Error("The tensor is disposed."); + } + reshape(t) { + if (this.ensureValid(), this.downloader || this.disposer) throw new Error("Cannot reshape a tensor that owns GPU resource."); + return la(this, t); + } + }; + }); + var Ge; + var Rn = U(() => { + "use strict"; + hr(); + Ge = Pe; + }); + var gr; + var pa; + var Re; + var Oe; + var Un = U(() => { + "use strict"; + Dn(); + gr = (e, t) => { + (typeof Me.trace > "u" ? !Me.wasm.trace : !Me.trace) || console.timeStamp(`${e}::ORT::${t}`); + }, pa = (e, t) => { + let r = new Error().stack?.split(/\r\n|\r|\n/g) || [], n = false; + for (let o = 0; o < r.length; o++) { + if (n && !r[o].includes("TRACE_FUNC")) { + let i = `FUNC_${e}::${r[o].trim().split(" ")[1]}`; + t && (i += `::${t}`), gr("CPU", i); + return; + } + r[o].includes("TRACE_FUNC") && (n = true); + } + }, Re = (e) => { + (typeof Me.trace > "u" ? !Me.wasm.trace : !Me.trace) || pa("BEGIN", e); + }, Oe = (e) => { + (typeof Me.trace > "u" ? !Me.wasm.trace : !Me.trace) || pa("END", e); + }; + }); + var br; + var ma = U(() => { + "use strict"; + Bn(); + Rn(); + Un(); + br = class e { + constructor(t) { + this.handler = t; + } + async run(t, r, n) { + Re(); + let o = {}, i = {}; + if (typeof t != "object" || t === null || t instanceof Ge || Array.isArray(t)) throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values."); + let a = true; + if (typeof r == "object") { + if (r === null) throw new TypeError("Unexpected argument[1]: cannot be null."); + if (r instanceof Ge) throw new TypeError("'fetches' cannot be a Tensor"); + if (Array.isArray(r)) { + if (r.length === 0) throw new TypeError("'fetches' cannot be an empty array."); + a = false; + for (let c of r) { + if (typeof c != "string") throw new TypeError("'fetches' must be a string array or an object."); + if (this.outputNames.indexOf(c) === -1) throw new RangeError(`'fetches' contains invalid output name: ${c}.`); + o[c] = null; + } + if (typeof n == "object" && n !== null) i = n; + else if (typeof n < "u") throw new TypeError("'options' must be an object."); + } else { + let c = false, p = Object.getOwnPropertyNames(r); + for (let m of this.outputNames) if (p.indexOf(m) !== -1) { + let f = r[m]; + (f === null || f instanceof Ge) && (c = true, a = false, o[m] = f); + } + if (c) { + if (typeof n == "object" && n !== null) i = n; + else if (typeof n < "u") throw new TypeError("'options' must be an object."); + } else i = r; + } + } else if (typeof r < "u") throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'."); + for (let c of this.inputNames) if (typeof t[c] > "u") throw new Error(`input '${c}' is missing in 'feeds'.`); + if (a) for (let c of this.outputNames) o[c] = null; + let u = await this.handler.run(t, o, i), d = {}; + for (let c in u) if (Object.hasOwnProperty.call(u, c)) { + let p = u[c]; + p instanceof Ge ? d[c] = p : d[c] = new Ge(p.type, p.data, p.dims); + } + return Oe(), d; + } + async release() { + return this.handler.dispose(); + } + static async create(t, r, n, o) { + Re(); + let i, a = {}; + if (typeof t == "string") { + if (i = t, typeof r == "object" && r !== null) a = r; + else if (typeof r < "u") throw new TypeError("'options' must be an object."); + } else if (t instanceof Uint8Array) { + if (i = t, typeof r == "object" && r !== null) a = r; + else if (typeof r < "u") throw new TypeError("'options' must be an object."); + } else if (t instanceof ArrayBuffer || typeof SharedArrayBuffer < "u" && t instanceof SharedArrayBuffer) { + let p = t, m = 0, f = t.byteLength; + if (typeof r == "object" && r !== null) a = r; + else if (typeof r == "number") { + if (m = r, !Number.isSafeInteger(m)) throw new RangeError("'byteOffset' must be an integer."); + if (m < 0 || m >= p.byteLength) throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`); + if (f = t.byteLength - m, typeof n == "number") { + if (f = n, !Number.isSafeInteger(f)) throw new RangeError("'byteLength' must be an integer."); + if (f <= 0 || m + f > p.byteLength) throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength - m}].`); + if (typeof o == "object" && o !== null) a = o; + else if (typeof o < "u") throw new TypeError("'options' must be an object."); + } else if (typeof n < "u") throw new TypeError("'byteLength' must be a number."); + } else if (typeof r < "u") throw new TypeError("'options' must be an object."); + i = new Uint8Array(p, m, f); + } else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'."); + let [u, d] = await Fi(a), c = await u.createInferenceSessionHandler(i, d); + return Oe(), new e(c); + } + startProfiling() { + this.handler.startProfiling(); + } + endProfiling() { + this.handler.endProfiling(); + } + get inputNames() { + return this.handler.inputNames; + } + get outputNames() { + return this.handler.outputNames; + } + get inputMetadata() { + return this.handler.inputMetadata; + } + get outputMetadata() { + return this.handler.outputMetadata; + } + }; + }); + var Gp; + var fa = U(() => { + "use strict"; + ma(); + Gp = br; + }); + var ha = U(() => { + "use strict"; + }); + var ga = U(() => { + "use strict"; + }); + var ba = U(() => { + "use strict"; + }); + var ya = U(() => { + "use strict"; + }); + var Nn = {}; + Dt(Nn, { InferenceSession: () => Gp, TRACE: () => gr, TRACE_FUNC_BEGIN: () => Re, TRACE_FUNC_END: () => Oe, Tensor: () => Ge, env: () => ge, registerBackend: () => $t }); + var We = U(() => { + "use strict"; + qi(); + Qi(); + fa(); + Rn(); + ha(); + ga(); + Un(); + ba(); + ya(); + }); + var yr = U(() => { + "use strict"; + }); + var $a = {}; + Dt($a, { default: () => Hp }); + var wa; + var va; + var Hp; + var xa = U(() => { + "use strict"; + Vn(); + ht(); + _r(); + wa = "ort-wasm-proxy-worker", va = globalThis.self?.name === wa; + va && (self.onmessage = (e) => { + let { type: t, in: r } = e.data; + try { + switch (t) { + case "init-wasm": + wr(r.wasm).then(() => { + vr(r).then(() => { + postMessage({ type: t }); + }, (n) => { + postMessage({ type: t, err: n }); + }); + }, (n) => { + postMessage({ type: t, err: n }); + }); + break; + case "init-ep": { + let { epName: n, env: o } = r; + $r(o, n).then(() => { + postMessage({ type: t }); + }, (i) => { + postMessage({ type: t, err: i }); + }); + break; + } + case "copy-from": { + let { buffer: n } = r, o = jt(n); + postMessage({ type: t, out: o }); + break; + } + case "create": { + let { model: n, options: o } = r; + xr(n, o).then((i) => { + postMessage({ type: t, out: i }); + }, (i) => { + postMessage({ type: t, err: i }); + }); + break; + } + case "release": + Sr(r), postMessage({ type: t }); + break; + case "run": { + let { sessionId: n, inputIndices: o, inputs: i, outputIndices: a, options: u } = r; + Tr(n, o, i, a, new Array(a.length).fill(null), u).then((d) => { + d.some((c) => c[3] !== "cpu") ? postMessage({ type: t, err: "Proxy does not support non-cpu tensor location." }) : postMessage({ type: t, out: d }, Cr([...i, ...d])); + }, (d) => { + postMessage({ type: t, err: d }); + }); + break; + } + case "end-profiling": + Ir(r), postMessage({ type: t }); + break; + default: + } + } catch (n) { + postMessage({ type: t, err: n }); + } + }); + Hp = va ? null : (e) => new Worker(e ?? Ue, { type: "module", name: wa }); + }); + var Ta = {}; + Dt(Ta, { default: () => Fp }); + var Wn; + var Sa; + var Fp; + var qp; + var Ia = U(() => { + "use strict"; + Sa = (Wn = import_meta.url, async function(e = {}) { + var t, r, n = e, o = new Promise((s, l) => { + t = s, r = l; + }), i = typeof window == "object", a = typeof WorkerGlobalScope < "u", u = a && self.name?.startsWith("em-pthread"); + n.mountExternalData = (s, l) => { + s.startsWith("./") && (s = s.substring(2)), (n.Eb || (n.Eb = /* @__PURE__ */ new Map())).set(s, l); + }, n.unmountExternalData = () => { + delete n.Eb; + }; + var d = globalThis.SharedArrayBuffer ?? new WebAssembly.Memory({ initial: 0, maximum: 0, pc: true }).buffer.constructor; + let c = (s) => async (...l) => { + try { + if (n.Fb) throw Error("Session already started"); + let h = n.Fb = { dc: l[0], errors: [] }, y = await s(...l); + if (n.Fb !== h) throw Error("Session mismatch"); + n.Jb?.flush(); + let w = h.errors; + if (0 < w.length) { + let A = await Promise.all(w); + if (A = A.filter((B) => B), 0 < A.length) throw Error(A.join(` +`)); + } + return y; + } finally { + n.Fb = null; + } + }; + n.jsepInit = (s, l) => { + if (s === "webgpu") { + [n.Jb, n.Ub, n.Yb, n.Kb, n.Xb, n.jb, n.Zb, n.ac, n.Vb, n.Wb, n.$b] = l; + let h = n.Jb; + n.jsepRegisterBuffer = (y, w, A, B) => h.registerBuffer(y, w, A, B), n.jsepGetBuffer = (y) => h.getBuffer(y), n.jsepCreateDownloader = (y, w, A) => h.createDownloader(y, w, A), n.jsepOnCreateSession = (y) => { + h.onCreateSession(y); + }, n.jsepOnReleaseSession = (y) => { + h.onReleaseSession(y); + }, n.jsepOnRunStart = (y) => h.onRunStart(y), n.bc = (y, w) => { + h.upload(y, w); + }; + } else if (s === "webnn") { + let h = l[0]; + [n.nc, n.Nb, n.webnnEnsureTensor, n.Ob, n.webnnDownloadTensor] = l.slice(1), n.webnnReleaseTensorId = n.Nb, n.webnnUploadTensor = n.Ob, n.webnnOnRunStart = (y) => h.onRunStart(y), n.webnnOnRunEnd = h.onRunEnd.bind(h), n.webnnRegisterMLContext = (y, w) => { + h.registerMLContext(y, w); + }, n.webnnOnReleaseSession = (y) => { + h.onReleaseSession(y); + }, n.webnnCreateMLTensorDownloader = (y, w) => h.createMLTensorDownloader(y, w), n.webnnRegisterMLTensor = (y, w, A, B) => h.registerMLTensor(y, w, A, B), n.webnnCreateMLContext = (y) => h.createMLContext(y), n.webnnRegisterMLConstant = (y, w, A, B, R, G) => h.registerMLConstant(y, w, A, B, R, n.Eb, G), n.webnnRegisterGraphInput = h.registerGraphInput.bind(h), n.webnnIsGraphInput = h.isGraphInput.bind(h), n.webnnCreateTemporaryTensor = h.createTemporaryTensor.bind(h), n.webnnIsInt64Supported = h.isInt64Supported.bind(h); + } + }; + let p = () => { + let s = (l, h, y) => (...w) => { + let A = Ze, B = h?.(); + w = l(...w); + let R = h?.(); + return B !== R && (l = R, y(B), h = y = null), Ze != A ? new Promise((G, K) => { + Sn = { resolve: G, reject: K }; + }) : w; + }; + (() => { + for (let l of ["_OrtAppendExecutionProvider", "_OrtCreateSession", "_OrtRun", "_OrtRunWithBinding", "_OrtBindInput"]) n[l] = s(n[l], () => n[l], (h) => n[l] = h); + })(), c !== void 0 && (n._OrtRun = c(n._OrtRun), n._OrtRunWithBinding = c(n._OrtRunWithBinding)), p = void 0; + }; + n.asyncInit = () => { + p?.(); + }; + var m, f, b = Object.assign({}, n), g = (s, l) => { + throw l; + }, _ = ""; + (i || a) && (a ? _ = self.location.href : typeof document < "u" && document.currentScript && (_ = document.currentScript.src), Wn && (_ = Wn), _ = _.startsWith("blob:") ? "" : _.slice(0, _.replace(/[?#].*/, "").lastIndexOf("/") + 1), a && (f = (s) => { + var l = new XMLHttpRequest(); + return l.open("GET", s, false), l.responseType = "arraybuffer", l.send(null), new Uint8Array(l.response); + }), m = async (s) => { + if (X(s)) return new Promise((h, y) => { + var w = new XMLHttpRequest(); + w.open("GET", s, true), w.responseType = "arraybuffer", w.onload = () => { + w.status == 200 || w.status == 0 && w.response ? h(w.response) : y(w.status); + }, w.onerror = y, w.send(null); + }); + var l = await fetch(s, { credentials: "same-origin" }); + if (l.ok) return l.arrayBuffer(); + throw Error(l.status + " : " + l.url); + }); + var S = console.log.bind(console), $ = console.error.bind(console), v = S, x = $; + Object.assign(n, b), b = null; + var T, E, I, z, O, D, L, q, Q, W, Z, we, H, j = n.wasmBinary, te = false, X = (s) => s.startsWith("file://"); + function ue() { + return T.buffer != z.buffer && Ce(), z; + } + function he() { + return T.buffer != z.buffer && Ce(), O; + } + function ye() { + return T.buffer != z.buffer && Ce(), D; + } + function re() { + return T.buffer != z.buffer && Ce(), L; + } + function C() { + return T.buffer != z.buffer && Ce(), q; + } + function V() { + return T.buffer != z.buffer && Ce(), Q; + } + function de() { + return T.buffer != z.buffer && Ce(), W; + } + function ze() { + return T.buffer != z.buffer && Ce(), H; + } + if (u) { + let s = function(l) { + try { + var h = l.data, y = h.Bb; + if (y === "load") { + let w = []; + self.onmessage = (A) => w.push(A), self.startWorker = () => { + postMessage({ Bb: "loaded" }); + for (let A of w) s(A); + self.onmessage = s; + }; + for (let A of h.Rb) n[A] && !n[A].proxy || (n[A] = (...B) => { + postMessage({ Bb: "callHandler", Qb: A, args: B }); + }, A == "print" && (v = n[A]), A == "printErr" && (x = n[A])); + T = h.kc, Ce(), ve(h.lc); + } else if (y === "run") { + _c(h.Ab), An(h.Ab, 0, 0, 1, 0, 0), No(), $n(h.Ab), $e || (Oi(), $e = true); + try { + wc(h.fc, h.Hb); + } catch (w) { + if (w != "unwind") throw w; + } + } else h.target !== "setimmediate" && (y === "checkMailbox" ? $e && nr() : y && (x(`worker: received unknown command ${y}`), x(h))); + } catch (w) { + throw Bi(), w; + } + }; + var wg = s, ve, $e = false; + x = function(...l) { + l = l.join(" "), console.error(l); + }, self.alert = function(...l) { + postMessage({ Bb: "alert", text: l.join(" "), ic: cr() }); + }, self.onunhandledrejection = (l) => { + throw l.reason || l; + }, self.onmessage = s; + } + function Ce() { + var s = T.buffer; + n.HEAP8 = z = new Int8Array(s), n.HEAP16 = D = new Int16Array(s), n.HEAPU8 = O = new Uint8Array(s), n.HEAPU16 = L = new Uint16Array(s), n.HEAP32 = q = new Int32Array(s), n.HEAPU32 = Q = new Uint32Array(s), n.HEAPF32 = W = new Float32Array(s), n.HEAPF64 = H = new Float64Array(s), n.HEAP64 = Z = new BigInt64Array(s), n.HEAPU64 = we = new BigUint64Array(s); + } + function _t() { + u ? startWorker(n) : Y.Ca(); + } + u || (T = new WebAssembly.Memory({ initial: 256, maximum: 65536, shared: true }), Ce()); + var kt, Pt = 0, Lt = null; + function zo() { + if (--Pt == 0 && Lt) { + var s = Lt; + Lt = null, s(); + } + } + function dt(s) { + throw x(s = "Aborted(" + s + ")"), te = true, s = new WebAssembly.RuntimeError(s + ". Build with -sASSERTIONS for more info."), r(s), s; + } + function Oo() { + return { a: { L: yc, Aa: bc, b: $c, $: Go, A: qo, pa: jo, X: Zo, Z: Qo, qa: Yo, na: Xo, ga: Jo, ma: ei, J: ti, Y: ri, V: ni, oa: oi, W: ii, va: xc, E: Tc, Q: Ic, O: Ac, D: kc, u: Pc, r: zc, P: Oc, z: Vc, R: Wc, ja: Lc, T: Gc, aa: Hc, M: Fc, F: qc, ia: $n, sa: jc, t: Kc, Ba: Zc, w: Xc, o: Jc, l: tp, c: _n, n: rp, j: ip, v: ap, p: sp, f: up, s: dp, m: lp, e: cp, k: pp, i: mp, g: fp, d: hp, da: gp, ea: bp, fa: yp, ba: _i, ca: wi, N: vi, xa: wp, ua: xp, h: Sp, C: Tp, G: Ip, ta: vp, x: Cp, ra: Ap, U: Ep, q: _p, y: kp, K: Pp, S: zp, za: Op, ya: Bp, ka: Ti, la: Ii, _: hn, B: Ci, I: Ai, ha: Ei, H: ki, a: T, wa: fn } }; + } + var cn = { 829644: (s, l, h, y, w) => { + if (n === void 0 || !n.Eb) return 1; + if ((s = Te(Number(s >>> 0))).startsWith("./") && (s = s.substring(2)), !(s = n.Eb.get(s))) return 2; + if (l = Number(l >>> 0), h = Number(h >>> 0), y = Number(y >>> 0), l + h > s.byteLength) return 3; + try { + let A = s.subarray(l, l + h); + switch (w) { + case 0: + he().set(A, y >>> 0); + break; + case 1: + n.mc ? n.mc(y, A) : n.bc(y, A); + break; + default: + return 4; + } + return 0; + } catch { + return 4; + } + }, 830468: (s, l, h) => { + n.Ob(s, he().subarray(l >>> 0, l + h >>> 0)); + }, 830532: () => n.nc(), 830574: (s) => { + n.Nb(s); + }, 830611: () => { + n.Vb(); + }, 830642: () => { + n.Wb(); + }, 830671: () => { + n.$b(); + }, 830696: (s) => n.Ub(s), 830729: (s) => n.Yb(s), 830761: (s, l, h) => { + n.Kb(Number(s), Number(l), Number(h), true); + }, 830824: (s, l, h) => { + n.Kb(Number(s), Number(l), Number(h)); + }, 830881: () => typeof wasmOffsetConverter < "u", 830938: (s) => { + n.jb("Abs", s, void 0); + }, 830989: (s) => { + n.jb("Neg", s, void 0); + }, 831040: (s) => { + n.jb("Floor", s, void 0); + }, 831093: (s) => { + n.jb("Ceil", s, void 0); + }, 831145: (s) => { + n.jb("Reciprocal", s, void 0); + }, 831203: (s) => { + n.jb("Sqrt", s, void 0); + }, 831255: (s) => { + n.jb("Exp", s, void 0); + }, 831306: (s) => { + n.jb("Erf", s, void 0); + }, 831357: (s) => { + n.jb("Sigmoid", s, void 0); + }, 831412: (s, l, h) => { + n.jb("HardSigmoid", s, { alpha: l, beta: h }); + }, 831491: (s) => { + n.jb("Log", s, void 0); + }, 831542: (s) => { + n.jb("Sin", s, void 0); + }, 831593: (s) => { + n.jb("Cos", s, void 0); + }, 831644: (s) => { + n.jb("Tan", s, void 0); + }, 831695: (s) => { + n.jb("Asin", s, void 0); + }, 831747: (s) => { + n.jb("Acos", s, void 0); + }, 831799: (s) => { + n.jb("Atan", s, void 0); + }, 831851: (s) => { + n.jb("Sinh", s, void 0); + }, 831903: (s) => { + n.jb("Cosh", s, void 0); + }, 831955: (s) => { + n.jb("Asinh", s, void 0); + }, 832008: (s) => { + n.jb("Acosh", s, void 0); + }, 832061: (s) => { + n.jb("Atanh", s, void 0); + }, 832114: (s) => { + n.jb("Tanh", s, void 0); + }, 832166: (s) => { + n.jb("Not", s, void 0); + }, 832217: (s, l, h) => { + n.jb("Clip", s, { min: l, max: h }); + }, 832286: (s) => { + n.jb("Clip", s, void 0); + }, 832338: (s, l) => { + n.jb("Elu", s, { alpha: l }); + }, 832396: (s) => { + n.jb("Gelu", s, void 0); + }, 832448: (s) => { + n.jb("Relu", s, void 0); + }, 832500: (s, l) => { + n.jb("LeakyRelu", s, { alpha: l }); + }, 832564: (s, l) => { + n.jb("ThresholdedRelu", s, { alpha: l }); + }, 832634: (s, l) => { + n.jb("Cast", s, { to: l }); + }, 832692: (s) => { + n.jb("Add", s, void 0); + }, 832743: (s) => { + n.jb("Sub", s, void 0); + }, 832794: (s) => { + n.jb("Mul", s, void 0); + }, 832845: (s) => { + n.jb("Div", s, void 0); + }, 832896: (s) => { + n.jb("Pow", s, void 0); + }, 832947: (s) => { + n.jb("Equal", s, void 0); + }, 833e3: (s) => { + n.jb("Greater", s, void 0); + }, 833055: (s) => { + n.jb("GreaterOrEqual", s, void 0); + }, 833117: (s) => { + n.jb("Less", s, void 0); + }, 833169: (s) => { + n.jb("LessOrEqual", s, void 0); + }, 833228: (s, l, h, y, w) => { + n.jb("ReduceMean", s, { keepDims: !!l, noopWithEmptyAxes: !!h, axes: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] }); + }, 833403: (s, l, h, y, w) => { + n.jb("ReduceMax", s, { keepDims: !!l, noopWithEmptyAxes: !!h, axes: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] }); + }, 833577: (s, l, h, y, w) => { + n.jb("ReduceMin", s, { keepDims: !!l, noopWithEmptyAxes: !!h, axes: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] }); + }, 833751: (s, l, h, y, w) => { + n.jb("ReduceProd", s, { keepDims: !!l, noopWithEmptyAxes: !!h, axes: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] }); + }, 833926: (s, l, h, y, w) => { + n.jb("ReduceSum", s, { keepDims: !!l, noopWithEmptyAxes: !!h, axes: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] }); + }, 834100: (s, l, h, y, w) => { + n.jb("ReduceL1", s, { keepDims: !!l, noopWithEmptyAxes: !!h, axes: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] }); + }, 834273: (s, l, h, y, w) => { + n.jb("ReduceL2", s, { keepDims: !!l, noopWithEmptyAxes: !!h, axes: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] }); + }, 834446: (s, l, h, y, w) => { + n.jb("ReduceLogSum", s, { keepDims: !!l, noopWithEmptyAxes: !!h, axes: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] }); + }, 834623: (s, l, h, y, w) => { + n.jb("ReduceSumSquare", s, { keepDims: !!l, noopWithEmptyAxes: !!h, axes: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] }); + }, 834803: (s, l, h, y, w) => { + n.jb("ReduceLogSumExp", s, { keepDims: !!l, noopWithEmptyAxes: !!h, axes: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] }); + }, 834983: (s) => { + n.jb("Where", s, void 0); + }, 835036: (s, l, h) => { + n.jb("Transpose", s, { perm: l ? Array.from(C().subarray(Number(l) >>> 0, Number(h) >>> 0)) : [] }); + }, 835160: (s, l, h, y) => { + n.jb("DepthToSpace", s, { blocksize: l, mode: Te(h), format: y ? "NHWC" : "NCHW" }); + }, 835293: (s, l, h, y) => { + n.jb("DepthToSpace", s, { blocksize: l, mode: Te(h), format: y ? "NHWC" : "NCHW" }); + }, 835426: (s, l, h, y, w, A, B, R, G, K, ae, le, _e, ke, Bt) => { + n.jb("ConvTranspose", s, { format: G ? "NHWC" : "NCHW", autoPad: l, dilations: [h], group: y, kernelShape: [w], pads: [A, B], strides: [R], wIsConst: () => !!ue()[K >>> 0], outputPadding: ae ? Array.from(C().subarray(Number(ae) >>> 0, Number(le) >>> 0)) : [], outputShape: _e ? Array.from(C().subarray(Number(_e) >>> 0, Number(ke) >>> 0)) : [], activation: Te(Bt) }); + }, 835859: (s, l, h, y, w, A, B, R, G, K, ae, le, _e, ke) => { + n.jb("ConvTranspose", s, { format: R ? "NHWC" : "NCHW", autoPad: l, dilations: Array.from(C().subarray(Number(h) >>> 0, 2 + (Number(h) >>> 0) >>> 0)), group: y, kernelShape: Array.from(C().subarray(Number(w) >>> 0, 2 + (Number(w) >>> 0) >>> 0)), pads: Array.from(C().subarray(Number(A) >>> 0, 4 + (Number(A) >>> 0) >>> 0)), strides: Array.from(C().subarray(Number(B) >>> 0, 2 + (Number(B) >>> 0) >>> 0)), wIsConst: () => !!ue()[G >>> 0], outputPadding: K ? Array.from(C().subarray(Number(K) >>> 0, Number(ae) >>> 0)) : [], outputShape: le ? Array.from(C().subarray(Number(le) >>> 0, Number(_e) >>> 0)) : [], activation: Te(ke) }); + }, 836520: (s, l, h, y, w, A, B, R, G, K, ae, le, _e, ke, Bt) => { + n.jb("ConvTranspose", s, { format: G ? "NHWC" : "NCHW", autoPad: l, dilations: [h], group: y, kernelShape: [w], pads: [A, B], strides: [R], wIsConst: () => !!ue()[K >>> 0], outputPadding: ae ? Array.from(C().subarray(Number(ae) >>> 0, Number(le) >>> 0)) : [], outputShape: _e ? Array.from(C().subarray(Number(_e) >>> 0, Number(ke) >>> 0)) : [], activation: Te(Bt) }); + }, 836953: (s, l, h, y, w, A, B, R, G, K, ae, le, _e, ke) => { + n.jb("ConvTranspose", s, { format: R ? "NHWC" : "NCHW", autoPad: l, dilations: Array.from(C().subarray(Number(h) >>> 0, 2 + (Number(h) >>> 0) >>> 0)), group: y, kernelShape: Array.from(C().subarray(Number(w) >>> 0, 2 + (Number(w) >>> 0) >>> 0)), pads: Array.from(C().subarray(Number(A) >>> 0, 4 + (Number(A) >>> 0) >>> 0)), strides: Array.from(C().subarray(Number(B) >>> 0, 2 + (Number(B) >>> 0) >>> 0)), wIsConst: () => !!ue()[G >>> 0], outputPadding: K ? Array.from(C().subarray(Number(K) >>> 0, Number(ae) >>> 0)) : [], outputShape: le ? Array.from(C().subarray(Number(le) >>> 0, Number(_e) >>> 0)) : [], activation: Te(ke) }); + }, 837614: (s, l) => { + n.jb("GlobalAveragePool", s, { format: l ? "NHWC" : "NCHW" }); + }, 837705: (s, l, h, y, w, A, B, R, G, K, ae, le, _e, ke) => { + n.jb("AveragePool", s, { format: ke ? "NHWC" : "NCHW", auto_pad: l, ceil_mode: h, count_include_pad: y, storage_order: w, dilations: A ? Array.from(C().subarray(Number(A) >>> 0, Number(B) >>> 0)) : [], kernel_shape: R ? Array.from(C().subarray(Number(R) >>> 0, Number(G) >>> 0)) : [], pads: K ? Array.from(C().subarray(Number(K) >>> 0, Number(ae) >>> 0)) : [], strides: le ? Array.from(C().subarray(Number(le) >>> 0, Number(_e) >>> 0)) : [] }); + }, 838184: (s, l) => { + n.jb("GlobalAveragePool", s, { format: l ? "NHWC" : "NCHW" }); + }, 838275: (s, l, h, y, w, A, B, R, G, K, ae, le, _e, ke) => { + n.jb("AveragePool", s, { format: ke ? "NHWC" : "NCHW", auto_pad: l, ceil_mode: h, count_include_pad: y, storage_order: w, dilations: A ? Array.from(C().subarray(Number(A) >>> 0, Number(B) >>> 0)) : [], kernel_shape: R ? Array.from(C().subarray(Number(R) >>> 0, Number(G) >>> 0)) : [], pads: K ? Array.from(C().subarray(Number(K) >>> 0, Number(ae) >>> 0)) : [], strides: le ? Array.from(C().subarray(Number(le) >>> 0, Number(_e) >>> 0)) : [] }); + }, 838754: (s, l) => { + n.jb("GlobalMaxPool", s, { format: l ? "NHWC" : "NCHW" }); + }, 838841: (s, l, h, y, w, A, B, R, G, K, ae, le, _e, ke) => { + n.jb("MaxPool", s, { format: ke ? "NHWC" : "NCHW", auto_pad: l, ceil_mode: h, count_include_pad: y, storage_order: w, dilations: A ? Array.from(C().subarray(Number(A) >>> 0, Number(B) >>> 0)) : [], kernel_shape: R ? Array.from(C().subarray(Number(R) >>> 0, Number(G) >>> 0)) : [], pads: K ? Array.from(C().subarray(Number(K) >>> 0, Number(ae) >>> 0)) : [], strides: le ? Array.from(C().subarray(Number(le) >>> 0, Number(_e) >>> 0)) : [] }); + }, 839316: (s, l) => { + n.jb("GlobalMaxPool", s, { format: l ? "NHWC" : "NCHW" }); + }, 839403: (s, l, h, y, w, A, B, R, G, K, ae, le, _e, ke) => { + n.jb("MaxPool", s, { format: ke ? "NHWC" : "NCHW", auto_pad: l, ceil_mode: h, count_include_pad: y, storage_order: w, dilations: A ? Array.from(C().subarray(Number(A) >>> 0, Number(B) >>> 0)) : [], kernel_shape: R ? Array.from(C().subarray(Number(R) >>> 0, Number(G) >>> 0)) : [], pads: K ? Array.from(C().subarray(Number(K) >>> 0, Number(ae) >>> 0)) : [], strides: le ? Array.from(C().subarray(Number(le) >>> 0, Number(_e) >>> 0)) : [] }); + }, 839878: (s, l, h, y, w) => { + n.jb("Gemm", s, { alpha: l, beta: h, transA: y, transB: w }); + }, 839982: (s) => { + n.jb("MatMul", s, void 0); + }, 840036: (s, l, h, y) => { + n.jb("ArgMax", s, { keepDims: !!l, selectLastIndex: !!h, axis: y }); + }, 840144: (s, l, h, y) => { + n.jb("ArgMin", s, { keepDims: !!l, selectLastIndex: !!h, axis: y }); + }, 840252: (s, l) => { + n.jb("Softmax", s, { axis: l }); + }, 840315: (s, l) => { + n.jb("Concat", s, { axis: l }); + }, 840375: (s, l, h, y, w) => { + n.jb("Split", s, { axis: l, numOutputs: h, splitSizes: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] }); + }, 840531: (s) => { + n.jb("Expand", s, void 0); + }, 840585: (s, l) => { + n.jb("Gather", s, { axis: Number(l) }); + }, 840656: (s, l) => { + n.jb("GatherElements", s, { axis: Number(l) }); + }, 840735: (s, l) => { + n.jb("GatherND", s, { batch_dims: Number(l) }); + }, 840814: (s, l, h, y, w, A, B, R, G, K, ae) => { + n.jb("Resize", s, { antialias: l, axes: h ? Array.from(C().subarray(Number(h) >>> 0, Number(y) >>> 0)) : [], coordinateTransformMode: Te(w), cubicCoeffA: A, excludeOutside: B, extrapolationValue: R, keepAspectRatioPolicy: Te(G), mode: Te(K), nearestMode: Te(ae) }); + }, 841176: (s, l, h, y, w, A, B) => { + n.jb("Slice", s, { starts: l ? Array.from(C().subarray(Number(l) >>> 0, Number(h) >>> 0)) : [], ends: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [], axes: A ? Array.from(C().subarray(Number(A) >>> 0, Number(B) >>> 0)) : [] }); + }, 841440: (s) => { + n.jb("Tile", s, void 0); + }, 841492: (s, l, h) => { + n.jb("InstanceNormalization", s, { epsilon: l, format: h ? "NHWC" : "NCHW" }); + }, 841606: (s, l, h) => { + n.jb("InstanceNormalization", s, { epsilon: l, format: h ? "NHWC" : "NCHW" }); + }, 841720: (s) => { + n.jb("Range", s, void 0); + }, 841773: (s, l) => { + n.jb("Einsum", s, { equation: Te(l) }); + }, 841854: (s, l, h, y, w) => { + n.jb("Pad", s, { mode: l, value: h, pads: y ? Array.from(C().subarray(Number(y) >>> 0, Number(w) >>> 0)) : [] }); + }, 841997: (s, l, h, y, w, A) => { + n.jb("BatchNormalization", s, { epsilon: l, momentum: h, spatial: !!w, trainingMode: !!y, format: A ? "NHWC" : "NCHW" }); + }, 842166: (s, l, h, y, w, A) => { + n.jb("BatchNormalization", s, { epsilon: l, momentum: h, spatial: !!w, trainingMode: !!y, format: A ? "NHWC" : "NCHW" }); + }, 842335: (s, l, h) => { + n.jb("CumSum", s, { exclusive: Number(l), reverse: Number(h) }); + }, 842432: (s, l, h) => { + n.jb("DequantizeLinear", s, { axis: l, blockSize: h }); + }, 842522: (s, l, h, y, w) => { + n.jb("GridSample", s, { align_corners: l, mode: Te(h), padding_mode: Te(y), format: w ? "NHWC" : "NCHW" }); + }, 842692: (s, l, h, y, w) => { + n.jb("GridSample", s, { align_corners: l, mode: Te(h), padding_mode: Te(y), format: w ? "NHWC" : "NCHW" }); + }, 842862: (s, l) => { + n.jb("ScatterND", s, { reduction: Te(l) }); + }, 842947: (s, l, h, y, w, A, B, R, G) => { + n.jb("Attention", s, { numHeads: l, isUnidirectional: h, maskFilterValue: y, scale: w, doRotary: A, qkvHiddenSizes: B ? Array.from(C().subarray(Number(R) >>> 0, Number(R) + B >>> 0)) : [], pastPresentShareBuffer: !!G }); + }, 843219: (s) => { + n.jb("BiasAdd", s, void 0); + }, 843274: (s) => { + n.jb("BiasSplitGelu", s, void 0); + }, 843335: (s) => { + n.jb("FastGelu", s, void 0); + }, 843391: (s, l, h, y, w, A, B, R, G, K, ae, le, _e, ke, Bt, Rp) => { + n.jb("Conv", s, { format: le ? "NHWC" : "NCHW", auto_pad: l, dilations: h ? Array.from(C().subarray(Number(h) >>> 0, Number(y) >>> 0)) : [], group: w, kernel_shape: A ? Array.from(C().subarray(Number(A) >>> 0, Number(B) >>> 0)) : [], pads: R ? Array.from(C().subarray(Number(R) >>> 0, Number(G) >>> 0)) : [], strides: K ? Array.from(C().subarray(Number(K) >>> 0, Number(ae) >>> 0)) : [], w_is_const: () => !!ue()[Number(_e) >>> 0], activation: Te(ke), activation_params: Bt ? Array.from(de().subarray(Number(Bt) >>> 0, Number(Rp) >>> 0)) : [] }); + }, 843975: (s) => { + n.jb("Gelu", s, void 0); + }, 844027: (s, l, h, y, w, A, B, R, G) => { + n.jb("GroupQueryAttention", s, { numHeads: l, kvNumHeads: h, scale: y, softcap: w, doRotary: A, rotaryInterleaved: B, smoothSoftmax: R, localWindowSize: G }); + }, 844244: (s, l, h, y) => { + n.jb("LayerNormalization", s, { axis: l, epsilon: h, simplified: !!y }); + }, 844355: (s, l, h, y) => { + n.jb("LayerNormalization", s, { axis: l, epsilon: h, simplified: !!y }); + }, 844466: (s, l, h, y, w, A) => { + n.jb("MatMulNBits", s, { k: l, n: h, accuracyLevel: y, bits: w, blockSize: A }); + }, 844593: (s, l, h, y, w, A) => { + n.jb("MultiHeadAttention", s, { numHeads: l, isUnidirectional: h, maskFilterValue: y, scale: w, doRotary: A }); + }, 844752: (s, l) => { + n.jb("QuickGelu", s, { alpha: l }); + }, 844816: (s, l, h, y, w) => { + n.jb("RotaryEmbedding", s, { interleaved: !!l, numHeads: h, rotaryEmbeddingDim: y, scale: w }); + }, 844955: (s, l, h) => { + n.jb("SkipLayerNormalization", s, { epsilon: l, simplified: !!h }); + }, 845057: (s, l, h) => { + n.jb("SkipLayerNormalization", s, { epsilon: l, simplified: !!h }); + }, 845159: (s, l, h, y) => { + n.jb("GatherBlockQuantized", s, { gatherAxis: l, quantizeAxis: h, blockSize: y }); + }, 845280: (s) => { + n.Zb(s); + }, 845314: (s, l) => n.ac(Number(s), Number(l), n.Fb.dc, n.Fb.errors) }; + function bc(s, l, h) { + return mi(async () => { + await n.Xb(Number(s), Number(l), Number(h)); + }); + } + function yc() { + return typeof wasmOffsetConverter < "u"; + } + class pn { + name = "ExitStatus"; + constructor(l) { + this.message = `Program terminated with exit(${l})`, this.status = l; + } + } + var Bo = (s) => { + s.terminate(), s.onmessage = () => { + }; + }, mn = [], Do = (s) => { + ct.length == 0 && (Wo(), Vo(ct[0])); + var l = ct.pop(); + if (!l) return 6; + Gt.push(l), wt[s.Ab] = l, l.Ab = s.Ab; + var h = { Bb: "run", fc: s.ec, Hb: s.Hb, Ab: s.Ab }; + return l.postMessage(h, s.Mb), 0; + }, lt = 0, xe = (s, l, ...h) => { + for (var y = 2 * h.length, w = Pn(), A = kn(8 * y), B = A >>> 3, R = 0; R < h.length; R++) { + var G = h[R]; + typeof G == "bigint" ? (Z[B + 2 * R] = 1n, Z[B + 2 * R + 1] = G) : (Z[B + 2 * R] = 0n, ze()[B + 2 * R + 1 >>> 0] = G); + } + return s = Di(s, 0, y, A, l), mr(w), s; + }; + function fn(s) { + if (u) return xe(0, 1, s); + if (I = s, !(0 < lt)) { + for (var l of Gt) Bo(l); + for (l of ct) Bo(l); + ct = [], Gt = [], wt = {}, te = true; + } + g(0, new pn(s)); + } + function Mo(s) { + if (u) return xe(1, 0, s); + hn(s); + } + var hn = (s) => { + if (I = s, u) throw Mo(s), "unwind"; + fn(s); + }, ct = [], Gt = [], Ro = [], wt = {}, Uo = (s) => { + var l = s.Ab; + delete wt[l], ct.push(s), Gt.splice(Gt.indexOf(s), 1), s.Ab = 0, Mi(l); + }; + function No() { + Ro.forEach((s) => s()); + } + var Vo = (s) => new Promise((l) => { + s.onmessage = (w) => { + var A = (w = w.data).Bb; + if (w.Gb && w.Gb != cr()) { + var B = wt[w.Gb]; + B ? B.postMessage(w, w.Mb) : x(`Internal error! Worker sent a message "${A}" to target pthread ${w.Gb}, but that thread no longer exists!`); + } else A === "checkMailbox" ? nr() : A === "spawnThread" ? Do(w) : A === "cleanupThread" ? Uo(wt[w.hc]) : A === "loaded" ? (s.loaded = true, l(s)) : A === "alert" ? alert(`Thread ${w.ic}: ${w.text}`) : w.target === "setimmediate" ? s.postMessage(w) : A === "callHandler" ? n[w.Qb](...w.args) : A && x(`worker sent an unknown command ${A}`); + }, s.onerror = (w) => { + throw x(`worker sent an error! ${w.filename}:${w.lineno}: ${w.message}`), w; + }; + var h, y = []; + for (h of []) n.propertyIsEnumerable(h) && y.push(h); + s.postMessage({ Bb: "load", Rb: y, kc: T, lc: E }); + }); + function Wo() { + var s = new Worker((() => { + let l = URL; + return import_meta.url > "file:" && import_meta.url < "file;" ? new l("ort.bundle.min.mjs", import_meta.url) : new URL(import_meta.url); + })(), { type: "module", workerData: "em-pthread", name: "em-pthread" }); + ct.push(s); + } + var _c = (s) => { + Ce(); + var l = V()[s + 52 >>> 2 >>> 0]; + s = V()[s + 56 >>> 2 >>> 0], Ni(l, l - s), mr(l); + }, wc = (s, l) => { + lt = 0, s = Vi(s, l), 0 < lt ? I = s : En(s); + }; + class vc { + constructor(l) { + this.Ib = l - 24; + } + } + function $c(s, l, h) { + var y = new vc(s >>>= 0); + throw l >>>= 0, h >>>= 0, V()[y.Ib + 16 >>> 2 >>> 0] = 0, V()[y.Ib + 4 >>> 2 >>> 0] = l, V()[y.Ib + 8 >>> 2 >>> 0] = h, s; + } + function Lo(s, l, h, y) { + return u ? xe(2, 1, s, l, h, y) : Go(s, l, h, y); + } + function Go(s, l, h, y) { + if (s >>>= 0, h >>>= 0, y >>>= 0, d === void 0) return 6; + var w = []; + return u && w.length === 0 ? Lo(s, l >>>= 0, h, y) : (s = { ec: h, Ab: s, Hb: y, Mb: w }, u ? (s.Bb = "spawnThread", postMessage(s, w), 0) : Do(s)); + } + var Ho = typeof TextDecoder < "u" ? new TextDecoder() : void 0, Fo = (s, l = 0, h = NaN) => { + var y = (l >>>= 0) + h; + for (h = l; s[h] && !(h >= y); ) ++h; + if (16 < h - l && s.buffer && Ho) return Ho.decode(s.buffer instanceof ArrayBuffer ? s.subarray(l, h) : s.slice(l, h)); + for (y = ""; l < h; ) { + var w = s[l++]; + if (128 & w) { + var A = 63 & s[l++]; + if ((224 & w) == 192) y += String.fromCharCode((31 & w) << 6 | A); + else { + var B = 63 & s[l++]; + 65536 > (w = (240 & w) == 224 ? (15 & w) << 12 | A << 6 | B : (7 & w) << 18 | A << 12 | B << 6 | 63 & s[l++]) ? y += String.fromCharCode(w) : (w -= 65536, y += String.fromCharCode(55296 | w >> 10, 56320 | 1023 & w)); + } + } else y += String.fromCharCode(w); + } + return y; + }, Te = (s, l) => (s >>>= 0) ? Fo(he(), s, l) : ""; + function qo(s, l, h) { + return u ? xe(3, 1, s, l, h) : 0; + } + function jo(s, l) { + if (u) return xe(4, 1, s, l); + } + var Ko = (s) => { + for (var l = 0, h = 0; h < s.length; ++h) { + var y = s.charCodeAt(h); + 127 >= y ? l++ : 2047 >= y ? l += 2 : 55296 <= y && 57343 >= y ? (l += 4, ++h) : l += 3; + } + return l; + }, zt = (s, l, h) => { + var y = he(); + if (l >>>= 0, 0 < h) { + var w = l; + h = l + h - 1; + for (var A = 0; A < s.length; ++A) { + var B = s.charCodeAt(A); + if (55296 <= B && 57343 >= B && (B = 65536 + ((1023 & B) << 10) | 1023 & s.charCodeAt(++A)), 127 >= B) { + if (l >= h) break; + y[l++ >>> 0] = B; + } else { + if (2047 >= B) { + if (l + 1 >= h) break; + y[l++ >>> 0] = 192 | B >> 6; + } else { + if (65535 >= B) { + if (l + 2 >= h) break; + y[l++ >>> 0] = 224 | B >> 12; + } else { + if (l + 3 >= h) break; + y[l++ >>> 0] = 240 | B >> 18, y[l++ >>> 0] = 128 | B >> 12 & 63; + } + y[l++ >>> 0] = 128 | B >> 6 & 63; + } + y[l++ >>> 0] = 128 | 63 & B; + } + } + y[l >>> 0] = 0, s = l - w; + } else s = 0; + return s; + }; + function Zo(s, l) { + if (u) return xe(5, 1, s, l); + } + function Qo(s, l, h) { + if (u) return xe(6, 1, s, l, h); + } + function Yo(s, l, h) { + return u ? xe(7, 1, s, l, h) : 0; + } + function Xo(s, l) { + if (u) return xe(8, 1, s, l); + } + function Jo(s, l, h) { + if (u) return xe(9, 1, s, l, h); + } + function ei(s, l, h, y) { + if (u) return xe(10, 1, s, l, h, y); + } + function ti(s, l, h, y) { + if (u) return xe(11, 1, s, l, h, y); + } + function ri(s, l, h, y) { + if (u) return xe(12, 1, s, l, h, y); + } + function ni(s) { + if (u) return xe(13, 1, s); + } + function oi(s, l) { + if (u) return xe(14, 1, s, l); + } + function ii(s, l, h) { + if (u) return xe(15, 1, s, l, h); + } + var ai, pt, xc = () => dt(""), Ke = (s) => { + for (var l = ""; he()[s >>> 0]; ) l += ai[he()[s++ >>> 0]]; + return l; + }, gn = {}, bn = {}, Sc = {}; + function it(s, l, h = {}) { + return (function(y, w, A = {}) { + var B = w.name; + if (!y) throw new pt(`type "${B}" must have a positive integer typeid pointer`); + if (bn.hasOwnProperty(y)) { + if (A.Sb) return; + throw new pt(`Cannot register type '${B}' twice`); + } + bn[y] = w, delete Sc[y], gn.hasOwnProperty(y) && (w = gn[y], delete gn[y], w.forEach((R) => R())); + })(s, l, h); + } + var si = (s, l, h) => { + switch (l) { + case 1: + return h ? (y) => ue()[y >>> 0] : (y) => he()[y >>> 0]; + case 2: + return h ? (y) => ye()[y >>> 1 >>> 0] : (y) => re()[y >>> 1 >>> 0]; + case 4: + return h ? (y) => C()[y >>> 2 >>> 0] : (y) => V()[y >>> 2 >>> 0]; + case 8: + return h ? (y) => Z[y >>> 3] : (y) => we[y >>> 3]; + default: + throw new TypeError(`invalid integer width (${l}): ${s}`); + } + }; + function Tc(s, l, h) { + h >>>= 0, it(s >>>= 0, { name: l = Ke(l >>> 0), fromWireType: (y) => y, toWireType: function(y, w) { + if (typeof w != "bigint" && typeof w != "number") throw w = w === null ? "null" : (y = typeof w) == "object" || y === "array" || y === "function" ? w.toString() : "" + w, new TypeError(`Cannot convert "${w}" to ${this.name}`); + return typeof w == "number" && (w = BigInt(w)), w; + }, Cb: mt, readValueFromPointer: si(l, h, l.indexOf("u") == -1), Db: null }); + } + var mt = 8; + function Ic(s, l, h, y) { + it(s >>>= 0, { name: l = Ke(l >>> 0), fromWireType: function(w) { + return !!w; + }, toWireType: function(w, A) { + return A ? h : y; + }, Cb: mt, readValueFromPointer: function(w) { + return this.fromWireType(he()[w >>> 0]); + }, Db: null }); + } + var yn = [], at = []; + function _n(s) { + 9 < (s >>>= 0) && --at[s + 1] == 0 && (at[s] = void 0, yn.push(s)); + } + var De = (s) => { + if (!s) throw new pt("Cannot use deleted val. handle = " + s); + return at[s]; + }, Ve = (s) => { + switch (s) { + case void 0: + return 2; + case null: + return 4; + case true: + return 6; + case false: + return 8; + default: + let l = yn.pop() || at.length; + return at[l] = s, at[l + 1] = 1, l; + } + }; + function wn(s) { + return this.fromWireType(V()[s >>> 2 >>> 0]); + } + var Cc = { name: "emscripten::val", fromWireType: (s) => { + var l = De(s); + return _n(s), l; + }, toWireType: (s, l) => Ve(l), Cb: mt, readValueFromPointer: wn, Db: null }; + function Ac(s) { + return it(s >>> 0, Cc); + } + var Ec = (s, l) => { + switch (l) { + case 4: + return function(h) { + return this.fromWireType(de()[h >>> 2 >>> 0]); + }; + case 8: + return function(h) { + return this.fromWireType(ze()[h >>> 3 >>> 0]); + }; + default: + throw new TypeError(`invalid float width (${l}): ${s}`); + } + }; + function kc(s, l, h) { + h >>>= 0, it(s >>>= 0, { name: l = Ke(l >>> 0), fromWireType: (y) => y, toWireType: (y, w) => w, Cb: mt, readValueFromPointer: Ec(l, h), Db: null }); + } + function Pc(s, l, h, y, w) { + if (s >>>= 0, h >>>= 0, l = Ke(l >>> 0), w === -1 && (w = 4294967295), w = (R) => R, y === 0) { + var A = 32 - 8 * h; + w = (R) => R << A >>> A; + } + var B = l.includes("unsigned") ? function(R, G) { + return G >>> 0; + } : function(R, G) { + return G; + }; + it(s, { name: l, fromWireType: w, toWireType: B, Cb: mt, readValueFromPointer: si(l, h, y !== 0), Db: null }); + } + function zc(s, l, h) { + function y(A) { + var B = V()[A >>> 2 >>> 0]; + return A = V()[A + 4 >>> 2 >>> 0], new w(ue().buffer, A, B); + } + var w = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, BigInt64Array, BigUint64Array][l]; + it(s >>>= 0, { name: h = Ke(h >>> 0), fromWireType: y, Cb: mt, readValueFromPointer: y }, { Sb: true }); + } + function Oc(s, l) { + it(s >>>= 0, { name: l = Ke(l >>> 0), fromWireType: function(h) { + for (var y, w = V()[h >>> 2 >>> 0], A = h + 4, B = A, R = 0; R <= w; ++R) { + var G = A + R; + R != w && he()[G >>> 0] != 0 || (B = Te(B, G - B), y === void 0 ? y = B : (y += "\0", y += B), B = G + 1); + } + return Qe(h), y; + }, toWireType: function(h, y) { + y instanceof ArrayBuffer && (y = new Uint8Array(y)); + var w = typeof y == "string"; + if (!(w || y instanceof Uint8Array || y instanceof Uint8ClampedArray || y instanceof Int8Array)) throw new pt("Cannot pass non-string to std::string"); + var A = w ? Ko(y) : y.length, B = pr(4 + A + 1), R = B + 4; + if (V()[B >>> 2 >>> 0] = A, w) zt(y, R, A + 1); + else if (w) for (w = 0; w < A; ++w) { + var G = y.charCodeAt(w); + if (255 < G) throw Qe(B), new pt("String has UTF-16 code units that do not fit in 8 bits"); + he()[R + w >>> 0] = G; + } + else for (w = 0; w < A; ++w) he()[R + w >>> 0] = y[w]; + return h !== null && h.push(Qe, B), B; + }, Cb: mt, readValueFromPointer: wn, Db(h) { + Qe(h); + } }); + } + var ui = typeof TextDecoder < "u" ? new TextDecoder("utf-16le") : void 0, Bc = (s, l) => { + for (var h = s >> 1, y = h + l / 2; !(h >= y) && re()[h >>> 0]; ) ++h; + if (32 < (h <<= 1) - s && ui) return ui.decode(he().slice(s, h)); + for (h = "", y = 0; !(y >= l / 2); ++y) { + var w = ye()[s + 2 * y >>> 1 >>> 0]; + if (w == 0) break; + h += String.fromCharCode(w); + } + return h; + }, Dc = (s, l, h) => { + if (h ??= 2147483647, 2 > h) return 0; + var y = l; + h = (h -= 2) < 2 * s.length ? h / 2 : s.length; + for (var w = 0; w < h; ++w) { + var A = s.charCodeAt(w); + ye()[l >>> 1 >>> 0] = A, l += 2; + } + return ye()[l >>> 1 >>> 0] = 0, l - y; + }, Mc = (s) => 2 * s.length, Rc = (s, l) => { + for (var h = 0, y = ""; !(h >= l / 4); ) { + var w = C()[s + 4 * h >>> 2 >>> 0]; + if (w == 0) break; + ++h, 65536 <= w ? (w -= 65536, y += String.fromCharCode(55296 | w >> 10, 56320 | 1023 & w)) : y += String.fromCharCode(w); + } + return y; + }, Uc = (s, l, h) => { + if (l >>>= 0, h ??= 2147483647, 4 > h) return 0; + var y = l; + h = y + h - 4; + for (var w = 0; w < s.length; ++w) { + var A = s.charCodeAt(w); + if (55296 <= A && 57343 >= A && (A = 65536 + ((1023 & A) << 10) | 1023 & s.charCodeAt(++w)), C()[l >>> 2 >>> 0] = A, (l += 4) + 4 > h) break; + } + return C()[l >>> 2 >>> 0] = 0, l - y; + }, Nc = (s) => { + for (var l = 0, h = 0; h < s.length; ++h) { + var y = s.charCodeAt(h); + 55296 <= y && 57343 >= y && ++h, l += 4; + } + return l; + }; + function Vc(s, l, h) { + if (s >>>= 0, l >>>= 0, h = Ke(h >>>= 0), l === 2) var y = Bc, w = Dc, A = Mc, B = (R) => re()[R >>> 1 >>> 0]; + else l === 4 && (y = Rc, w = Uc, A = Nc, B = (R) => V()[R >>> 2 >>> 0]); + it(s, { name: h, fromWireType: (R) => { + for (var G, K = V()[R >>> 2 >>> 0], ae = R + 4, le = 0; le <= K; ++le) { + var _e = R + 4 + le * l; + le != K && B(_e) != 0 || (ae = y(ae, _e - ae), G === void 0 ? G = ae : (G += "\0", G += ae), ae = _e + l); + } + return Qe(R), G; + }, toWireType: (R, G) => { + if (typeof G != "string") throw new pt(`Cannot pass non-string to C++ string type ${h}`); + var K = A(G), ae = pr(4 + K + l); + return V()[ae >>> 2 >>> 0] = K / l, w(G, ae + 4, K + l), R !== null && R.push(Qe, ae), ae; + }, Cb: mt, readValueFromPointer: wn, Db(R) { + Qe(R); + } }); + } + function Wc(s, l) { + it(s >>>= 0, { Tb: true, name: l = Ke(l >>> 0), Cb: 0, fromWireType: () => { + }, toWireType: () => { + } }); + } + function Lc(s) { + An(s >>> 0, !a, 1, !i, 131072, false), No(); + } + var vn = (s) => { + if (!te) try { + if (s(), !(0 < lt)) try { + u ? En(I) : hn(I); + } catch (l) { + l instanceof pn || l == "unwind" || g(0, l); + } + } catch (l) { + l instanceof pn || l == "unwind" || g(0, l); + } + }; + function $n(s) { + s >>>= 0, typeof Atomics.jc == "function" && (Atomics.jc(C(), s >>> 2, s).value.then(nr), s += 128, Atomics.store(C(), s >>> 2, 1)); + } + var nr = () => { + var s = cr(); + s && ($n(s), vn(Ui)); + }; + function Gc(s, l) { + (s >>>= 0) == l >>> 0 ? setTimeout(nr) : u ? postMessage({ Gb: s, Bb: "checkMailbox" }) : (s = wt[s]) && s.postMessage({ Bb: "checkMailbox" }); + } + var xn = []; + function Hc(s, l, h, y, w) { + for (l >>>= 0, y /= 2, xn.length = y, h = w >>> 0 >>> 3, w = 0; w < y; w++) xn[w] = Z[h + 2 * w] ? Z[h + 2 * w + 1] : ze()[h + 2 * w + 1 >>> 0]; + return (l ? cn[l] : Mp[s])(...xn); + } + var Fc = () => { + lt = 0; + }; + function qc(s) { + s >>>= 0, u ? postMessage({ Bb: "cleanupThread", hc: s }) : Uo(wt[s]); + } + function jc(s) { + } + var or = (s, l) => { + var h = bn[s]; + if (h === void 0) throw s = zi(s), h = Ke(s), Qe(s), new pt(`${l} has unknown type ${h}`); + return h; + }, di = (s, l, h) => { + var y = []; + return s = s.toWireType(y, h), y.length && (V()[l >>> 2 >>> 0] = Ve(y)), s; + }; + function Kc(s, l, h) { + return l >>>= 0, h >>>= 0, s = De(s >>> 0), l = or(l, "emval::as"), di(l, h, s); + } + function Zc(s, l) { + return l >>>= 0, s = De(s >>> 0), (l = or(l, "emval::as")).toWireType(null, s); + } + var ir = (s) => { + try { + s(); + } catch (l) { + dt(l); + } + }, ft = 0, Ze = null, li = 0, ar = [], ci = {}, pi = {}, Qc = 0, Sn = null, Yc = []; + function mi(s) { + return (function(l) { + if (!te) { + if (ft === 0) { + var h = false, y = false; + l((w = 0) => { + if (!te && (li = w, h = true, y)) { + ft = 2, ir(() => Gi(Ze)), typeof MainLoop < "u" && MainLoop.Pb && MainLoop.resume(), w = false; + try { + var A = (function() { + var G = C()[Ze + 8 >>> 2 >>> 0]; + return G = Y[pi[G]], --lt, G(); + })(); + } catch (G) { + A = G, w = true; + } + var B = false; + if (!Ze) { + var R = Sn; + R && (Sn = null, (w ? R.reject : R.resolve)(A), B = true); + } + if (w && !B) throw A; + } + }), y = true, h || (ft = 1, Ze = (function() { + var w = pr(65548), A = w + 12; + V()[w >>> 2 >>> 0] = A, V()[w + 4 >>> 2 >>> 0] = A + 65536, A = ar[0]; + var B = ci[A]; + return B === void 0 && (B = Qc++, ci[A] = B, pi[B] = A), A = B, C()[w + 8 >>> 2 >>> 0] = A, w; + })(), typeof MainLoop < "u" && MainLoop.Pb && MainLoop.pause(), ir(() => Wi(Ze))); + } else ft === 2 ? (ft = 0, ir(Hi), Qe(Ze), Ze = null, Yc.forEach(vn)) : dt(`invalid state: ${ft}`); + return li; + } + })((l) => { + s().then(l); + }); + } + function Xc(s) { + return s >>>= 0, mi(async () => { + var l = await De(s); + return Ve(l); + }); + } + var sr = []; + function Jc(s, l, h, y) { + return h >>>= 0, y >>>= 0, (s = sr[s >>> 0])(null, l = De(l >>> 0), h, y); + } + var ep = {}, ur = (s) => { + var l = ep[s]; + return l === void 0 ? Ke(s) : l; + }; + function tp(s, l, h, y, w) { + return h >>>= 0, y >>>= 0, w >>>= 0, (s = sr[s >>> 0])(l = De(l >>> 0), l[h = ur(h)], y, w); + } + var fi = () => typeof globalThis == "object" ? globalThis : Function("return this")(); + function rp(s) { + return (s >>>= 0) == 0 ? Ve(fi()) : (s = ur(s), Ve(fi()[s])); + } + var np = (s) => { + var l = sr.length; + return sr.push(s), l; + }, op = (s, l) => { + for (var h = Array(s), y = 0; y < s; ++y) h[y] = or(V()[l + 4 * y >>> 2 >>> 0], "parameter " + y); + return h; + }, hi = (s, l) => Object.defineProperty(l, "name", { value: s }); + function ip(s, l, h) { + var y = (l = op(s, l >>> 0)).shift(); + s--; + var w = `return function (obj, func, destructorsRef, args) { +`, A = 0, B = []; + h === 0 && B.push("obj"); + for (var R = ["retType"], G = [y], K = 0; K < s; ++K) B.push("arg" + K), R.push("argType" + K), G.push(l[K]), w += ` var arg${K} = argType${K}.readValueFromPointer(args${A ? "+" + A : ""}); +`, A += l[K].Cb; + return w += ` var rv = ${h === 1 ? "new func" : "func.call"}(${B.join(", ")}); +`, y.Tb || (R.push("emval_returnValue"), G.push(di), w += ` return emval_returnValue(retType, destructorsRef, rv); +`), R.push(w + `}; +`), s = (function(ae) { + var le = Function; + if (!(le instanceof Function)) throw new TypeError(`new_ called with constructor type ${typeof le} which is not a function`); + var _e = hi(le.name || "unknownFunctionName", function() { + }); + return _e.prototype = le.prototype, _e = new _e(), (ae = le.apply(_e, ae)) instanceof Object ? ae : _e; + })(R)(...G), h = `methodCaller<(${l.map((ae) => ae.name).join(", ")}) => ${y.name}>`, np(hi(h, s)); + } + function ap(s) { + return s = ur(s >>> 0), Ve(n[s]); + } + function sp(s, l) { + return l >>>= 0, s = De(s >>> 0), l = De(l), Ve(s[l]); + } + function up(s) { + 9 < (s >>>= 0) && (at[s + 1] += 1); + } + function dp() { + return Ve([]); + } + function lp(s) { + s = De(s >>> 0); + for (var l = Array(s.length), h = 0; h < s.length; h++) l[h] = s[h]; + return Ve(l); + } + function cp(s) { + return Ve(ur(s >>> 0)); + } + function pp() { + return Ve({}); + } + function mp(s) { + for (var l = De(s >>>= 0); l.length; ) { + var h = l.pop(); + l.pop()(h); + } + _n(s); + } + function fp(s, l, h) { + l >>>= 0, h >>>= 0, s = De(s >>> 0), l = De(l), h = De(h), s[l] = h; + } + function hp(s, l) { + return l >>>= 0, s = (s = or(s >>> 0, "_emval_take_value")).readValueFromPointer(l), Ve(s); + } + function gp(s, l) { + s = -9007199254740992 > s || 9007199254740992 < s ? NaN : Number(s), l >>>= 0, s = new Date(1e3 * s), C()[l >>> 2 >>> 0] = s.getUTCSeconds(), C()[l + 4 >>> 2 >>> 0] = s.getUTCMinutes(), C()[l + 8 >>> 2 >>> 0] = s.getUTCHours(), C()[l + 12 >>> 2 >>> 0] = s.getUTCDate(), C()[l + 16 >>> 2 >>> 0] = s.getUTCMonth(), C()[l + 20 >>> 2 >>> 0] = s.getUTCFullYear() - 1900, C()[l + 24 >>> 2 >>> 0] = s.getUTCDay(), s = (s.getTime() - Date.UTC(s.getUTCFullYear(), 0, 1, 0, 0, 0, 0)) / 864e5 | 0, C()[l + 28 >>> 2 >>> 0] = s; + } + var gi = (s) => s % 4 == 0 && (s % 100 != 0 || s % 400 == 0), bi = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335], yi = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; + function bp(s, l) { + s = -9007199254740992 > s || 9007199254740992 < s ? NaN : Number(s), l >>>= 0, s = new Date(1e3 * s), C()[l >>> 2 >>> 0] = s.getSeconds(), C()[l + 4 >>> 2 >>> 0] = s.getMinutes(), C()[l + 8 >>> 2 >>> 0] = s.getHours(), C()[l + 12 >>> 2 >>> 0] = s.getDate(), C()[l + 16 >>> 2 >>> 0] = s.getMonth(), C()[l + 20 >>> 2 >>> 0] = s.getFullYear() - 1900, C()[l + 24 >>> 2 >>> 0] = s.getDay(); + var h = (gi(s.getFullYear()) ? bi : yi)[s.getMonth()] + s.getDate() - 1 | 0; + C()[l + 28 >>> 2 >>> 0] = h, C()[l + 36 >>> 2 >>> 0] = -60 * s.getTimezoneOffset(), h = new Date(s.getFullYear(), 6, 1).getTimezoneOffset(); + var y = new Date(s.getFullYear(), 0, 1).getTimezoneOffset(); + s = 0 | (h != y && s.getTimezoneOffset() == Math.min(y, h)), C()[l + 32 >>> 2 >>> 0] = s; + } + function yp(s) { + s >>>= 0; + var l = new Date(C()[s + 20 >>> 2 >>> 0] + 1900, C()[s + 16 >>> 2 >>> 0], C()[s + 12 >>> 2 >>> 0], C()[s + 8 >>> 2 >>> 0], C()[s + 4 >>> 2 >>> 0], C()[s >>> 2 >>> 0], 0), h = C()[s + 32 >>> 2 >>> 0], y = l.getTimezoneOffset(), w = new Date(l.getFullYear(), 6, 1).getTimezoneOffset(), A = new Date(l.getFullYear(), 0, 1).getTimezoneOffset(), B = Math.min(A, w); + return 0 > h ? C()[s + 32 >>> 2 >>> 0] = +(w != A && B == y) : 0 < h != (B == y) && (w = Math.max(A, w), l.setTime(l.getTime() + 6e4 * ((0 < h ? B : w) - y))), C()[s + 24 >>> 2 >>> 0] = l.getDay(), h = (gi(l.getFullYear()) ? bi : yi)[l.getMonth()] + l.getDate() - 1 | 0, C()[s + 28 >>> 2 >>> 0] = h, C()[s >>> 2 >>> 0] = l.getSeconds(), C()[s + 4 >>> 2 >>> 0] = l.getMinutes(), C()[s + 8 >>> 2 >>> 0] = l.getHours(), C()[s + 12 >>> 2 >>> 0] = l.getDate(), C()[s + 16 >>> 2 >>> 0] = l.getMonth(), C()[s + 20 >>> 2 >>> 0] = l.getYear(), s = l.getTime(), BigInt(isNaN(s) ? -1 : s / 1e3); + } + function _i(s, l, h, y, w, A, B) { + return u ? xe(16, 1, s, l, h, y, w, A, B) : -52; + } + function wi(s, l, h, y, w, A) { + if (u) return xe(17, 1, s, l, h, y, w, A); + } + var Ht = {}, _p = () => performance.timeOrigin + performance.now(); + function vi(s, l) { + if (u) return xe(18, 1, s, l); + if (Ht[s] && (clearTimeout(Ht[s].id), delete Ht[s]), !l) return 0; + var h = setTimeout(() => { + delete Ht[s], vn(() => Ri(s, performance.timeOrigin + performance.now())); + }, l); + return Ht[s] = { id: h, qc: l }, 0; + } + function wp(s, l, h, y) { + s >>>= 0, l >>>= 0, h >>>= 0, y >>>= 0; + var w = (/* @__PURE__ */ new Date()).getFullYear(), A = new Date(w, 0, 1).getTimezoneOffset(); + w = new Date(w, 6, 1).getTimezoneOffset(); + var B = Math.max(A, w); + V()[s >>> 2 >>> 0] = 60 * B, C()[l >>> 2 >>> 0] = +(A != w), s = (l = (R) => { + var G = Math.abs(R); + return `UTC${0 <= R ? "-" : "+"}${String(Math.floor(G / 60)).padStart(2, "0")}${String(G % 60).padStart(2, "0")}`; + })(A), l = l(w), w < A ? (zt(s, h, 17), zt(l, y, 17)) : (zt(s, y, 17), zt(l, h, 17)); + } + var vp = () => Date.now(), $p = 1; + function xp(s, l, h) { + if (!(0 <= s && 3 >= s)) return 28; + if (s === 0) s = Date.now(); + else { + if (!$p) return 52; + s = performance.timeOrigin + performance.now(); + } + return Z[h >>> 0 >>> 3] = BigInt(Math.round(1e6 * s)), 0; + } + var Tn = [], $i = (s, l) => { + Tn.length = 0; + for (var h; h = he()[s++ >>> 0]; ) { + var y = h != 105; + l += (y &= h != 112) && l % 8 ? 4 : 0, Tn.push(h == 112 ? V()[l >>> 2 >>> 0] : h == 106 ? Z[l >>> 3] : h == 105 ? C()[l >>> 2 >>> 0] : ze()[l >>> 3 >>> 0]), l += y ? 8 : 4; + } + return Tn; + }; + function Sp(s, l, h) { + return s >>>= 0, l = $i(l >>> 0, h >>> 0), cn[s](...l); + } + function Tp(s, l, h) { + return s >>>= 0, l = $i(l >>> 0, h >>> 0), cn[s](...l); + } + var Ip = () => { + }; + function Cp(s, l) { + return x(Te(s >>> 0, l >>> 0)); + } + var Ap = () => { + throw lt += 1, "unwind"; + }; + function Ep() { + return 4294901760; + } + var kp = () => navigator.hardwareConcurrency; + function Pp() { + return dt("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"), 0; + } + function zp(s) { + s >>>= 0; + var l = he().length; + if (s <= l || 4294901760 < s) return false; + for (var h = 1; 4 >= h; h *= 2) { + var y = l * (1 + 0.2 / h); + y = Math.min(y, s + 100663296); + e: { + y = (Math.min(4294901760, 65536 * Math.ceil(Math.max(s, y) / 65536)) - T.buffer.byteLength + 65535) / 65536 | 0; + try { + T.grow(y), Ce(); + var w = 1; + break e; + } catch { + } + w = void 0; + } + if (w) return true; + } + return false; + } + var dr = () => (dt("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"), 0), Ot = {}, xi = (s) => { + s.forEach((l) => { + var h = dr(); + h && (Ot[h] = l); + }); + }; + function Op() { + var s = Error().stack.toString().split(` +`); + return s[0] == "Error" && s.shift(), xi(s), Ot.Lb = dr(), Ot.cc = s, Ot.Lb; + } + function Bp(s, l, h) { + if (s >>>= 0, l >>>= 0, Ot.Lb == s) var y = Ot.cc; + else (y = Error().stack.toString().split(` +`))[0] == "Error" && y.shift(), xi(y); + for (var w = 3; y[w] && dr() != s; ) ++w; + for (s = 0; s < h && y[s + w]; ++s) C()[l + 4 * s >>> 2 >>> 0] = dr(); + return s; + } + var In, Cn = {}, Si = () => { + if (!In) { + var s, l = { USER: "web_user", LOGNAME: "web_user", PATH: "/", PWD: "/", HOME: "/home/web_user", LANG: (typeof navigator == "object" && navigator.languages && navigator.languages[0] || "C").replace("-", "_") + ".UTF-8", _: "./this.program" }; + for (s in Cn) Cn[s] === void 0 ? delete l[s] : l[s] = Cn[s]; + var h = []; + for (s in l) h.push(`${s}=${l[s]}`); + In = h; + } + return In; + }; + function Ti(s, l) { + if (u) return xe(19, 1, s, l); + s >>>= 0, l >>>= 0; + var h = 0; + return Si().forEach((y, w) => { + var A = l + h; + for (w = V()[s + 4 * w >>> 2 >>> 0] = A, A = 0; A < y.length; ++A) ue()[w++ >>> 0] = y.charCodeAt(A); + ue()[w >>> 0] = 0, h += y.length + 1; + }), 0; + } + function Ii(s, l) { + if (u) return xe(20, 1, s, l); + s >>>= 0, l >>>= 0; + var h = Si(); + V()[s >>> 2 >>> 0] = h.length; + var y = 0; + return h.forEach((w) => y += w.length + 1), V()[l >>> 2 >>> 0] = y, 0; + } + function Ci(s) { + return u ? xe(21, 1, s) : 52; + } + function Ai(s, l, h, y) { + return u ? xe(22, 1, s, l, h, y) : 52; + } + function Ei(s, l, h, y) { + return u ? xe(23, 1, s, l, h, y) : 70; + } + var Dp = [null, [], []]; + function ki(s, l, h, y) { + if (u) return xe(24, 1, s, l, h, y); + l >>>= 0, h >>>= 0, y >>>= 0; + for (var w = 0, A = 0; A < h; A++) { + var B = V()[l >>> 2 >>> 0], R = V()[l + 4 >>> 2 >>> 0]; + l += 8; + for (var G = 0; G < R; G++) { + var K = he()[B + G >>> 0], ae = Dp[s]; + K === 0 || K === 10 ? ((s === 1 ? v : x)(Fo(ae)), ae.length = 0) : ae.push(K); + } + w += R; + } + return V()[y >>> 2 >>> 0] = w, 0; + } + u || (function() { + for (var s = n.numThreads - 1; s--; ) Wo(); + mn.unshift(() => { + Pt++, (function(l) { + u ? l() : Promise.all(ct.map(Vo)).then(l); + })(() => zo()); + }); + })(); + for (var Pi = Array(256), lr = 0; 256 > lr; ++lr) Pi[lr] = String.fromCharCode(lr); + ai = Pi, pt = n.BindingError = class extends Error { + constructor(s) { + super(s), this.name = "BindingError"; + } + }, n.InternalError = class extends Error { + constructor(s) { + super(s), this.name = "InternalError"; + } + }, at.push(0, 1, void 0, 1, null, 1, true, 1, false, 1), n.count_emval_handles = () => at.length / 2 - 5 - yn.length; + var Y, Mp = [fn, Mo, Lo, qo, jo, Zo, Qo, Yo, Xo, Jo, ei, ti, ri, ni, oi, ii, _i, wi, vi, Ti, Ii, Ci, Ai, Ei, ki]; + (async function() { + function s(y, w) { + return Y = y.exports, Y = (function() { + var A = Y, B = {}; + for (let [R, G] of Object.entries(A)) B[R] = typeof G == "function" ? (...K) => { + ar.push(R); + try { + return G(...K); + } finally { + te || (ar.pop(), Ze && ft === 1 && ar.length === 0 && (ft = 0, lt += 1, ir(Li), typeof Fibers < "u" && Fibers.rc())); + } + } : G; + return B; + })(), Y = (function() { + var A = Y, B = (G) => (K) => G(K) >>> 0, R = (G) => () => G() >>> 0; + return (A = Object.assign({}, A)).Da = B(A.Da), A.fb = R(A.fb), A.hb = B(A.hb), A.tb = B(A.tb), A.ub = R(A.ub), A.__cxa_get_exception_ptr = B(A.__cxa_get_exception_ptr), A; + })(), Ro.push(Y.ib), E = w, zo(), Y; + } + Pt++; + var l = Oo(); + if (n.instantiateWasm) return new Promise((y) => { + n.instantiateWasm(l, (w, A) => { + s(w, A), y(w.exports); + }); + }); + if (u) return new Promise((y) => { + ve = (w) => { + var A = new WebAssembly.Instance(w, Oo()); + y(s(A, w)); + }; + }); + kt ??= n.locateFile ? n.locateFile ? n.locateFile("ort-wasm-simd-threaded.jsep.wasm", _) : _ + "ort-wasm-simd-threaded.jsep.wasm" : new URL("ort-wasm-simd-threaded.jsep.wasm", import_meta.url).href; + try { + var h = await (async function(y) { + var w = kt; + if (!j && typeof WebAssembly.instantiateStreaming == "function" && !X(w)) try { + var A = fetch(w, { credentials: "same-origin" }); + return await WebAssembly.instantiateStreaming(A, y); + } catch (B) { + x(`wasm streaming compile failed: ${B}`), x("falling back to ArrayBuffer instantiation"); + } + return (async function(B, R) { + try { + var G = await (async function(K) { + if (!j) try { + var ae = await m(K); + return new Uint8Array(ae); + } catch { + } + if (K == kt && j) K = new Uint8Array(j); + else { + if (!f) throw "both async and sync fetching of the wasm failed"; + K = f(K); + } + return K; + })(B); + return await WebAssembly.instantiate(G, R); + } catch (K) { + x(`failed to asynchronously prepare wasm: ${K}`), dt(K); + } + })(w, y); + })(l); + return s(h.instance, h.module); + } catch (y) { + return r(y), Promise.reject(y); + } + })(); + var zi = (s) => (zi = Y.Da)(s), Oi = () => (Oi = Y.Ea)(); + n._OrtInit = (s, l) => (n._OrtInit = Y.Fa)(s, l), n._OrtGetLastError = (s, l) => (n._OrtGetLastError = Y.Ga)(s, l), n._OrtCreateSessionOptions = (s, l, h, y, w, A, B, R, G, K) => (n._OrtCreateSessionOptions = Y.Ha)(s, l, h, y, w, A, B, R, G, K), n._OrtAppendExecutionProvider = (s, l, h, y, w) => (n._OrtAppendExecutionProvider = Y.Ia)(s, l, h, y, w), n._OrtAddFreeDimensionOverride = (s, l, h) => (n._OrtAddFreeDimensionOverride = Y.Ja)(s, l, h), n._OrtAddSessionConfigEntry = (s, l, h) => (n._OrtAddSessionConfigEntry = Y.Ka)(s, l, h), n._OrtReleaseSessionOptions = (s) => (n._OrtReleaseSessionOptions = Y.La)(s), n._OrtCreateSession = (s, l, h) => (n._OrtCreateSession = Y.Ma)(s, l, h), n._OrtReleaseSession = (s) => (n._OrtReleaseSession = Y.Na)(s), n._OrtGetInputOutputCount = (s, l, h) => (n._OrtGetInputOutputCount = Y.Oa)(s, l, h), n._OrtGetInputOutputMetadata = (s, l, h, y) => (n._OrtGetInputOutputMetadata = Y.Pa)(s, l, h, y), n._OrtFree = (s) => (n._OrtFree = Y.Qa)(s), n._OrtCreateTensor = (s, l, h, y, w, A) => (n._OrtCreateTensor = Y.Ra)(s, l, h, y, w, A), n._OrtGetTensorData = (s, l, h, y, w) => (n._OrtGetTensorData = Y.Sa)(s, l, h, y, w), n._OrtReleaseTensor = (s) => (n._OrtReleaseTensor = Y.Ta)(s), n._OrtCreateRunOptions = (s, l, h, y) => (n._OrtCreateRunOptions = Y.Ua)(s, l, h, y), n._OrtAddRunConfigEntry = (s, l, h) => (n._OrtAddRunConfigEntry = Y.Va)(s, l, h), n._OrtReleaseRunOptions = (s) => (n._OrtReleaseRunOptions = Y.Wa)(s), n._OrtCreateBinding = (s) => (n._OrtCreateBinding = Y.Xa)(s), n._OrtBindInput = (s, l, h) => (n._OrtBindInput = Y.Ya)(s, l, h), n._OrtBindOutput = (s, l, h, y) => (n._OrtBindOutput = Y.Za)(s, l, h, y), n._OrtClearBoundOutputs = (s) => (n._OrtClearBoundOutputs = Y._a)(s), n._OrtReleaseBinding = (s) => (n._OrtReleaseBinding = Y.$a)(s), n._OrtRunWithBinding = (s, l, h, y, w) => (n._OrtRunWithBinding = Y.ab)(s, l, h, y, w), n._OrtRun = (s, l, h, y, w, A, B, R) => (n._OrtRun = Y.bb)(s, l, h, y, w, A, B, R), n._OrtEndProfiling = (s) => (n._OrtEndProfiling = Y.cb)(s), n._JsepOutput = (s, l, h) => (n._JsepOutput = Y.db)(s, l, h), n._JsepGetNodeName = (s) => (n._JsepGetNodeName = Y.eb)(s); + var cr = () => (cr = Y.fb)(), Qe = n._free = (s) => (Qe = n._free = Y.gb)(s), pr = n._malloc = (s) => (pr = n._malloc = Y.hb)(s), An = (s, l, h, y, w, A) => (An = Y.kb)(s, l, h, y, w, A), Bi = () => (Bi = Y.lb)(), Di = (s, l, h, y, w) => (Di = Y.mb)(s, l, h, y, w), Mi = (s) => (Mi = Y.nb)(s), En = (s) => (En = Y.ob)(s), Ri = (s, l) => (Ri = Y.pb)(s, l), Ui = () => (Ui = Y.qb)(), Ni = (s, l) => (Ni = Y.rb)(s, l), mr = (s) => (mr = Y.sb)(s), kn = (s) => (kn = Y.tb)(s), Pn = () => (Pn = Y.ub)(), Vi = n.dynCall_ii = (s, l) => (Vi = n.dynCall_ii = Y.vb)(s, l), Wi = (s) => (Wi = Y.wb)(s), Li = () => (Li = Y.xb)(), Gi = (s) => (Gi = Y.yb)(s), Hi = () => (Hi = Y.zb)(); + return n.stackSave = () => Pn(), n.stackRestore = (s) => mr(s), n.stackAlloc = (s) => kn(s), n.setValue = function(s, l, h = "i8") { + switch (h.endsWith("*") && (h = "*"), h) { + case "i1": + case "i8": + ue()[s >>> 0] = l; + break; + case "i16": + ye()[s >>> 1 >>> 0] = l; + break; + case "i32": + C()[s >>> 2 >>> 0] = l; + break; + case "i64": + Z[s >>> 3] = BigInt(l); + break; + case "float": + de()[s >>> 2 >>> 0] = l; + break; + case "double": + ze()[s >>> 3 >>> 0] = l; + break; + case "*": + V()[s >>> 2 >>> 0] = l; + break; + default: + dt(`invalid type for setValue: ${h}`); + } + }, n.getValue = function(s, l = "i8") { + switch (l.endsWith("*") && (l = "*"), l) { + case "i1": + case "i8": + return ue()[s >>> 0]; + case "i16": + return ye()[s >>> 1 >>> 0]; + case "i32": + return C()[s >>> 2 >>> 0]; + case "i64": + return Z[s >>> 3]; + case "float": + return de()[s >>> 2 >>> 0]; + case "double": + return ze()[s >>> 3 >>> 0]; + case "*": + return V()[s >>> 2 >>> 0]; + default: + dt(`invalid type for getValue: ${l}`); + } + }, n.UTF8ToString = Te, n.stringToUTF8 = zt, n.lengthBytesUTF8 = Ko, (function s() { + if (0 < Pt) Lt = s; + else if (u) t(n), _t(); + else { + for (; 0 < mn.length; ) mn.shift()(n); + 0 < Pt ? Lt = s : (n.calledRun = true, te || (_t(), t(n))); + } + })(), n.PTR_SIZE = 4, o; + }), Fp = Sa, qp = globalThis.self?.name?.startsWith("em-pthread"); + qp && Sa(); + }); + var Ea; + var Gn; + var jp; + var Ue; + var ka; + var Ln; + var Kp; + var Zp; + var Pa; + var Qp; + var Ca; + var za; + var Aa; + var Oa; + var _r = U(() => { + "use strict"; + yr(); + Ea = typeof location > "u" ? void 0 : location.origin, Gn = import_meta.url > "file:" && import_meta.url < "file;", jp = () => { + if (true) { + if (Gn) { + let e = URL; + return new URL(new e("ort.bundle.min.mjs", import_meta.url).href, Ea).href; + } + return import_meta.url; + } + }, Ue = jp(), ka = () => { + if (Ue && !Ue.startsWith("blob:")) return Ue.substring(0, Ue.lastIndexOf("/") + 1); + }, Ln = (e, t) => { + try { + let r = t ?? Ue; + return (r ? new URL(e, r) : new URL(e)).origin === Ea; + } catch { + return false; + } + }, Kp = (e, t) => { + let r = t ?? Ue; + try { + return (r ? new URL(e, r) : new URL(e)).href; + } catch { + return; + } + }, Zp = (e, t) => `${t ?? "./"}${e}`, Pa = async (e) => { + let r = await (await fetch(e, { credentials: "same-origin" })).blob(); + return URL.createObjectURL(r); + }, Qp = async (e) => (await import( + /*webpackIgnore:true*/ + e + )).default, Ca = (xa(), Ft($a)).default, za = async () => { + if (!Ue) throw new Error("Failed to load proxy worker: cannot determine the script source URL."); + if (Ln(Ue)) return [void 0, Ca()]; + let e = await Pa(Ue); + return [e, Ca(e)]; + }, Aa = (Ia(), Ft(Ta)).default, Oa = async (e, t, r) => { + if (!e && !t && Aa && Ue && Ln(Ue)) return [void 0, Aa]; + { + let n = "ort-wasm-simd-threaded.jsep.mjs", o = e ?? Kp(n, t), i = r && o && !Ln(o, t), a = i ? await Pa(o) : o ?? Zp(n, t); + return [i ? a : void 0, await Qp(a)]; + } + }; + }); + var Hn; + var Fn; + var Ar; + var Ba; + var Yp; + var Xp; + var Jp; + var wr; + var fe; + var ht = U(() => { + "use strict"; + _r(); + Fn = false, Ar = false, Ba = false, Yp = () => { + if (typeof SharedArrayBuffer > "u") return false; + try { + return typeof MessageChannel < "u" && new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)), WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5, 4, 1, 3, 1, 1, 10, 11, 1, 9, 0, 65, 0, 254, 16, 2, 0, 26, 11])); + } catch { + return false; + } + }, Xp = () => { + try { + return WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 30, 1, 28, 0, 65, 0, 253, 15, 253, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 253, 186, 1, 26, 11])); + } catch { + return false; + } + }, Jp = () => { + try { + return WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 19, 1, 17, 0, 65, 1, 253, 15, 65, 2, 253, 15, 65, 3, 253, 15, 253, 147, 2, 11])); + } catch { + return false; + } + }, wr = async (e) => { + if (Fn) return Promise.resolve(); + if (Ar) throw new Error("multiple calls to 'initializeWebAssembly()' detected."); + if (Ba) throw new Error("previous call to 'initializeWebAssembly()' failed."); + Ar = true; + let t = e.initTimeout, r = e.numThreads; + if (e.simd !== false) { + if (e.simd === "relaxed") { + if (!Jp()) throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment."); + } else if (!Xp()) throw new Error("WebAssembly SIMD is not supported in the current environment."); + } + let n = Yp(); + r > 1 && !n && (typeof self < "u" && !self.crossOriginIsolated && console.warn("env.wasm.numThreads is set to " + r + ", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."), console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."), e.numThreads = r = 1); + let o = e.wasmPaths, i = typeof o == "string" ? o : void 0, a = o?.mjs, u = a?.href ?? a, d = o?.wasm, c = d?.href ?? d, p = e.wasmBinary, [m, f] = await Oa(u, i, r > 1), b = false, g = []; + if (t > 0 && g.push(new Promise((_) => { + setTimeout(() => { + b = true, _(); + }, t); + })), g.push(new Promise((_, S) => { + let $ = { numThreads: r }; + if (p) $.wasmBinary = p; + else if (c || i) $.locateFile = (v) => c ?? i + v; + else if (u && u.indexOf("blob:") !== 0) $.locateFile = (v) => new URL(v, u).href; + else if (m) { + let v = ka(); + v && ($.locateFile = (x) => v + x); + } + f($).then((v) => { + Ar = false, Fn = true, Hn = v, _(), m && URL.revokeObjectURL(m); + }, (v) => { + Ar = false, Ba = true, S(v); + }); + })), await Promise.race(g), b) throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`); + }, fe = () => { + if (Fn && Hn) return Hn; + throw new Error("WebAssembly is not initialized yet."); + }; + }); + var Ne; + var Kt; + var pe; + var Er = U(() => { + "use strict"; + ht(); + Ne = (e, t) => { + let r = fe(), n = r.lengthBytesUTF8(e) + 1, o = r._malloc(n); + return r.stringToUTF8(e, o, n), t.push(o), o; + }, Kt = (e, t, r, n) => { + if (typeof e == "object" && e !== null) { + if (r.has(e)) throw new Error("Circular reference in options"); + r.add(e); + } + Object.entries(e).forEach(([o, i]) => { + let a = t ? t + o : o; + if (typeof i == "object") Kt(i, a + ".", r, n); + else if (typeof i == "string" || typeof i == "number") n(a, i.toString()); + else if (typeof i == "boolean") n(a, i ? "1" : "0"); + else throw new Error(`Can't handle extra config type: ${typeof i}`); + }); + }, pe = (e) => { + let t = fe(), r = t.stackSave(); + try { + let n = t.PTR_SIZE, o = t.stackAlloc(2 * n); + t._OrtGetLastError(o, o + n); + let i = Number(t.getValue(o, n === 4 ? "i32" : "i64")), a = t.getValue(o + n, "*"), u = a ? t.UTF8ToString(a) : ""; + throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${u}`); + } finally { + t.stackRestore(r); + } + }; + }); + var Da; + var Ma = U(() => { + "use strict"; + ht(); + Er(); + Da = (e) => { + let t = fe(), r = 0, n = [], o = e || {}; + try { + if (e?.logSeverityLevel === void 0) o.logSeverityLevel = 2; + else if (typeof e.logSeverityLevel != "number" || !Number.isInteger(e.logSeverityLevel) || e.logSeverityLevel < 0 || e.logSeverityLevel > 4) throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`); + if (e?.logVerbosityLevel === void 0) o.logVerbosityLevel = 0; + else if (typeof e.logVerbosityLevel != "number" || !Number.isInteger(e.logVerbosityLevel)) throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`); + e?.terminate === void 0 && (o.terminate = false); + let i = 0; + return e?.tag !== void 0 && (i = Ne(e.tag, n)), r = t._OrtCreateRunOptions(o.logSeverityLevel, o.logVerbosityLevel, !!o.terminate, i), r === 0 && pe("Can't create run options."), e?.extra !== void 0 && Kt(e.extra, "", /* @__PURE__ */ new WeakSet(), (a, u) => { + let d = Ne(a, n), c = Ne(u, n); + t._OrtAddRunConfigEntry(r, d, c) !== 0 && pe(`Can't set a run config entry: ${a} - ${u}.`); + }), [r, n]; + } catch (i) { + throw r !== 0 && t._OrtReleaseRunOptions(r), n.forEach((a) => t._free(a)), i; + } + }; + }); + var em; + var tm; + var rm; + var kr; + var nm; + var Ra; + var Ua = U(() => { + "use strict"; + ht(); + Er(); + em = (e) => { + switch (e) { + case "disabled": + return 0; + case "basic": + return 1; + case "extended": + return 2; + case "all": + return 99; + default: + throw new Error(`unsupported graph optimization level: ${e}`); + } + }, tm = (e) => { + switch (e) { + case "sequential": + return 0; + case "parallel": + return 1; + default: + throw new Error(`unsupported execution mode: ${e}`); + } + }, rm = (e) => { + e.extra || (e.extra = {}), e.extra.session || (e.extra.session = {}); + let t = e.extra.session; + t.use_ort_model_bytes_directly || (t.use_ort_model_bytes_directly = "1"), e.executionProviders && e.executionProviders.some((r) => (typeof r == "string" ? r : r.name) === "webgpu") && (e.enableMemPattern = false); + }, kr = (e, t, r, n) => { + let o = Ne(t, n), i = Ne(r, n); + fe()._OrtAddSessionConfigEntry(e, o, i) !== 0 && pe(`Can't set a session config entry: ${t} - ${r}.`); + }, nm = async (e, t, r) => { + for (let n of t) { + let o = typeof n == "string" ? n : n.name, i = []; + switch (o) { + case "webnn": + if (o = "WEBNN", typeof n != "string") { + let m = n?.deviceType; + m && kr(e, "deviceType", m, r); + } + break; + case "webgpu": + if (o = "JS", typeof n != "string") { + let p = n; + if (p?.preferredLayout) { + if (p.preferredLayout !== "NCHW" && p.preferredLayout !== "NHWC") throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${p.preferredLayout}`); + kr(e, "preferredLayout", p.preferredLayout, r); + } + } + break; + case "wasm": + case "cpu": + continue; + default: + throw new Error(`not supported execution provider: ${o}`); + } + let a = Ne(o, r), u = i.length, d = 0, c = 0; + if (u > 0) { + d = fe()._malloc(u * fe().PTR_SIZE), r.push(d), c = fe()._malloc(u * fe().PTR_SIZE), r.push(c); + for (let p = 0; p < u; p++) fe().setValue(d + p * fe().PTR_SIZE, i[p][0], "*"), fe().setValue(c + p * fe().PTR_SIZE, i[p][1], "*"); + } + await fe()._OrtAppendExecutionProvider(e, a, d, c, u) !== 0 && pe(`Can't append execution provider: ${o}.`); + } + }, Ra = async (e) => { + let t = fe(), r = 0, n = [], o = e || {}; + rm(o); + try { + let i = em(o.graphOptimizationLevel ?? "all"), a = tm(o.executionMode ?? "sequential"), u = typeof o.logId == "string" ? Ne(o.logId, n) : 0, d = o.logSeverityLevel ?? 2; + if (!Number.isInteger(d) || d < 0 || d > 4) throw new Error(`log serverity level is not valid: ${d}`); + let c = o.logVerbosityLevel ?? 0; + if (!Number.isInteger(c) || c < 0 || c > 4) throw new Error(`log verbosity level is not valid: ${c}`); + let p = typeof o.optimizedModelFilePath == "string" ? Ne(o.optimizedModelFilePath, n) : 0; + if (r = t._OrtCreateSessionOptions(i, !!o.enableCpuMemArena, !!o.enableMemPattern, a, !!o.enableProfiling, 0, u, d, c, p), r === 0 && pe("Can't create session options."), o.executionProviders && await nm(r, o.executionProviders, n), o.enableGraphCapture !== void 0) { + if (typeof o.enableGraphCapture != "boolean") throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`); + kr(r, "enableGraphCapture", o.enableGraphCapture.toString(), n); + } + if (o.freeDimensionOverrides) for (let [m, f] of Object.entries(o.freeDimensionOverrides)) { + if (typeof m != "string") throw new Error(`free dimension override name must be a string: ${m}`); + if (typeof f != "number" || !Number.isInteger(f) || f < 0) throw new Error(`free dimension override value must be a non-negative integer: ${f}`); + let b = Ne(m, n); + t._OrtAddFreeDimensionOverride(r, b, f) !== 0 && pe(`Can't set a free dimension override: ${m} - ${f}.`); + } + return o.extra !== void 0 && Kt(o.extra, "", /* @__PURE__ */ new WeakSet(), (m, f) => { + kr(r, m, f, n); + }), [r, n]; + } catch (i) { + throw r !== 0 && t._OrtReleaseSessionOptions(r) !== 0 && pe("Can't release session options."), n.forEach((a) => t._free(a)), i; + } + }; + }); + var Mt; + var Ye; + var gt; + var Pr; + var Zt; + var zr; + var Or; + var qn; + var ee = U(() => { + "use strict"; + Mt = (e) => { + switch (e) { + case "int8": + return 3; + case "uint8": + return 2; + case "bool": + return 9; + case "int16": + return 5; + case "uint16": + return 4; + case "int32": + return 6; + case "uint32": + return 12; + case "float16": + return 10; + case "float32": + return 1; + case "float64": + return 11; + case "string": + return 8; + case "int64": + return 7; + case "uint64": + return 13; + case "int4": + return 22; + case "uint4": + return 21; + default: + throw new Error(`unsupported data type: ${e}`); + } + }, Ye = (e) => { + switch (e) { + case 3: + return "int8"; + case 2: + return "uint8"; + case 9: + return "bool"; + case 5: + return "int16"; + case 4: + return "uint16"; + case 6: + return "int32"; + case 12: + return "uint32"; + case 10: + return "float16"; + case 1: + return "float32"; + case 11: + return "float64"; + case 8: + return "string"; + case 7: + return "int64"; + case 13: + return "uint64"; + case 22: + return "int4"; + case 21: + return "uint4"; + default: + throw new Error(`unsupported data type: ${e}`); + } + }, gt = (e, t) => { + let r = [-1, 4, 1, 1, 2, 2, 4, 8, -1, 1, 2, 8, 4, 8, -1, -1, -1, -1, -1, -1, -1, 0.5, 0.5][e], n = typeof t == "number" ? t : t.reduce((o, i) => o * i, 1); + return r > 0 ? Math.ceil(n * r) : void 0; + }, Pr = (e) => { + switch (e) { + case "float16": + return typeof Float16Array < "u" && Float16Array.from ? Float16Array : Uint16Array; + case "float32": + return Float32Array; + case "uint8": + return Uint8Array; + case "int8": + return Int8Array; + case "uint16": + return Uint16Array; + case "int16": + return Int16Array; + case "int32": + return Int32Array; + case "bool": + return Uint8Array; + case "float64": + return Float64Array; + case "uint32": + return Uint32Array; + case "int64": + return BigInt64Array; + case "uint64": + return BigUint64Array; + default: + throw new Error(`unsupported type: ${e}`); + } + }, Zt = (e) => { + switch (e) { + case "verbose": + return 0; + case "info": + return 1; + case "warning": + return 2; + case "error": + return 3; + case "fatal": + return 4; + default: + throw new Error(`unsupported logging level: ${e}`); + } + }, zr = (e) => e === "float32" || e === "float16" || e === "int32" || e === "int64" || e === "uint32" || e === "uint8" || e === "bool" || e === "uint4" || e === "int4", Or = (e) => e === "float32" || e === "float16" || e === "int32" || e === "int64" || e === "uint32" || e === "uint64" || e === "int8" || e === "uint8" || e === "bool" || e === "uint4" || e === "int4", qn = (e) => { + switch (e) { + case "none": + return 0; + case "cpu": + return 1; + case "cpu-pinned": + return 2; + case "texture": + return 3; + case "gpu-buffer": + return 4; + case "ml-tensor": + return 5; + default: + throw new Error(`unsupported data location: ${e}`); + } + }; + }); + var Qt; + var jn = U(() => { + "use strict"; + yr(); + Qt = async (e) => { + if (typeof e == "string") if (false) try { + let { readFile: t } = On("node:fs/promises"); + return new Uint8Array(await t(e)); + } catch (t) { + if (t.code === "ERR_FS_FILE_TOO_LARGE") { + let { createReadStream: r } = On("node:fs"), n = r(e), o = []; + for await (let i of n) o.push(i); + return new Uint8Array(Buffer.concat(o)); + } + throw t; + } + else { + let t = await fetch(e); + if (!t.ok) throw new Error(`failed to load external data file: ${e}`); + let r = t.headers.get("Content-Length"), n = r ? parseInt(r, 10) : 0; + if (n < 1073741824) return new Uint8Array(await t.arrayBuffer()); + { + if (!t.body) throw new Error(`failed to load external data file: ${e}, no response body.`); + let o = t.body.getReader(), i; + try { + i = new ArrayBuffer(n); + } catch (u) { + if (u instanceof RangeError) { + let d = Math.ceil(n / 65536); + i = new WebAssembly.Memory({ initial: d, maximum: d }).buffer; + } else throw u; + } + let a = 0; + for (; ; ) { + let { done: u, value: d } = await o.read(); + if (u) break; + let c = d.byteLength; + new Uint8Array(i, a, c).set(d), a += c; + } + return new Uint8Array(i, 0, n); + } + } + else return e instanceof Blob ? new Uint8Array(await e.arrayBuffer()) : e instanceof Uint8Array ? e : new Uint8Array(e); + }; + }); + var om; + var im; + var Na; + var Va; + var Br; + var am; + var se; + var Xe = U(() => { + "use strict"; + ee(); + om = ["V", "I", "W", "E", "F"], im = (e, t) => { + console.log(`[${om[e]},${(/* @__PURE__ */ new Date()).toISOString()}]${t}`); + }, Br = (e, t) => { + Na = e, Va = t; + }, am = (e, t) => { + let r = Zt(e), n = Zt(Na); + r >= n && im(r, typeof t == "function" ? t() : t); + }, se = (...e) => { + Va && am(...e); + }; + }); + var Kn; + var Je; + var k; + var Tt; + var Dr; + var Wa; + var La; + var ne = U(() => { + "use strict"; + Kn = class { + static calcMatMulShape(t, r) { + return t[1] !== r[0] ? void 0 : [t[0], r[1]]; + } + }, Je = class { + static calcShape(t, r, n = false) { + let o = t.length, i = r.length; + if (o === 0) return r; + if (i === 0) return t; + let a = Math.max(t.length, r.length), u = new Array(a); + if (n) { + if (o < 2 || i < 2) return; + let d = Kn.calcMatMulShape([t[o - 2], t[o - 1]], [r[i - 2], r[i - 1]]); + if (d === void 0) return; + [u[a - 2], u[a - 1]] = d; + } + for (let d = n ? 3 : 1; d <= a; d++) { + let c = o - d < 0 ? 1 : t[o - d], p = i - d < 0 ? 1 : r[i - d]; + if (c !== p && c > 1 && p > 1) return; + let m = Math.max(c, p); + if (c && p) u[a - d] = Math.max(c, p); + else { + if (m > 1) return; + u[a - d] = 0; + } + } + return u; + } + static isValidBroadcast(t, r) { + let n = t.length, o = r.length; + if (n > o) return false; + for (let i = 1; i <= n; i++) if (t[n - i] !== 1 && t[n - i] !== r[o - i]) return false; + return true; + } + }, k = class e { + static size(t) { + return e.getSizeFromDimensionRange(t, 0, t.length); + } + static convertShape(t, r = 4) { + let n = t.length; + if (n === 0) return []; + let o = new Array(n), i = n - 1; + for (; i >= 0; ) { + if (t[i] % r === 0) { + o[i] = t[i] / r; + break; + } + if (r % t[i] !== 0) throw new Error("cannot convert shape"); + o[i] = 1, r /= t[i], i--; + } + for (i--; i >= 0; i--) o[i] = t[i]; + return o; + } + static sizeFromDimension(t, r) { + if (r < 0 || r > t.length) throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`); + return e.getSizeFromDimensionRange(t, r, t.length); + } + static sizeToDimension(t, r) { + if (r < 0 || r > t.length) throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${t.length} dimensions.`); + return e.getSizeFromDimensionRange(t, 0, r); + } + static getSizeFromDimensionRange(t, r, n) { + let o = 1; + for (let i = r; i < n; i++) { + if (t[i] < 0) throw new Error("cannot get valid size from specified dimension range. Most likely the range contains negative values in them."); + o *= Number(t[i]); + } + return o; + } + static computeStrides(t) { + let r = t.length; + if (r === 0) return []; + if (r === 1) return [1]; + let n = new Array(r); + n[r - 1] = 1, n[r - 2] = t[r - 1]; + for (let o = r - 3; o >= 0; --o) n[o] = n[o + 1] * t[o + 1]; + return n; + } + static normalizeAxis(t, r) { + if (t < -r && t >= r) throw new Error("unsupported axis for this operation."); + return t < 0 ? t + r : t; + } + static normalizeAxes(t, r) { + return t.map((n) => this.normalizeAxis(n, r ?? t.length)); + } + static sortBasedOnPerm(t, r) { + return r ? r.map((n) => t[n]) : t.slice().reverse(); + } + static padShape(t, r) { + let n = t.length; + return t.map((o, i) => o + r[i] + r[i + n]); + } + static areEqual(t, r) { + return t.length !== r.length ? false : t.every((n, o) => n === r[o]); + } + }, Tt = class e { + static adjustPoolAttributes(t, r, n, o, i, a) { + if (!t && n.length !== r.length - 2) throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions"); + if (t) for (let u = 0; u < r.length - 2; u++) u >= n.length ? n.push(r[u + 2]) : n[u] = r[u + 2]; + for (let u = 0; u < n.length; u++) if (u < o.length) { + if (o[u] < 0) throw new Error("strides should be greater than or equal to 1"); + } else o.push(1); + for (let u = 0; u < n.length; u++) if (u < i.length) { + if (i[u] < 0) throw new Error("dilations should be greater than or equal to 1"); + } else i.push(1); + for (let u = 0; u < n.length * 2; u++) if (u < a.length) { + if (a[u] < 0) throw new Error("pad should be greater than or equal to 1"); + } else a.push(0); + for (let u = 0; u < n.length; u++) { + if (n[u] <= 0) throw new Error("kernel shapes need to be greater than 0"); + if (a[u] >= n[u] || a[u + n.length] >= n[u]) throw new Error("pads should be smaller than kernel"); + } + } + static adjustPadsBasedOnAutoPad(t, r, n, o, i, a, u) { + if (u) { + if (i.length !== 2 * (t.length - 2)) throw new Error("length of pads should be twice the length of data dimensions"); + if (r.length !== t.length - 2) throw new Error("length of strides should be the length of data dimensions"); + if (o.length !== t.length - 2) throw new Error("length of kernel shapes should be the length of data dimensions"); + for (let d = 0; d < t.length - 2; d++) e.adjustPadAndReturnShape(t[d + (a ? 1 : 2)], r[d], n[d], o[d], i, d, d + t.length - 2, u); + } + } + static computePoolOutputShape(t, r, n, o, i, a, u) { + if (r.length <= 0) throw new Error("input shape must be of size greater than 0"); + let d = [r[0], r[1]]; + return e.computeShapeHelper(t, r, d, n, o, i, a, u), d; + } + static computeConvOutputShape(t, r, n, o, i, a, u) { + if (t.length <= 0 || r.length <= 0) throw new Error("invalid input tensor dims or invalid filter tensor dims"); + let d = [t[0], r[0]]; + return e.computeShapeHelper(false, t, d, n, o, i, a, u), d; + } + static computeShapeHelper(t, r, n, o, i, a, u, d) { + if (t) for (let c = 0; c < r.length - 2; c++) n.push(1); + else for (let c = 0; c < r.length - 2; c++) n.push(e.adjustPadAndReturnShape(r[c + 2], o[c], i[c], a[c], u, c, c + r.length - 2, d)); + } + static adjustPadAndReturnShape(t, r, n, o, i, a, u, d) { + let c = n * (o - 1) + 1; + if (d && d !== "NOTSET") switch (d) { + case "VALID": + return i[a] = 0, i[u] = 0, Math.floor((t - c) / r + 1); + case "SAME_LOWER": + case "SAME_UPPER": + if (n !== 1) throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER"); + { + let m = ((t + r - 1) / r - 1) * r + o - t; + return i[a] = Math.floor(d === "SAME_LOWER" ? (m + 1) / 2 : m / 2), i[u] = m - i[a], Math.floor((t + m - o) / r + 1); + } + default: + throw new Error("Unsupported AutoPad type"); + } + else return Math.floor((t + i[a] + i[u] - c) / r + 1); + } + }, Dr = class { + static getShapeOfGemmResult(t, r, n, o, i) { + if (t.length !== 2 || n.length !== 2) throw new Error("shape need to be of size 2"); + let a, u, d; + r ? (a = t[1], u = t[0]) : (a = t[0], u = t[1]); + let c = -1; + if (o ? (d = n[0], c = 1) : (d = n[1], c = 0), n[c] !== u) throw new Error("dimension mismatch"); + if (a <= 0 || d <= 0 || u <= 0) throw new Error("invalid shape specified"); + if (i && !Je.isValidBroadcast(i, [a, d])) throw new Error("gemm: invalid bias shape for broadcast"); + return [a, d, u]; + } + }, Wa = -34028234663852886e22, La = 34028234663852886e22; + }); + var Mr; + var Zn = U(() => { + "use strict"; + ee(); + Mr = (e, t) => new (Pr(t))(e); + }); + var Yn; + var Ha; + var sm; + var Ga; + var um; + var Fa; + var Rr; + var Ur; + var Qn; + var qa; + var ja = U(() => { + "use strict"; + Xe(); + Yn = (e, t = true) => { + if (e.byteLength % 8 !== 0) throw new Error("Invalid Uint8Array length - must be a multiple of 8 (BigInt)."); + let r = e.byteLength / 8, n = new BigInt64Array(e.buffer, e.byteOffset, r), o = new Int32Array(r); + for (let i = 0; i < r; i++) { + let a = n[i]; + if (a > 2147483647n || a < -2147483648n) throw new Error(`Overflow occurred when converting BigInt to Int32 at index ${i}: ${a}`); + o[i] = Number(a); + } + return t ? new Uint8Array(o.buffer) : o; + }, Ha = (e, t = true) => { + if (e.byteLength % 4 !== 0) throw new Error("Invalid Uint8Array length - must be a multiple of 4 (Int32)."); + let r = e.byteLength / 4, n = new Int32Array(e.buffer, e.byteOffset, r), o = BigInt64Array.from(n, BigInt); + return t ? new Uint8Array(o.buffer) : o; + }, sm = 1, Ga = () => sm++, um = /* @__PURE__ */ new Map([["float32", 32], ["float16", 16], ["int32", 32], ["uint32", 32], ["int64", 64], ["uint64", 64], ["int8", 8], ["uint8", 8], ["int4", 4], ["uint4", 4]]), Fa = (e, t) => { + let r = um.get(e); + if (!r) throw new Error("Unsupported data type."); + return t.length > 0 ? Math.ceil(t.reduce((n, o) => n * o) * r / 8) : 0; + }, Rr = class { + constructor(t) { + this.shouldConvertInt64toInt32 = false; + this.isInt64ToInt32Converted = false; + let { sessionId: r, context: n, tensor: o, dataType: i, shape: a, shouldConvertInt64toInt32: u = false } = t; + this.sessionId = r, this.mlContext = n, this.mlTensor = o, this.dataType = i, this.tensorShape = a, this.shouldConvertInt64toInt32 = u; + } + get tensor() { + return this.mlTensor; + } + get type() { + return this.dataType; + } + get shape() { + return this.tensorShape; + } + get byteLength() { + return Fa(this.dataType, this.tensorShape); + } + destroy() { + se("verbose", () => "[WebNN] TensorWrapper.destroy"), this.mlTensor.destroy(); + } + write(t) { + this.mlContext.writeTensor(this.mlTensor, t); + } + async read(t, r) { + if (t) { + let n = await this.mlContext.readTensor(this.mlTensor), o = Ha(new Uint8Array(n)); + if (r) { + (r instanceof ArrayBuffer ? new Uint8Array(r) : new Uint8Array(r.buffer, r.byteOffset, r.byteLength)).set(o); + return; + } else return o.buffer; + } else return r ? this.mlContext.readTensor(this.mlTensor, r) : this.mlContext.readTensor(this.mlTensor); + } + canReuseTensor(t, r, n) { + return this.mlContext === t && this.dataType === r && this.tensorShape.length === n.length && this.tensorShape.every((o, i) => o === n[i]); + } + setIsInt64ToInt32Converted(t) { + this.isInt64ToInt32Converted = t; + } + }, Ur = class { + constructor(t, r) { + this.tensorManager = t; + this.wrapper = r; + } + get tensorWrapper() { + return this.wrapper; + } + releaseTensor() { + this.tensorWrapper && (this.tensorManager.releaseTensor(this.tensorWrapper), this.wrapper = void 0); + } + async ensureTensor(t, r, n, o) { + let i = r, a = this.tensorManager.getMLContext(t), u = i === "int64" && !a.opSupportLimits().input.dataTypes.includes("int64"); + if (u && (i = "int32", se("verbose", () => "[WebNN] TensorIdTracker.ensureTensor: convert dataType from int64 to int32")), this.wrapper) { + if (this.wrapper.canReuseTensor(a, i, n)) return this.wrapper.tensor; + if (o) { + if (this.wrapper.byteLength !== Fa(i, n)) throw new Error("Unable to copy data to tensor with different size."); + this.activeUpload = new Uint8Array(await this.wrapper.read()); + } + this.tensorManager.releaseTensor(this.wrapper); + } + let d = typeof MLTensorUsage > "u" ? void 0 : MLTensorUsage.READ | MLTensorUsage.WRITE; + return this.wrapper = await this.tensorManager.getCachedTensor(t, i, n, d, true, true, u), o && this.activeUpload && (this.wrapper.write(this.activeUpload), this.activeUpload = void 0), this.wrapper.tensor; + } + upload(t) { + let r = t; + if (this.wrapper) if (this.wrapper.shouldConvertInt64toInt32 && (r = Yn(t, true), this.wrapper.setIsInt64ToInt32Converted(true)), r.byteLength === this.wrapper.byteLength) { + this.wrapper.write(r); + return; + } else se("verbose", () => "Data size does not match tensor size. Releasing tensor."), this.releaseTensor(); + this.activeUpload ? this.activeUpload.set(r) : this.activeUpload = new Uint8Array(r); + } + async download(t) { + if (this.activeUpload) { + let r = this.wrapper?.isInt64ToInt32Converted ? Ha(this.activeUpload) : this.activeUpload; + if (t) { + t instanceof ArrayBuffer ? new Uint8Array(t).set(r) : new Uint8Array(t.buffer, t.byteOffset, t.byteLength).set(r); + return; + } else return r.buffer; + } + if (!this.wrapper) throw new Error("Tensor has not been created."); + return t ? this.wrapper.read(this.wrapper?.shouldConvertInt64toInt32, t) : this.wrapper.read(this.wrapper?.shouldConvertInt64toInt32); + } + }, Qn = class { + constructor(t) { + this.backend = t; + this.tensorTrackersById = /* @__PURE__ */ new Map(); + this.freeTensors = []; + this.externalTensors = /* @__PURE__ */ new Set(); + } + getMLContext(t) { + let r = this.backend.getMLContext(t); + if (!r) throw new Error("MLContext not found for session."); + return r; + } + reserveTensorId() { + let t = Ga(); + return this.tensorTrackersById.set(t, new Ur(this)), t; + } + releaseTensorId(t) { + let r = this.tensorTrackersById.get(t); + r && (this.tensorTrackersById.delete(t), r.tensorWrapper && this.releaseTensor(r.tensorWrapper)); + } + async ensureTensor(t, r, n, o, i) { + se("verbose", () => `[WebNN] TensorManager.ensureTensor {tensorId: ${r}, dataType: ${n}, shape: ${o}, copyOld: ${i}}`); + let a = this.tensorTrackersById.get(r); + if (!a) throw new Error("Tensor not found."); + return a.ensureTensor(t, n, o, i); + } + upload(t, r) { + let n = this.tensorTrackersById.get(t); + if (!n) throw new Error("Tensor not found."); + n.upload(r); + } + async download(t, r) { + se("verbose", () => `[WebNN] TensorManager.download {tensorId: ${t}, dstBuffer: ${r?.byteLength}}`); + let n = this.tensorTrackersById.get(t); + if (!n) throw new Error("Tensor not found."); + return n.download(r); + } + releaseTensorsForSession(t) { + for (let r of this.freeTensors) r.sessionId === t && r.destroy(); + this.freeTensors = this.freeTensors.filter((r) => r.sessionId !== t); + } + registerTensor(t, r, n, o) { + let i = this.getMLContext(t), a = Ga(), u = new Rr({ sessionId: t, context: i, tensor: r, dataType: n, shape: o }); + return this.tensorTrackersById.set(a, new Ur(this, u)), this.externalTensors.add(u), a; + } + async getCachedTensor(t, r, n, o, i, a, u = false) { + let d = this.getMLContext(t); + for (let [p, m] of this.freeTensors.entries()) if (m.canReuseTensor(d, r, n)) { + se("verbose", () => `[WebNN] Reusing tensor {dataType: ${r}, shape: ${n}}`); + let f = this.freeTensors.splice(p, 1)[0]; + return f.sessionId = t, f; + } + se("verbose", () => `[WebNN] MLContext.createTensor {dataType: ${r}, shape: ${n}}`); + let c = await d.createTensor({ dataType: r, shape: n, dimensions: n, usage: o, writable: i, readable: a }); + return new Rr({ sessionId: t, context: d, tensor: c, dataType: r, shape: n, shouldConvertInt64toInt32: u }); + } + releaseTensor(t) { + this.externalTensors.has(t) && this.externalTensors.delete(t), this.freeTensors.push(t); + } + }, qa = (...e) => new Qn(...e); + }); + var Xn; + var dm; + var Nr; + var Ka = U(() => { + "use strict"; + ee(); + ht(); + Zn(); + ja(); + Xe(); + Xn = /* @__PURE__ */ new Map([[1, "float32"], [10, "float16"], [6, "int32"], [12, "uint32"], [7, "int64"], [13, "uint64"], [22, "int4"], [21, "uint4"], [3, "int8"], [2, "uint8"], [9, "uint8"]]), dm = (e, t) => { + if (e === t) return true; + if (e === void 0 || t === void 0) return false; + let r = Object.keys(e).sort(), n = Object.keys(t).sort(); + return r.length === n.length && r.every((o, i) => o === n[i] && e[o] === t[o]); + }, Nr = class { + constructor(t) { + this.tensorManager = qa(this); + this.mlContextBySessionId = /* @__PURE__ */ new Map(); + this.sessionIdsByMLContext = /* @__PURE__ */ new Map(); + this.mlContextCache = []; + this.sessionGraphInputs = /* @__PURE__ */ new Map(); + this.temporaryGraphInputs = []; + this.temporarySessionTensorIds = /* @__PURE__ */ new Map(); + Br(t.logLevel, !!t.debug); + } + get currentSessionId() { + if (this.activeSessionId === void 0) throw new Error("No active session"); + return this.activeSessionId; + } + onRunStart(t) { + se("verbose", () => `[WebNN] onRunStart {sessionId: ${t}}`), this.activeSessionId = t; + } + onRunEnd(t) { + se("verbose", () => `[WebNN] onRunEnd {sessionId: ${t}}`); + let r = this.temporarySessionTensorIds.get(t); + if (r) { + for (let n of r) se("verbose", () => `[WebNN] releasing temporary tensor {tensorId: ${n}}`), this.tensorManager.releaseTensorId(n); + this.temporarySessionTensorIds.delete(t), this.activeSessionId = void 0; + } + } + async createMLContext(t) { + if (t instanceof GPUDevice) { + let n = this.mlContextCache.findIndex((o) => o.gpuDevice === t); + if (n !== -1) return this.mlContextCache[n].mlContext; + { + let o = await navigator.ml.createContext(t); + return this.mlContextCache.push({ gpuDevice: t, mlContext: o }), o; + } + } else if (t === void 0) { + let n = this.mlContextCache.findIndex((o) => o.options === void 0 && o.gpuDevice === void 0); + if (n !== -1) return this.mlContextCache[n].mlContext; + { + let o = await navigator.ml.createContext(); + return this.mlContextCache.push({ mlContext: o }), o; + } + } + let r = this.mlContextCache.findIndex((n) => dm(n.options, t)); + if (r !== -1) return this.mlContextCache[r].mlContext; + { + let n = await navigator.ml.createContext(t); + return this.mlContextCache.push({ options: t, mlContext: n }), n; + } + } + registerMLContext(t, r) { + this.mlContextBySessionId.set(t, r); + let n = this.sessionIdsByMLContext.get(r); + n || (n = /* @__PURE__ */ new Set(), this.sessionIdsByMLContext.set(r, n)), n.add(t), this.temporaryGraphInputs.length > 0 && (this.sessionGraphInputs.set(t, this.temporaryGraphInputs), this.temporaryGraphInputs = []); + } + onReleaseSession(t) { + this.sessionGraphInputs.delete(t); + let r = this.mlContextBySessionId.get(t); + if (!r) return; + this.tensorManager.releaseTensorsForSession(t), this.mlContextBySessionId.delete(t); + let n = this.sessionIdsByMLContext.get(r); + if (n.delete(t), n.size === 0) { + this.sessionIdsByMLContext.delete(r); + let o = this.mlContextCache.findIndex((i) => i.mlContext === r); + o !== -1 && this.mlContextCache.splice(o, 1); + } + } + getMLContext(t) { + return this.mlContextBySessionId.get(t); + } + reserveTensorId() { + return this.tensorManager.reserveTensorId(); + } + releaseTensorId(t) { + se("verbose", () => `[WebNN] releaseTensorId {tensorId: ${t}}`), this.tensorManager.releaseTensorId(t); + } + async ensureTensor(t, r, n, o, i) { + let a = Xn.get(n); + if (!a) throw new Error(`Unsupported ONNX data type: ${n}`); + return this.tensorManager.ensureTensor(t ?? this.currentSessionId, r, a, o, i); + } + async createTemporaryTensor(t, r, n) { + se("verbose", () => `[WebNN] createTemporaryTensor {onnxDataType: ${r}, shape: ${n}}`); + let o = Xn.get(r); + if (!o) throw new Error(`Unsupported ONNX data type: ${r}`); + let i = this.tensorManager.reserveTensorId(); + await this.tensorManager.ensureTensor(t, i, o, n, false); + let a = this.temporarySessionTensorIds.get(t); + return a ? a.push(i) : this.temporarySessionTensorIds.set(t, [i]), i; + } + uploadTensor(t, r) { + if (!fe().shouldTransferToMLTensor) throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false"); + se("verbose", () => `[WebNN] uploadTensor {tensorId: ${t}, data: ${r.byteLength}}`), this.tensorManager.upload(t, r); + } + async downloadTensor(t, r) { + return this.tensorManager.download(t, r); + } + createMLTensorDownloader(t, r) { + return async () => { + let n = await this.tensorManager.download(t); + return Mr(n, r); + }; + } + registerMLTensor(t, r, n, o) { + let i = Xn.get(n); + if (!i) throw new Error(`Unsupported ONNX data type: ${n}`); + let a = this.tensorManager.registerTensor(t, r, i, o); + return se("verbose", () => `[WebNN] registerMLTensor {tensor: ${r}, dataType: ${i}, dimensions: ${o}} -> {tensorId: ${a}}`), a; + } + registerMLConstant(t, r, n, o, i, a, u = false) { + if (!a) throw new Error("External mounted files are not available."); + let d = t; + t.startsWith("./") && (d = t.substring(2)); + let c = a.get(d); + if (!c) throw new Error(`File with name ${d} not found in preloaded files.`); + if (r + n > c.byteLength) throw new Error("Out of bounds: data offset and length exceed the external file data size."); + let p = c.slice(r, r + n).buffer, m; + switch (i.dataType) { + case "float32": + m = new Float32Array(p); + break; + case "float16": + m = typeof Float16Array < "u" && Float16Array.from ? new Float16Array(p) : new Uint16Array(p); + break; + case "int32": + m = new Int32Array(p); + break; + case "uint32": + m = new Uint32Array(p); + break; + case "int64": + u ? (m = Yn(new Uint8Array(p), false), i.dataType = "int32") : m = new BigInt64Array(p); + break; + case "uint64": + m = new BigUint64Array(p); + break; + case "int8": + m = new Int8Array(p); + break; + case "int4": + case "uint4": + case "uint8": + m = new Uint8Array(p); + break; + default: + throw new Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`); + } + return se("verbose", () => `[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}} ${u ? "(Note: it was int64 data type and registered to int32 as workaround)" : ""}`), o.constant(i, m); + } + registerGraphInput(t) { + this.temporaryGraphInputs.push(t); + } + isGraphInput(t, r) { + let n = this.sessionGraphInputs.get(t); + return n ? n.includes(r) : false; + } + isInt64Supported(t) { + return !!this.mlContextBySessionId.get(t)?.opSupportLimits().input.dataTypes.includes("int64"); + } + flush() { + } + }; + }); + var Vr = U(() => { + "use strict"; + }); + var Za; + var Jn; + var eo; + var lm; + var cm; + var Qa; + var ro; + var to; + var Xa; + var Ja = U(() => { + "use strict"; + Xe(); + Vr(); + Za = /* @__PURE__ */ new Map([[64, 250], [128, 200], [256, 200], [512, 200], [2048, 230], [4096, 200], [8192, 50], [16384, 50], [32768, 50], [65536, 50], [131072, 50], [262144, 50], [524288, 50], [1048576, 50], [2097152, 30], [4194304, 20], [8388608, 10], [12582912, 10], [16777216, 10], [26214400, 15], [33554432, 22], [44236800, 2], [58982400, 6], [67108864, 6], [134217728, 6], [167772160, 6]]), Jn = [], eo = (e) => Math.ceil(Number(e) / 16) * 16, lm = (e) => { + for (let t = 0; t < Jn.length; t++) { + let r = Jn[t]; + if (e <= r) return r; + } + return Math.ceil(e / 16) * 16; + }, cm = 1, Qa = () => cm++, ro = async (e, t, r, n) => { + let o = eo(r), i = e.device.createBuffer({ size: o, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ }); + try { + let a = e.getCommandEncoder(); + e.endComputePass(), a.copyBufferToBuffer(t, 0, i, 0, o), e.flush(), await i.mapAsync(GPUMapMode.READ); + let u = i.getMappedRange(); + if (n) { + let d = n(); + return d.set(new Uint8Array(u, 0, r)), d; + } else return new Uint8Array(u.slice(0, r)); + } finally { + i.destroy(); + } + }, to = class { + constructor(t) { + this.backend = t; + this.storageCache = /* @__PURE__ */ new Map(), this.freeBuffers = /* @__PURE__ */ new Map(), this.freeUniformBuffers = /* @__PURE__ */ new Map(), this.buffersPending = [], this.capturedPendingBuffers = /* @__PURE__ */ new Map(); + for (let [r] of Za) Jn.push(r), this.freeBuffers.set(r, []), this.freeUniformBuffers.set(r, []); + this.sessionCount = 0; + } + upload(t, r) { + let n = r.buffer, o = r.byteOffset, i = r.byteLength, a = eo(i), u = this.storageCache.get(t); + if (!u) throw new Error("gpu data for uploading does not exist"); + if (Number(u.originalSize) !== i) throw new Error(`inconsistent data size. gpu data size=${u.originalSize}, data size=${i}`); + let d = this.backend.device.createBuffer({ mappedAtCreation: true, size: a, usage: GPUBufferUsage.MAP_WRITE | GPUBufferUsage.COPY_SRC }), c = d.getMappedRange(); + new Uint8Array(c).set(new Uint8Array(n, o, i)), d.unmap(); + let p = this.backend.device.createCommandEncoder(); + p.copyBufferToBuffer(d, 0, u.gpuData.buffer, 0, a), this.backend.device.queue.submit([p.finish()]), d.destroy(), se("verbose", () => `[WebGPU] GpuDataManager.upload(id=${t})`); + } + memcpy(t, r) { + let n = this.storageCache.get(t); + if (!n) throw new Error("source gpu data for memcpy does not exist"); + let o = this.storageCache.get(r); + if (!o) throw new Error("destination gpu data for memcpy does not exist"); + if (n.originalSize !== o.originalSize) throw new Error("inconsistent source and destination gpu data size"); + let i = eo(n.originalSize), a = this.backend.getCommandEncoder(); + this.backend.endComputePass(), a.copyBufferToBuffer(n.gpuData.buffer, 0, o.gpuData.buffer, 0, i); + } + registerExternalBuffer(t, r, n) { + let o; + if (n) { + if (o = n[0], t === n[1]) return se("verbose", () => `[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${o}, buffer is the same, skip.`), o; + if (this.backend.capturedCommandList.has(this.backend.currentSessionId)) throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. + Please use the previous external buffer!`); + } else o = Qa(); + return this.storageCache.set(o, { gpuData: { id: o, type: 0, buffer: t }, originalSize: r }), se("verbose", () => `[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${o}, registered.`), o; + } + unregisterExternalBuffer(t) { + t !== void 0 && (this.storageCache.delete(t), se("verbose", () => `[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${t}`)); + } + create(t, r = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST) { + let n = lm(t), o, i = (r & GPUBufferUsage.STORAGE) === GPUBufferUsage.STORAGE, a = (r & GPUBufferUsage.UNIFORM) === GPUBufferUsage.UNIFORM; + if (i || a) { + let c = (i ? this.freeBuffers : this.freeUniformBuffers).get(n); + c ? c.length > 0 ? o = c.pop() : o = this.backend.device.createBuffer({ size: n, usage: r }) : o = this.backend.device.createBuffer({ size: n, usage: r }); + } else o = this.backend.device.createBuffer({ size: n, usage: r }); + let u = { id: Qa(), type: 0, buffer: o }; + return this.storageCache.set(u.id, { gpuData: u, originalSize: Number(t) }), se("verbose", () => `[WebGPU] GpuDataManager.create(size=${t}) => id=${u.id}`), u; + } + get(t) { + return this.storageCache.get(t)?.gpuData; + } + release(t) { + let r = typeof t == "bigint" ? Number(t) : t, n = this.storageCache.get(r); + if (!n) { + if (this.storageCache.size === 0) return 0; + throw new Error("releasing data does not exist"); + } + return se("verbose", () => `[WebGPU] GpuDataManager.release(id=${r}), gpuDataId=${n.gpuData.id}`), this.storageCache.delete(r), this.buffersPending.push(n.gpuData.buffer), n.originalSize; + } + async download(t, r) { + let n = this.storageCache.get(Number(t)); + if (!n) throw new Error("data does not exist"); + await ro(this.backend, n.gpuData.buffer, n.originalSize, r); + } + refreshPendingBuffers() { + if (this.buffersPending.length !== 0) if (this.backend.sessionStatus === "default") { + for (let t of this.buffersPending) { + let r = Za.get(t.size); + if ((t.usage & GPUBufferUsage.STORAGE) === GPUBufferUsage.STORAGE) { + let n = this.freeBuffers.get(t.size) || []; + r === void 0 || n.length >= r ? t.destroy() : n.push(t); + } else if ((t.usage & GPUBufferUsage.UNIFORM) === GPUBufferUsage.UNIFORM) { + let n = this.freeUniformBuffers.get(t.size) || []; + r === void 0 || n.length >= r ? t.destroy() : n.push(t); + } else t.destroy(); + } + this.buffersPending = []; + } else { + let t = this.capturedPendingBuffers.get(this.backend.currentSessionId); + t || (t = [], this.capturedPendingBuffers.set(this.backend.currentSessionId, t)); + for (let r of this.buffersPending) t.push(r); + this.buffersPending = []; + } + } + dispose() { + this.freeBuffers.forEach((t) => { + t.forEach((r) => { + r.destroy(); + }); + }), this.freeUniformBuffers.forEach((t) => { + t.forEach((r) => { + r.destroy(); + }); + }), this.storageCache.forEach((t) => { + t.gpuData.buffer.destroy(); + }), this.capturedPendingBuffers.forEach((t) => { + t.forEach((r) => { + r.destroy(); + }); + }), this.storageCache = /* @__PURE__ */ new Map(), this.freeBuffers = /* @__PURE__ */ new Map(), this.freeUniformBuffers = /* @__PURE__ */ new Map(), this.capturedPendingBuffers = /* @__PURE__ */ new Map(); + } + onCreateSession() { + this.sessionCount += 1; + } + onReleaseSession(t) { + let r = this.capturedPendingBuffers.get(t); + r && (r.forEach((n) => { + n.destroy(); + }), this.capturedPendingBuffers.delete(t)), this.sessionCount -= 1, this.sessionCount === 0 && (se("warning", () => "[WebGPU] Clearing webgpu buffer cache"), this.storageCache.forEach((n) => { + n.gpuData.buffer.destroy(); + }), this.storageCache = /* @__PURE__ */ new Map()); + } + }, Xa = (...e) => new to(...e); + }); + var no; + var J; + var Se = U(() => { + "use strict"; + no = class { + constructor(t) { + Object.assign(this, t); + } + get cacheKey() { + return this.key || (this.key = Object.getOwnPropertyNames(this).sort().map((t) => `${this[t]}`).join(";")), this.key; + } + }, J = (e) => new no(e); + }); + var It; + var io; + var be; + var Ae; + var N; + var ce; + var ao; + var Ct; + var He; + var F; + var Wr; + var P; + var M; + var es; + var Lr; + var oo; + var ts; + var ie = U(() => { + "use strict"; + ee(); + ne(); + It = 64, io = (e, t) => { + if (t === 3) throw new Error("vec3 has same alignment as vec4, use vec4 instead"); + switch (Number(e)) { + case 10: + return t > 1 ? `vec${t}` : "f16"; + case 1: + return t > 1 ? `vec${t}` : "f32"; + case 6: + return t > 1 ? `vec${t}` : "i32"; + case 12: + return t > 1 ? `vec${t}` : "u32"; + case 7: + if (t > 1) throw new Error("currently not supported vecX of uint64 yet"); + return ["vec2", "i32"]; + case 13: + if (t > 1) throw new Error("currently not supported vecX of uint64 yet"); + return ["vec2", "u32"]; + case 9: + if (t !== 4) throw new Error("bool must be vec4"); + return ["u32", "vec4"]; + case 22: + return "i32"; + case 21: + return "u32"; + default: + throw new Error(`Unknown data type: ${e}`); + } + }, be = (e, t = 1) => { + let r = io(e, t); + return typeof r == "string" ? r : r[0]; + }, Ae = (e, t = 1) => { + let r = io(e, t); + return typeof r == "string" ? r : r[1]; + }, N = (...e) => { + let t = []; + return e.forEach((r) => { + r.length !== 0 && t.push({ type: 12, data: r }, { type: 12, data: k.computeStrides(r) }); + }), t; + }, ce = (e) => e % 4 === 0 ? 4 : e % 2 === 0 ? 2 : 1, ao = (e = "f32", t, r = "0") => !t || t === 1 ? `${e}(${r})` : `vec${t}<${e}>(${r})`, Ct = (e, t, r) => e === "f32" ? r : t === 1 ? `f32(${r})` : `vec${t}(${r})`, He = (e, t) => t === 4 ? `(${e}.x + ${e}.y + ${e}.z + ${e}.w)` : t === 2 ? `(${e}.x + ${e}.y)` : t === 3 ? `(${e}.x + ${e}.y + ${e}.z)` : e, F = (e, t, r, n) => e.startsWith("uniforms.") && r > 4 ? typeof t == "string" ? n === "f16" ? `${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]` : `${e}[(${t}) / 4][(${t}) % 4]` : n === "f16" ? `${e}[${Math.floor(t / 8)}][${Math.floor(t % 8 / 4)}][${t % 8 % 4}]` : `${e}[${Math.floor(t / 4)}][${t % 4}]` : r > 1 ? `${e}[${t}]` : e, Wr = (e, t, r, n, o) => { + let i = typeof r == "number", a = i ? r : r.length, u = [...new Array(a).keys()], d = a < 2 ? "u32" : a <= 4 ? `vec${a}` : `array`, c = io(t, o), p = typeof c == "string" ? c : c[1], m = typeof c == "string" ? c : c[0], f = { indices: d, value: p, storage: m, tensor: t }, b = (C) => typeof C == "string" ? C : `${C}u`, g = { offsetToIndices: false, indicesToOffset: false, broadcastedIndicesToOffset: false, set: false, setByIndices: false, get: false, getByIndices: false }, _ = i ? "uniforms." : "", S = `${_}${e}_shape`, $ = `${_}${e}_strides`, v = ""; + for (let C = 0; C < a - 1; C++) v += ` + let dim${C} = current / ${F($, C, a)}; + let rest${C} = current % ${F($, C, a)}; + indices[${C}] = dim${C}; + current = rest${C}; + `; + v += `indices[${a - 1}] = current;`; + let x = a < 2 ? "" : ` + fn o2i_${e}(offset: u32) -> ${f.indices} { + var indices: ${f.indices}; + var current = offset; + ${v} + return indices; + }`, T = (C) => (g.offsetToIndices = true, a < 2 ? C : `o2i_${e}(${C})`), E = []; + if (a >= 2) for (let C = a - 1; C >= 0; C--) E.push(`${F($, C, a)} * (indices[${C}])`); + let I = a < 2 ? "" : ` + fn i2o_${e}(indices: ${f.indices}) -> u32 { + return ${E.join("+")}; + }`, z = (C) => (g.indicesToOffset = true, a < 2 ? C : `i2o_${e}(${C})`), O = (...C) => a === 0 ? "0u" : `${f.indices}(${C.map(b).join(",")})`, D = (C, V) => a < 2 ? `${C}` : `${F(C, V, a)}`, L = (C, V, de) => a < 2 ? `${C}=${de};` : `${F(C, V, a)}=${de};`, q = {}, Q = (C, V) => { + g.broadcastedIndicesToOffset = true; + let de = `${V.name}broadcastedIndicesTo${e}Offset`; + if (de in q) return `${de}(${C})`; + let ze = []; + for (let ve = a - 1; ve >= 0; ve--) { + let $e = V.indicesGet("outputIndices", ve + V.rank - a); + ze.push(`${D($, ve)} * (${$e} % ${D(S, ve)})`); + } + return q[de] = `fn ${de}(outputIndices: ${V.type.indices}) -> u32 { + return ${ze.length > 0 ? ze.join("+") : "0u"}; + }`, `${de}(${C})`; + }, W = (C, V) => (() => { + if (f.storage === f.value) return `${e}[${C}]=${V};`; + if (f.storage === "vec2" && f.value === "i32") return `${e}[${C}]=vec2(u32(${V}), select(0u, 0xFFFFFFFFu, ${V} < 0));`; + if (f.storage === "vec2" && f.value === "u32") return `${e}[${C}]=vec2(u32(${V}), 0u);`; + if (f.storage === "u32" && f.value === "vec4") return `${e}[${C}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${V}));`; + throw new Error(`not supported combination of storage type ${f.storage} and value type ${f.value} yet`); + })(), Z = (C) => (() => { + if (f.storage === f.value) return `${e}[${C}]`; + if (f.storage === "vec2" && f.value === "i32") return `i32(${e}[${C}].x)`; + if (f.storage === "vec2" && f.value === "u32") return `u32(${e}[${C}].x)`; + if (f.storage === "u32" && f.value === "vec4") return `vec4(bool(${e}[${C}] & 0xFFu), bool(${e}[${C}] & 0xFF00u), bool(${e}[${C}] & 0xFF0000u), bool(${e}[${C}] & 0xFF000000u))`; + throw new Error(`not supported combination of storage type ${f.storage} and value type ${f.value} yet`); + })(), we = a < 2 ? "" : ` + fn get_${e}ByIndices(indices: ${f.indices}) -> ${p} { + return ${Z(`i2o_${e}(indices)`)}; + }`, H = a < 2 ? "" : (() => { + let C = u.map((de) => `d${de}: u32`).join(", "), V = u.map((de) => `d${de}`).join(", "); + return ` + fn get_${e}(${C}) -> ${p} { + return get_${e}ByIndices(${O(V)}); + }`; + })(), j = (...C) => { + if (C.length !== a) throw new Error(`indices length must be ${a}`); + let V = C.map(b).join(","); + return a === 0 ? Z("0u") : a === 1 ? Z(V[0]) : (g.get = true, g.getByIndices = true, g.indicesToOffset = true, `get_${e}(${V})`); + }, te = (C) => a < 2 ? Z(C) : (g.getByIndices = true, g.indicesToOffset = true, `get_${e}ByIndices(${C})`), X = a < 2 ? "" : ` + fn set_${e}ByIndices(indices: ${f.indices}, value: ${p}) { + ${W(`i2o_${e}(indices)`, "value")} + }`, ue = a < 2 ? "" : (() => { + let C = u.map((de) => `d${de}: u32`).join(", "), V = u.map((de) => `d${de}`).join(", "); + return ` + fn set_${e}(${C}, value: ${p}) { + set_${e}ByIndices(${O(V)}, value); + }`; + })(); + return { impl: () => { + let C = [], V = false; + return g.offsetToIndices && (C.push(x), V = true), g.indicesToOffset && (C.push(I), V = true), g.broadcastedIndicesToOffset && (Object.values(q).forEach((de) => C.push(de)), V = true), g.set && (C.push(ue), V = true), g.setByIndices && (C.push(X), V = true), g.get && (C.push(H), V = true), g.getByIndices && (C.push(we), V = true), !i && V && C.unshift(`const ${S} = ${f.indices}(${r.join(",")});`, `const ${$} = ${f.indices}(${k.computeStrides(r).join(",")});`), C.join(` +`); + }, type: f, offsetToIndices: T, indicesToOffset: z, broadcastedIndicesToOffset: Q, indices: O, indicesGet: D, indicesSet: L, set: (...C) => { + if (C.length !== a + 1) throw new Error(`indices length must be ${a}`); + let V = C[a]; + if (typeof V != "string") throw new Error("value must be string"); + let de = C.slice(0, a).map(b).join(","); + return a === 0 ? W("0u", V) : a === 1 ? W(de[0], V) : (g.set = true, g.setByIndices = true, g.indicesToOffset = true, `set_${e}(${de}, ${V})`); + }, setByOffset: W, setByIndices: (C, V) => a < 2 ? W(C, V) : (g.setByIndices = true, g.indicesToOffset = true, `set_${e}ByIndices(${C}, ${V});`), get: j, getByOffset: Z, getByIndices: te, usage: n, name: e, strides: $, shape: S, rank: a }; + }, P = (e, t, r, n = 1) => Wr(e, t, r, "input", n), M = (e, t, r, n = 1) => Wr(e, t, r, "output", n), es = (e, t, r) => Wr(e, t, r, "atomicOutput", 1), Lr = (e, t, r, n = 1) => Wr(e, t, r, "internal", n), oo = class { + constructor(t, r) { + this.normalizedDispatchGroup = t; + this.limits = r; + this.internalVariables = []; + this.variables = []; + this.uniforms = []; + this.variableIndex = 0; + } + guardAgainstOutOfBoundsWorkgroupSizes(t) { + return `if (global_idx >= ${typeof t == "number" ? `${t}u` : t}) { return; }`; + } + mainStart(t = It) { + let r = typeof t == "number" ? t : t[0], n = typeof t == "number" ? 1 : t[1], o = typeof t == "number" ? 1 : t[2]; + if (r > this.limits.maxComputeWorkgroupSizeX || n > this.limits.maxComputeWorkgroupSizeY || o > this.limits.maxComputeWorkgroupSizeZ) throw new Error(`workgroup size [${r}, ${n}, ${o}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`); + if (r * n * o > this.limits.maxComputeInvocationsPerWorkgroup) throw new Error(`workgroup size [${r}, ${n}, ${o}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`); + let i = this.normalizedDispatchGroup[1] === 1 && this.normalizedDispatchGroup[2] === 1, a = i ? `@builtin(global_invocation_id) global_id : vec3, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(local_invocation_id) local_id : vec3` : `@builtin(global_invocation_id) global_id : vec3, + @builtin(local_invocation_id) local_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(num_workgroups) num_workgroups : vec3`, u = i ? `let global_idx = global_id.x; + let workgroup_index = workgroup_id.x;` : `let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + + workgroup_id.y * num_workgroups[0] + workgroup_id.x; + let global_idx = workgroup_index * ${r * n * o}u + local_idx;`; + return `@compute @workgroup_size(${r}, ${n}, ${o}) + fn main(${a}) { + ${u} + `; + } + appendVariableUniforms(t) { + t.rank !== 0 && (t.shape.startsWith("uniforms.") && this.uniforms.push({ name: t.shape.replace("uniforms.", ""), type: "u32", length: t.rank }), t.strides.startsWith("uniforms.") && this.uniforms.push({ name: t.strides.replace("uniforms.", ""), type: "u32", length: t.rank })); + } + declareVariable(t, r) { + if (t.usage === "internal") throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead."); + this.variables.push(t), this.appendVariableUniforms(t); + let n = t.usage === "input" ? "read" : "read_write", o = t.usage === "atomicOutput" ? "atomic" : t.type.storage; + return `@group(0) @binding(${r}) var ${t.name}: array<${o}>;`; + } + declareVariables(...t) { + return t.map((r) => this.declareVariable(r, this.variableIndex++)).join(` +`); + } + registerInternalVariable(t) { + if (t.usage !== "internal") throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead."); + this.internalVariables.push(t), this.appendVariableUniforms(t); + } + registerInternalVariables(...t) { + return t.forEach((r) => this.registerInternalVariable(r)), this; + } + registerUniform(t, r, n = 1) { + return this.uniforms.push({ name: t, type: r, length: n }), this; + } + registerUniforms(t) { + return this.uniforms = this.uniforms.concat(t), this; + } + uniformDeclaration() { + if (this.uniforms.length === 0) return ""; + let t = []; + for (let { name: r, type: n, length: o } of this.uniforms) if (o && o > 4) n === "f16" ? t.push(`@align(16) ${r}:array, ${Math.ceil(o / 8)}>`) : t.push(`${r}:array, ${Math.ceil(o / 4)}>`); + else { + let i = o == null || o === 1 ? n : `vec${o}<${n}>`; + t.push(`${r}:${i}`); + } + return ` + struct Uniforms { ${t.join(", ")} }; + @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`; + } + get additionalImplementations() { + return this.uniformDeclaration() + this.variables.map((t) => t.impl()).join(` +`) + this.internalVariables.map((t) => t.impl()).join(` +`); + } + get variablesInfo() { + if (this.uniforms.length === 0) return; + let t = (r) => [12, 10, 1, 6][["u32", "f16", "f32", "i32"].indexOf(r)]; + return this.uniforms.map((r) => [t(r.type), r.length ?? 1]); + } + }, ts = (e, t) => new oo(e, t); + }); + var pm; + var rs; + var mm; + var fm; + var hm; + var gm; + var Ee; + var ns; + var os; + var st = U(() => { + "use strict"; + ee(); + ne(); + Se(); + ie(); + pm = (e, t) => { + if (!e || e.length !== 1) throw new Error("Transpose requires 1 input."); + if (t.length !== 0 && t.length !== e[0].dims.length) throw new Error(`perm size ${t.length} does not match input rank ${e[0].dims.length}`); + }, rs = (e, t) => t.length !== 0 ? t : [...new Array(e).keys()].reverse(), mm = (e, t) => k.sortBasedOnPerm(e, rs(e.length, t)), fm = (e, t, r, n) => { + let o = `fn perm(i: ${n.type.indices}) -> ${r.type.indices} { + var a: ${r.type.indices};`; + for (let i = 0; i < t; ++i) o += `a[${e[i]}]=i[${i}];`; + return o += "return a;}"; + }, hm = (e, t) => { + let r = [], n = []; + for (let o = 0; o < e.length; ++o) e[o] !== 1 && r.push(e[o]), e[t[o]] !== 1 && n.push(t[o]); + return { newShape: r, newPerm: n }; + }, gm = (e, t) => { + let r = 0; + for (let n = 0; n < e.length; ++n) if (t[e[n]] !== 1) { + if (e[n] < r) return false; + r = e[n]; + } + return true; + }, Ee = (e, t) => { + let r = e.dataType, n = e.dims.length, o = rs(n, t), i = mm(e.dims, o), a = e.dims, u = i, d = n < 2 || gm(o, e.dims), c; + if (d) return c = (_) => { + let S = P("input", r, a, 4), $ = M("output", r, u, 4); + return ` + ${_.registerUniform("output_size", "u32").declareVariables(S, $)} + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + output[global_idx] = input[global_idx]; + }`; + }, { name: "TransposeCopy", shaderCache: { inputDependencies: ["type"] }, getRunData: () => { + let _ = k.size(i); + return { outputs: [{ dims: i, dataType: e.dataType }], dispatchGroup: { x: Math.ceil(_ / 64 / 4) }, programUniforms: [{ type: 12, data: Math.ceil(_ / 4) }] }; + }, getShaderSource: c }; + let { newShape: p, newPerm: m } = hm(e.dims, o), f = k.areEqual(m, [2, 3, 1]), b = k.areEqual(m, [3, 1, 2]); + if (p.length === 2 || f || b) { + a = f ? [p[0], p[1] * p[2]] : b ? [p[0] * p[1], p[2]] : p, u = [a[1], a[0]]; + let _ = 16; + return c = (S) => { + let $ = P("a", r, a.length), v = M("output", r, u.length); + return ` + ${S.registerUniform("output_size", "u32").declareVariables($, v)} + var tile : array, ${_}>; + ${S.mainStart([_, _, 1])} + let stride = (uniforms.output_shape[1] - 1) / ${_} + 1; + let workgroup_id_x = workgroup_index % stride; + let workgroup_id_y = workgroup_index / stride; + let input_col = workgroup_id_y * ${_}u + local_id.x; + let input_row = workgroup_id_x * ${_}u + local_id.y; + if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { + tile[local_id.y][local_id.x] = ${$.getByIndices(`${$.type.indices}(input_row, input_col)`)}; + } + workgroupBarrier(); + + let output_col = workgroup_id_x * ${_}u + local_id.x; + let output_row = workgroup_id_y * ${_}u + local_id.y; + if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { + ${v.setByIndices(`${v.type.indices}(output_row, output_col)`, "tile[local_id.x][local_id.y]")} + } + }`; + }, { name: "TransposeShared", shaderCache: { inputDependencies: ["type"] }, getRunData: () => { + let S = k.size(i); + return { outputs: [{ dims: i, dataType: e.dataType }], dispatchGroup: { x: Math.ceil(u[1] / _), y: Math.ceil(u[0] / _) }, programUniforms: [{ type: 12, data: S }, ...N(a, u)] }; + }, getShaderSource: c }; + } + return c = (_) => { + let S = P("a", r, a.length), $ = M("output", r, u.length); + return ` + ${_.registerUniform("output_size", "u32").declareVariables(S, $)} + + ${fm(o, n, S, $)} + + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${$.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${$.setByOffset("global_idx", S.getByIndices("aIndices"))} + }`; + }, { name: "Transpose", shaderCache: { hint: `${t}`, inputDependencies: ["rank"] }, getRunData: () => { + let _ = k.size(i); + return { outputs: [{ dims: i, dataType: e.dataType }], dispatchGroup: { x: Math.ceil(_ / 64) }, programUniforms: [{ type: 12, data: _ }, ...N(a, u)] }; + }, getShaderSource: c }; + }, ns = (e, t) => { + pm(e.inputs, t.perm), e.compute(Ee(e.inputs[0], t.perm)); + }, os = (e) => J({ perm: e.perm }); + }); + var bm; + var ym; + var _m; + var wm; + var vm; + var $m; + var xm; + var Sm; + var Tm; + var Im; + var et; + var is; + var as; + var ss; + var us; + var ds; + var ls; + var cs; + var ps; + var ms; + var fs; + var hs = U(() => { + "use strict"; + ee(); + ne(); + ie(); + Gr(); + st(); + bm = { max: "select(bestValue, candidate, candidate > bestValue)", min: "select(bestValue, candidate, candidate < bestValue)", mean: "bestValue + candidate", sum: "bestValue + candidate", prod: "bestValue * candidate", sumSquare: "bestValue + candidate * candidate", logSumExp: "bestValue + exp(candidate)", l1: "bestValue + abs(candidate)", l2: "bestValue + candidate * candidate", logSum: "bestValue + candidate" }, ym = { max: "select(bestValue, candidate, candidate > bestValue)", min: "select(bestValue, candidate, candidate < bestValue)", mean: "bestValue + candidate", sum: "bestValue + candidate", prod: "bestValue * candidate", sumSquare: "bestValue + candidate", logSumExp: "bestValue + candidate", l1: "bestValue + candidate", l2: "bestValue + candidate", logSum: "bestValue + candidate" }, _m = { max: "_A[offset]", min: "_A[offset]", mean: "0", sum: "0", prod: "1", sumSquare: "0", logSumExp: "0", l1: "0", l2: "0", logSum: "0" }, wm = { max: "bestValue", min: "bestValue", sum: "bestValue", prod: "bestValue", sumSquare: "bestValue", logSumExp: "log(bestValue)", l1: "bestValue", l2: "sqrt(bestValue)", logSum: "log(bestValue)" }, vm = (e, t) => { + let r = []; + for (let n = t - e; n < t; ++n) r.push(n); + return r; + }, $m = (e, t) => { + let r = [], n = e.length; + for (let i = 0; i < n; i++) t.indexOf(i) === -1 && r.push(e[i]); + let o = t.map((i) => e[i]); + return [r, o]; + }, xm = (e, t) => { + let r = e.length + t.length, n = [], o = 0; + for (let i = 0; i < r; i++) t.indexOf(i) === -1 ? n.push(e[o++]) : n.push(1); + return n; + }, Sm = (e, t) => { + for (let r = 0; r < e.length; ++r) if (e[e.length - r - 1] !== t - 1 - r) return false; + return true; + }, Tm = (e, t) => { + let r = []; + if (!Sm(e, t)) { + for (let n = 0; n < t; ++n) e.indexOf(n) === -1 && r.push(n); + e.forEach((n) => r.push(n)); + } + return r; + }, Im = (e, t, r, n, o, i, a) => { + let u = r[0].dims, d = k.size(i), c = k.size(a), p = P("_A", r[0].dataType, u), m = M("output", o, i), f = 64; + d === 1 && (f = 256); + let b = ` + var aBestValues : array; + `, g = (_) => ` + ${_.registerUniform("reduceSize", "u32").declareVariables(p, m)} + ${b} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${_.mainStart(f)} + + let outputIndex = global_idx / ${f}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${_m[n]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${f}) { + let candidate = f32(${p.getByOffset("offset + k")}); + bestValue = ${bm[n]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${f}u); + for (var currentSize = reduceSize / 2u; reduceSize > 1u; + currentSize = reduceSize / 2u) { + let interval = DIV_CEIL(reduceSize, 2u); + if (local_idx < currentSize) { + let candidate = aBestValues[local_idx + interval]; + bestValue = ${ym[n]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${m.setByOffset("outputIndex", `${n === "mean" ? `${m.type.storage}(bestValue / f32(uniforms.reduceSize))` : `${m.type.storage}(${wm[n]})`}`)}; + } + }`; + return { name: e, shaderCache: { hint: `${t};${f}`, inputDependencies: ["type"] }, getShaderSource: g, getRunData: () => ({ outputs: [{ dims: i, dataType: o }], dispatchGroup: { x: d }, programUniforms: [{ type: 12, data: c }] }) }; + }, et = (e, t, r, n) => { + let o = e.inputs.length === 1 ? r : so(e.inputs, r), i = o.axes; + i.length === 0 && !o.noopWithEmptyAxes && (i = e.inputs[0].dims.map((b, g) => g)); + let a = k.normalizeAxes(i, e.inputs[0].dims.length), u = a, d = e.inputs[0], c = Tm(u, e.inputs[0].dims.length); + c.length > 0 && (d = e.compute(Ee(e.inputs[0], c), { inputs: [0], outputs: [-1] })[0], u = vm(u.length, d.dims.length)); + let [p, m] = $m(d.dims, u), f = p; + o.keepDims && (f = xm(p, a)), e.compute(Im(t, o.cacheKey, [d], n, e.inputs[0].dataType, f, m), { inputs: [d] }); + }, is = (e, t) => { + et(e, "ReduceMeanShared", t, "mean"); + }, as = (e, t) => { + et(e, "ReduceL1Shared", t, "l1"); + }, ss = (e, t) => { + et(e, "ReduceL2Shared", t, "l2"); + }, us = (e, t) => { + et(e, "ReduceLogSumExpShared", t, "logSumExp"); + }, ds = (e, t) => { + et(e, "ReduceMaxShared", t, "max"); + }, ls = (e, t) => { + et(e, "ReduceMinShared", t, "min"); + }, cs = (e, t) => { + et(e, "ReduceProdShared", t, "prod"); + }, ps = (e, t) => { + et(e, "ReduceSumShared", t, "sum"); + }, ms = (e, t) => { + et(e, "ReduceSumSquareShared", t, "sumSquare"); + }, fs = (e, t) => { + et(e, "ReduceLogSumShared", t, "logSum"); + }; + }); + var tt; + var Cm; + var Hr; + var so; + var rt; + var Am; + var Em; + var km; + var Pm; + var zm; + var Om; + var Bm; + var Dm; + var Mm; + var Rm; + var nt; + var gs; + var bs; + var ys; + var _s; + var ws; + var vs; + var $s; + var xs; + var Ss; + var Ts; + var Gr = U(() => { + "use strict"; + ee(); + ne(); + Se(); + ie(); + hs(); + tt = (e) => { + if (!e || e.length === 0 || e.length > 2) throw new Error("Reduce op requires 1 or 2 inputs."); + if (e.length === 2 && e[1].dims.length !== 1) throw new Error("Invalid axes input dims."); + }, Cm = (e) => ["", "", `var value = ${e.getByIndices("input_indices")};`, ""], Hr = (e, t, r, n, o, i, a = false, u = false) => { + let d = [], c = r[0].dims, p = c.length, m = k.normalizeAxes(o, p), f = !u && m.length === 0; + c.forEach((S, $) => { + f || m.indexOf($) >= 0 ? a && d.push(1) : d.push(S); + }); + let b = d.length, g = k.size(d); + return { name: e, shaderCache: t, getShaderSource: (S) => { + let $ = [], v = P("_A", r[0].dataType, p), x = M("output", i, b), T = n(v, x, m), E = T[2]; + for (let I = 0, z = 0; I < p; I++) f || m.indexOf(I) >= 0 ? (a && z++, E = `for(var j${I}: u32 = 0; j${I} < ${c[I]}; j${I}++) { + ${T[2].includes("last_index") ? `let last_index = j${I};` : ""} + ${v.indicesSet("input_indices", I, `j${I}`)} + ${E} + }`) : ($.push(`${v.indicesSet("input_indices", I, x.indicesGet("output_indices", z))};`), z++); + return ` + + ${S.registerUniform("output_size", "u32").declareVariables(v, x)} + + ${S.mainStart()} + ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${v.type.indices}; + let output_indices = ${x.offsetToIndices("global_idx")}; + + ${$.join(` +`)} + ${T[0]} // init ops for reduce max/min + ${T[1]} + ${E} + ${T[3]} + ${T.length === 4 ? x.setByOffset("global_idx", "value") : T.slice(4).join(` +`)} + }`; + }, getRunData: () => ({ outputs: [{ dims: d, dataType: i }], dispatchGroup: { x: Math.ceil(g / 64) }, programUniforms: [{ type: 12, data: g }, ...N(c, d)] }) }; + }, so = (e, t) => { + let r = []; + return e[1].dims[0] > 0 && e[1].getBigInt64Array().forEach((n) => r.push(Number(n))), J({ axes: r, keepDims: t.keepDims, noopWithEmptyAxes: t.noopWithEmptyAxes }); + }, rt = (e, t, r, n) => { + let o = e.inputs, i = o.length === 1 ? r : so(o, r); + e.compute(Hr(t, { hint: i.cacheKey, inputDependencies: ["rank"] }, [o[0]], i.noopWithEmptyAxes && i.axes.length === 0 ? Cm : n, i.axes, o[0].dataType, i.keepDims, i.noopWithEmptyAxes), { inputs: [0] }); + }, Am = (e, t) => { + tt(e.inputs), rt(e, "ReduceLogSum", t, (n, o) => [`var value = ${o.type.storage}(0);`, "", `value += ${n.getByIndices("input_indices")};`, "value = log(value);"]); + }, Em = (e, t) => { + tt(e.inputs), rt(e, "ReduceL1", t, (n, o) => [`var value = ${o.type.storage}(0);`, "", `value += abs(${n.getByIndices("input_indices")});`, ""]); + }, km = (e, t) => { + tt(e.inputs), rt(e, "ReduceL2", t, (n, o) => [`var t = ${o.type.value}(0); var value = ${o.type.value}(0);`, "", `t = ${n.getByIndices("input_indices")}; value += (t * t);`, "value = sqrt(value);"]); + }, Pm = (e, t) => { + tt(e.inputs), rt(e, "ReduceLogSumExp", t, (n, o) => [`var value = ${o.type.storage}(0);`, "", `value += exp(${n.getByIndices("input_indices")});`, "value = log(value);"]); + }, zm = (e, t) => { + tt(e.inputs), rt(e, "ReduceMax", t, (n, o, i) => { + let a = []; + for (let u = 0; u < n.rank; u++) (i.indexOf(u) >= 0 || i.length === 0) && a.push(n.indicesSet("input_indices", u, 0)); + return [`${a.join(` +`)}`, `var value = ${n.getByIndices("input_indices")};`, `value = max(value, ${n.getByIndices("input_indices")});`, ""]; + }); + }, Om = (e, t) => { + tt(e.inputs), rt(e, "ReduceMean", t, (n, o, i) => { + let a = 1; + for (let u = 0; u < n.rank; u++) (i.indexOf(u) >= 0 || i.length === 0) && (a *= e.inputs[0].dims[u]); + return ["var sum = f32(0);", "", `sum += f32(${n.getByIndices("input_indices")});`, `let value = ${o.type.value}(sum / ${a});`]; + }); + }, Bm = (e, t) => { + tt(e.inputs), rt(e, "ReduceMin", t, (n, o, i) => { + let a = []; + for (let u = 0; u < n.rank; u++) (i.indexOf(u) >= 0 || i.length === 0) && a.push(`input_indices[${u}] = 0;`); + return [`${a.join(` +`)}`, `var value = ${n.getByIndices("input_indices")};`, `value = min(value, ${n.getByIndices("input_indices")});`, ""]; + }); + }, Dm = (e, t) => { + tt(e.inputs), rt(e, "ReduceProd", t, (n, o) => [`var value = ${o.type.storage}(1);`, "", `value *= ${n.getByIndices("input_indices")};`, ""]); + }, Mm = (e, t) => { + tt(e.inputs), rt(e, "ReduceSum", t, (n, o) => [`var value = ${o.type.storage}(0);`, "", `value += ${n.getByIndices("input_indices")};`, ""]); + }, Rm = (e, t) => { + tt(e.inputs), rt(e, "ReduceSumSquare", t, (n, o) => [`var t = ${o.type.value}(0); var value = ${o.type.value}(0);`, "", `t = ${n.getByIndices("input_indices")}; value += t * t;`, ""]); + }, nt = (e, t, r) => { + if (t.length === 0) return r; + let n = 1, o = 1; + for (let i = 0; i < t.length; i++) t.indexOf(i) === -1 ? n *= e[i] : o *= e[i]; + return o < 32 && n > 1024; + }, gs = (e, t) => { + nt(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Om(e, t) : is(e, t); + }, bs = (e, t) => { + nt(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Em(e, t) : as(e, t); + }, ys = (e, t) => { + nt(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? km(e, t) : ss(e, t); + }, _s = (e, t) => { + nt(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Pm(e, t) : us(e, t); + }, ws = (e, t) => { + nt(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? zm(e, t) : ds(e, t); + }, vs = (e, t) => { + nt(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Bm(e, t) : ls(e, t); + }, $s = (e, t) => { + nt(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Dm(e, t) : cs(e, t); + }, xs = (e, t) => { + nt(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Mm(e, t) : ps(e, t); + }, Ss = (e, t) => { + nt(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Rm(e, t) : ms(e, t); + }, Ts = (e, t) => { + nt(e.inputs[0].dims, t.axes, t.noopWithEmptyAxes) ? Am(e, t) : fs(e, t); + }; + }); + var Is; + var Cs; + var As; + var uo; + var Es = U(() => { + "use strict"; + ee(); + Se(); + Gr(); + Is = (e) => { + if (!e || e.length === 0 || e.length > 2) throw new Error("ArgMinMaxOp op requires 1 or 2 inputs."); + if (e[0].dataType !== 1) throw new Error("Invalid input type."); + }, Cs = (e, t) => { + Is(e.inputs); + let r = (n, o, i) => { + let a = []; + for (let u = 0; u < n.rank; u++) (i.indexOf(u) >= 0 || i.length === 0) && a.push(`input_indices[${u}] = 0;`); + return [`${a.join(` +`)}`, `var value = ${n.getByIndices("input_indices")}; +var best_index : i32 = 0;`, `if (${n.getByIndices("input_indices")} ${t.selectLastIndex > 0 ? "<=" : "<"} value) { + value = ${n.getByIndices("input_indices")}; + best_index = i32(last_index); + }`, "", o.setByOffset("global_idx", "best_index")]; + }; + e.compute(Hr("ArgMin", { hint: t.cacheKey, inputDependencies: ["rank"] }, [e.inputs[0]], r, [t.axis], 7, t.keepDims), { inputs: [0] }); + }, As = (e, t) => { + Is(e.inputs); + let r = (n, o, i) => { + let a = []; + for (let u = 0; u < n.rank; u++) (i.indexOf(u) >= 0 || i.length === 0) && a.push(`input_indices[${u}] = 0;`); + return [`${a.join(` +`)}`, `var value = ${n.getByIndices("input_indices")}; +var best_index : i32 = 0;`, `if (${n.getByIndices("input_indices")} ${t.selectLastIndex > 0 ? ">=" : ">"} value) { + value = ${n.getByIndices("input_indices")}; + best_index = i32(last_index); + }`, "", o.setByOffset("global_idx", "best_index")]; + }; + e.compute(Hr("argMax", { hint: t.cacheKey, inputDependencies: ["rank"] }, [e.inputs[0]], r, [t.axis], 7, t.keepDims), { inputs: [0] }); + }, uo = (e) => J(e); + }); + var Um; + var lo; + var Nm; + var Vm; + var Wm; + var Rt; + var Lm; + var ks; + var Fr = U(() => { + "use strict"; + ee(); + ne(); + Vr(); + ie(); + Um = (e, t) => { + let r = e[0], n = e[1], o = e[2], i = e[3], a = e[4], u = e[5]; + if (a && u) throw new Error("Attention cannot have both past and attention_bias"); + if (r.dims.length !== 3) throw new Error('Input "input" must have 3 dimensions'); + let d = r.dims[0], c = r.dims[1], p = r.dims[2]; + if (o.dims.length !== 1) throw new Error('Input "bias" is expected to have 1 dimensions'); + if (n.dims.length !== 2) throw new Error('Input "weights" is expected to have 2 dimensions'); + if (n.dims[0] !== p) throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0"); + if (o.dims[0] !== n.dims[1]) throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"'); + let m = o.dims[0] / 3, f = m, b = f; + if (t.qkvHiddenSizes.length > 0) { + if (t.qkvHiddenSizes.length !== 3) throw new Error("qkv_hidden_sizes attribute should have 3 elements"); + for (let x of t.qkvHiddenSizes) if (x % t.numHeads !== 0) throw new Error("qkv_hidden_sizes should be divisible by num_heads"); + m = t.qkvHiddenSizes[0], f = t.qkvHiddenSizes[1], b = t.qkvHiddenSizes[2]; + } + let g = c; + if (m !== f) throw new Error("qkv_hidden_sizes first element should be same as the second"); + if (o.dims[0] !== m + f + b) throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes'); + let _ = 0; + if (a) { + if (f !== b) throw new Error('Input "past" expect k_hidden_size == v_hidden_size'); + if (a.dims.length !== 5) throw new Error('Input "past" must have 5 dimensions'); + if (a.dims[0] !== 2) throw new Error('Input "past" first dimension must be 2'); + if (a.dims[1] !== d) throw new Error('Input "past" second dimension must be batch_size'); + if (a.dims[2] !== t.numHeads) throw new Error('Input "past" third dimension must be num_heads'); + if (a.dims[4] !== f / t.numHeads) throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads'); + t.pastPresentShareBuffer || (_ = a.dims[3]); + } + let S = g + _, $ = -1, v = 0; + if (i) throw new Error("Mask not supported"); + if (a) throw new Error("past is not supported"); + if (u) { + if (u.dims.length !== 4) throw new Error('Input "attention_bias" must have 4 dimensions'); + if (u.dims[0] !== d || u.dims[1] !== t.numHeads || u.dims[2] !== c || u.dims[3] !== S) throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)'); + } + return { batchSize: d, sequenceLength: c, pastSequenceLength: _, kvSequenceLength: g, totalSequenceLength: S, maxSequenceLength: $, inputHiddenSize: p, hiddenSize: m, vHiddenSize: b, headSize: Math.floor(m / t.numHeads), vHeadSize: Math.floor(b / t.numHeads), numHeads: t.numHeads, isUnidirectional: false, pastPresentShareBuffer: false, maskFilterValue: t.maskFilterValue, maskType: v, scale: t.scale, broadcastResPosBias: false, passPastInKv: false, qkvFormat: 1 }; + }, lo = (e, t, r) => t && e ? ` + let total_sequence_length_input = u32(${t.getByOffset("0")}); + let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); + let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; + let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; + total_sequence_length = u32(${e?.getByOffset("batchIdx")}) + 1; + var past_sequence_length: u32 = 0; + if (is_first_prompt == false) { + past_sequence_length = total_sequence_length - sequence_length; + } + ` : ` + ${r ? "let past_sequence_length = uniforms.past_sequence_length" : ""}; + let present_sequence_length = total_sequence_length; + `, Nm = (e, t, r, n, o, i, a, u) => { + let d = ce(a ? 1 : i), c = 64, p = i / d; + p < c && (c = 32); + let m = Math.ceil(i / d / c), f = [{ type: 12, data: t }, { type: 12, data: r }, { type: 12, data: n }, { type: 12, data: o }, { type: 12, data: p }, { type: 12, data: m }], b = be(e.dataType, d), g = Ae(1, d), _ = ["type"]; + a && _.push("type"), u && _.push("type"); + let S = ($) => { + let v = M("x", e.dataType, e.dims, d), x = [v], T = a ? P("seq_lens", a.dataType, a.dims) : void 0; + T && x.push(T); + let E = u ? P("total_sequence_length_input", u.dataType, u.dims) : void 0; + E && x.push(E); + let I = Ae(e.dataType), z = [{ name: "batch_size", type: "u32" }, { name: "num_heads", type: "u32" }, { name: "past_sequence_length", type: "u32" }, { name: "sequence_length", type: "u32" }, { name: "total_sequence_length", type: "u32" }, { name: "elements_per_thread", type: "u32" }]; + return ` + var thread_max: array; + var thread_sum: array; + ${$.registerUniforms(z).declareVariables(...x)} + ${$.mainStart([c, 1, 1])} + let batchIdx = workgroup_id.z / uniforms.num_heads; + let headIdx = workgroup_id.z % uniforms.num_heads; + let sequence_length = uniforms.sequence_length; + var total_sequence_length = uniforms.total_sequence_length; + ${lo(T, E, false)} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = (global_idx / ${c}) * uniforms.total_sequence_length + local_offset; + let seq_causal_length = ${a ? "u32(past_sequence_length + workgroup_id.y + 1)" : "total_sequence_length"}; + var thread_max_vector = ${g}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + thread_max_vector = max(${g}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(() => { + switch (d) { + case 1: + return "thread_max_vector"; + case 2: + return "max(thread_max_vector.x, thread_max_vector.y)"; + case 4: + return "max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))"; + default: + throw new Error(`Unsupported components: ${d}`); + } + })()}; + workgroupBarrier(); + + var max_value = f32(-3.402823e+38f); + for (var i = 0u; i < ${c}; i++) { + max_value = max(thread_max[i], max_value); + } + + var sum_vector = ${g}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + sum_vector += exp(${g}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(() => { + switch (d) { + case 1: + return "sum_vector"; + case 2: + return "sum_vector.x + sum_vector.y"; + case 4: + return "sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w"; + default: + throw new Error(`Unsupported components: ${d}`); + } + })()}; + workgroupBarrier(); + + var sum: f32 = 0; + for (var i = 0u; i < ${c}; i++) { + sum += thread_sum[i]; + } + + if (sum == 0) { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + x[offset + i] = ${v.type.value}(${I}(1.0) / ${I}(seq_causal_length)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + var f32input = ${g}(x[offset + i]); + x[offset + i] = ${v.type.value}(exp(f32input - max_value) / sum); + } + } + ${a ? ` + for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { + x[offset + total_seq_id] = ${v.type.value}(${I}(0)); + }` : ""}; + }`; + }; + return { name: "AttentionProbsSoftmax", shaderCache: { hint: `${c};${b};${d}`, inputDependencies: _ }, getShaderSource: S, getRunData: () => ({ outputs: [], dispatchGroup: { x: 1, y: o, z: t * r }, programUniforms: f }) }; + }, Vm = (e, t, r, n, o, i, a, u, d) => { + let c = a + i.kvSequenceLength, p = [i.batchSize, i.numHeads, i.sequenceLength, c], m = e > 1 && n, f = i.kvNumHeads ? i.kvNumHeads : i.numHeads, b = m ? [i.batchSize, f, c, i.headSize] : void 0, g = i.nReps ? i.nReps : 1, _ = i.scale === 0 ? 1 / Math.sqrt(i.headSize) : i.scale, S = ce(i.headSize), $ = i.headSize / S, v = 12, x = { x: Math.ceil(c / v), y: Math.ceil(i.sequenceLength / v), z: i.batchSize * i.numHeads }, T = [{ type: 12, data: i.sequenceLength }, { type: 12, data: $ }, { type: 12, data: c }, { type: 12, data: i.numHeads }, { type: 12, data: i.headSize }, { type: 1, data: _ }, { type: 12, data: a }, { type: 12, data: i.kvSequenceLength }, { type: 12, data: g }], E = m && n && k.size(n.dims) > 0, I = ["type", "type"]; + E && I.push("type"), o && I.push("type"), u && I.push("type"), d && I.push("type"); + let z = [{ dims: p, dataType: t.dataType, gpuDataType: 0 }]; + m && z.push({ dims: b, dataType: t.dataType, gpuDataType: 0 }); + let O = (D) => { + let L = P("q", t.dataType, t.dims, S), q = P("key", r.dataType, r.dims, S), Q = [L, q]; + if (E) { + let X = P("past_key", n.dataType, n.dims, S); + Q.push(X); + } + o && Q.push(P("attention_bias", o.dataType, o.dims)); + let W = u ? P("seq_lens", u.dataType, u.dims) : void 0; + W && Q.push(W); + let Z = d ? P("total_sequence_length_input", d.dataType, d.dims) : void 0; + Z && Q.push(Z); + let we = M("output", t.dataType, p), H = [we]; + m && H.push(M("present_key", t.dataType, b, S)); + let j = Ae(1, S), te = [{ name: "M", type: "u32" }, { name: "K", type: "u32" }, { name: "N", type: "u32" }, { name: "num_heads", type: "u32" }, { name: "head_size", type: "u32" }, { name: "alpha", type: "f32" }, { name: "past_sequence_length", type: "u32" }, { name: "kv_sequence_length", type: "u32" }, { name: "n_reps", type: "u32" }]; + return ` + const TILE_SIZE = ${v}u; + + var tileQ: array<${L.type.storage}, ${v * v}>; + var tileK: array<${L.type.storage}, ${v * v}>; + ${D.registerUniforms(te).declareVariables(...Q, ...H)} + ${D.mainStart([v, v, 1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z % uniforms.num_heads; + let kvHeadIdx = ${g === 1 ? "headIdx" : "headIdx / uniforms.n_reps"}; + let kv_num_heads = ${g === 1 ? "uniforms.num_heads" : "uniforms.num_heads / uniforms.n_reps"}; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let m = workgroup_id.y * TILE_SIZE; + let n = workgroup_id.x * TILE_SIZE; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.N; + ${lo(W, Z, true)} + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; + let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + ${E && m ? "let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;" : ""}; + let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; + ${m ? "let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;" : ""} + var value = ${j}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; + } + if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${E && m ? ` + if (n + local_id.y < past_sequence_length) { + tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; + }` : ` + if (n + local_id.y < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + }`} + ${m ? `if (n + local_id.y < present_sequence_length) { + present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx]; + }` : ""} + } + workgroupBarrier(); + + for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { + value += ${j}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); + } + + workgroupBarrier(); + } + + if (global_id.y < uniforms.M && global_id.x < total_sequence_length) { + let headOffset = workgroup_id.z * uniforms.M * uniforms.N; + let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; + var sum: f32 = ${(() => { + switch (S) { + case 1: + return "value"; + case 2: + return "value.x + value.y"; + case 4: + return "value.x + value.y + value.z + value.w"; + default: + throw new Error(`Unsupported components: ${S}`); + } + })()}; + output[outputIdx] = ${we.type.value} (sum * uniforms.alpha) + ${o ? "attention_bias[outputIdx]" : "0.0"}; + } + }`; + }; + return { name: "AttentionProbs", shaderCache: { hint: `${S};${o !== void 0};${n !== void 0};${e}`, inputDependencies: I }, getRunData: () => ({ outputs: z, dispatchGroup: x, programUniforms: T }), getShaderSource: O }; + }, Wm = (e, t, r, n, o, i, a = void 0, u = void 0) => { + let d = i + o.kvSequenceLength, c = o.nReps ? o.nReps : 1, p = o.vHiddenSize * c, m = e > 1 && n, f = o.kvNumHeads ? o.kvNumHeads : o.numHeads, b = m ? [o.batchSize, f, d, o.headSize] : void 0, g = [o.batchSize, o.sequenceLength, p], _ = 12, S = { x: Math.ceil(o.vHeadSize / _), y: Math.ceil(o.sequenceLength / _), z: o.batchSize * o.numHeads }, $ = [{ type: 12, data: o.sequenceLength }, { type: 12, data: d }, { type: 12, data: o.vHeadSize }, { type: 12, data: o.numHeads }, { type: 12, data: o.headSize }, { type: 12, data: p }, { type: 12, data: i }, { type: 12, data: o.kvSequenceLength }, { type: 12, data: c }], v = m && n && k.size(n.dims) > 0, x = ["type", "type"]; + v && x.push("type"), a && x.push("type"), u && x.push("type"); + let T = [{ dims: g, dataType: t.dataType, gpuDataType: 0 }]; + m && T.push({ dims: b, dataType: t.dataType, gpuDataType: 0 }); + let E = (I) => { + let z = P("probs", t.dataType, t.dims), O = P("v", r.dataType, r.dims), D = [z, O]; + v && D.push(P("past_value", n.dataType, n.dims)); + let L = a ? P("seq_lens", a.dataType, a.dims) : void 0; + a && D.push(L); + let q = u ? P("total_sequence_length_input", u.dataType, u.dims) : void 0; + u && D.push(q); + let W = [M("output", t.dataType, g)]; + m && W.push(M("present_value", t.dataType, b)); + let Z = [{ name: "M", type: "u32" }, { name: "K", type: "u32" }, { name: "N", type: "u32" }, { name: "num_heads", type: "u32" }, { name: "head_size", type: "u32" }, { name: "v_hidden_size", type: "u32" }, { name: "past_sequence_length", type: "u32" }, { name: "kv_sequence_length", type: "u32" }, { name: "n_reps", type: "u32" }]; + return ` + const TILE_SIZE = ${_}u; + var tileQ: array<${z.type.value}, ${_ * _}>; + var tileV: array<${z.type.value}, ${_ * _}>; + ${I.registerUniforms(Z).declareVariables(...D, ...W)} + ${I.mainStart([_, _, 1])} + let headIdx = workgroup_id.z % uniforms.num_heads; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let kvHeadIdx = ${c === 1 ? "headIdx" : "headIdx / uniforms.n_reps"}; + let kv_num_heads = ${c === 1 ? "uniforms.num_heads" : "uniforms.num_heads / uniforms.n_reps"}; + let m = global_id.y; + let n = global_id.x; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.K; + ${lo(L, q, true)} + let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch + ${v && m ? "let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;" : ""}; + let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; + ${m ? "let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;" : ""} + var value = ${z.type.storage}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${v && m ? ` + if (w + local_id.y < past_sequence_length) { + tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; + } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N]; + } + ` : ` + if (w + local_id.y < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N]; + }`} + ${m ? ` + if (w + local_id.y < present_sequence_length) { + present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; + }` : ""} + } + workgroupBarrier(); + for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { + value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; + } + workgroupBarrier(); + } + + // we need to transpose output from BNSH_v to BSND_v + if (m < uniforms.M && n < uniforms.N) { + let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + + headIdx * uniforms.N + n; + output[outputIdx] = value; + } + }`; + }; + return { name: "AttentionScore", shaderCache: { hint: `${n !== void 0};${e}`, inputDependencies: x }, getRunData: () => ({ outputs: T, dispatchGroup: S, programUniforms: $ }), getShaderSource: E }; + }, Rt = (e, t, r, n, o, i, a, u, d, c, p = void 0, m = void 0) => { + let f = Math.min(e.outputCount, 1 + (a ? 1 : 0) + (u ? 1 : 0)), b = f > 1 ? c.pastSequenceLength : 0, g = b + c.kvSequenceLength, _ = d && k.size(d.dims) > 0 ? d : void 0, S = [t, r]; + f > 1 && a && k.size(a.dims) > 0 && S.push(a), _ && S.push(_), p && S.push(p), m && S.push(m); + let $ = e.compute(Vm(f, t, r, a, _, c, b, p, m), { inputs: S, outputs: f > 1 ? [-1, 1] : [-1] })[0]; + e.compute(Nm($, c.batchSize, c.numHeads, b, c.sequenceLength, g, p, m), { inputs: p && m ? [$, p, m] : [$], outputs: [] }); + let v = [$, n]; + f > 1 && u && k.size(u.dims) > 0 && v.push(u), p && v.push(p), m && v.push(m), e.compute(Wm(f, $, n, u, c, b, p, m), { inputs: v, outputs: f > 1 ? [0, 2] : [0] }); + }, Lm = (e, t) => { + let r = [t.batchSize, t.numHeads, t.sequenceLength, t.headSize], n = t.sequenceLength, o = t.inputHiddenSize, i = t.headSize, a = 12, u = { x: Math.ceil(t.headSize / a), y: Math.ceil(t.sequenceLength / a), z: t.batchSize * t.numHeads }, d = [e.inputs[0], e.inputs[1], e.inputs[2]], c = [{ type: 12, data: n }, { type: 12, data: o }, { type: 12, data: i }, { type: 12, data: t.numHeads }, { type: 12, data: t.headSize }, { type: 12, data: t.hiddenSize }, { type: 12, data: t.hiddenSize + t.hiddenSize + t.vHiddenSize }], p = (m) => { + let f = M("output_q", d[0].dataType, r), b = M("output_k", d[0].dataType, r), g = M("output_v", d[0].dataType, r), _ = P("input", d[0].dataType, d[0].dims), S = P("weight", d[1].dataType, d[1].dims), $ = P("bias", d[2].dataType, d[2].dims), v = _.type.storage, x = [{ name: "M", type: "u32" }, { name: "K", type: "u32" }, { name: "N", type: "u32" }, { name: "num_heads", type: "u32" }, { name: "head_size", type: "u32" }, { name: "hidden_size", type: "u32" }, { name: "ldb", type: "u32" }]; + return ` + const TILE_SIZE = ${a}u; + var tileInput: array<${v}, ${a * a}>; + var tileWeightQ: array<${v}, ${a * a}>; + var tileWeightK: array<${v}, ${a * a}>; + var tileWeightV: array<${v}, ${a * a}>; + ${m.registerUniforms(x).declareVariables(_, S, $, f, b, g)} + ${m.mainStart([a, a, 1])} + let batchIndex = workgroup_id.z / uniforms.num_heads; + let headNumber = workgroup_id.z % uniforms.num_heads; + let m = global_id.y; + let n = global_id.x; + + let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; + let biasOffsetQ = headNumber * uniforms.head_size; + let biasOffsetK = uniforms.hidden_size + biasOffsetQ; + let biasOffsetV = uniforms.hidden_size + biasOffsetK; + + var valueQ = ${v}(0); + var valueK = ${v}(0); + var valueV = ${v}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + let offset = n + (w + local_id.y) * uniforms.ldb; + tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; + tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; + tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; + } + workgroupBarrier(); + for (var k: u32 = 0u; k ({ outputs: [{ dims: r, dataType: e.inputs[0].dataType, gpuDataType: 0 }, { dims: r, dataType: e.inputs[0].dataType, gpuDataType: 0 }, { dims: r, dataType: e.inputs[0].dataType, gpuDataType: 0 }], dispatchGroup: u, programUniforms: c }), getShaderSource: p }, { inputs: d, outputs: [-1, -1, -1] }); + }, ks = (e, t) => { + let r = Um(e.inputs, t), [n, o, i] = Lm(e, r); + return Rt(e, n, o, i, e.inputs[4], void 0, void 0, void 0, e.inputs[5], r); + }; + }); + var Gm; + var Hm; + var Fm; + var Ps; + var zs = U(() => { + "use strict"; + We(); + ee(); + ne(); + Se(); + ie(); + Gm = (e, t) => { + if (!e || e.length !== 5) throw new Error("BatchNormalization requires 5 inputs"); + let r = (n, o, i) => { + let a = o.length; + if (a !== n.length) throw new Error(`${i}: num dimensions != ${a}`); + o.forEach((u, d) => { + if (u !== n[d]) throw new Error(`${i}: dim[${d}] do not match`); + }); + }; + if (e[0].dims.length > 1) { + let n = t.format === "NHWC" ? t.spatial ? e[0].dims.slice(-1) : e[0].dims.slice(-1).concat(e[0].dims.slice(1, e[0].dims.length - 1)) : e[0].dims.slice(1, t.spatial ? 2 : void 0); + r(e[1].dims, n, "Invalid input scale"), r(e[2].dims, n, "Invalid input B"), r(e[3].dims, n, "Invalid input mean"), r(e[4].dims, n, "Invalid input var"); + } else r(e[1].dims, [1], "Invalid input scale"), r(e[2].dims, [1], "Invalid input B"), r(e[3].dims, [1], "Invalid input mean"), r(e[4].dims, [1], "Invalid input var"); + }, Hm = (e, t) => { + let { epsilon: r, spatial: n, format: o } = t, i = e[0].dims, a = n ? ce(i[i.length - 1]) : 1, u = o === "NHWC" && i.length > 1 ? a : 1, d = k.size(i) / a, c = n, p = c ? i.length : i, m = P("x", e[0].dataType, e[0].dims, a), f = P("scale", e[1].dataType, e[1].dims, u), b = P("bias", e[2].dataType, e[2].dims, u), g = P("inputMean", e[3].dataType, e[3].dims, u), _ = P("inputVar", e[4].dataType, e[4].dims, u), S = M("y", e[0].dataType, p, a), $ = () => { + let x = ""; + if (n) x = `let cOffset = ${i.length === 1 ? "0u" : o === "NHWC" ? `outputIndices[${i.length - 1}] / ${a}` : "outputIndices[1]"};`; + else if (o === "NCHW") x = ` + ${S.indicesSet("outputIndices", "0", "0")} + let cOffset = ${S.indicesToOffset("outputIndices")};`; + else { + x = `var cIndices = ${f.type.indices}(0); + cIndices[0] = outputIndices[${i.length - 1}];`; + for (let T = 1; T < f.rank; T++) x += `cIndices[${T}] = outputIndices[${T}];`; + x += `let cOffset = ${f.indicesToOffset("cIndices")};`; + } + return x; + }, v = (x) => ` + const epsilon = ${r}; + ${x.registerUniform("outputSize", "u32").declareVariables(m, f, b, g, _, S)} + ${x.mainStart()} + ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${S.offsetToIndices(`global_idx * ${a}`)}; + ${$()} + let scale = ${f.getByOffset("cOffset")}; + let bias = ${b.getByOffset("cOffset")}; + let inputMean = ${g.getByOffset("cOffset")}; + let inputVar = ${_.getByOffset("cOffset")}; + let x = ${m.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${S.setByOffset("global_idx", "value")} + }`; + return { name: "BatchNormalization", shaderCache: { hint: `${t.epsilon}_${t.format}_${n}_${a}`, inputDependencies: c ? ["rank", "type", "type", "type", "type"] : void 0 }, getShaderSource: v, getRunData: () => ({ outputs: [{ dims: e[0].dims, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(d / 64) }, programUniforms: c ? [{ type: 12, data: d }, ...N(i)] : [{ type: 12, data: d }] }) }; + }, Fm = (e) => J(e), Ps = (e, t) => { + let { inputs: r, outputCount: n } = e, o = Fm({ ...t, outputCount: n }); + if (ge.webgpu.validateInputContent && Gm(r, o), t.trainingMode) throw new Error("BatchNormalization trainingMode is not supported yet."); + e.compute(Hm(r, o)); + }; + }); + var qm; + var jm; + var Os; + var Bs = U(() => { + "use strict"; + ne(); + ie(); + qm = (e) => { + if (e[0].dims.length !== 3) throw new Error("input should have 3 dimensions"); + if (![320, 640, 1280].includes(e[0].dims[2])) throw new Error("number of channels should be 320, 640 or 1280"); + if (e[1].dims.length !== 1) throw new Error("bias is expected to have 1 dimensions"); + if (e[0].dims[2] !== e[1].dims[0]) throw new Error("last dimension of input and bias are not the same"); + }, jm = (e) => { + let t = e[0].dims, r = e[0].dims[2], n = k.size(t) / 4, o = e[0].dataType, i = P("input", o, t, 4), a = P("bias", o, [r], 4), u = P("residual", o, t, 4), d = M("output", o, t, 4); + return { name: "BiasAdd", getRunData: () => ({ outputs: [{ dims: t, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(n / 64) } }), getShaderSource: (p) => ` + const channels = ${r}u / 4; + ${p.declareVariables(i, a, u, d)} + + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes(n)} + let value = ${i.getByOffset("global_idx")} + + ${a.getByOffset("global_idx % channels")} + ${u.getByOffset("global_idx")}; + ${d.setByOffset("global_idx", "value")} + }` }; + }, Os = (e) => { + qm(e.inputs), e.compute(jm(e.inputs)); + }; + }); + var Km; + var me; + var Ds; + var Ms; + var Rs; + var Us; + var Ns; + var Vs; + var Ws; + var Ls; + var Gs; + var Zm; + var Hs; + var Fs; + var qs; + var js; + var Yt; + var Ks; + var qr; + var Zs; + var Qs; + var Ys; + var Xs; + var Js; + var eu; + var tu; + var ru; + var nu; + var ou; + var iu; + var au; + var su; + var uu; + var du; + var lu; + var cu; + var pu; + var co; + var po; + var mu; + var fu; + var hu; + var Qm; + var Ym; + var gu; + var jr = U(() => { + "use strict"; + ee(); + ne(); + Se(); + ie(); + Km = (e, t, r, n, o, i, a) => { + let u = Math.ceil(t / 4), d = ""; + typeof o == "string" ? d = `${o}(a)` : d = o("a"); + let c = P("inputData", r, [u], 4), p = M("outputData", n, [u], 4), m = [{ name: "vec_size", type: "u32" }]; + return a && m.push(...a), ` + ${e.registerUniforms(m).declareVariables(c, p)} + + ${i ?? ""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${c.getByOffset("global_idx")}; + ${p.setByOffset("global_idx", d)} + }`; + }, me = (e, t, r, n, o, i = e.dataType, a, u) => { + let d = [{ type: 12, data: Math.ceil(k.size(e.dims) / 4) }]; + return a && d.push(...a), { name: t, shaderCache: { hint: o, inputDependencies: ["type"] }, getShaderSource: (c) => Km(c, k.size(e.dims), e.dataType, i, r, n, u), getRunData: (c) => ({ outputs: [{ dims: e.dims, dataType: i }], dispatchGroup: { x: Math.ceil(k.size(c[0].dims) / 64 / 4) }, programUniforms: d }) }; + }, Ds = (e) => { + e.compute(me(e.inputs[0], "Abs", "abs")); + }, Ms = (e) => { + e.compute(me(e.inputs[0], "Acos", "acos")); + }, Rs = (e) => { + e.compute(me(e.inputs[0], "Acosh", "acosh")); + }, Us = (e) => { + e.compute(me(e.inputs[0], "Asin", "asin")); + }, Ns = (e) => { + e.compute(me(e.inputs[0], "Asinh", "asinh")); + }, Vs = (e) => { + e.compute(me(e.inputs[0], "Atan", "atan")); + }, Ws = (e) => { + e.compute(me(e.inputs[0], "Atanh", "atanh")); + }, Ls = (e) => J(e), Gs = (e, t) => { + let r; + switch (t.to) { + case 10: + r = "vec4"; + break; + case 1: + r = "vec4"; + break; + case 12: + r = "vec4"; + break; + case 6: + r = "vec4"; + break; + case 9: + r = "vec4"; + break; + default: + throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`); + } + e.compute(me(e.inputs[0], "Cast", r, void 0, t.cacheKey, t.to)); + }, Zm = (e) => { + let t, r, n = e.length >= 2 && e[1].data !== 0, o = e.length >= 3 && e[2].data !== 0; + switch (e[0].dataType) { + case 1: + t = n ? e[1].getFloat32Array()[0] : -34028234663852886e22, r = o ? e[2].getFloat32Array()[0] : 34028234663852886e22; + break; + case 10: + t = n ? e[1].getUint16Array()[0] : 64511, r = o ? e[2].getUint16Array()[0] : 31743; + break; + default: + throw new Error("Unsupport data type"); + } + return J({ min: t, max: r }); + }, Hs = (e, t) => { + let r = t || Zm(e.inputs), n = Ae(e.inputs[0].dataType); + e.compute(me(e.inputs[0], "Clip", (o) => `clamp(${o}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`, void 0, r.cacheKey, void 0, [{ type: e.inputs[0].dataType, data: r.min }, { type: e.inputs[0].dataType, data: r.max }], [{ name: "min", type: n }, { name: "max", type: n }]), { inputs: [0] }); + }, Fs = (e) => { + e.compute(me(e.inputs[0], "Ceil", "ceil")); + }, qs = (e) => { + e.compute(me(e.inputs[0], "Cos", "cos")); + }, js = (e) => { + e.compute(me(e.inputs[0], "Cosh", "cosh")); + }, Yt = (e) => J(e), Ks = (e, t) => { + let r = Ae(e.inputs[0].dataType); + e.compute(me(e.inputs[0], "Elu", (n) => `elu_vf32(${n})`, ` + const elu_alpha_ = ${r}(${t.alpha}); + + fn elu_f32(a: ${r}) -> ${r} { + return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); + } + + fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> { + return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); + }`, t.cacheKey)); + }, qr = (e = "f32") => ` +const r0: ${e} = 0.3275911; +const r1: ${e} = 0.254829592; +const r2: ${e} = -0.284496736; +const r3: ${e} = 1.421413741; +const r4: ${e} = -1.453152027; +const r5: ${e} = 1.061405429; + +fn erf_vf32(v: vec4<${e}>) -> vec4<${e}> { + let absv = abs(v); + let x = 1.0 / (1.0 + r0 * absv); + return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv)); +}`, Zs = (e) => { + let t = Ae(e.inputs[0].dataType); + e.compute(me(e.inputs[0], "Erf", (r) => `erf_vf32(${r})`, qr(t))); + }, Qs = (e) => { + e.compute(me(e.inputs[0], "Exp", "exp")); + }, Ys = (e) => { + e.compute(me(e.inputs[0], "Floor", "floor")); + }, Xs = (e) => { + let t = Ae(e.inputs[0].dataType); + e.compute(me(e.inputs[0], "Gelu", (r) => `0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`, qr(t))); + }, Js = (e, t) => { + let r = Ae(e.inputs[0].dataType); + e.compute(me(e.inputs[0], "LeakyRelu", (n) => `select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${r}>(0.0))`, `const leaky_relu_alpha_ = ${r}(${t.alpha});`, t.cacheKey)); + }, eu = (e) => { + e.compute(me(e.inputs[0], "Not", (t) => `!${t}`)); + }, tu = (e) => { + e.compute(me(e.inputs[0], "Neg", (t) => `-${t}`)); + }, ru = (e) => { + e.compute(me(e.inputs[0], "Reciprocal", (t) => `1.0/${t}`)); + }, nu = (e) => { + let t = Ae(e.inputs[0].dataType); + e.compute(me(e.inputs[0], "Relu", (r) => `select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`)); + }, ou = (e) => { + e.compute(me(e.inputs[0], "Sigmoid", (t) => `(1.0 / (1.0 + exp(-${t})))`)); + }, iu = (e) => J(e), au = (e, t) => { + let r = Ae(e.inputs[0].dataType); + e.compute(me(e.inputs[0], "HardSigmoid", (n) => `max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${n} + vec4<${r}>(${t.beta})))`, void 0, t.cacheKey)); + }, su = (e) => { + e.compute(me(e.inputs[0], "Sin", "sin")); + }, uu = (e) => { + e.compute(me(e.inputs[0], "Sinh", "sinh")); + }, du = (e) => { + e.compute(me(e.inputs[0], "Sqrt", "sqrt")); + }, lu = (e) => { + e.compute(me(e.inputs[0], "Tan", "tan")); + }, cu = (e) => `sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`, pu = (e) => { + e.compute(me(e.inputs[0], "Tanh", cu)); + }, co = (e = "f32") => ` +const fast_gelu_a: ${e} = 0.5; +const fast_gelu_b: ${e} = 0.7978845608028654; +const fast_gelu_c: ${e} = 0.035677408136300125; + +fn tanh_v(v: vec4<${e}>) -> vec4<${e}> { + return ${cu("v")}; +} +`, po = (e) => `(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`, mu = (e) => { + let t = Ae(e.inputs[0].dataType); + e.compute(me(e.inputs[0], "FastGelu", po, co(t), void 0, e.inputs[0].dataType)); + }, fu = (e, t) => { + let r = Ae(e.inputs[0].dataType); + return e.compute(me(e.inputs[0], "ThresholdedRelu", (n) => `select(vec4<${r}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`, `const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`, t.cacheKey)), 0; + }, hu = (e) => { + e.compute(me(e.inputs[0], "Log", "log")); + }, Qm = (e, t) => ` +const alpha = vec4<${e}>(${t}); +const one = ${e}(1.0); +const zero = ${e}(0.0); + +fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { + let v = x *alpha; + var x1 : vec4<${e}>; + for (var i = 0; i < 4; i = i + 1) { + if (v[i] >= zero) { + x1[i] = one / (one + exp(-v[i])); + } else { + x1[i] = one - one / (one + exp(v[i])); + } + } + return x * x1; +} +`, Ym = (e) => `quick_gelu_impl(${e})`, gu = (e, t) => { + let r = Ae(e.inputs[0].dataType); + e.compute(me(e.inputs[0], "QuickGelu", Ym, Qm(r, t.alpha), t.cacheKey, e.inputs[0].dataType)); + }; + }); + var Xm; + var Jm; + var yu; + var _u = U(() => { + "use strict"; + ne(); + ie(); + jr(); + Xm = (e) => { + if (e[0].dims.length !== 3) throw new Error("input should have 3 dimensions"); + if (![2560, 5120, 10240].includes(e[0].dims[2])) throw new Error("hidden state should be 2560, 5120 or 10240"); + if (e[1].dims.length !== 1) throw new Error("bias is expected to have 1 dimensions"); + if (e[0].dims[2] !== e[1].dims[0]) throw new Error("last dimension of input and bias are not the same"); + }, Jm = (e) => { + let t = e[0].dims.slice(); + t[2] = t[2] / 2; + let r = P("input", e[0].dataType, e[0].dims, 4), n = P("bias", e[0].dataType, [e[0].dims[2]], 4), o = M("output", e[0].dataType, t, 4), i = k.size(t) / 4, a = be(e[0].dataType); + return { name: "BiasSplitGelu", getRunData: () => ({ outputs: [{ dims: t, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(i / 64) } }), getShaderSource: (d) => ` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${e[0].dims[2] / 4 / 2}u; + + ${d.declareVariables(r, n, o)} + + ${qr(a)} + + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes(i)} + let biasIdx = global_idx % halfChannels; + let batchIndex = global_idx / halfChannels; + let inputOffset = biasIdx + batchIndex * halfChannels * 2; + let valueLeft = input[inputOffset] + bias[biasIdx]; + let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; + let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); + + ${o.setByOffset("global_idx", "valueLeft * geluRight")} + }` }; + }, yu = (e) => { + Xm(e.inputs), e.compute(Jm(e.inputs)); + }; + }); + var ef; + var tf; + var ot; + var wu; + var vu; + var $u; + var xu; + var Su; + var Tu; + var Iu; + var Cu; + var Au; + var Eu; + var ku = U(() => { + "use strict"; + ee(); + ne(); + ie(); + ef = (e, t, r, n, o, i, a, u, d, c, p, m) => { + let f, b; + typeof u == "string" ? f = b = (v, x) => `${u}((${v}),(${x}))` : typeof u == "function" ? f = b = u : (f = u.scalar, b = u.vector); + let g = M("outputData", p, n.length, 4), _ = P("aData", d, t.length, 4), S = P("bData", c, r.length, 4), $; + if (o) if (i) { + let v = k.size(t) === 1, x = k.size(r) === 1, T = t.length > 0 && t[t.length - 1] % 4 === 0, E = r.length > 0 && r[r.length - 1] % 4 === 0; + v || x ? $ = g.setByOffset("global_idx", b(v ? `${_.type.value}(${_.getByOffset("0")}.x)` : _.getByOffset("global_idx"), x ? `${S.type.value}(${S.getByOffset("0")}.x)` : S.getByOffset("global_idx"))) : $ = ` + let outputIndices = ${g.offsetToIndices("global_idx * 4u")}; + let offsetA = ${_.broadcastedIndicesToOffset("outputIndices", g)}; + let offsetB = ${S.broadcastedIndicesToOffset("outputIndices", g)}; + ${g.setByOffset("global_idx", b(a || T ? _.getByOffset("offsetA / 4u") : `${_.type.value}(${_.getByOffset("offsetA / 4u")}[offsetA % 4u])`, a || E ? S.getByOffset("offsetB / 4u") : `${S.type.value}(${S.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `; + } else $ = g.setByOffset("global_idx", b(_.getByOffset("global_idx"), S.getByOffset("global_idx"))); + else { + if (!i) throw new Error("no necessary to use scalar implementation for element-wise binary op implementation."); + let v = (x, T, E = "") => { + let I = `aData[indexA${T}][componentA${T}]`, z = `bData[indexB${T}][componentB${T}]`; + return ` + let outputIndices${T} = ${g.offsetToIndices(`global_idx * 4u + ${T}u`)}; + let offsetA${T} = ${_.broadcastedIndicesToOffset(`outputIndices${T}`, g)}; + let offsetB${T} = ${S.broadcastedIndicesToOffset(`outputIndices${T}`, g)}; + let indexA${T} = offsetA${T} / 4u; + let indexB${T} = offsetB${T} / 4u; + let componentA${T} = offsetA${T} % 4u; + let componentB${T} = offsetB${T} % 4u; + ${x}[${T}] = ${E}(${f(I, z)}); + `; + }; + p === 9 ? $ = ` + var data = vec4(0); + ${v("data", 0, "u32")} + ${v("data", 1, "u32")} + ${v("data", 2, "u32")} + ${v("data", 3, "u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));` : $ = ` + ${v("outputData[global_idx]", 0)} + ${v("outputData[global_idx]", 1)} + ${v("outputData[global_idx]", 2)} + ${v("outputData[global_idx]", 3)} + `; + } + return ` + ${e.registerUniform("vec_size", "u32").declareVariables(_, S, g)} + + ${m ?? ""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${$} + }`; + }, tf = (e, t, r, n, o, i, a = r.dataType) => { + let u = r.dims.map((_) => Number(_) ?? 1), d = n.dims.map((_) => Number(_) ?? 1), c = !k.areEqual(u, d), p = u, m = k.size(u), f = false, b = false, g = [c]; + if (c) { + let _ = Je.calcShape(u, d, false); + if (!_) throw new Error("Can't perform binary op on the given tensors"); + p = _.slice(), m = k.size(p); + let S = k.size(u) === 1, $ = k.size(d) === 1, v = u.length > 0 && u[u.length - 1] % 4 === 0, x = d.length > 0 && d[d.length - 1] % 4 === 0; + g.push(S), g.push($), g.push(v), g.push(x); + let T = 1; + for (let E = 1; E < p.length; E++) { + let I = u[u.length - E], z = d[d.length - E]; + if (I === z) T *= I; + else break; + } + T % 4 === 0 ? (b = true, f = true) : (S || $ || v || x) && (f = true); + } else f = true; + return g.push(f), { name: e, shaderCache: { hint: t + g.map((_) => _.toString()).join("_"), inputDependencies: ["rank", "rank"] }, getShaderSource: (_) => ef(_, u, d, p, f, c, b, o, r.dataType, n.dataType, a, i), getRunData: () => ({ outputs: [{ dims: p, dataType: a }], dispatchGroup: { x: Math.ceil(m / 64 / 4) }, programUniforms: [{ type: 12, data: Math.ceil(k.size(p) / 4) }, ...N(u, d, p)] }) }; + }, ot = (e, t, r, n, o, i) => { + e.compute(tf(t, o ?? "", e.inputs[0], e.inputs[1], r, n, i)); + }, wu = (e) => { + ot(e, "Add", (t, r) => `${t}+${r}`); + }, vu = (e) => { + ot(e, "Div", (t, r) => `${t}/${r}`); + }, $u = (e) => { + ot(e, "Equal", { scalar: (t, r) => `u32(${t}==${r})`, vector: (t, r) => `vec4(${t}==${r})` }, void 0, void 0, 9); + }, xu = (e) => { + ot(e, "Mul", (t, r) => `${t}*${r}`); + }, Su = (e) => { + let t = P("input", e.inputs[0].dataType, e.inputs[0].dims).type.value; + ot(e, "Pow", { scalar: (n, o) => `pow_custom(${n},${o})`, vector: (n, o) => `pow_vector_custom(${n},${o})` }, ` + fn pow_custom(a : ${t}, b : ${t}) -> ${t} { + if (b == ${t}(0.0)) { + return ${t}(1.0); + } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) { + return ${t}(pow(f32(a), f32(b))); // NaN + } + return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t === "i32" ? "round" : ""}(pow(f32(abs(a)), f32(b)))); + } + fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> { + // TODO: implement vectorized pow + return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); + } + `); + }, Tu = (e) => { + ot(e, "Sub", (t, r) => `${t}-${r}`); + }, Iu = (e) => { + ot(e, "Greater", { scalar: (t, r) => `u32(${t}>${r})`, vector: (t, r) => `vec4(${t}>${r})` }, void 0, void 0, 9); + }, Cu = (e) => { + ot(e, "Less", { scalar: (t, r) => `u32(${t}<${r})`, vector: (t, r) => `vec4(${t}<${r})` }, void 0, void 0, 9); + }, Au = (e) => { + ot(e, "GreaterOrEqual", { scalar: (t, r) => `u32(${t}>=${r})`, vector: (t, r) => `vec4(${t}>=${r})` }, void 0, void 0, 9); + }, Eu = (e) => { + ot(e, "LessOrEqual", { scalar: (t, r) => `u32(${t}<=${r})`, vector: (t, r) => `vec4(${t}<=${r})` }, void 0, void 0, 9); + }; + }); + var nf; + var of; + var af; + var sf; + var Pu; + var zu; + var Ou = U(() => { + "use strict"; + ee(); + ne(); + Se(); + ie(); + nf = (e, t) => { + if (!e || e.length < 1) throw new Error("too few inputs"); + let r = 0, n = e[r], o = n.dataType, i = n.dims.length; + e.forEach((a, u) => { + if (u !== r) { + if (a.dataType !== o) throw new Error("input tensors should be one type"); + if (a.dims.length !== i) throw new Error("input tensors should have the same shape"); + a.dims.forEach((d, c) => { + if (c !== t && d !== n.dims[c]) throw new Error("non concat dimensions must match"); + }); + } + }); + }, of = (e, t) => ` + fn calculateInputIndex(index: u32) -> u32 { + let sizeInConcatAxis = array(${t}); + for (var i: u32 = 0u; i < ${e}; i += 1u ) { + if (index < sizeInConcatAxis[i]) { + return i; + } + } + return ${e}u; + }`, af = (e, t) => { + let r = e.length, n = []; + for (let o = 0; o < r; ++o) { + let i = t.setByOffset("global_idx", e[o].getByIndices("indices")); + r === 1 ? n.push(i) : o === 0 ? n.push(`if (inputIndex == ${o}u) { ${i} }`) : o === r - 1 ? n.push(`else { ${i} }`) : n.push(`else if (inputIndex == ${o}) { ${i} }`); + } + return n.join(` +`); + }, sf = (e, t, r, n) => { + let o = k.size(r), i = new Array(e.length), a = new Array(e.length), u = 0, d = [], c = [], p = [{ type: 12, data: o }]; + for (let _ = 0; _ < e.length; ++_) u += e[_].dims[t], i[_] = u, c.push(e[_].dims.length), a[_] = P(`input${_}`, n, c[_]), d.push("rank"), p.push({ type: 12, data: i[_] }); + for (let _ = 0; _ < e.length; ++_) p.push(...N(e[_].dims)); + p.push(...N(r)); + let m = M("output", n, r.length), f = m.indicesGet("indices", t), b = Array.from(Array(i.length).keys()).map((_) => `uniforms.sizeInConcatAxis${_}`).join(","), g = (_) => ` + + ${(() => { + _.registerUniform("outputSize", "u32"); + for (let S = 0; S < e.length; S++) _.registerUniform(`sizeInConcatAxis${S}`, "u32"); + return _.declareVariables(...a, m); + })()} + + ${of(i.length, b)} + + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + var indices = ${m.offsetToIndices("global_idx")}; + + let inputIndex = calculateInputIndex(${f}); + if (inputIndex != 0u) { + let sizeInConcatAxis = array(${b}); + ${f} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${af(a, m)} + }`; + return { name: "Concat", shaderCache: { hint: `${t}`, inputDependencies: d }, getRunData: () => ({ outputs: [{ dims: r, dataType: n }], dispatchGroup: { x: Math.ceil(o / 64) }, programUniforms: p }), getShaderSource: g }; + }, Pu = (e, t) => { + let r = e.inputs, n = r[0].dims, o = k.normalizeAxis(t.axis, n.length); + nf(r, o); + let i = n.slice(); + i[o] = r.reduce((u, d) => u + (d.dims.length > o ? d.dims[o] : 0), 0); + let a = r.filter((u) => k.size(u.dims) > 0); + e.compute(sf(a, o, i, r[0].dataType), { inputs: a }); + }, zu = (e) => J({ axis: e.axis }); + }); + var Fe; + var qe; + var je; + var Kr; + var bt = U(() => { + "use strict"; + ee(); + ne(); + Fe = (e, t, r = "f32") => { + switch (e.activation) { + case "Relu": + return `value = max(value, ${t}(0.0));`; + case "Sigmoid": + return `value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`; + case "Clip": + return `value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`; + case "HardSigmoid": + return `value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`; + case "LeakyRelu": + return `value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`; + case "Tanh": + return `let e2x = exp(-2.0 * abs(value)); + value = sign(value) * (1.0 - e2x) / (1.0 + e2x); + `; + case "": + return ""; + default: + throw new Error(`Unsupported activation ${e.activation}`); + } + }, qe = (e, t) => { + e.activation === "Clip" ? t.push({ type: 1, data: e.clipMax }, { type: 1, data: e.clipMin }) : e.activation === "HardSigmoid" ? t.push({ type: 1, data: e.alpha }, { type: 1, data: e.beta }) : e.activation === "LeakyRelu" && t.push({ type: 1, data: e.alpha }); + }, je = (e, t) => { + e.activation === "Clip" ? t.push({ name: "clip_max", type: "f32" }, { name: "clip_min", type: "f32" }) : e.activation === "HardSigmoid" ? t.push({ name: "alpha", type: "f32" }, { name: "beta", type: "f32" }) : e.activation === "LeakyRelu" && t.push({ name: "alpha", type: "f32" }); + }, Kr = (e) => { + let t = e?.activation || ""; + if (t === "HardSigmoid") { + let [r, n] = e?.activation_params || [0.2, 0.5]; + return { activation: t, alpha: r, beta: n }; + } else if (t === "Clip") { + let [r, n] = e?.activation_params || [Wa, La]; + return { activation: t, clipMax: n, clipMin: r }; + } else if (t === "LeakyRelu") { + let [r] = e?.activation_params || [0.01]; + return { activation: t, alpha: r }; + } + return { activation: t }; + }; + }); + var Ie; + var Bu; + var Zr = U(() => { + "use strict"; + Ie = (e, t) => { + switch (e) { + case 1: + return t; + case 2: + return `vec2<${t}>`; + case 3: + return `vec3<${t}>`; + case 4: + return `vec4<${t}>`; + default: + throw new Error(`${e}-component is not supported.`); + } + }, Bu = (e) => ` + ${e ? "value = value + getBiasByOutputCoords(coords);" : ""} + `; + }); + var Du; + var Mu = U(() => { + "use strict"; + Du = (e) => ` +fn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 { + return dot(coords, vec4( + shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1)); +} +fn getOutputIndexFromCoords(coords : vec4) -> i32 { + return dot(coords, vec4( + i32(${e}.x), i32(${e}.y), i32(${e}.z), 1)); +} +`; + }); + var Xt; + var Qr; + var Yr = U(() => { + "use strict"; + ee(); + ne(); + ie(); + bt(); + Xt = (e, t, r, n, o) => { + let i = n - r; + return ` + ${Array.from({ length: r }).map((a, u) => ` + if (${F(t.shape, u, t.rank)} != 1) { + ${t.indicesSet(e, u, F(o, u + i, n))} + } else { + ${t.indicesSet(e, u, 0)} + }`).join("")} +`; + }, Qr = (e, t, r, n, o = false, i) => { + let a = e[0].dims, u = e[1].dims, d = a[a.length - 2], c = u[u.length - 1], p = a[a.length - 1], m = ce(c), f = ce(p), b = ce(d), g = k.size(r) / m / b, _ = e.length > 2, S = n ? n.slice(0, -2) : r.slice(0, -2), v = [k.size(S), d, c], x = [{ type: 12, data: g }, { type: 12, data: d }, { type: 12, data: c }, { type: 12, data: p }]; + qe(t, x), x.push(...N(S, a, u)), _ && x.push(...N(e[2].dims)), x.push(...N(v)); + let T = (E) => { + let I = Lr("batch_dims", e[0].dataType, S.length), z = P("a", e[0].dataType, a.length, f), O = P("b", e[1].dataType, u.length, m), D = M("output", e[0].dataType, v.length, m), L = be(D.type.tensor), q = Fe(t, D.type.value, L), Q = [z, O], W = ""; + if (_) { + let H = o ? m : 1; + Q.push(P("bias", e[2].dataType, e[2].dims.length, H)), W = `${o ? `value += bias[col / ${H}];` : `value += ${D.type.value}(bias[row + i]);`}`; + } + let Z = [{ name: "output_size", type: "u32" }, { name: "M", type: "u32" }, { name: "N", type: "u32" }, { name: "K", type: "u32" }]; + je(t, Z); + let we = () => { + let H = `var a_data: ${z.type.value};`; + for (let j = 0; j < f; j++) H += ` + let b_data${j} = b[(b_offset + (k + ${j}) * uniforms.N + col) / ${m}];`; + for (let j = 0; j < b; j++) { + H += `a_data = a[(a_offset + (row + ${j}) * uniforms.K + k) / ${f}];`; + for (let te = 0; te < f; te++) H += ` + values[${j}] = fma(${O.type.value}(a_data${f === 1 ? "" : `[${te}]`}), b_data${te}, values[${j}]); +`; + } + return H; + }; + return ` + ${E.registerUniforms(Z).registerInternalVariables(I).declareVariables(...Q, D)} + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let col = (global_idx % (uniforms.N / ${m})) * ${m}; + var index1 = global_idx / (uniforms.N / ${m}); + let stride1 = uniforms.M / ${b}; + let row = (index1 % stride1) * ${b}; + let batch = index1 / stride1; + + ${r.length === 2 ? "" : `let batch_indices = ${I.offsetToIndices("batch")};`} + + var a_indices: ${z.type.indices}; + ${Xt("a_indices", z, z.rank - 2, I.rank, "batch_indices")} + ${z.indicesSet("a_indices", z.rank - 2, 0)} + ${z.indicesSet("a_indices", z.rank - 1, 0)} + let a_offset = ${z.indicesToOffset("a_indices")}; + + var b_indices: ${O.type.indices}; + ${Xt("b_indices", O, O.rank - 2, I.rank, "batch_indices")} + ${O.indicesSet("b_indices", O.rank - 2, 0)} + ${O.indicesSet("b_indices", O.rank - 1, 0)} + let b_offset = ${O.indicesToOffset("b_indices")}; + var values: array<${D.type.value}, ${b}>; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${f}) { + ${we()} + } + for (var i = 0u; i < ${b}u; i++) { + var value = values[i]; + ${W} + ${q} + let cur_indices = ${D.type.indices}(batch, row + i, col); + let offset = ${D.indicesToOffset("cur_indices")}; + ${D.setByOffset(`offset / ${m}`, "value")}; + } + } + `; + }; + return { name: "MatMulNaive", shaderCache: { hint: `${t.activation};${m};${f};${b};${o}`, inputDependencies: _ ? ["rank", "rank", "rank"] : ["rank", "rank"] }, getRunData: () => ({ outputs: [{ dims: i ? i(r) : r, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(g / 64) }, programUniforms: x }), getShaderSource: T }; + }; + }); + var uf; + var df; + var mo; + var Ru; + var lf; + var fo; + var cf; + var Jt; + var Xr = U(() => { + "use strict"; + ee(); + ne(); + ie(); + bt(); + Yr(); + Zr(); + uf = (e, t) => e ? ` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart / innerElementSize + inputCol${t ? ", batchIndices" : ""}); + ` : ` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRow + innerRow, + kStart / innerElementSize + inputCol${t ? ", batchIndices" : ""}); + `, df = (e, t) => e ? ` + let ACached0 = mm_Asub[k * innerElementSize][localRow]; + let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; + let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; + ${t === 3 ? "" : "let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"} + for (var i = 0; i < rowPerThread; i = i + 1) { + acc[i] = BCached0 * ACached0[i] + acc[i]; + acc[i] = BCached1 * ACached1[i] + acc[i]; + acc[i] = BCached2 * ACached2[i] + acc[i]; + ${t === 3 ? "" : "acc[i] = BCached3 * ACached3[i] + acc[i];"} + }` : ` + for (var i = 0; i < rowPerThread; i = i + 1) { + let ACached = mm_Asub[tileRow + i][k]; + acc[i] = BCached0 * ACached.x + acc[i]; + acc[i] = BCached1 * ACached.y + acc[i]; + acc[i] = BCached2 * ACached.z + acc[i]; + ${t === 3 ? "" : "acc[i] = BCached3 * ACached.w + acc[i];"} + }`, mo = (e, t, r = "f32", n, o = false, i = 32, a = false, u = 32) => { + let d = t[1] * e[1], c = t[0] * e[0], p = o ? d : i, m = o ? i : d, f = p / t[0], b = i / t[1]; + if (!((o && f === 4 && e[1] === 4 || !o && (f === 3 || f === 4)) && p % t[0] === 0 && i % t[1] === 0 && e[0] === 4)) throw new Error(`If transposeA ${o} is true, innerElementSize ${f} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${f} must be 3 or 4. + tileAWidth ${p} must be divisible by workgroupSize[0]${t[0]}. tileInner ${i} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`); + return ` +var mm_Asub: array, ${p / f}>, ${m}>; +var mm_Bsub: array, ${c / e[0]}>, ${i}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${f}; +const tileInner = ${i}; + +@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let localRow = i32(localId.y); + let tileRow = localRow * rowPerThread; + let tileCol = i32(localId.x); + + let globalRow =i32(globalId.y) * rowPerThread; + let globalCol = i32(globalId.x); + let batch = ${a ? "0" : "i32(globalId.z)"}; + ${n ? `let batchIndices = ${n.offsetToIndices("u32(batch)")};` : ""} + let globalRowStart = i32(workgroupId.y) * ${d}; + + let num_tiles = ${a ? `${Math.ceil(u / i)}` : "(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${a ? `i32(globalId.z) * ${u}` : "0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${b}; + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let inputRow = tileRow + innerRow; + let inputCol = tileCol; + ${uf(o, n)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${b}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n ? ", batchIndices" : ""}); + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { + let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; + let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; + let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; + ${f === 3 ? "" : "let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${df(o, f)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`; + }, Ru = (e, t) => e ? ` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart + inputCol${t ? ", batchIndices" : ""}); + ` : ` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRowStart + inputRow, + kStart + inputCol${t ? ", batchIndices" : ""}); + `, lf = (e) => e ? "let ACached = mm_Asub[k][tileRow + innerRow];" : "let ACached = mm_Asub[tileRow + innerRow][k];", fo = (e, t, r = "f32", n, o = false, i = 32, a = false, u = 32, d = false) => { + let c = e[1] * t[1], p = e[0] * t[0], m = o ? c : i, f = o ? i : c; + if (!(f % t[1] === 0 && m % t[0] === 0 && i % t[1] === 0)) throw new Error(`tileAHight ${f} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${m} must be divisible by workgroupSize[0]${t[0]}, tileInner ${i} must be divisible by workgroupSize[1]${t[1]}`); + let b = f / t[1], g = m / t[0], _ = i / t[1], S = d ? ` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${c}; + let globalColStart = i32(workgroupId.x) * ${p}; + + // Loop over shared dimension. + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var inputRow = localRow; inputRow < ${f}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${m}; inputCol = inputCol + ${t[0]}) { + ${Ru(o, n)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${i}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${p}; inputCol = inputCol + ${t[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${n ? ", batchIndices" : ""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${r}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}]; + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let ACached = ${o ? `mm_Asub[k][localRow + innerRow * ${t[1]}];` : `mm_Asub[localRow + innerRow * ${t[1]}][k];`} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + + ACached * BCached[innerCol]; + } + } + } + workgroupBarrier(); + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let gRow = globalRowStart + localRow + innerRow * ${t[1]}; + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let gCol = globalColStart + localCol + innerCol * ${t[0]}; + mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); + } + } + ` : ` +let tileRow = i32(localId.y) * rowPerThread; +let tileCol = i32(localId.x) * colPerThread; + +let globalRow = i32(globalId.y) * rowPerThread; +let globalCol = i32(globalId.x) * colPerThread; +let globalRowStart = i32(workgroupId.y) * ${c}; + +let tileRowA = i32(localId.y) * ${b}; +let tileColA = i32(localId.x) * ${g}; +let tileRowB = i32(localId.y) * ${_}; +// Loop over shared dimension. +for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < ${b}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${g}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${Ru(o, n)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol + innerCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalCol + innerCol${n ? ", batchIndices" : ""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${r}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][tileCol + inner]; + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + ${lf(o)} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; + } + } + } + + workgroupBarrier(); +} + +for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + mm_write(batch, globalRow + innerRow, globalCol + innerCol, + acc[innerRow][innerCol]); + } +} +`; + return ` + var mm_Asub : array, ${f}>; + var mm_Bsub : array, ${i}>; + const rowPerThread = ${e[1]}; + const colPerThread = ${e[0]}; + const tileInner = ${i}; + +@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let batch = ${a ? "0" : "i32(globalId.z)"}; + ${n ? `let batchIndices = ${n.offsetToIndices("u32(batch)")};` : ""} + let num_tiles = ${a ? `${Math.ceil(u / i)}` : "(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${a ? `i32(globalId.z) * ${u}` : "0"}; + + var acc : array, rowPerThread>; + ${S} + } +`; + }, cf = (e, t, r, n, o = false) => { + let [i, a, u, d] = n, c = be(n[0].type.tensor); + return ` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${Ie(e, c)} { + var value = ${Ie(e, c)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + var aIndices: ${a.type.indices}; + ${Xt("aIndices", a, a.rank - 2, i.rank, "batchIndices")} + ${a.indicesSet("aIndices", a.rank - 2, "u32(row)")} + ${a.indicesSet("aIndices", a.rank - 1, "u32(colIn)")} + value = ${a.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${Ie(e, c)} { + var value = ${Ie(e, c)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + var bIndices: ${u.type.indices}; + ${Xt("bIndices", u, u.rank - 2, i.rank, "batchIndices")} + ${u.indicesSet("bIndices", u.rank - 2, "u32(row)")} + ${u.indicesSet("bIndices", u.rank - 1, "u32(colIn)")} + value = ${u.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Ie(e, c)}) { + let col = colIn * ${e}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${t ? `value = value + ${o ? "bias[colIn]" : `${Ie(e, c)}(bias[row])`};` : ""} + ${r} + ${d.setByIndices("vec3(coords)", "value")} + } + } + `; + }, Jt = (e, t, r, n, o = false, i) => { + let a = e[0].dims, u = e[1].dims, d = a.slice(0, -2), c = u.slice(0, -2), p = n ? n.slice(0, -2) : r.slice(0, -2), m = k.size(p), f = a[a.length - 2], b = a[a.length - 1], g = u[u.length - 1], _ = b % 4 === 0 && g % 4 === 0, S = f <= 8 ? [4, 1, 1] : [4, 4, 1], $ = [8, 8, 1], v = [Math.ceil(g / $[0] / S[0]), Math.ceil(f / $[1] / S[1]), Math.ceil(m / $[2] / S[2])], x = _ ? 4 : 1, T = [...d, f, b / x], E = T.length, I = [...c, b, g / x], z = I.length, O = [m, f, g / x], D = [{ type: 6, data: f }, { type: 6, data: g }, { type: 6, data: b }]; + qe(t, D), D.push(...N(p, T, I)); + let L = ["rank", "rank"], q = e.length > 2; + q && (D.push(...N(e[2].dims)), L.push("rank")), D.push(...N(O)); + let Q = (W) => { + let Z = p.length, we = Lr("batchDims", e[0].dataType, Z, 1), H = be(e[0].dataType), j = P("a", e[0].dataType, E, x), te = P("b", e[1].dataType, z, x), X = M("result", e[0].dataType, O.length, x), ue = [j, te]; + if (q) { + let V = o ? x : 1; + ue.push(P("bias", e[2].dataType, e[2].dims.length, V)); + } + let he = [{ name: "dim_a_outer", type: "i32" }, { name: "dim_b_outer", type: "i32" }, { name: "dim_inner", type: "i32" }]; + je(t, he); + let ye = be(X.type.tensor), re = Fe(t, X.type.value, ye), C = cf(x, q, re, [we, j, te, X], o); + return ` + ${W.registerUniforms(he).registerInternalVariables(we).declareVariables(...ue, X)} + ${C} + ${_ ? mo(S, $, H, we) : fo(S, $, H, we)} + `; + }; + return { name: "MatMul", shaderCache: { hint: `${S};${t.activation};${_};${o}`, inputDependencies: L }, getRunData: () => ({ outputs: [{ dims: i ? i(r) : r, dataType: e[0].dataType }], dispatchGroup: { x: v[0], y: v[1], z: v[2] }, programUniforms: D }), getShaderSource: Q }; + }; + }); + var pf; + var Uu; + var Nu = U(() => { + "use strict"; + ee(); + Xe(); + ie(); + bt(); + Zr(); + Mu(); + Xr(); + pf = (e, t, r, n, o = false, i, a = 4, u = 4, d = 4, c = "f32") => { + let p = (L) => { + switch (L) { + case 1: + return "resData = x[xIndex];"; + case 3: + return `resData = vec3<${c}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`; + case 4: + return "resData = x[xIndex / 4];"; + default: + throw new Error(`innerElementSize ${L} is not supported.`); + } + }, m = (L) => { + switch (L) { + case 1: + return "return w[row * i32(uniforms.w_shape[3]) + colIn];"; + case 4: + return "return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];"; + default: + throw new Error(`innerElementSize ${L} is not supported.`); + } + }, f = e ? ` + let coord = vec4(batch, xRow, xCol, xCh); + ` : ` + let coord = vec4(batch, xCh, xRow, xCol); + `, b = e ? ` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + ` : ` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `, g = e ? "i32(uniforms.x_shape[1])" : "i32(uniforms.x_shape[2])", _ = e ? "i32(uniforms.x_shape[2])" : "i32(uniforms.x_shape[3])", S = e ? "row" : "col", $ = e ? "col" : "row", v = ` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e ? "i32(uniforms.result_shape[2])" : "i32(uniforms.result_shape[3])"}; + let outRow = ${S} / outWidth; + let outCol = ${S} % outWidth; + + let WRow = ${$} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${$} / inChannels % i32(uniforms.w_shape[1]); + let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; + let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; + let xCh = ${$} % inChannels; + var resData = ${Ie(a, c)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${g} && xCol >= 0 && xCol < ${_}) { + ${f} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${p(a)} + } + return resData;`, x = e ? t && n ? ` + let col = colIn * ${a}; + ${v}` : ` + let col = colIn * ${a}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${v} + } + return ${Ie(a, c)}(0.0);` : n && r ? ` + let col = colIn * ${a}; + ${v}` : ` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${v} + } + return ${Ie(a, c)}(0.0);`, T = e ? n && r ? m(u) : ` + let col = colIn * ${u}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${m(u)} + } + return ${Ie(u, c)}(0.0);` : ` + let col = colIn * ${u}; + if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { + ${m(u)} + } + return ${Ie(u, c)}(0.0);`, E = Ie(d, c), I = e ? Ie(a, c) : Ie(u, c), z = e ? Ie(u, c) : Ie(a, c), O = Fe(i, E, c); + return ` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${I} { + ${e ? x : T} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${z} { + ${e ? T : x} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${E}) { + let col = colIn * ${d}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) + { + var value = valueIn; + let outWidth = ${e ? "i32(uniforms.result_shape[2])" : "i32(uniforms.result_shape[3])"}; + ${b} + ${Bu(o)} + ${O} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`; + }, Uu = (e, t, r, n, o, i, a, u, d) => { + let c = t.format === "NHWC", p = c ? e[0].dims[3] : e[0].dims[1], m = r[0], f = c ? r[2] : r[3], b = c ? r[1] : r[2], g = c ? r[3] : r[1], _ = c && (p % 4 === 0 || p % 3 === 0) && g % 4 === 0, S = c ? g : f * b, $ = c ? f * b : g, v = [8, 8, 1], x = n <= 8 ? [4, 1, 1] : [4, 4, 1], T = [Math.ceil(S / v[0] / x[0]), Math.ceil($ / v[1] / x[1]), Math.ceil(m / v[2] / x[2])]; + se("verbose", () => `[conv2d_mm_webgpu] dispatch = ${T}`); + let E = _ ? c && p % 4 !== 0 ? 3 : 4 : 1, I = v[1] * x[1], z = v[0] * x[0], O = Math.max(v[0] * E, v[1]), D = n % I === 0, L = o % z === 0, q = i % O === 0, Q = _ ? [E, 4, 4] : [1, 1, 1], W = [{ type: 6, data: n }, { type: 6, data: o }, { type: 6, data: i }, { type: 6, data: [t.pads[0], t.pads[1]] }, { type: 6, data: t.strides }, { type: 6, data: t.dilations }]; + qe(t, W), W.push(...N(e[0].dims, e[1].dims)); + let Z = ["rank", "rank"]; + a && (W.push(...N(e[2].dims)), Z.push("rank")), W.push(...N(r)); + let we = (H) => { + let j = [{ name: "dim_a_outer", type: "i32" }, { name: "dim_b_outer", type: "i32" }, { name: "dim_inner", type: "i32" }, { name: "pad", type: "i32", length: 2 }, { name: "stride", type: "i32", length: 2 }, { name: "dilation", type: "i32", length: 2 }]; + je(t, j); + let te = _ ? 4 : 1, X = be(e[0].dataType), ue = ` + fn setOutputAtIndex(flatIndex : i32, value : ${_ ? `vec4<${X}>` : X}) { + result[flatIndex] = ${_ ? `vec4<${X}>` : X}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${_ ? `vec4<${X}>` : X}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${_ ? "/ 4" : ""}, value); + }`, he = P("x", e[0].dataType, e[0].dims.length, E === 3 ? 1 : E), ye = P("w", e[1].dataType, e[1].dims.length, te), re = [he, ye], C = M("result", e[0].dataType, r.length, te); + if (a) { + let V = P("bias", e[2].dataType, e[2].dims.length, te); + re.push(V), ue += ` + fn getBiasByOutputCoords(coords : vec4) -> ${_ ? `vec4<${X}>` : X} { + return bias[coords.${c ? "w" : "y"}${_ ? "/ 4" : ""}]; + }`; + } + return ` + ${Du("uniforms.result_strides")} + //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4, + // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2, + // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 }; + ${H.registerUniforms(j).declareVariables(...re, C)} + ${ue} + ${pf(c, D, L, q, a, t, Q[0], Q[1], Q[2], X)} + ${_ ? mo(x, v, X, void 0, !c, O) : fo(x, v, X, void 0, !c, O, false, void 0, u)}`; + }; + return { name: "Conv2DMatMul", shaderCache: { hint: `${t.cacheKey};${E};${_};${D};${L};${q};${I};${z};${O}`, inputDependencies: Z }, getRunData: () => ({ outputs: [{ dims: d ? d(r) : r, dataType: e[0].dataType }], dispatchGroup: { x: T[0], y: T[1], z: T[2] }, programUniforms: W }), getShaderSource: we }; + }; + }); + var mf; + var Vu; + var Jr; + var ff; + var Wu; + var hf; + var Lu; + var Gu; + var Hu = U(() => { + "use strict"; + ee(); + Xe(); + ne(); + ie(); + bt(); + Zr(); + mf = (e) => { + let t = 1; + for (let r = 0; r < e.length; r++) t *= e[r]; + return t; + }, Vu = (e) => typeof e == "number" ? [e, e, e] : e, Jr = (e, t) => t <= 1 ? e : e + (e - 1) * (t - 1), ff = (e, t, r, n = 1) => { + let o = Jr(t, n); + return Math.floor((e[0] * (r - 1) - r + o) / 2); + }, Wu = (e, t, r, n, o) => { + o == null && (o = ff(e, t[0], n[0])); + let i = [0, 0, 0, r]; + for (let a = 0; a < 3; a++) e[a] + 2 * o >= t[a] && (i[a] = Math.trunc((e[a] - t[a] + 2 * o) / n[a] + 1)); + return i; + }, hf = (e, t, r, n, o, i, a, u, d, c) => { + let p, m, f, b; + if (e === "VALID" && (e = 0), typeof e == "number") { + p = { top: e, bottom: e, left: e, right: e, front: e, back: e }; + let g = Wu([t, r, n, 1], [u, d, c], 1, [o, i, a], e); + m = g[0], f = g[1], b = g[2]; + } else if (Array.isArray(e)) { + if (!e.every((_, S, $) => _ === $[0])) throw Error(`Unsupported padding parameter: ${e}`); + p = { top: e[0], bottom: e[1], left: e[2], right: e[3], front: e[4], back: e[5] }; + let g = Wu([t, r, n, 1], [u, d, c], 1, [o, i, a], e[0]); + m = g[0], f = g[1], b = g[2]; + } else if (e === "SAME_UPPER") { + m = Math.ceil(t / o), f = Math.ceil(r / i), b = Math.ceil(n / a); + let g = (m - 1) * o + u - t, _ = (f - 1) * i + d - r, S = (b - 1) * a + c - n, $ = Math.floor(g / 2), v = g - $, x = Math.floor(_ / 2), T = _ - x, E = Math.floor(S / 2), I = S - E; + p = { top: x, bottom: T, left: E, right: I, front: $, back: v }; + } else throw Error(`Unknown padding parameter: ${e}`); + return { padInfo: p, outDepth: m, outHeight: f, outWidth: b }; + }, Lu = (e, t, r, n, o, i = false, a = "channelsLast") => { + let u, d, c, p, m; + if (a === "channelsLast") [u, d, c, p, m] = e; + else if (a === "channelsFirst") [u, m, d, c, p] = e; + else throw new Error(`Unknown dataFormat ${a}`); + let [f, , b, g, _] = t, [S, $, v] = Vu(r), [x, T, E] = Vu(n), I = Jr(b, x), z = Jr(g, T), O = Jr(_, E), { padInfo: D, outDepth: L, outHeight: q, outWidth: Q } = hf(o, d, c, p, S, $, v, I, z, O), W = i ? f * m : f, Z = [0, 0, 0, 0, 0]; + return a === "channelsFirst" ? Z = [u, W, L, q, Q] : a === "channelsLast" && (Z = [u, L, q, Q, W]), { batchSize: u, dataFormat: a, inDepth: d, inHeight: c, inWidth: p, inChannels: m, outDepth: L, outHeight: q, outWidth: Q, outChannels: W, padInfo: D, strideDepth: S, strideHeight: $, strideWidth: v, filterDepth: b, filterHeight: g, filterWidth: _, effectiveFilterDepth: I, effectiveFilterHeight: z, effectiveFilterWidth: O, dilationDepth: x, dilationHeight: T, dilationWidth: E, inShape: e, outShape: Z, filterShape: t }; + }, Gu = (e, t, r, n, o, i) => { + let a = i === "channelsLast", u = a ? e[0].dims[3] : e[0].dims[1], d = false, c = [64, 1, 1], p = { x: r.map((v, x) => x) }, m = [Math.ceil(mf(p.x.map((v) => r[v])) / c[0]), 1, 1]; + se("verbose", () => `[conv3d_naive_webgpu] dispatch = ${m}`); + let f = d ? a && u % 4 !== 0 ? 3 : 4 : 1, b = k.size(r), g = [{ type: 12, data: b }, { type: 12, data: n }, { type: 12, data: o }, { type: 12, data: t.strides }, { type: 12, data: t.dilations }]; + qe(t, g), g.push(...N(e[0].dims, e[1].dims)); + let _ = ["rank", "rank"], S = e.length === 3; + S && (g.push(...N(e[2].dims)), _.push("rank")), g.push(...N(r)); + let $ = (v) => { + let x = [{ name: "output_size", type: "u32" }, { name: "filter_dims", type: "u32", length: n.length }, { name: "pads", type: "u32", length: o.length }, { name: "strides", type: "u32", length: t.strides.length }, { name: "dilations", type: "u32", length: t.dilations.length }]; + je(t, x); + let T = d ? 4 : 1, E = be(e[0].dataType), I = P("x", e[0].dataType, e[0].dims.length, f === 3 ? 1 : f), z = P("W", e[1].dataType, e[1].dims.length, T), O = [I, z], D = M("result", e[0].dataType, r.length, T), L = ""; + if (S) { + let W = P("bias", e[2].dataType, e[2].dims.length, T); + O.push(W), L += ` + fn getBiasByOutputCoords(coords : array) -> ${d ? `vec4<${E}>` : E} { + return bias[${a ? F("coords", 4, 5) : F("coords", 1, 5)}${d ? "/ 4" : ""}]; + }`; + } + let q = Ie(f, E), Q = Fe(t, q, E); + return ` + ${L} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${I.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${z.getByIndices("aIndices")}; + } + ${v.registerUniforms(x).declareVariables(...O, D)} + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${D.offsetToIndices("global_idx")}; + let batch = ${F("coords", 0, I.rank)}; + let d2 = ${a ? F("coords", I.rank - 1, I.rank) : F("coords", 1, I.rank)}; + let xFRCCorner = vec3(${a ? F("coords", 1, I.rank) : F("coords", 2, I.rank)}, + ${a ? F("coords", 2, I.rank) : F("coords", 3, I.rank)}, + ${a ? F("coords", 3, I.rank) : F("coords", 4, I.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${a ? F("uniforms.x_shape", 1, I.rank) : F("uniforms.x_shape", 2, I.rank)}; + let xShapeZ = ${a ? F("uniforms.x_shape", 2, I.rank) : F("uniforms.x_shape", 3, I.rank)}; + let xShapeW = ${a ? F("uniforms.x_shape", 3, I.rank) : F("uniforms.x_shape", 4, I.rank)}; + let xShapeU = ${a ? F("uniforms.x_shape", 4, I.rank) : F("uniforms.x_shape", 1, I.rank)}; + let inputDepthNearestVec4 = (xShapeU / 4) * 4; + let inputDepthVec4Remainder = xShapeU % 4; + + var value = 0.0; + for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { + let xF = xFCorner + wF * uniforms.dilations[0]; + if (xF < 0 || xF >= xShapeY) { + continue; + } + + for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { + let xR = xRCorner + wR * uniforms.dilations[1]; + if (xR < 0 || xR >= xShapeZ) { + continue; + } + + for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { + let xC = xCCorner + wC * uniforms.dilations[2]; + if (xC < 0 || xC >= xShapeW) { + continue; + } + + for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { + ${a ? `let xValues = vec4( + getX(batch, xF, xR, xC, d1), + getX(batch, xF, xR, xC, d1 + 1), + getX(batch, xF, xR, xC, d1 + 2), + getX(batch, xF, xR, xC, d1 + 3)); + ` : `let xValues = vec4( + getX(batch, d1, xF, xR, xC), + getX(batch, d1 + 1, xF, xR, xC), + getX(batch, d1 + 2, xF, xR, xC), + getX(batch, d1 + 3, xF, xR, xC)); + `} + let wValues = vec4( + getW(d2, d1, wF, wR, wC), + getW(d2, d1 + 1, wF, wR, wC), + getW(d2, d1 + 2, wF, wR, wC), + getW(d2, d1 + 3, wF, wR, wC)); + value += dot(xValues, wValues); + } + if (inputDepthVec4Remainder == 1) { + ${a ? `value += getX(batch, xF, xR, xC, inputDepthNearestVec4) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);` : `value += getX(batch, inputDepthNearestVec4, xF, xR, xC) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} + } else if (inputDepthVec4Remainder == 2) { + ${a ? `let xValues = vec2( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); + ` : `let xValues = vec2( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); + `} + let wValues = vec2( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); + value += dot(xValues, wValues); + } else if (inputDepthVec4Remainder == 3) { + ${a ? `let xValues = vec3( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); + ` : `let xValues = vec3( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); + `} + let wValues = vec3( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); + value += dot(xValues, wValues); + } + } + } + } + ${S ? "value = value + getBiasByOutputCoords(coords)" : ""}; + ${Q} + result[global_idx] = f32(value); + }`; + }; + return { name: "Conv3DNaive", shaderCache: { hint: `${t.cacheKey};${a};${f};${S}`, inputDependencies: _ }, getRunData: () => ({ outputs: [{ dims: r, dataType: e[0].dataType }], dispatchGroup: { x: m[0], y: m[1], z: m[2] }, programUniforms: g }), getShaderSource: $ }; + }; + }); + var Fu; + var qu; + var ju = U(() => { + "use strict"; + ee(); + ne(); + ie(); + bt(); + Fu = (e, t, r, n) => { + let o = e.length > 2, i = o ? "value += b[output_channel];" : "", a = e[0].dims, u = e[1].dims, d = t.format === "NHWC", c = d ? r[3] : r[1], p = c / t.group, m = d && p >= 4 ? ce(c) : 1, f = k.size(r) / m, b = [{ type: 12, data: f }, { type: 12, data: t.dilations }, { type: 12, data: [t.strides[0], t.strides[1]] }, { type: 12, data: [t.pads[0], t.pads[1]] }, { type: 12, data: p }]; + qe(t, b), b.push(...N(a, [u[0], u[1], u[2], u[3] / m])); + let g = o ? ["rank", "rank", "rank"] : ["rank", "rank"]; + b.push(...N([r[0], r[1], r[2], r[3] / m])); + let _ = (S) => { + let $ = M("output", e[0].dataType, r.length, m), v = be($.type.tensor), x = Fe(t, $.type.value, v), T = P("x", e[0].dataType, a.length), E = P("w", e[1].dataType, u.length, m), I = [T, E]; + o && I.push(P("b", e[2].dataType, e[2].dims, m)); + let z = [{ name: "output_size", type: "u32" }, { name: "dilations", type: "u32", length: t.dilations.length }, { name: "strides", type: "u32", length: 2 }, { name: "pads", type: "u32", length: 2 }, { name: "output_channels_per_group", type: "u32" }]; + je(t, z); + let O = d ? ` + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { + continue; + } + + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + let xVal = ${T.get("batch", "xHeight", "xWidth", "input_channel")}; + let wVal = ${E.get("wHeight", "wWidth", "wInChannel", "output_channel")}; + value += xVal * wVal; + } + } + } + ` : ` + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) { + continue; + } + + let xVal = ${T.get("batch", "input_channel", "xHeight", "xWidth")}; + let wVal = ${E.get("output_channel", "wInChannel", "wHeight", "wWidth")}; + value += xVal * wVal; + } + } + } + `; + return ` + ${S.registerUniforms(z).declareVariables(...I, $)} + + ${S.mainStart()} + ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${$.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${d ? 3 : 1}]; + let xRCCorner: vec2 = vec2(outputIndices[${d ? 1 : 2}], outputIndices[${d ? 2 : 3}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel * ${m} / uniforms.output_channels_per_group; + var in_channel_offset = group_id * uniforms.w_shape[${d ? 2 : 1}]; + + var value: ${$.type.value} = ${$.type.value}(0); + ${O} + ${i} + ${x} + ${$.setByOffset("global_idx", "value")} + }`; + }; + return { name: "GroupedConv", shaderCache: { hint: `${t.cacheKey}_${m}`, inputDependencies: g }, getRunData: () => ({ outputs: [{ dims: n ? n(r) : r, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(f / 64) }, programUniforms: b }), getShaderSource: _ }; + }, qu = (e, t, r, n) => { + let o = e.length > 2, i = ce(r[3]), a = ce(r[2]), u = k.size(r) / i / a, d = [e[0].dims[0], e[0].dims[1], e[0].dims[2], e[0].dims[3] / i], c = [e[1].dims[0], e[1].dims[1], e[1].dims[2], e[1].dims[3] / i], p = [r[0], r[1], r[2], r[3] / i], m = [{ type: 12, data: u }, { type: 6, data: [t.strides[0], t.strides[1]] }, { type: 6, data: [t.pads[0], t.pads[1]] }]; + qe(t, m), m.push(...N(d, c, p)); + let f = (a - 1) * t.strides[1] + c[1], b = (g) => { + let _ = M("output", e[0].dataType, p.length, i), S = be(_.type.tensor), $ = Fe(t, _.type.value, S), v = P("x", e[0].dataType, d.length, i), x = P("w", e[1].dataType, c.length, i), T = [v, x]; + o && T.push(P("b", e[2].dataType, e[2].dims, i)); + let E = o ? "value += b[output_channel];" : "", I = [{ name: "output_size", type: "u32" }, { name: "strides", type: "i32", length: 2 }, { name: "pads", type: "i32", length: 2 }]; + return je(t, I), ` + ${g.registerUniforms(I).declareVariables(...T, _)} + ${g.mainStart()} + ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let width0 = uniforms.output_shape[3]; + let output_channel = global_idx % width0; + var index1 = global_idx / width0; + let width1 = uniforms.output_shape[2] / ${a}u; + let col = (index1 % width1) * ${a}u; + index1 = index1 / width1; + let row = index1 % uniforms.output_shape[1]; + let batch = index1 / uniforms.output_shape[1]; + + let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; + + var x_vals: array<${v.type.value}, ${f}>; + var values: array<${_.type.value}, ${a}>; + let input_channel = output_channel; + // Use constant instead of uniform can give better performance for w's height/width. + for (var w_height: u32 = 0u; w_height < ${c[0]}; w_height++) { + let x_height = x_corner.x + i32(w_height); + if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { + for (var i = 0; i < ${f}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${v.get("batch", "u32(x_height)", "u32(x_width)", "input_channel")}; + } else { + x_vals[i] = ${v.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${c[1]}; w_width++) { + let w_val = ${x.get("w_height", "w_width", "0", "output_channel")}; + for (var i = 0u; i < ${a}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${a}u; i++) { + var value = values[i]; + ${E} + ${$} + ${_.set("batch", "row", "col + i", "output_channel", "value")}; + } + }`; + }; + return { name: "GroupedConv-Vectorize", shaderCache: { hint: `${t.cacheKey};${i};${a};${f};${c[0]};${c[1]}`, inputDependencies: o ? ["rank", "rank", "type"] : ["rank", "rank"] }, getRunData: () => ({ outputs: [{ dims: n ? n(r) : r, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(u / 64) }, programUniforms: m }), getShaderSource: b }; + }; + }); + var gf; + var ho; + var bf; + var go; + var bo; + var Ku; + var yf; + var _f; + var yo; + var Zu = U(() => { + "use strict"; + ne(); + Nu(); + Hu(); + Xr(); + ju(); + bt(); + Yr(); + st(); + gf = (e, t, r, n, o, i) => { + let a = e[0], u = e.slice(i ? 1 : 2, i ? 3 : 4), d = u.length, c = t[0], m = t.slice(2).map((g, _) => g + (g - 1) * (r[_] - 1)), b = u.map((g, _) => g + n[_] + n[_ + d]).map((g, _) => Math.floor((g - m[_] + o[_]) / o[_])); + return b.splice(0, 0, a), b.splice(i ? 3 : 1, 0, c), b; + }, ho = [2, 3, 1, 0], bf = (e, t) => { + if (!e || e.length !== 2 && e.length !== 3) throw new Error("Conv requires 2 or 3 inputs"); + if (e[0].dims.length > 5) throw new Error("greater than 5D is not supported"); + if (e[0].dims.length !== e[1].dims.length) throw new Error("filter does not have same dimension as input"); + let r = e[0].dims[t.format === "NHWC" ? e[0].dims.length - 1 : 1], n = e[1].dims[1] * t.group; + if (r !== n) throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL"); + if (e.length === 3 && (e[2].dims.length !== 1 || e[1].dims[0] !== e[2].dims[0])) throw new Error("invalid bias"); + let o = e[0].dims.length - 2; + if (t.dilations.length !== o) throw new Error(`dilations should be ${o}D`); + if (t.strides.length !== o) throw new Error(`strides should be ${o}D`); + if (t.pads.length !== o * 2) throw new Error(`pads should be ${o * 2}D`); + if (t.kernelShape.length !== 0 && t.kernelShape.length !== e[1].dims.length - 2) throw new Error("invalid kernel shape"); + }, go = (e, t) => { + let r = e.kernelShape.slice(); + r.length < t[1].dims.length - 2 && r.push(...Array(t[1].dims.length - 2 - r.length).fill(0)); + for (let i = 2; i < t[1].dims.length; ++i) r[i - 2] === 0 && (r[i - 2] = t[1].dims[i]); + let n = e.pads.slice(); + Tt.adjustPadsBasedOnAutoPad(t[0].dims, e.strides, e.dilations, r, n, e.format === "NHWC", e.autoPad); + let o = Object.assign({}, e); + return Object.assign(o, { kernelShape: r, pads: n }), o; + }, bo = (e) => { + let t = Kr(e), r = e.format, n = ["NOTSET", "VALID", "SAME_UPPER", "SAME_LOWER"][e.auto_pad], o = e.dilations, i = e.group, a = e.kernel_shape, u = e.pads, d = e.strides, c = e.w_is_const(); + return { autoPad: n, format: r, dilations: o, group: i, kernelShape: a, pads: u, strides: d, wIsConst: c, ...t, cacheKey: `${e.format};${t.activation};` }; + }, Ku = (e, t, r, n) => { + let o = r.format === "NHWC", i = gf(t[0].dims, t[1].dims, r.dilations, r.pads, r.strides, o); + if (r.group !== 1) { + let I = [t[0]]; + if (o) { + let O = e.kernelCustomData.wT ?? e.compute(Ee(t[1], ho), { inputs: [1], outputs: [r.wIsConst ? -2 : -1] })[0]; + r.wIsConst && !e.kernelCustomData.wT && (e.kernelCustomData.wT = O), I.push(O); + } else I.push(t[1]); + t.length === 3 && I.push(t[2]), !e.adapterInfo.isArchitecture("ampere") && o && t[1].dims[0] === r.group && t[1].dims[1] === 1 && r.dilations[0] === 1 && r.dilations[1] === 1 ? e.compute(qu(I, r, i, n), { inputs: I }) : e.compute(Fu(I, r, i, n), { inputs: I }); + return; + } + let a = t.length === 3, u = t[0].dims[o ? 1 : 2], d = t[0].dims[o ? 2 : 3], c = t[0].dims[o ? 3 : 1], p = t[1].dims[2], m = t[1].dims[3], f = i[o ? 1 : 2], b = i[o ? 2 : 3], g = i[o ? 3 : 1], _ = o && p === u && m === d && r.pads[0] === 0 && r.pads[1] === 0; + if (_ || p === 1 && m === 1 && r.dilations[0] === 1 && r.dilations[1] === 1 && r.strides[0] === 1 && r.strides[1] === 1 && r.pads[0] === 0 && r.pads[1] === 0) { + let I = i[0], z, O, D, L = []; + if (o) { + let W = e.kernelCustomData.wT ?? e.compute(Ee(t[1], ho), { inputs: [1], outputs: [r.wIsConst ? -2 : -1] })[0]; + if (r.wIsConst && !e.kernelCustomData.wT && (e.kernelCustomData.wT = W), _) { + let Z = u * d * c; + z = t[0].reshape([1, I, Z]), O = W.reshape([1, Z, g]), D = [1, I, g]; + } else z = t[0].reshape([I, u * d, c]), O = W.reshape([1, c, g]), D = [I, f * b, g]; + L.push(z), L.push(O); + } else z = t[0].reshape([I, c, u * d]), O = t[1].reshape([1, g, c]), D = [I, g, f * b], L.push(O), L.push(z); + a && L.push(t[2]); + let q = D[2], Q = L[0].dims[L[0].dims.length - 1]; + q < 8 && Q < 8 ? e.compute(Qr(L, r, i, D, o, n), { inputs: L }) : e.compute(Jt(L, r, i, D, o, n), { inputs: L }); + return; + } + let S = true, $ = e.kernelCustomData.wT ?? e.compute(Ee(t[1], ho), { inputs: [1], outputs: [r.wIsConst ? -2 : -1] })[0]; + r.wIsConst && !e.kernelCustomData.wT && (e.kernelCustomData.wT = $); + let v = [t[0], $]; + a && v.push(t[2]); + let x = o ? f * b : g, T = o ? g : f * b, E = p * m * c; + e.compute(Uu(v, r, i, x, T, E, a, S, n), { inputs: v }); + }, yf = (e, t) => { + let r = t.format === "NHWC", n = [e.inputs[0].reshape(r ? [e.inputs[0].dims[0], 1, e.inputs[0].dims[1], e.inputs[0].dims[2]] : [e.inputs[0].dims[0], e.inputs[0].dims[1], 1, e.inputs[0].dims[2]]), e.inputs[1].reshape([e.inputs[1].dims[0], e.inputs[1].dims[1], 1, e.inputs[1].dims[2]])]; + e.inputs.length === 3 && n.push(e.inputs[2]); + let o = [0, t.pads[0], 0, t.pads[1]], i = [1].concat(t.strides), a = [1].concat(t.dilations), u = [1].concat(t.kernelShape), d = go({ ...t, pads: o, strides: i, dilations: a, kernelShape: u }, n); + Ku(e, n, d, (c) => r ? [c[0], c[2], c[3]] : [c[0], c[1], c[3]]); + }, _f = (e, t, r) => { + let n = r.format === "NHWC" ? "channelsLast" : "channelsFirst", o = go(r, t), i = r.autoPad === "NOTSET" ? r.pads : r.autoPad, a = Lu(t[0].dims, t[1].dims, r.strides, r.dilations, i, false, n); + e.compute(Gu(t, o, a.outShape, [a.filterDepth, a.filterHeight, a.filterWidth], [a.padInfo.front, a.padInfo.top, a.padInfo.left], n)); + }, yo = (e, t) => { + if (bf(e.inputs, t), e.inputs[0].dims.length === 3) yf(e, t); + else if (e.inputs[0].dims.length === 5) _f(e, e.inputs, t); + else { + let r = go(t, e.inputs); + Ku(e, e.inputs, r); + } + }; + }); + var Qu; + var Yu = U(() => { + "use strict"; + ee(); + Xe(); + ne(); + ie(); + Qu = (e, t, r) => { + let n = e.length > 2, o = t.outputShape, i = t.format === "NHWC", a = t.group, u = e[1].dims, d = u[2] / a, c = u[3], p = i ? ce(d) : 1, m = i && c === 1 && d >= 4, f = m ? Math.floor(d / 4) * 4 : Math.floor(d / p) * p, b = d - f, g = i ? ce(c) : 1, _ = i ? c === 1 ? p : g : 1, S = k.size(o) / g, $ = [Math.ceil(S / 64), 1, 1]; + se("verbose", () => `[conv2d_backprop_webgpu] dispatch = ${$}`); + let v = ["rank", "rank"], x = [t.strides[0], t.strides[1]], T = [t.kernelShape[i ? 1 : 2], t.kernelShape[i ? 2 : 3]], E = [t.dilations[0], t.dilations[1]], I = [T[0] + (t.dilations[0] <= 1 ? 0 : (t.kernelShape[i ? 1 : 2] - 1) * (t.dilations[0] - 1)), T[1] + (t.dilations[1] <= 1 ? 0 : (t.kernelShape[i ? 2 : 3] - 1) * (t.dilations[1] - 1))], z = [I[0] - 1 - Math.floor((t.pads[0] + t.pads[2]) / 2), I[1] - 1 - Math.floor((t.pads[1] + t.pads[3]) / 2)], O = [{ type: 12, data: S }, { type: 12, data: x }, { type: 12, data: T }, { type: 12, data: E }, { type: 12, data: I }, { type: 6, data: z }, { type: 12, data: f }, { type: 12, data: d }, { type: 12, data: c }, ...N(e[0].dims, e[1].dims)]; + n && (O.push(...N(e[2].dims)), v.push("rank")), O.push(...N(o)); + let D = (L) => { + let q = [{ name: "output_size", type: "u32" }, { name: "strides", type: "u32", length: x.length }, { name: "filter_dims", type: "u32", length: T.length }, { name: "dilations", type: "u32", length: T.length }, { name: "effective_filter_dims", type: "u32", length: I.length }, { name: "pads", type: "i32", length: z.length }, { name: "input_channels_per_group_int", type: "u32" }, { name: "input_channels_per_group", type: "u32" }, { name: "output_channels_per_group", type: "u32" }], Q = be(e[0].dataType), W = i ? 1 : 2, Z = i ? 2 : 3, we = i ? 3 : 1, H = P("W", e[1].dataType, e[1].dims.length, _), j = P("Dy", e[0].dataType, e[0].dims.length, p), te = [j, H]; + n && te.push(P("bias", e[2].dataType, [o[we]].length, g)); + let X = M("result", e[0].dataType, o.length, g), ue = () => { + let re = ""; + if (m) p === 4 ? re += ` + let xValue = ${j.getByOffset("x_offset")}; + let wValue = ${H.getByOffset("w_offset")}; + dotProd = dotProd + dot(xValue, wValue); + x_offset += 1u; + w_offset += 1u;` : p === 2 ? re += ` + dotProd = dotProd + dot(vec4<${Q}>(${j.getByOffset("x_offset")}, ${j.getByOffset("x_offset + 1u")}), vec4<${Q}>(${H.getByOffset("w_offset")}, ${H.getByOffset("w_offset + 1u")})); + x_offset += 2u; + w_offset += 2u;` : p === 1 && (re += ` + dotProd = dotProd + dot(vec4<${Q}>(${j.getByOffset("x_offset")}, ${j.getByOffset("x_offset + 1u")}, ${j.getByOffset("x_offset + 2u")}, ${j.getByOffset("x_offset + 3u")}), vec4<${Q}>(${H.getByOffset("w_offset")}, ${H.getByOffset("w_offset + 1u")}, ${H.getByOffset("w_offset + 2u")}, ${H.getByOffset("w_offset + 3u")})); + x_offset += 4u; + w_offset += 4u;`); + else if (re += ` + let xValue = ${i ? j.getByOffset(`${j.indicesToOffset(`${j.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}`) : j.get("batch", "inputChannel", "idyR", "idyC")}; + `, p === 1) re += ` + let w_offset = ${H.indicesToOffset(`${H.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; + let wValue = ${H.getByOffset(`w_offset / ${_}`)}; + dotProd = dotProd + xValue * wValue;`; + else for (let C = 0; C < p; C++) re += ` + let wValue${C} = ${H.getByOffset(`${H.indicesToOffset(`${H.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel + ${C}, wOutChannel)`)} / ${_}`)}; + dotProd = dotProd + xValue[${C}] * wValue${C};`; + return re; + }, he = () => { + if (b === 0) return ""; + if (!m) throw new Error(`packInputAs4 ${m} is not true.`); + let re = ""; + if (p === 1) { + re += "dotProd = dotProd"; + for (let C = 0; C < b; C++) re += ` + + ${j.getByOffset(`x_offset + ${C}`)} * ${H.getByOffset(`w_offset + ${C}`)}`; + re += ";"; + } else if (p === 2) { + if (b !== 2) throw new Error(`Invalid inputChannelsRemainder ${b}.`); + re += ` + let xValue = ${j.getByOffset("x_offset")}; + let wValue = ${H.getByOffset("w_offset")}; + dotProd = dotProd + dot(xValue, wValue);`; + } + return re; + }, ye = ` + let outputIndices = ${X.offsetToIndices(`global_idx * ${g}`)}; + let batch = ${X.indicesGet("outputIndices", 0)}; + let d1 = ${X.indicesGet("outputIndices", we)}; + let r = ${X.indicesGet("outputIndices", W)}; + let c = ${X.indicesGet("outputIndices", Z)}; + let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads; + let dyRCorner = dyCorner.x; + let dyCCorner = dyCorner.y; + let groupId = d1 / uniforms.output_channels_per_group; + let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + var dotProd = ${X.type.value}(0.0); + var wR: u32 = 0; + if (uniforms.dilations.x == 1) { + // Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0 + wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner); + } + for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { + if (wR % uniforms.dilations.x != 0) { + continue; + } + let dyR = (${Q}(dyRCorner) + ${Q}(wR)) / ${Q}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${Q}(uniforms.Dy_shape[${W}]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + var wC: u32 = 0; + if (uniforms.dilations.y == 1) { + // Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0 + wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner); + } + for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { + if (wC % uniforms.dilations.y != 0) { + continue; + } + let dyC = (${Q}(dyCCorner) + ${Q}(wC)) / ${Q}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${Q}(uniforms.Dy_shape[${Z}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC: u32 = u32(dyC); + var inputChannel = groupId * uniforms.input_channels_per_group; + ${m ? ` + var x_offset = ${j.indicesToOffset(`${j.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}; + var w_offset = ${H.indicesToOffset(`${H.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${_}; + ` : ""} + for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${m ? 4 : p}) { + ${ue()} + inputChannel = inputChannel + ${m ? 4 : p}; + } + ${he()} + wC = wC + uniforms.strides.y - 1; + } + wR = wR + uniforms.strides[0] - 1; + } + let value = dotProd${n ? ` + bias[d1 / ${g}]` : ""}; + ${X.setByOffset("global_idx", "value")}; + `; + return ` + ${L.registerUniforms(q).declareVariables(...te, X)} + ${L.mainStart()} + ${L.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${ye}}`; + }; + return { name: "ConvTranspose2D", shaderCache: { hint: `${t.cacheKey};${p}${_}${g}${m}${b}`, inputDependencies: v }, getRunData: () => ({ dispatchGroup: { x: $[0], y: $[1], z: $[2] }, outputs: [{ dims: r ? r(o) : o, dataType: e[0].dataType }], programUniforms: O }), getShaderSource: D }; + }; + }); + var wf; + var vf; + var $f; + var Xu; + var Ju; + var xf; + var ed; + var Sf; + var td; + var rd = U(() => { + "use strict"; + Yu(); + bt(); + st(); + wf = (e, t, r, n, o, i) => (e - 1) * t + r + (n - 1) * o + 1 - i, vf = (e, t, r, n, o) => { + let i = Math.floor(e / 2); + t === "SAME_UPPER" ? (r[n] = i, r[o] = e - i) : t === "SAME_LOWER" && (r[n] = e - i, r[o] = i); + }, $f = (e, t, r, n, o, i, a, u, d, c) => { + let p = e.length - 2, m = c.length === 0; + d.length < p && d.push(...Array(p - d.length).fill(0)); + let f = e[0], b = t[u ? 3 : 1] * o; + for (let g = 0, _ = e.length - p - (u ? 1 : 0); g < p; ++g, ++_) { + let S = e[_], $ = m ? S * a[g] : c[g], v = wf(S, a[g], i[g], t[_], r[g], $); + vf(v, n, i, g, g + p), m && c.push(a[g] * (S - 1) + d[g] + (t[_] - 1) * r[g] + 1 - i[g] - i[g + p]); + } + c.splice(0, 0, f), c.splice(u ? 3 : 1, 0, b); + }, Xu = (e, t) => { + let r = e.kernelShape.slice(); + if (e.kernelShape.length === 0 || e.kernelShape.reduce((m, f) => m * f, 1) === 0) { + r.length = 0; + for (let m = 2; m < t[1].dims.length; ++m) r.push(t[1].dims[m]); + } + let n = e.format === "NHWC"; + r.splice(0, 0, t[1].dims[0]), r.splice(n ? 3 : 1, 0, t[1].dims[1]); + let o = e.pads.slice(), i = e.outputShape.slice(), a = e.outputPadding.slice(), u = t[0].dims, d = e.dilations.slice(); + if (d.reduce((m, f) => m + f, 0) === 0) { + let m = t[0].dims.length - 2; + d = new Array(m).fill(1); + } + let c = e.strides.slice(); + if (c.reduce((m, f) => m + f, 0) === 0) { + let m = t[0].dims.length - 2; + c = new Array(m).fill(1); + } + $f(u, r, d, e.autoPad, e.group, o, c, n, a, i); + let p = Object.assign({}, e); + return Object.assign(p, { kernelShape: r, pads: o, outputPadding: a, outputShape: i, dilations: d, strides: c }), p; + }, Ju = (e) => { + let t = Kr(e), r = e.format, n = ["NOTSET", "VALID", "SAME_UPPER", "SAME_LOWER"][typeof e.autoPad > "u" ? 0 : e.autoPad], o = e.dilations, i = e.group, a = e.kernelShape, u = e.pads, d = e.strides, c = e.wIsConst(), p = e.outputPadding, m = e.outputShape; + return { autoPad: n, format: r, dilations: o, group: i, kernelShape: a, outputPadding: p, outputShape: m, pads: u, strides: d, wIsConst: c, ...t, cacheKey: `${e.format};${t.activation};` }; + }, xf = (e, t) => { + if (!e || e.length !== 2 && e.length !== 3) throw new Error("Conv requires 2 or 3 inputs"); + if (e[0].dims.length !== 4 && e[0].dims.length !== 3) throw new Error("currently only support 2-dimensional conv"); + if (e[0].dims.length !== e[1].dims.length) throw new Error("filter does not have same dimension as input"); + let r = e[0].dims[t.format === "NHWC" ? e[0].dims.length - 1 : 1], n = e[1].dims[0]; + if (r !== n) throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL"); + let o = e[1].dims[1] * t.group; + if (e.length === 3 && (e[2].dims.length !== 1 || e[2].dims[0] !== o)) throw new Error("invalid bias"); + let i = e[0].dims.length - 2; + if (t.dilations.reduce((p, m) => p + m, 0) > 0 && t.dilations.length !== i) throw new Error(`dilations should be ${i}D`); + if (t.strides.reduce((p, m) => p + m, 0) > 0 && t.strides.length !== i) throw new Error(`strides should be ${i}D`); + if (t.pads.reduce((p, m) => p + m, 0) > 0 && t.pads.length !== i * 2) throw new Error(`pads should be ${i * 2}D`); + if (t.outputPadding.length !== i && t.outputPadding.length !== 0) throw new Error(`output_padding should be ${i}D`); + if (t.kernelShape.reduce((p, m) => p + m, 0) > 0 && t.kernelShape.length !== 0 && t.kernelShape.length !== e[1].dims.length - 2) throw new Error("invalid kernel shape"); + if (t.outputShape.length !== 0 && t.outputShape.length !== e[0].dims.length - 2) throw new Error("invalid output shape"); + }, ed = (e, t, r, n) => { + let o = e.kernelCustomData.wT ?? e.compute(Ee(t[1], [2, 3, 0, 1]), { inputs: [1], outputs: [r.wIsConst ? -2 : -1] })[0]; + r.wIsConst && !e.kernelCustomData.wT && (e.kernelCustomData.wT = o); + let i = [t[0], o]; + t.length === 3 && i.push(t[2]), e.compute(Qu(i, r, n), { inputs: i }); + }, Sf = (e, t) => { + let r = t.format === "NHWC", n = [e.inputs[0].reshape(r ? [e.inputs[0].dims[0], 1, e.inputs[0].dims[1], e.inputs[0].dims[2]] : [e.inputs[0].dims[0], e.inputs[0].dims[1], 1, e.inputs[0].dims[2]]), e.inputs[1].reshape([e.inputs[1].dims[0], e.inputs[1].dims[1], 1, e.inputs[1].dims[2]])]; + e.inputs.length === 3 && n.push(e.inputs[2]); + let o = t.kernelShape; + (o.length === 0 || o[0] === 0) && (o = [e.inputs[1].dims[2]]); + let i = t.dilations; + (i.length === 0 || i[0] === 0) && (i = [1]); + let a = t.strides; + (a.length === 0 || a[0] === 0) && (a = [1]); + let u = t.pads; + u.length === 0 && (u = [0, 0]), u = [0, u[0], 0, u[1]], a = [1].concat(a), i = [1].concat(i), o = [1].concat(o); + let d = t.outputPadding; + d = [0].concat(d); + let c = Xu({ ...t, pads: u, strides: a, dilations: i, kernelShape: o, outputPadding: d }, n); + ed(e, n, c, (p) => r ? [p[0], p[2], p[3]] : [p[0], p[1], p[3]]); + }, td = (e, t) => { + if (xf(e.inputs, t), e.inputs[0].dims.length === 3) Sf(e, t); + else { + let r = Xu(t, e.inputs); + ed(e, e.inputs, r); + } + }; + }); + var Tf; + var nd; + var od; + var id = U(() => { + "use strict"; + ee(); + ne(); + Se(); + ie(); + Tf = (e, t, r, n) => { + let o = k.size(t), i = t.length, a = P("input", e, i), u = M("output", e, i), d = r.dataType === 6 ? r.getInt32Array()[0] : Number(r.getBigInt64Array()[0]), c = k.normalizeAxis(d, i), p = (m) => { + let f = ` i32(${a.indicesGet("inputIndices", "uniforms.axis")}) `, b = F("uniforms.input_shape", "uniforms.axis", i), g = n.reverse ? f + (n.exclusive ? " + 1" : "") : "0", _ = n.reverse ? b : f + (n.exclusive ? "" : " + 1"); + return ` + ${m.registerUniform("outputSize", "u32").registerUniform("axis", "u32").declareVariables(a, u)} + ${m.mainStart()} + ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${u.offsetToIndices("global_idx")}; + var sum = ${u.type.value}(0); + let first : i32 = ${g}; + let last : i32 = ${_}; + for (var i : i32 = first; i < last; i++) { + ${a.indicesSet("inputIndices", "uniforms.axis", "u32(i)")}; + sum = sum + ${a.getByIndices("inputIndices")}; + } + ${u.setByOffset("global_idx", "sum")}; + }`; + }; + return { name: "CumSum", shaderCache: { hint: n.cacheKey, inputDependencies: ["rank"] }, getRunData: () => ({ outputs: [{ dims: t, dataType: e }], dispatchGroup: { x: Math.ceil(o / 64) }, programUniforms: [{ type: 12, data: o }, { type: 12, data: c }, ...N(t, t)] }), getShaderSource: p }; + }, nd = (e, t) => { + let r = e.inputs[0].dims, n = e.inputs[0].dataType, o = e.inputs[1]; + e.compute(Tf(n, r, o, t), { inputs: [0] }); + }, od = (e) => { + let t = e.exclusive === 1, r = e.reverse === 1; + return J({ exclusive: t, reverse: r }); + }; + }); + var If; + var Cf; + var Af; + var ad; + var sd; + var ud = U(() => { + "use strict"; + ee(); + ne(); + Se(); + ie(); + If = (e) => { + if (!e || e.length !== 1) throw new Error("DepthToSpace requires 1 input."); + if (e[0].dims.length !== 4) throw new Error("DepthToSpace requires 4D input."); + }, Cf = (e, t, r, n) => { + let o = []; + o.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { + var a: ${r.type.indices};`); + for (let i = 0; i < t; ++i) o.push(r.indicesSet("a", e[i], `i[${i}]`)); + return o.push("return a;}"), o.join(` +`); + }, Af = (e, t) => { + let r, n, o, i, a, u, d = t.format === "NHWC", c = t.blocksize, p = t.mode === "DCR"; + d ? ([r, n, o, i] = e.dims, a = p ? [r, n, o, c, c, i / c ** 2] : [r, n, o, i / c ** 2, c, c], u = p ? [0, 1, 3, 2, 4, 5] : [0, 1, 4, 2, 5, 3]) : ([r, n, o, i] = [e.dims[0], e.dims[2], e.dims[3], e.dims[1]], a = p ? [r, c, c, i / c ** 2, n, o] : [r, i / c ** 2, c, c, n, o], u = p ? [0, 3, 4, 1, 5, 2] : [0, 1, 4, 2, 5, 3]); + let m = e.reshape(a), f = m.dims.length, b = e.dataType, g = P("a", b, f), _ = M("output", b, f), S = ($) => ` + ${$.registerUniform("output_size", "u32").declareVariables(g, _)} + + ${Cf(u, f, g, _)} + + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${_.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${_.setByOffset("global_idx", g.getByIndices("aIndices"))} + }`; + return { name: "DepthToSpace", shaderCache: { hint: `${e.dims};${t.blocksize};${t.mode}`, inputDependencies: ["rank"] }, getRunData: ($) => { + let v = d ? [r, n * c, o * c, i / c ** 2] : [r, i / c ** 2, n * c, o * c], x = k.size(v), T = m.dims, E = k.sortBasedOnPerm(T, u); + return { outputs: [{ dims: v, dataType: $[0].dataType }], dispatchGroup: { x: Math.ceil(x / 64) }, programUniforms: [{ type: 12, data: x }, ...N(T, E)] }; + }, getShaderSource: S }; + }, ad = (e, t) => { + If(e.inputs), e.compute(Af(e.inputs[0], t)); + }, sd = (e) => J({ blocksize: e.blocksize, mode: e.mode, format: e.format }); + }); + var _o; + var en; + var dd; + var Ef; + var kf; + var wo; + var vo; + var ld; + var Pf; + var cd; + var pd; + var md = U(() => { + "use strict"; + ee(); + ne(); + Se(); + ie(); + _o = "[a-zA-Z]|\\.\\.\\.", en = "(" + _o + ")+", dd = "^" + en + "$", Ef = "(" + en + ",)*" + en, kf = "^" + Ef + "$", wo = class { + constructor(t = -1) { + this.symbolToIndices = /* @__PURE__ */ new Map(), this.inputIndex = t; + } + addSymbol(t, r) { + let n = this.symbolToIndices.get(t); + n === void 0 ? n = [r] : n.push(r), this.symbolToIndices.set(t, n); + } + }, vo = class { + constructor(t, r) { + this.equation = r; + this.hasEllipsis = false, this.symbolToInfo = /* @__PURE__ */ new Map(), this.lhs = new Array(), this.outputDims = []; + let [n, o] = r.includes("->") ? r.split("->", 2) : [r, ""]; + if (!n.match(RegExp(kf))) throw new Error("Invalid LHS term"); + if (n.split(",").forEach((u, d) => { + let c = t[d].dims.slice(); + if (!u.match(RegExp(dd))) throw new Error("Invalid LHS term"); + let p = this.processTerm(u, true, c, d); + this.lhs.push(p); + }), o === "") o += [...this.symbolToInfo.entries()].filter(([u, d]) => d.count === 1 || u === "...").map(([u]) => u).join(""); + else if (!o.match(RegExp(en))) throw new Error("Invalid RHS"); + o.match(RegExp(_o, "g"))?.forEach((u) => { + if (u === "...") this.outputDims = this.outputDims.concat(this.ellipsisDims); + else { + let d = this.symbolToInfo.get(u); + if (d === void 0) throw new Error("Invalid RHS symbol"); + this.outputDims.push(d.dimValue); + } + }), this.rhs = this.processTerm(o, false, this.outputDims); + } + addSymbol(t, r, n) { + let o = this.symbolToInfo.get(t); + if (o !== void 0) { + if (o.dimValue !== r && o.count !== 1) throw new Error("Dimension mismatch"); + o.count++, o.inputIndices.push(n); + } else o = { count: 1, dimValue: r, inputIndices: [n] }; + this.symbolToInfo.set(t, o); + } + processTerm(t, r, n, o = -1) { + let i = n.length, a = false, u = [], d = 0; + if (!t.match(RegExp(dd)) && !r && t !== "") throw new Error("Invalid LHS term"); + let c = t.match(RegExp(_o, "g")), p = new wo(o); + return c?.forEach((m, f) => { + if (m === "...") { + if (a) throw new Error("Only one ellipsis is allowed per input term"); + a = true; + let b = i - c.length + 1; + if (b < 0) throw new Error("Ellipsis out of bounds"); + if (u = n.slice(d, d + b), this.hasEllipsis) { + if (this.ellipsisDims.length !== u.length || this.ellipsisDims.toString() !== u.toString()) throw new Error("Ellipsis dimensions mismatch"); + } else if (r) this.hasEllipsis = true, this.ellipsisDims = u; + else throw new Error("Ellipsis must be specified in the LHS"); + for (let g = 0; g < u.length; g++) { + let _ = String.fromCharCode(48 + g); + p.addSymbol(_, f + g), this.addSymbol(_, n[d++], o); + } + } else p.addSymbol(m, f + (this.hasEllipsis ? this.ellipsisDims.length - 1 : 0)), this.addSymbol(m, n[d++], o); + }), p; + } + }, ld = (e) => e + "_max", Pf = (e, t, r, n) => { + let i = e.map((p) => p.length).map((p, m) => P(`input${m}`, t, p)), a = k.size(n), u = M("output", t, n.length), d = [...r.symbolToInfo.keys()].filter((p) => !r.rhs.symbolToIndices.has(p)), c = (p) => { + let m = [], f = "var prod = 1.0;", b = "var sum = 0.0;", g = "sum += prod;", _ = [], S = [], $ = [], v = [], x = r.symbolToInfo.size === r.rhs.symbolToIndices.size; + r.symbolToInfo.forEach((E, I) => { + if (r.rhs.symbolToIndices.has(I)) { + let z = r.rhs.symbolToIndices.get(I)?.[0]; + z !== void 0 && r.lhs.forEach((O, D) => { + if (E.inputIndices.includes(D)) { + let L = O.symbolToIndices.get(I); + if (L === void 0) throw new Error("Invalid symbol error"); + L.forEach((q) => { + m.push(`${i[D].indicesSet(`input${D}Indices`, q, u.indicesGet("outputIndices", z))}`); + }); + } + }); + } else r.lhs.forEach((z, O) => { + if (E.inputIndices.includes(O)) { + let D = z.symbolToIndices.get(I); + if (D === void 0) throw new Error("Invalid symbol error"); + D.forEach((L) => { + _.push(`${i[O].indicesSet(`input${O}Indices`, L, `${I}`)}`); + }), v.push(`prod *= ${i[O].getByIndices(`input${O}Indices`)};`); + } + }), S.push(`for(var ${I}: u32 = 0; ${I} < uniforms.${ld(I)}; ${I}++) {`), $.push("}"); + }); + let T = x ? [...m, `let sum = ${i.map((E, I) => E.getByIndices(`input${I}Indices`)).join(" * ")};`] : [...m, b, ...S, ..._, f, ...v, g, ...$]; + return ` + ${p.registerUniforms(d.map((E) => ({ name: `${ld(E)}`, type: "u32" }))).registerUniform("outputSize", "u32").declareVariables(...i, u)} + + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${u.offsetToIndices("global_idx")}; + ${i.map((E, I) => `var input${I}Indices: ${i[I].type.indices};`).join(` +`)} + ${T.join(` +`)}; + ${u.setByOffset("global_idx", "sum")}; + }`; + }; + return { name: "Einsum", shaderCache: { hint: r.equation, inputDependencies: e.map(() => "rank") }, getRunData: () => { + let p = d.filter((f) => r.symbolToInfo.has(f)).map((f) => ({ type: 12, data: r.symbolToInfo.get(f)?.dimValue || 0 })); + p.push({ type: 12, data: a }); + let m = e.map((f, b) => [...N(f)]).reduce((f, b) => f.concat(b), p); + return m.push(...N(n)), { outputs: [{ dims: n, dataType: t }], dispatchGroup: { x: Math.ceil(a / 64) }, programUniforms: m }; + }, getShaderSource: c }; + }, cd = (e, t) => { + let r = new vo(e.inputs, t.equation), n = r.outputDims, o = e.inputs.map((i, a) => i.dims); + e.compute(Pf(o, e.inputs[0].dataType, r, n)); + }, pd = (e) => { + let t = e.equation.replace(/\s+/g, ""); + return J({ equation: t }); + }; + }); + var zf; + var fd; + var Of; + var Bf; + var hd; + var gd = U(() => { + "use strict"; + ee(); + ne(); + ie(); + zf = (e) => { + if (!e || e.length !== 2) throw new Error("Expand requires 2 input."); + let t = e[0].dims, r = Array.from(e[1].getBigInt64Array(), Number), n = r.length < t.length ? 0 : r.length - t.length, o = t.length < r.length ? 0 : t.length - r.length; + for (; n < r.length && o < t.length; ++n, ++o) if (r[n] !== t[o] && r[n] !== 1 && t[o] !== 1) throw new Error("Expand requires shape to be broadcastable to input"); + }, fd = (e, t) => { + let r = e.length - t.length, n = []; + for (let o = 0; o < r; ++o) n.push(e[o]); + for (let o = 0; o < t.length; ++o) n.push(t[o] === 1 ? e[o + r] : t[o]); + return n; + }, Of = (e, t) => e.length > t.length ? fd(e, t) : fd(t, e), Bf = (e) => { + let t = e[0].dims, r = Array.from(e[1].getBigInt64Array(), Number), n = Of(t, r), o = e[0].dataType, i = o === 9 || k.size(t) === 1, a = o === 9 || t.length > 0 && t[t.length - 1] % 4 === 0 ? 4 : 1, u = i || n.length > 0 && n[n.length - 1] % 4 === 0 ? 4 : 1, d = Math.ceil(k.size(n) / u), c = (m) => { + let f = P("input", o, t.length, a), b = M("output", o, n.length, u), g; + if (o === 9) { + let _ = (S, $, v = "") => ` + let outputIndices${$} = ${b.offsetToIndices(`outputOffset + ${$}u`)}; + let offset${$} = ${f.broadcastedIndicesToOffset(`outputIndices${$}`, b)}; + let index${$} = offset${$} / 4u; + let component${$} = offset${$} % 4u; + ${S}[${$}] = ${v}(${f.getByOffset(`index${$}`)}[component${$}]); + `; + g = ` + let outputOffset = global_idx * ${u}; + var data = vec4(0); + ${_("data", 0, "u32")} + ${_("data", 1, "u32")} + ${_("data", 2, "u32")} + ${_("data", 3, "u32")} + ${b.setByOffset("global_idx", "data")} + }`; + } else g = ` + let outputIndices = ${b.offsetToIndices(`global_idx * ${u}`)}; + let inputOffset = ${f.broadcastedIndicesToOffset("outputIndices", b)}; + let data = ${b.type.value}(${f.getByOffset(`inputOffset / ${a}`)}); + ${b.setByOffset("global_idx", "data")} + }`; + return ` + ${m.registerUniform("vec_size", "u32").declareVariables(f, b)} + ${m.mainStart()} + ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${g}`; + }, p = [{ type: 12, data: d }, ...N(t, n)]; + return { name: "Expand", shaderCache: { hint: `${n.length};${a}${u}`, inputDependencies: ["rank"] }, getShaderSource: c, getRunData: () => ({ outputs: [{ dims: n, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(d / 64) }, programUniforms: p }) }; + }, hd = (e) => { + zf(e.inputs), e.compute(Bf(e.inputs), { inputs: [0] }); + }; + }); + var Df; + var bd; + var yd = U(() => { + "use strict"; + ee(); + ne(); + ie(); + jr(); + Df = (e) => { + let t = e[0].dataType, r = k.size(e[0].dims), n = k.size(e[1].dims), o = n % 4 === 0, i = (a) => { + let u = P("x", t, [1], 4), d = P("bias", t, [1], 4), c = M("y", t, [1], 4), p = [{ name: "output_vec_size", type: "u32" }, { name: "bias_size", type: "u32" }], m = (b) => ` + let bias${b}_offset: u32 = (global_idx * 4 + ${b}) % uniforms.bias_size; + let bias${b} = ${d.getByOffset(`bias${b}_offset / 4`)}[bias${b}_offset % 4];`, f = o ? ` + let bias = ${d.getByOffset("global_idx % (uniforms.bias_size / 4)")};` : `${m(0)}${m(1)}${m(2)}${m(3)} + let bias = ${u.type.value}(bias0, bias1, bias2, bias3);`; + return `${a.registerUniforms(p).declareVariables(u, d, c)} + + ${co(Ae(t))} + + ${a.mainStart(It)} + ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${u.getByOffset("global_idx")}; + ${f} + let x_in = x + bias; + ${c.setByOffset("global_idx", po("x_in"))} + }`; + }; + return { name: "FastGeluWithBias", shaderCache: { hint: `${o}`, inputDependencies: ["type", "type"] }, getShaderSource: i, getRunData: (a) => ({ outputs: [{ dims: a[0].dims, dataType: a[0].dataType }], programUniforms: [{ type: 12, data: Math.ceil(r / 4) }, { type: 12, data: n }], dispatchGroup: { x: Math.ceil(r / It / 4) } }) }; + }, bd = (e) => { + e.inputs.length < 2 || k.size(e.inputs[1].dims) === 0 ? mu(e) : e.compute(Df(e.inputs)); + }; + }); + var Mf; + var Rf; + var _d; + var wd; + var vd = U(() => { + "use strict"; + ee(); + ne(); + Se(); + ie(); + Mf = (e) => { + if (!e || e.length !== 2) throw new Error("Gather requires 2 inputs."); + }, Rf = (e, t) => { + let r = e[0].dims, n = e[1].dims, o = r.length, i = k.normalizeAxis(t.axis, o), a = r.slice(0); + a.splice(i, 1, ...n); + let u = r[i], d = e[0].dataType === 9 ? 4 : 1, c = Math.ceil(k.size(a) / d), p = [{ type: 12, data: c }, { type: 6, data: u }, { type: 12, data: i }, ...N(e[0].dims, e[1].dims, a)], m = (f) => { + let b = P("data", e[0].dataType, e[0].dims.length, d), g = P("inputIndices", e[1].dataType, e[1].dims.length), _ = M("output", e[0].dataType, a.length, d), S = (v) => { + let x = n.length, T = `var indicesIndices${v} = ${g.type.indices}(0);`; + for (let E = 0; E < x; E++) T += `${x > 1 ? `indicesIndices${v}[${E}]` : `indicesIndices${v}`} = ${a.length > 1 ? `outputIndices${v}[uniforms.axis + ${E}]` : `outputIndices${v}`};`; + T += ` + var idx${v} = ${g.getByIndices(`indicesIndices${v}`)}; + if (idx${v} < 0) { + idx${v} = idx${v} + uniforms.axisDimLimit; + } + var dataIndices${v} : ${b.type.indices}; + `; + for (let E = 0, I = 0; E < o; E++) E === i ? (T += `${o > 1 ? `dataIndices${v}[${E}]` : `dataIndices${v}`} = u32(idx${v});`, I += x) : (T += `${o > 1 ? `dataIndices${v}[${E}]` : `dataIndices${v}`} = ${a.length > 1 ? `outputIndices${v}[${I}]` : `outputIndices${v}`};`, I++); + return T; + }, $; + if (e[0].dataType === 9) { + let v = (x, T, E = "") => ` + let outputIndices${T} = ${_.offsetToIndices(`outputOffset + ${T}u`)}; + ${S(T)}; + let offset${T} = ${b.indicesToOffset(`dataIndices${T}`)}; + let index${T} = offset${T} / 4u; + let component${T} = offset${T} % 4u; + ${x}[${T}] = ${E}(${b.getByOffset(`index${T}`)}[component${T}]); + `; + $ = ` + let outputOffset = global_idx * ${d}; + var value = vec4(0); + ${v("value", 0, "u32")} + ${v("value", 1, "u32")} + ${v("value", 2, "u32")} + ${v("value", 3, "u32")} + ${_.setByOffset("global_idx", "value")} + `; + } else $ = ` + let outputIndices = ${_.offsetToIndices("global_idx")}; + ${S("")}; + let value = ${b.getByIndices("dataIndices")}; + ${_.setByOffset("global_idx", "value")}; + `; + return ` + ${f.registerUniform("outputSize", "u32").registerUniform("axisDimLimit", "i32").registerUniform("axis", "u32").declareVariables(b, g, _)} + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${$} + }`; + }; + return { name: "Gather", shaderCache: { hint: t.cacheKey, inputDependencies: ["rank", "rank"] }, getRunData: () => ({ outputs: [{ dims: a, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(c / 64) }, programUniforms: p }), getShaderSource: m }; + }, _d = (e) => J({ axis: e.axis }), wd = (e, t) => { + let r = e.inputs; + Mf(r), e.compute(Rf(e.inputs, t)); + }; + }); + var Uf; + var $d; + var xd; + var Sd = U(() => { + "use strict"; + ee(); + ne(); + ie(); + Uf = (e, t, r, n, o, i, a, u, d) => { + let c = [{ type: 12, data: i }, { type: 12, data: n }, { type: 12, data: o }, { type: 12, data: r }, { type: 12, data: a }, { type: 12, data: u }, { type: 12, data: d }], p = [i]; + c.push(...N(t.dims, p)); + let m = (f) => { + let b = P("indices_data", t.dataType, t.dims.length), g = M("input_slice_offsets_data", 12, 1, 1), _ = [b, g], S = [{ name: "output_size", type: "u32" }, { name: "batch_dims", type: "u32" }, { name: "input_dims", type: "u32", length: o.length }, { name: "sizes_from_slice_dims_data", type: "u32", length: r.length }, { name: "num_slices_per_batch", type: "u32" }, { name: "input_batch_stride", type: "u32" }, { name: "num_slice_dims", type: "u32" }]; + return ` + ${f.registerUniforms(S).declareVariables(..._)} + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let batch_idx = global_idx / uniforms.num_slices_per_batch; + let base_offset = batch_idx * uniforms.input_batch_stride; + + let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; + var relative_slice_offset = 0; + for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { + var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); + let input_dim_idx = uniforms.batch_dims + dim_idx; + if (index < 0) { + ${o.length === 1 ? "index += i32(uniforms.input_dims);" : "index += i32(uniforms.input_dims[input_dim_idx]);"} + } + ${r.length === 1 ? "relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);" : "relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} + } + + input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); + }`; + }; + return e.compute({ name: "computeSliceOffsets", shaderCache: { hint: `${o.length}_${r.length}`, inputDependencies: ["rank"] }, getRunData: () => ({ outputs: [{ dims: p, dataType: e.inputs[1].dataType }], dispatchGroup: { x: Math.ceil(i / 64) }, programUniforms: c }), getShaderSource: m }, { inputs: [t], outputs: [-1] })[0]; + }, $d = (e, t) => { + let r = e.inputs, n = r[0].dims, o = r[0].dataType, i = r[1].dims, a = i[i.length - 1], u = k.sizeToDimension(i, i.length - 1), d = k.sizeFromDimension(n, t.batchDims + a), c = k.sizeToDimension(n, t.batchDims), p = k.sizeFromDimension(n, t.batchDims), m = u / c, f = new Array(a), b = d; + for (let T = 0; T < a; ++T) f[a - 1 - T] = b, b *= n[t.batchDims + a - 1 - T]; + let g = Uf(e, r[1], f, t.batchDims, n, u, m, p, a), _ = t.batchDims + a; + if (_ > n.length) throw new Error("last dimension of indices must not be larger than rank of input tensor"); + let S = i.slice(0, -1).concat(n.slice(_)), $ = k.size(S), v = [{ type: 12, data: $ }, { type: 12, data: d }, ...N(r[0].dims, g.dims, S)], x = (T) => { + let E = P("data", r[0].dataType, r[0].dims.length), I = P("slice_offsets", 12, g.dims.length), z = M("output", r[0].dataType, S.length); + return ` + ${T.registerUniform("output_size", "u32").registerUniform("slice_size", "u32").declareVariables(E, I, z)} + ${T.mainStart()} + ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let slice_offset = slice_offsets[global_idx / uniforms.slice_size]; + output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size]; + }`; + }; + e.compute({ name: "GatherND", shaderCache: { hint: t.cacheKey, inputDependencies: ["rank", "rank"] }, getRunData: () => ({ outputs: [{ dims: S, dataType: o }], dispatchGroup: { x: Math.ceil($ / 64) }, programUniforms: v }), getShaderSource: x }, { inputs: [r[0], g] }); + }, xd = (e) => ({ batchDims: e.batch_dims, cacheKey: "" }); + }); + var Nf; + var Vf; + var Td; + var Id; + var Cd = U(() => { + "use strict"; + ee(); + ne(); + Se(); + ie(); + Nf = (e, t) => { + if (e.length < 3 || e.length > 4) throw new Error("GatherBlockQuantized requires 3 or 4 inputs."); + let r = k.normalizeAxis(t.quantizeAxis, e[0].dims.length), n = t.blockSize, o = e[0], i = e[2], a = e.length === 4 ? e[3] : void 0; + if (i.dims.length !== o.dims.length || !o.dims.map((u, d) => d === r ? Math.ceil(u / n) === i.dims[d] : u === i.dims[d]).reduce((u, d) => u && d, true)) throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis."); + if (a) { + if (a.dataType !== o.dataType) throw new Error("Zero point must have the same data type as the input tensor."); + if (a.dims.length !== i.dims.length || !a.dims.map((u, d) => u === i.dims[d]).reduce((u, d) => u && d, true)) throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis."); + } + }, Vf = (e, t) => { + let r = e[0].dims, n = e[1].dims, o = r.length, i = k.normalizeAxis(t.gatherAxis, o), a = k.normalizeAxis(t.quantizeAxis, o), u = r.slice(0); + u.splice(i, 1, ...n); + let d = k.size(u), c = e[2].dataType, m = e[0].dataType === 22, f = [{ type: 12, data: d }, { type: 12, data: a }, { type: 12, data: i }, { type: 12, data: t.blockSize }, ...N(...e.map((g, _) => g.dims), u)], b = (g) => { + let _ = P("data", e[0].dataType, e[0].dims.length), S = P("inputIndices", e[1].dataType, e[1].dims.length), $ = P("scales", e[2].dataType, e[2].dims.length), v = e.length > 3 ? P("zeroPoint", e[3].dataType, e[3].dims.length) : void 0, x = M("output", c, u.length), T = [_, S, $]; + v && T.push(v); + let E = [{ name: "output_size", type: "u32" }, { name: "quantize_axis", type: "u32" }, { name: "gather_axis", type: "u32" }, { name: "block_size", type: "u32" }]; + return ` + ${g.registerUniforms(E).declareVariables(...T, x)} + ${g.mainStart()} + let output_indices = ${x.offsetToIndices("global_idx")}; + var indices_indices = ${S.type.indices}(0); + ${n.length > 1 ? ` + for (var i: u32 = 0; i < ${n.length}; i++) { + let index = ${x.indicesGet("output_indices", "uniforms.gather_axis + i")}; + ${S.indicesSet("indices_indices", "i", "index")}; + }` : `indices_indices = ${x.indicesGet("output_indices", "uniforms.gather_axis")};`}; + var data_indices = ${_.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${x.indicesGet("output_indices", "i")}; + ${_.indicesSet("data_indices", "i", "index")}; + } + var index_from_indices = ${S.getByIndices("indices_indices")}; + if (index_from_indices < 0) { + index_from_indices += ${r[i]}; + } + ${_.indicesSet("data_indices", "uniforms.gather_axis", "u32(index_from_indices)")}; + for (var i = uniforms.gather_axis + 1; i < ${u.length}; i++) { + let index = ${x.indicesGet("output_indices", `i + ${n.length} - 1`)}; + ${_.indicesSet("data_indices", "i", "index")}; + } + let data_offset = ${_.indicesToOffset("data_indices")}; + let data_index = data_offset % 8; + // Convert 4-bit packed data to 8-bit packed data. + let packed_4bit_quantized_data = ${_.getByOffset("data_offset / 8")}; + let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; + let quantized_data_vec = ${m ? "unpack4xI8" : "unpack4xU8"}(u32(packed_8bit_quantized_data)); + let quantized_data = quantized_data_vec[data_index / 2]; + var scale_indices = data_indices; + let quantize_axis_index = ${$.indicesGet("data_indices", "uniforms.quantize_axis")} / uniforms.block_size; + ${$.indicesSet("scale_indices", "uniforms.quantize_axis", "quantize_axis_index")}; + var scale = ${$.getByIndices("scale_indices")}; + ${v ? ` + let zero_point_indices = scale_indices; + let zero_point_offset = ${v.indicesToOffset("zero_point_indices")}; + let zero_point_index = zero_point_offset % 8; + let packed_4bit_zero_points = ${v.getByOffset("zero_point_offset / 8")}; + let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; + let zero_point_vec = ${m ? "unpack4xI8" : "unpack4xU8"}(u32(packed_8bit_zero_points)); + let zero_point = zero_point_vec[zero_point_index / 2];` : "var zero_point = 0"}; + let dequantized_data = ${Ae(c)}(quantized_data - zero_point) * scale; + ${x.setByOffset("global_idx", "dequantized_data")}; + }`; + }; + return { name: "GatherBlockQuantized", shaderCache: { hint: `${t.cacheKey};${e.filter((g, _) => _ !== 1).map((g) => g.dims.join("_")).join(";")}`, inputDependencies: Array.from({ length: e.length }, (g, _) => "rank") }, getRunData: () => ({ outputs: [{ dims: u, dataType: c }], dispatchGroup: { x: Math.ceil(d / 64) }, programUniforms: f }), getShaderSource: b }; + }, Td = (e, t) => { + let r = e.inputs; + Nf(r, t), e.compute(Vf(e.inputs, t)); + }, Id = (e) => J({ blockSize: e.blockSize, gatherAxis: e.gatherAxis, quantizeAxis: e.quantizeAxis }); + }); + var Wf; + var Lf; + var Ad; + var Ed; + var kd = U(() => { + "use strict"; + ee(); + ne(); + Se(); + ie(); + Wf = (e) => { + if (!e || e.length !== 2) throw new Error("GatherElements requires 2 inputs."); + if (e[0].dims.length < 1) throw new Error("GatherElements requires that the data input be rank >= 1."); + if (e[0].dims.length !== e[1].dims.length) throw new Error(`GatherElements requires that the data input and + indices input tensors be of same rank.`); + }, Lf = (e, t) => { + let r = e[0].dims, n = e[0].dataType, o = r.length, i = e[1].dims, a = e[1].dataType, u = k.normalizeAxis(t.axis, o), d = r[u], c = i.slice(0), p = k.size(c), m = P("input", n, o), f = P("indicesInput", a, i.length), b = M("output", n, c.length), g = [{ type: 12, data: p }, { type: 6, data: d }, { type: 12, data: u }]; + return g.push(...N(r, i, c)), { name: "GatherElements", shaderCache: { inputDependencies: ["rank", "rank"] }, getRunData: () => ({ outputs: [{ dims: c, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(p / 64) }, programUniforms: g }), getShaderSource: ($) => ` + ${$.registerUniform("outputSize", "u32").registerUniform("axisDimLimit", "i32").registerUniform("axis", "u32").declareVariables(m, f, b)} + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${b.offsetToIndices("global_idx")}; + + var idx = ${f.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${m.type.indices}(outputIndices); + ${m.indicesSet("inputIndices", "uniforms.axis", "u32(idx)")}; + let value = ${m.getByIndices("inputIndices")}; + + ${b.setByOffset("global_idx", "value")}; + }` }; + }, Ad = (e) => J({ axis: e.axis }), Ed = (e, t) => { + let r = e.inputs; + Wf(r), e.compute(Lf(e.inputs, t)); + }; + }); + var Gf; + var Hf; + var Pd; + var zd; + var Od = U(() => { + "use strict"; + ee(); + ne(); + ie(); + Gf = (e) => { + if (!e) throw new Error("Input is missing"); + if (e.length < 2 || e.length > 3) throw new Error("Invaid input number."); + if (e.length === 3 && e[2].dims.length > 2) throw new Error("Invalid input shape of C"); + if (e[0].dataType !== e[1].dataType || e.length === 3 && e[0].dataType !== e[2].dataType) throw new Error("Input types are mismatched"); + }, Hf = (e, t) => { + let r = e[0].dims.slice(), n = e[1].dims.slice(), [o, i, a] = Dr.getShapeOfGemmResult(r, t.transA, n, t.transB, e.length === 3 ? e[2].dims : void 0), u = [o, i]; + if (!u) throw new Error("Can't use gemm on the given tensors"); + let d = 16, c = Math.ceil(i / d), p = Math.ceil(o / d), m = true, f = k.size(u), b = [{ type: 12, data: m ? c : f }, { type: 12, data: o }, { type: 12, data: i }, { type: 12, data: a }, { type: 1, data: t.alpha }, { type: 1, data: t.beta }], g = ["type", "type"]; + e.length === 3 && (b.push(...N(e[2].dims)), g.push("rank")), b.push(...N(u)); + let _ = ($) => { + let v = ""; + t.transA && t.transB ? v = "value += a[k * uniforms.M + m] * b[n * uniforms.K + k];" : t.transA && !t.transB ? v = "value += a[k * uniforms.M + m] * b[k * uniforms.N + n];" : !t.transA && t.transB ? v = "value += a[m * uniforms.K + k] * b[n * uniforms.K + k];" : !t.transA && !t.transB && (v = "value += a[m * uniforms.K + k] * b[k * uniforms.N + n];"); + let x = t.alpha === 1 ? "" : "value *= uniforms.alpha;", T = P("a", e[0].dataType, e[0].dims), E = P("b", e[1].dataType, e[1].dims), I = T.type.value, z = null, O = [T, E]; + e.length === 3 && (z = P("c", e[2].dataType, e[2].dims.length), O.push(z)); + let D = M("output", e[0].dataType, u.length); + O.push(D); + let L = [{ name: "output_size", type: "u32" }, { name: "M", type: "u32" }, { name: "N", type: "u32" }, { name: "K", type: "u32" }, { name: "alpha", type: "f32" }, { name: "beta", type: "f32" }]; + return ` + ${$.registerUniforms(L).declareVariables(...O)} + + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${I}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${v} + } + + ${x} + ${z != null ? `let cOffset = ${z.broadcastedIndicesToOffset("vec2(m, n)", D)}; value += ${I}(uniforms.beta) * ${z.getByOffset("cOffset")};` : ""} + output[global_idx] = value; + }`; + }, S = ($) => { + let v = P("a", e[0].dataType, e[0].dims), x = P("b", e[1].dataType, e[1].dims), T = null, E = [v, x]; + e.length === 3 && (T = P("c", e[2].dataType, e[2].dims.length), E.push(T)); + let I = M("output", e[0].dataType, u.length); + E.push(I); + let z = [{ name: "num_tile_n", type: "u32" }, { name: "M", type: "u32" }, { name: "N", type: "u32" }, { name: "K", type: "u32" }, { name: "alpha", type: "f32" }, { name: "beta", type: "f32" }], O = "", D = ""; + t.transA && t.transB ? (D = ` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${v.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${x.type.value}(0); + } + `, O = "value += tile_a[k][local_id.y] * tile_b[local_id.x][k];") : t.transA && !t.transB ? (D = ` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${v.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${x.type.value}(0); + } + `, O = "value += tile_a[k][local_id.y] * tile_b[k][local_id.x];") : !t.transA && t.transB ? (D = ` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${v.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${x.type.value}(0); + } + `, O = "value += tile_a[local_id.y][k] * tile_b[local_id.x][k];") : !t.transA && !t.transB && (D = ` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${v.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${x.type.value}(0); + } + `, O = "value += tile_a[local_id.y][k] * tile_b[k][local_id.x];"); + let L = t.alpha === 1 ? "" : "value *= uniforms.alpha;"; + return ` + ${$.registerUniforms(z).declareVariables(...E)} + var tile_a: array, ${d}>; + var tile_b: array, ${d}>; + ${$.mainStart([d, d, 1])} + let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${d}; + let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${d}; + let num_tiles = (uniforms.K - 1) / ${d} + 1; + var k_start = 0u; + var value = ${I.type.value}(0); + for (var t: u32 = 0u; t < num_tiles; t++) { + ${D} + k_start = k_start + ${d}; + workgroupBarrier(); + + for (var k: u32 = 0u; k < ${d}; k++) { + ${O} + } + workgroupBarrier(); + } + + ${L} + let m = tile_row_start + local_id.y; + let n = tile_col_start + local_id.x; + ${T != null ? `let cOffset = ${T.broadcastedIndicesToOffset("vec2(m, n)", I)}; value += ${I.type.value}(uniforms.beta) * ${T.getByOffset("cOffset")};` : ""} + if (m < uniforms.M && n < uniforms.N) { + output[m * uniforms.N + n] = value; + } + }`; + }; + return m ? { name: "GemmShared", shaderCache: { hint: `${t.cacheKey}`, inputDependencies: g }, getRunData: () => ({ outputs: [{ dims: u, dataType: e[0].dataType }], dispatchGroup: { x: c * p }, programUniforms: b }), getShaderSource: S } : { name: "Gemm", shaderCache: { hint: `${t.cacheKey}`, inputDependencies: g }, getRunData: () => ({ outputs: [{ dims: u, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(f / 64) }, programUniforms: b }), getShaderSource: _ }; + }, Pd = (e) => { + let t = e.transA, r = e.transB, n = e.alpha, o = e.beta; + return { transA: t, transB: r, alpha: n, beta: o, cacheKey: `${e.transA};${e.transB};${e.alpha === 1}` }; + }, zd = (e, t) => { + Gf(e.inputs), e.compute(Hf(e.inputs, t)); + }; + }); + var ut; + var yt; + var Ut; + var Nt; + var Ff; + var qf; + var jf; + var Kf; + var Zf; + var Qf; + var Yf; + var Xf; + var Bd; + var Dd; + var Md = U(() => { + "use strict"; + ee(); + ne(); + Se(); + ie(); + [ut, yt, Ut, Nt] = [0, 1, 2, 3], Ff = (e) => { + if (e[0].dims.length !== 4) throw new Error("only 4-D tensor is supported."); + if (e[0].dims.length !== e[1].dims.length) throw new Error("input dimensions must be equal to grid dimensions"); + if (e[0].dims.length - 2 !== e[1].dims[e[1].dims.length - 1]) throw new Error(`last dimension of grid must be equal to ${e[0].dims.length - 2}`); + if (e[0].dims[0] !== e[1].dims[0]) throw new Error("grid batch size must match input batch size"); + }, qf = ` + fn gs_get_cubic_coeffs(x: f32) -> vec4 { + let cubic_alpha = -0.75f; + let x_abs = abs(x); + var coeffs: vec4; + coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha); + coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1); + coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1); + coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha); + return coeffs; + } +`, jf = (e) => ` + fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} { + var v: vec4; + var coeffs = gs_get_cubic_coeffs(x); + for (var i = 0; i < 4; i++) { + v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3]; + } + coeffs = gs_get_cubic_coeffs(y); + let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]); + return pixel; + } +`, Kf = (e) => ` + fn gs_denormalize(n: f32, length: i32) -> f32 { + ${e.alignCorners === 0 ? ` + // alignCorners: false => [-1, 1] to [-0.5, length - 0.5] + return ((n + 1.0) * f32(length) - 1.0) / 2.0; + ` : ` + // alignCorners: true => [-1, 1] to [0, length - 1] + return (n + 1.0) / 2.0 * (f32(length - 1)); + `} + } +`, Zf = (e) => ` + ${e.paddingMode === "reflection" ? ` + fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 { + var dx = 0.0; + var fx = f32(x); + let range = x_max - x_min; + if (fx < x_min) { + dx = x_min - fx; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_min + r; + } else { + fx = x_max - r; + } + } else if (fx > x_max) { + dx = fx - x_max; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_max - r; + } else { + fx = x_min + r; + } + } + return u32(fx); + }` : ""} +`, Qf = (e, t, r) => ` + fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${t} { + var pixel = ${t}(0); + var indices = vec4(0); + indices[${ut}] = batch; + indices[${yt}] = channel;` + (() => { + switch (r.paddingMode) { + case "zeros": + return ` + if (r >= 0 && r < H && c >=0 && c < W) { + indices[${Ut}] = u32(r); + indices[${Nt}] = u32(c); + } else { + return ${t}(0); + } + `; + case "border": + return ` + indices[${Ut}] = u32(clamp(r, 0, H - 1)); + indices[${Nt}] = u32(clamp(c, 0, W - 1)); + `; + case "reflection": + return ` + indices[${Ut}] = gs_reflect(r, border[1], border[3]); + indices[${Nt}] = gs_reflect(c, border[0], border[2]); + `; + default: + throw new Error(`padding mode ${r.paddingMode} is not supported`); + } + })() + ` + return ${e.getByIndices("indices")}; + } +`, Yf = (e, t, r) => (() => { + switch (r.mode) { + case "nearest": + return ` + let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${ut}], indices[${yt}], border); + `; + case "bilinear": + return ` + let x1 = i32(floor(x)); + let y1 = i32(floor(y)); + let x2 = x1 + 1; + let y2 = y1 + 1; + + let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${ut}], indices[${yt}], border); + let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${ut}], indices[${yt}], border); + let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${ut}], indices[${yt}], border); + let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${ut}], indices[${yt}], border); + + let dx2 = ${t}(f32(x2) - x); + let dx1 = ${t}(x - f32(x1)); + let dy2 = ${t}(f32(y2) - y); + let dy1 = ${t}(y - f32(y1)); + let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22); + `; + case "bicubic": + return ` + let x0 = i32(floor(x)) - 1; + let y0 = i32(floor(y)) - 1; + var p: mat4x4<${t}>; + for (var h = 0; h < 4; h++) { + for (var w = 0; w < 4; w++) { + p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${ut}], indices[${yt}], border); + } + } + + let dx = x - f32(x0 + 1); + let dy = y - f32(y0 + 1); + let result = gs_bicubic_interpolate(p, dx, dy); + `; + default: + throw new Error(`mode ${r.mode} is not supported`); + } + })() + `${e.setByOffset("global_idx", "result")}`, Xf = (e, t) => { + let r = P("x", e[0].dataType, e[0].dims.length), n = [e[1].dims[0], e[1].dims[1], e[1].dims[2]], o = P("grid", e[1].dataType, n.length, 2), i = [e[0].dims[0], e[0].dims[1], e[1].dims[1], e[1].dims[2]]; + t.format === "NHWC" && (i = [e[0].dims[0], e[1].dims[1], e[1].dims[2], e[0].dims[3]], [ut, yt, Ut, Nt] = [0, 3, 1, 2]); + let a = M("output", e[0].dataType, i.length), u = r.type.value, d = k.size(i), c = [{ type: 12, data: d }, ...N(e[0].dims, n, i)], p = (m) => ` + ${m.registerUniform("output_size", "u32").declareVariables(r, o, a)} + ${qf} + ${jf(u)} + ${Kf(t)} + ${Zf(t)} + ${Qf(r, u, t)} + + ${m.mainStart()} + ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let H_in = i32(uniforms.x_shape[${Ut}]); + let W_in = i32(uniforms.x_shape[${Nt}]); + + ${t.alignCorners === 0 ? ` + let x_min = -0.5; + let x_max = f32(W_in) - 0.5; + let y_min = -0.5; + let y_max = f32(H_in) - 0.5; + ` : ` + let x_min = 0.0; + let x_max = f32(W_in) - 1.0; + let y_min = 0.0; + let y_max = f32(H_in) - 1.0; + `}; + let border = vec4(x_min, y_min, x_max, y_max); + + let indices = ${a.offsetToIndices("global_idx")}; + var grid_indices = vec3(indices[${ut}], indices[${Ut}], indices[${Nt}]); + let nxy = ${o.getByIndices("grid_indices")}; + var x = gs_denormalize(f32(nxy[0]), W_in); + var y = gs_denormalize(f32(nxy[1]), H_in); + + ${Yf(a, u, t)} + }`; + return { name: "GridSample", shaderCache: { hint: `${t.cacheKey}`, inputDependencies: ["type", "type"] }, getRunData: (m) => { + let f = k.size(i); + return { outputs: [{ dims: i, dataType: m[0].dataType }], dispatchGroup: { x: Math.ceil(f / 64) }, programUniforms: c }; + }, getShaderSource: p }; + }, Bd = (e, t) => { + Ff(e.inputs), e.compute(Xf(e.inputs, t)); + }, Dd = (e) => J({ alignCorners: e.align_corners, mode: e.mode, paddingMode: e.padding_mode, format: e.format }); + }); + var Be; + var th; + var Ud; + var Rd; + var rh; + var er; + var Nd; + var $o = U(() => { + "use strict"; + ee(); + ne(); + Se(); + Vr(); + Fr(); + ie(); + st(); + Be = (e, t) => e.length > t && e[t].dims.length > 0 ? e[t] : void 0, th = (e, t) => { + let r = e[0], n = Be(e, 1), o = Be(e, 2), i = Be(e, 3), a = Be(e, 4), u = Be(e, 5), d = Be(e, 6), c = Be(e, 7); + if (r.dims.length !== 3 && r.dims.length !== 5) throw new Error("Input query is expected to have 3 or 5 dimensions"); + let p = r.dims[0], m = r.dims[1], f = r.dims.length === 3 ? r.dims[2] : t.numHeads * r.dims[4], b = m, g = 0, _ = 0, S = Math.floor(f / t.numHeads); + if (d && c && k.size(d.dims) && k.size(c.dims)) { + if (d.dims.length !== 4) throw new Error('Input "past_key" is expected to have 4 dimensions'); + if (d.dims[0] !== p || d.dims[1] !== t.numHeads || d.dims[3] !== S) throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)'); + if (c.dims[0] !== p || c.dims[1] !== t.numHeads || c.dims[3] !== S) throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)'); + if (d.dims[2] !== c.dims[2]) throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)'); + if (c.dims.length !== 4) throw new Error('Input "past_value" is expected to have 4 dimensions'); + g = d.dims[2], _ = d.dims[2]; + } else if (d && k.size(d.dims) || c && k.size(c.dims)) throw new Error('Input "past_key" and "past_value" shall be both present or both absent'); + let $; + if (n && k.size(n.dims) > 0) { + if (r.dims.length !== 3) throw new Error('Input "query" is expected to have 3 dimensions when key is given'); + if (n.dims.length < 3 || n.dims.length > 5) throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions'); + if (r.dims[0] !== n.dims[0]) throw new Error('Input "query" and "key" shall have same dim 0 (batch size)'); + if (n.dims.length === 3) { + if (n.dims[2] !== r.dims[2]) throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)'); + $ = 2, b = n.dims[1]; + } else if (n.dims.length === 5) { + if (n.dims[2] !== t.numHeads || n.dims[3] !== 2 || n.dims[4] !== S) throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv'); + if (o) throw new Error('Expect "value" be none when "key" has packed kv format.'); + $ = 5, b = n.dims[1]; + } else { + if (n.dims[1] !== t.numHeads || n.dims[3] !== S) throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key'); + $ = 0, b = n.dims[2]; + } + } else { + if (r.dims.length !== 5) throw new Error('Input "query" is expected to have 5 dimensions when key is empty'); + if (r.dims[2] !== t.numHeads || r.dims[3] !== 3) throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv'); + $ = 3; + } + if (i && k.size(i.dims) > 0) { + if (i.dims.length !== 1) throw new Error('Input "bias" is expected to have 1 dimension'); + if (n && n.dims.length === 5 && n.dims[3] === 2) throw new Error("bias is not allowed for packed kv."); + } + let v = g + b, x = 0; + if (a && k.size(a.dims) > 0) { + x = 8; + let z = a.dims; + throw z.length === 1 ? z[0] === p ? x = 1 : z[0] === 3 * p + 2 && (x = 3) : z.length === 2 && z[0] === p && z[1] === v && (x = 5), x === 8 ? new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)') : new Error("Mask not supported"); + } + let T = false, E = f; + if (o && k.size(o.dims) > 0) { + if (o.dims.length !== 3 && o.dims.length !== 4) throw new Error('Input "value" is expected to have 3 or 4 dimensions'); + if (r.dims[0] !== o.dims[0]) throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)'); + if (o.dims.length === 3) { + if (b !== o.dims[1]) throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)'); + E = o.dims[2]; + } else { + if (b !== o.dims[2]) throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)'); + E = o.dims[1] * o.dims[3], T = true; + } + } + let I = false; + if (a && k.size(a.dims) > 0) throw new Error("Key padding mask is not supported"); + if (u && k.size(u.dims) > 0) { + if (u.dims.length !== 4) throw new Error('Input "attention_bias" is expected to have 4 dimensions'); + if (u.dims[0] !== p || u.dims[1] !== t.numHeads || u.dims[2] !== m || u.dims[3] !== v) throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)'); + } + return { batchSize: p, sequenceLength: m, pastSequenceLength: g, kvSequenceLength: b, totalSequenceLength: v, maxSequenceLength: _, inputHiddenSize: 0, hiddenSize: f, vHiddenSize: E, headSize: S, vHeadSize: Math.floor(E / t.numHeads), numHeads: t.numHeads, isUnidirectional: false, pastPresentShareBuffer: false, maskFilterValue: t.maskFilterValue, maskType: x, scale: t.scale, broadcastResPosBias: I, passPastInKv: T, qkvFormat: $ }; + }, Ud = (e) => J({ ...e }), Rd = J({ perm: [0, 2, 1, 3] }), rh = (e, t, r, n, o, i, a) => { + let u = [n, o, i], d = k.size(u), c = [{ type: 12, data: d }, { type: 12, data: a }, { type: 12, data: i }], p = (m) => { + let f = M("qkv_with_bias", t.dataType, u), b = P("qkv", t.dataType, u), g = P("bias", r.dataType, u), _ = [{ name: "output_size", type: "u32" }, { name: "bias_offset", type: "u32" }, { name: "hidden_size", type: "u32" }]; + return ` + ${m.registerUniforms(_).declareVariables(b, g, f)} + ${m.mainStart()} + ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; + + qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; + }`; + }; + return e.compute({ name: "MultiHeadAttentionAddBias", shaderCache: { inputDependencies: ["type", "type"] }, getRunData: () => ({ outputs: [{ dims: u, dataType: t.dataType, gpuDataType: 0 }], dispatchGroup: { x: Math.ceil(d / 64) }, programUniforms: c }), getShaderSource: p }, { inputs: [t, r], outputs: [-1] })[0]; + }, er = (e, t, r, n, o, i, a, u) => { + let d = i; + if (a && k.size(a.dims) > 0) { + if (n === 1) throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV"); + return d = rh(e, i, a, t, n, r * o, u), d = d.reshape([t, n, r, o]), r === 1 || n === 1 ? d : e.compute(Ee(d, Rd.perm), { inputs: [d], outputs: [-1] })[0]; + } else return i.dims.length === 3 && (d = i.reshape([t, n, r, o])), r === 1 || n === 1 ? d : e.compute(Ee(d, Rd.perm), { inputs: [d], outputs: [-1] })[0]; + }, Nd = (e, t) => { + let r = th(e.inputs, t), n = e.inputs[0], o = Be(e.inputs, 1), i = Be(e.inputs, 2), a = Be(e.inputs, 3), u = Be(e.inputs, 4), d = Be(e.inputs, 5), c = Be(e.inputs, 6), p = Be(e.inputs, 7); + if (n.dims.length === 5) throw new Error("Packed QKV is not implemented"); + if (o?.dims.length === 5) throw new Error("Packed KV is not implemented"); + let m = o && i && o.dims.length === 4 && i.dims.length === 4, f = er(e, r.batchSize, r.numHeads, r.sequenceLength, r.headSize, n, a, 0); + if (m) return Rt(e, f, o, i, u, void 0, c, p, d, r); + if (!o || !i) throw new Error("key and value must be provided"); + let b = er(e, r.batchSize, r.numHeads, r.kvSequenceLength, r.headSize, o, a, r.hiddenSize), g = er(e, r.batchSize, r.numHeads, r.kvSequenceLength, r.vHeadSize, i, a, 2 * r.hiddenSize); + Rt(e, f, b, g, u, void 0, c, p, d, r); + }; + }); + var nh; + var oh; + var ih; + var ah; + var xo; + var Vd; + var Wd; + var So = U(() => { + "use strict"; + ee(); + ne(); + Se(); + ie(); + nh = (e) => { + if (!e || e.length < 1) throw new Error("too few inputs"); + }, oh = (e, t) => { + let r = [], n = t.numOutputs; + return e[1].dims[0] > 0 && (e[1].getBigInt64Array().forEach((o) => r.push(Number(o))), n = r.length), J({ numOutputs: n, axis: t.axis, splitSizes: r }); + }, ih = (e) => ` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${e}u; i += 1u ) { + if (index < ${F("uniforms.size_in_split_axis", "i", e)}) { + return i; + } + } + return ${e}u; +}`, ah = (e) => { + let t = e.length, r = []; + for (let n = 0; n < t; ++n) { + let o = e[n].setByIndices("indices", "input[global_idx]"); + t === 1 ? r.push(o) : n === 0 ? r.push(`if (output_number == ${n}u) { ${o} }`) : n === t - 1 ? r.push(`else { ${o} }`) : r.push(`else if (output_number == ${n}) { ${o} }`); + } + return ` + fn writeBufferData(output_number: u32, indices: ${e[0].type.indices}, global_idx: u32) { + ${r.join(` +`)} + }`; + }, xo = (e, t) => { + let r = e[0].dims, n = k.size(r), o = e[0].dataType, i = k.normalizeAxis(t.axis, r.length), a = new Array(t.numOutputs), u = P("input", o, r.length), d = new Array(t.numOutputs), c = [], p = [], m = 0, f = [{ type: 12, data: n }]; + for (let g = 0; g < t.numOutputs; g++) { + m += t.splitSizes[g], d[g] = m; + let _ = r.slice(); + _[i] = t.splitSizes[g], p.push(_), a[g] = M(`output${g}`, o, _.length), c.push({ dims: p[g], dataType: e[0].dataType }); + } + f.push({ type: 12, data: d }, ...N(r, ...p)); + let b = (g) => ` + ${g.registerUniform("input_size", "u32").registerUniform("size_in_split_axis", "u32", d.length).declareVariables(u, ...a)} + ${ih(d.length)} + ${ah(a)} + + ${g.mainStart()} + ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${u.offsetToIndices("global_idx")}; + var index = ${u.indicesGet("indices", i)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${F("uniforms.size_in_split_axis", "output_number - 1u", d.length)}; + ${u.indicesSet("indices", i, "index")}; + } + writeBufferData(output_number, indices, global_idx); + }`; + return { name: "Split", shaderCache: { hint: t.cacheKey, inputDependencies: ["rank"] }, getShaderSource: b, getRunData: () => ({ outputs: c, dispatchGroup: { x: Math.ceil(n / 64) }, programUniforms: f }) }; + }, Vd = (e, t) => { + nh(e.inputs); + let r = e.inputs.length === 1 ? t : oh(e.inputs, t); + e.compute(xo(e.inputs, r), { inputs: [0] }); + }, Wd = (e) => { + let t = e.axis, r = e.splitSizes, n = e.numOutputs < 0 ? r.length : e.numOutputs; + if (n !== r.length) throw new Error("numOutputs and splitSizes lengh must be equal"); + return J({ axis: t, numOutputs: n, splitSizes: r }); + }; + }); + var sh; + var tn; + var Ld; + var To = U(() => { + "use strict"; + ee(); + ne(); + Se(); + ie(); + sh = (e, t) => { + let [r, n, o, i] = e, { numHeads: a, rotaryEmbeddingDim: u } = t; + if (r.dims.length !== 3 && r.dims.length !== 4) throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`); + if (!k.areEqual(n.dims, []) && !k.areEqual(n.dims, [1]) && n.dims.length !== 2) throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`); + if (o.dims.length !== 2) throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`); + if (i.dims.length !== 2) throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${i.dims.length}`); + if (!k.areEqual(o.dims, i.dims)) throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape"); + if (u > 0 && a === 0) throw new Error("num_heads must be provided if rotary_embedding_dim is specified"); + let d = r.dims[0], c = r.dims[r.dims.length - 2], p = o.dims[0], m = k.sizeFromDimension(r.dims, 1) / c, f = u === 0 ? o.dims[1] * 2 : m / a; + if (u > f) throw new Error("rotary_embedding_dim must be less than or equal to head_size"); + if (n.dims.length === 2) { + if (d !== n.dims[0]) throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`); + if (c !== n.dims[1]) throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`); + } + if (f / 2 !== o.dims[1] && u / 2 !== o.dims[1]) throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`); + if (c > p) throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported"); + }, tn = (e, t) => { + let { interleaved: r, numHeads: n, rotaryEmbeddingDim: o, scale: i } = t, a = e[0].dims[0], u = k.sizeFromDimension(e[0].dims, 1), d = e[0].dims[e[0].dims.length - 2], c = u / d, p = e[2].dims[1], m = o === 0 ? p * 2 : c / n, f = new Array(a, d, c / m, m - p), b = k.computeStrides(f), g = [{ type: 1, data: i }, { type: 12, data: f }, { type: 12, data: b }, ...e[0].dims.length === 3 ? new Array({ type: 12, data: [u, c, m, 1] }) : [], ...e[0].dims.length === 4 ? new Array({ type: 12, data: [u, m, d * m, 1] }) : [], ...N(e[0].dims, e[1].dims, e[2].dims, e[3].dims, e[0].dims)], _ = (S) => { + let $ = P("input", e[0].dataType, e[0].dims.length), v = P("position_ids", e[1].dataType, e[1].dims.length), x = P("cos_cache", e[2].dataType, e[2].dims.length), T = P("sin_cache", e[3].dataType, e[3].dims.length), E = M("output", e[0].dataType, e[0].dims.length); + return S.registerUniforms([{ name: "scale", type: "f32" }, { name: "global_shape", type: "u32", length: f.length }, { name: "global_strides", type: "u32", length: b.length }, { name: "input_output_strides", type: "u32", length: b.length }]), ` + ${S.declareVariables($, v, x, T, E)} + + ${S.mainStart(It)} + let half_rotary_emb_dim = uniforms.${x.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${S.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${v.broadcastedIndicesToOffset("bsnh.xy", M("", v.type.tensor, 2))}; + let position_id = + u32(${v.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); + let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r}); + let j = i + select(half_rotary_emb_dim, 1, ${r}); + let re = ${$.getByOffset("i")} * ${x.get("position_id", "bsnh[3]")} - + ${$.getByOffset("j")} * ${T.get("position_id", "bsnh[3]")}; + ${E.setByOffset("i", "re")} + let im = ${$.getByOffset("i")} * ${T.get("position_id", "bsnh[3]")} + + ${$.getByOffset("j")} * ${x.get("position_id", "bsnh[3]")}; + ${E.setByOffset("j", "im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${E.setByOffset("k", $.getByOffset("k"))} + } + }`; + }; + return { name: "RotaryEmbedding", shaderCache: { hint: J({ interleaved: r }).cacheKey, inputDependencies: ["rank", "rank", "rank", "rank"] }, getShaderSource: _, getRunData: () => ({ outputs: [{ dims: e[0].dims, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(k.size(f) / It) }, programUniforms: g }) }; + }, Ld = (e, t) => { + sh(e.inputs, t), e.compute(tn(e.inputs, t)); + }; + }); + var uh; + var dh; + var Gd; + var lh; + var Hd; + var Fd = U(() => { + "use strict"; + Se(); + ee(); + Fr(); + $o(); + So(); + st(); + To(); + ie(); + uh = (e, t) => { + if (t.doRotary && e.length <= 7) throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified"); + let r = e[0], n = e[1], o = e[2], i = e[3], a = e[4]; + if (t.doRotary !== 0 && e.length <= 7) throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero"); + if (t.localWindowSize !== -1) throw new Error("Local attention is not supported"); + if (t.softcap !== 0) throw new Error("Softcap is not supported"); + if (t.rotaryInterleaved !== 0) throw new Error("Rotary interleaved is not supported"); + if (t.smoothSoftmax) throw new Error("Smooth softmax is not supported"); + if (r.dims.length !== 3 && r.dims.length !== 5) throw new Error("Input query is expected to have 3 or 5 dimensions"); + let u = false, d = r.dims[0], c = r.dims[1], p = r.dims.length === 3 ? u ? r.dims[2] / 3 : r.dims[2] : t.numHeads * r.dims[4], m = c, f = 0, b = !n || n.dims.length === 0, g = Math.floor(b ? p / (t.numHeads + 2 * t.kvNumHeads) : p / t.numHeads); + b && (p = g * t.numHeads); + let _ = i && i.dims.length !== 0, S = a && a.dims.length !== 0; + if (_ && i.dims.length === 4 && i.dims[0] === d && i.dims[1] !== t.kvNumHeads && i.dims[2] === t.kvNumHeads && i.dims[3] === g) throw new Error("BSNH pastKey/pastValue is not supported"); + if (_ && S) { + if (i.dims.length !== 4) throw new Error('Input "past_key" is expected to have 4 dimensions'); + if (a.dims.length !== 4) throw new Error('Input "past_value" is expected to have 4 dimensions'); + f = i.dims[2]; + } else if (_ || S) throw new Error('Input "past_key" and "past_value" shall be both present or both absent'); + let v = 1; + if (n && n.dims.length > 0) { + if (r.dims.length !== 3) throw new Error('Input "query" is expected to have 3 dimensions when key is given'); + if (n.dims.length < 3 || n.dims.length > 5) throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions'); + if (r.dims[0] !== n.dims[0]) throw new Error('Input "query" and "key" shall have same dim 0 (batch size)'); + if (n.dims.length === 3) { + if (r.dims[2] % n.dims[2] !== 0) throw new Error('Dimension 2 of "query" should be a multiple of "key"'); + m = n.dims[1]; + } else if (n.dims.length === 5) { + if (n.dims[2] !== t.numHeads || n.dims[3] !== 2 || n.dims[4] !== g) throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv'); + if (o) throw new Error('Expect "value" be none when "key" has packed kv format.'); + m = n.dims[1]; + } else { + if (n.dims[1] !== t.numHeads || n.dims[3] !== g) throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key'); + m = n.dims[2]; + } + } else { + if (r.dims.length !== 3 && r.dims.length !== 5) throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty'); + if (r.dims.length === 5 && (r.dims[2] !== t.numHeads || r.dims[3] !== 3)) throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv'); + v = 3; + } + let x = 0, T = false, E = t.kvNumHeads ? g * t.kvNumHeads : p; + if (o && o.dims.length > 0) { + if (o.dims.length !== 3 && o.dims.length !== 4) throw new Error('Input "value" is expected to have 3 or 4 dimensions'); + if (r.dims[0] !== o.dims[0]) throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)'); + if (o.dims.length === 3) { + if (m !== o.dims[1]) throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)'); + E = o.dims[2]; + } else { + if (m !== o.dims[2]) throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)'); + E = o.dims[1] * o.dims[3], T = true; + } + } + let I = e.length > 4 ? e[5] : void 0; + if (I && I.dims.length !== 1 && I.dims[0] !== d) throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size'); + return { batchSize: d, sequenceLength: c, pastSequenceLength: f, kvSequenceLength: m, totalSequenceLength: -1, maxSequenceLength: -1, inputHiddenSize: 0, hiddenSize: p, vHiddenSize: E, headSize: g, vHeadSize: Math.floor(E / t.kvNumHeads), numHeads: t.numHeads, kvNumHeads: t.kvNumHeads, nReps: t.numHeads / t.kvNumHeads, pastPresentShareBuffer: false, maskType: x, scale: t.scale, broadcastResPosBias: false, passPastInKv: T, qkvFormat: v }; + }, dh = J({ perm: [0, 2, 1, 3] }), Gd = (e, t, r) => { + let n = t, o = r.kvNumHeads; + return t.dims.length === 3 && r.kvSequenceLength !== 0 && (n = t.reshape([r.batchSize, r.kvSequenceLength, o, r.headSize]), n = e.compute(Ee(n, dh.perm), { inputs: [n], outputs: [-1] })[0]), n; + }, lh = (e, t, r, n) => { + let o = 7, i = ["type", "type"], a = [e * t], u = e * t, d = [{ type: 12, data: u }, { type: 12, data: t }, { type: 12, data: e }], c = (p) => { + let m = P("seq_lens", r.dataType, r.dims), f = P("total_seq_lens", n.dataType, n.dims), b = M("pos_ids", o, a), g = [{ name: "output_size", type: "u32" }, { name: "sequence_length", type: "u32" }, { name: "batch_size", type: "u32" }]; + return ` + ${p.registerUniforms(g).declareVariables(m, f, b)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let total_sequence_length = u32(${f.getByOffset("0")}); + let is_subsequent_prompt = uniforms.sequence_length > 1 && uniforms.sequence_length != total_sequence_length; + let is_first_prompt = !is_subsequent_prompt && uniforms.sequence_length == total_sequence_length; + let batch_idx = global_idx / uniforms.sequence_length; + let sequence_idx = i32(global_idx % uniforms.sequence_length); + var pos_id: i32 = 0; + let seqlen = ${m.getByOffset("batch_idx")}; + let total_seqlen = seqlen + 1; + if (is_first_prompt) { + if (sequence_idx < total_seqlen) { + pos_id = sequence_idx; + } else { + pos_id = 1; + } + ${b.setByOffset("global_idx", "pos_id")} + } else if (is_subsequent_prompt) { + let past_seqlen = total_seqlen - i32(uniforms.sequence_length); + if (past_seqlen + sequence_idx < total_seqlen) { + pos_id = past_seqlen + sequence_idx; + } else { + pos_id = 1; + } + ${b.setByOffset("global_idx", "pos_id")} + } else if (global_idx < uniforms.batch_size) { + ${b.setByOffset("global_idx", "seqlen")} + }; + } + `; + }; + return { name: "GeneratePositionIds", shaderCache: { hint: `${e};${t}`, inputDependencies: i }, getRunData: () => ({ outputs: [{ dims: a, dataType: o }], dispatchGroup: { x: Math.ceil(u / 64) }, programUniforms: d }), getShaderSource: c }; + }, Hd = (e, t) => { + let r = uh(e.inputs, t); + if (e.inputs[0].dims.length === 5) throw new Error("Packed QKV is not implemented"); + if (e.inputs[1]?.dims.length === 5) throw new Error("Packed KV is not implemented"); + let n = e.inputs[0], o = e.inputs[1] && e.inputs[1].dims.length > 0 ? e.inputs[1] : void 0, i = e.inputs[2] && e.inputs[2].dims.length > 0 ? e.inputs[2] : void 0, a = e.inputs[3] && e.inputs[3].dims.length !== 0 ? e.inputs[3] : void 0, u = e.inputs[4] && e.inputs[4].dims.length !== 0 ? e.inputs[4] : void 0, d = e.inputs.length > 4 ? e.inputs[5] : void 0, c = e.inputs.length > 5 ? e.inputs[6] : void 0, p = r.kvNumHeads ? r.kvNumHeads : r.numHeads, m = J({ axis: 2, numOutputs: 3, splitSizes: [r.numHeads * r.headSize, p * r.headSize, p * r.headSize] }), [f, b, g] = !o && !i ? e.compute(xo([n], m), { inputs: [n], outputs: [-1, -1, -1] }) : [n, o, i], _, S; + if (t.doRotary) { + let T = e.compute(lh(r.batchSize, r.sequenceLength, d, c), { inputs: [d, c], outputs: [-1] })[0], E = e.inputs[7], I = e.inputs[8], z = J({ interleaved: t.rotaryInterleaved !== 0, numHeads: r.numHeads, rotaryEmbeddingDim: 0, scale: t.scale }), O = [f, T, E, I], D = [-1]; + _ = e.compute(tn(O, z), { inputs: O, outputs: D })[0], O.splice(0, 1, b); + let L = J({ interleaved: t.rotaryInterleaved !== 0, numHeads: r.kvNumHeads, rotaryEmbeddingDim: 0, scale: t.scale }); + S = e.compute(tn(O, L), { inputs: O, outputs: D })[0]; + } + let $ = er(e, r.batchSize, r.numHeads, r.sequenceLength, r.headSize, t.doRotary ? _ : f, void 0, 0), v = Gd(e, t.doRotary ? S : b, r), x = Gd(e, g, r); + Rt(e, $, v, x, void 0, void 0, a, u, void 0, r, d, c); + }; + }); + var qd; + var ch; + var ph; + var jd; + var Kd = U(() => { + "use strict"; + ee(); + ne(); + st(); + ie(); + qd = (e, t, r, n, o, i, a, u) => { + let d = ce(i), c = d === 1 ? "f32" : `vec${d}f`, p = d === 1 ? "vec2f" : `mat2x${d}f`, m = o * a, f = 64; + m === 1 && (f = 256); + let b = [o, a, i / d], g = [o, a, 2], _ = ["rank", "type", "type"], S = []; + S.push(...N(b, g)); + let $ = (v) => { + let x = P("x", t.dataType, 3, d), T = P("scale", r.dataType, r.dims), E = P("bias", n.dataType, n.dims), I = M("output", 1, 3, 2), z = [x, T, E, I]; + return ` + var workgroup_shared : array<${p}, ${f}>; + const workgroup_size = ${f}u; + ${v.declareVariables(...z)} + ${v.mainStart(f)} + let batch = workgroup_index / uniforms.x_shape[1]; + let channel = workgroup_index % uniforms.x_shape[1]; + let hight = uniforms.x_shape[2]; + // initialize workgroup memory + var sum = ${c}(0); + var squared_sum = ${c}(0); + for (var h = local_idx; h < hight; h += workgroup_size) { + let value = ${c}(${x.get("batch", "channel", "h")}); + sum += value; + squared_sum += value * value; + } + workgroup_shared[local_idx] = ${p}(sum, squared_sum); + workgroupBarrier(); + + for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { + if (local_idx < currSize) { + workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; + } + workgroupBarrier(); + } + if (local_idx == 0) { + let sum_final = ${He("workgroup_shared[0][0]", d)} / f32(hight * ${d}); + let squared_sum_final = ${He("workgroup_shared[0][1]", d)} / f32(hight * ${d}); + + let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${u})); + let channel_scale = inv_std_dev * f32(scale[channel]); + let channel_shift = f32(bias[channel]) - sum_final * channel_scale; + output[workgroup_index] = vec2f(channel_scale, channel_shift); + } + }`; + }; + return e.compute({ name: "InstanceNormComputeChannelScaleShift", shaderCache: { hint: `${d};${u};${f}`, inputDependencies: _ }, getRunData: () => ({ outputs: [{ dims: g, dataType: 1 }], dispatchGroup: { x: m }, programUniforms: S }), getShaderSource: $ }, { inputs: [t, r, n], outputs: [-1] })[0]; + }, ch = (e, t, r) => { + let n = t[0].dims, o = n, i = 2, a = n[0], u = n[1], d = k.sizeFromDimension(n, i), c = ce(d), p = k.size(o) / c, m = qd(e, t[0], t[1], t[2], a, d, u, r.epsilon), f = [a, u, d / c], b = [a, u], g = ["type", "none"], _ = (S) => { + let $ = P("x", t[0].dataType, f.length, c), v = P("scale_shift", 1, b.length, 2), x = M("output", t[0].dataType, f.length, c), T = [$, v, x]; + return ` + ${S.registerUniform("output_size", "u32").declareVariables(...T)} + ${S.mainStart()} + ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let outputIndices = ${x.offsetToIndices("global_idx")}; + let batch = outputIndices[0]; + let channel = outputIndices[1]; + let scale_shift = ${v.getByIndices("vec2(batch, channel)")}; + let value = ${$.getByOffset("global_idx")} * ${x.type.value}(scale_shift.x) + ${x.type.value}(scale_shift.y); + ${x.setByOffset("global_idx", "value")}; + }`; + }; + e.compute({ name: "InstanceNormalization", shaderCache: { hint: `${c}`, inputDependencies: g }, getRunData: () => ({ outputs: [{ dims: o, dataType: t[0].dataType }], dispatchGroup: { x: Math.ceil(p / 64) }, programUniforms: [{ type: 12, data: p }, ...N(f, b, f)] }), getShaderSource: _ }, { inputs: [t[0], m] }); + }, ph = (e, t, r) => { + let n = t[0].dims, o = n, i = n[0], a = n[n.length - 1], u = k.sizeFromDimension(n, 1) / a, d = ce(a), c = k.size(o) / d, p = [{ type: 12, data: u }, { type: 12, data: Math.floor(a / d) }], m = ["type", "type"], f = false, b = [0, n.length - 1]; + for (let $ = 0; $ < n.length - 2; $++) f = f || n[$ + 1] !== 1, b.push($ + 1); + f = f && n[n.length - 1] !== 1; + let g = f ? e.compute(Ee(e.inputs[0], b), { inputs: [e.inputs[0]], outputs: [-1] })[0] : e.inputs[0].reshape(Array.from({ length: n.length }, ($, v) => n[b[v]])), _ = qd(e, g, t[1], t[2], i, u, a, r.epsilon), S = ($) => { + let v = be(t[0].dataType), x = d === 1 ? "vec2f" : `mat${d}x2f`, T = (z) => { + let O = z === 0 ? "x" : "y", D = d === 1 ? "f32" : `vec${d}f`; + switch (d) { + case 1: + return `${v}(${D}(scale.${O}))`; + case 2: + return `vec2<${v}>(${D}(scale[0].${O}, scale[1].${O}))`; + case 4: + return `vec4<${v}>(${D}(scale[0].${O}, scale[1].${O}, scale[2].${O}, scale[3].${O}))`; + default: + throw new Error(`Not supported compoents ${d}`); + } + }, E = P("input", t[0].dataType, t[0].dims, d), I = M("output", t[0].dataType, o, d); + return ` + @group(0) @binding(0) var input : array<${E.type.storage}>; + @group(0) @binding(1) var scale_input : array<${x}>; + @group(0) @binding(2) var output : array<${I.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${$.mainStart()} + let current_image_number = global_idx / (uniforms.C * uniforms.H); + let current_channel_number = global_idx % uniforms.C; + + let scale_offset = current_image_number * uniforms.C + current_channel_number; + let scale = scale_input[scale_offset]; + output[global_idx] = fma(input[global_idx], ${T(0)}, ${T(1)}); + }`; + }; + e.compute({ name: "InstanceNormalizationNHWC", shaderCache: { hint: `${d}`, inputDependencies: m }, getRunData: () => ({ outputs: [{ dims: o, dataType: t[0].dataType }], dispatchGroup: { x: Math.ceil(c / 64) }, programUniforms: p }), getShaderSource: S }, { inputs: [t[0], _] }); + }, jd = (e, t) => { + t.format === "NHWC" ? ph(e, e.inputs, t) : ch(e, e.inputs, t); + }; + }); + var mh; + var fh; + var Zd; + var Qd = U(() => { + "use strict"; + ee(); + ne(); + ie(); + mh = (e) => { + if (!e || e.length < 2) throw new Error("layerNorm requires at least 2 inputs."); + }, fh = (e, t, r) => { + let n = t.simplified, o = e[0].dims, i = e[1], a = !n && e[2], u = o, d = k.normalizeAxis(t.axis, o.length), c = k.sizeToDimension(o, d), p = k.sizeFromDimension(o, d), m = k.size(i.dims), f = a ? k.size(a.dims) : 0; + if (m !== p || a && f !== p) throw new Error(`Size of X.shape()[axis:] == ${p}. + Size of scale and bias (if provided) must match this. + Got scale size of ${m} and bias size of ${f}`); + let b = []; + for (let E = 0; E < o.length; ++E) E < d ? b.push(o[E]) : b.push(1); + let g = ce(p), _ = ["type", "type"], S = [{ type: 12, data: c }, { type: 1, data: p }, { type: 12, data: Math.floor(p / g) }, { type: 1, data: t.epsilon }]; + a && _.push("type"); + let $ = r > 1, v = r > 2, x = (E) => { + let I = be(e[0].dataType), z = [P("x", e[0].dataType, e[0].dims, g), P("scale", i.dataType, i.dims, g)]; + a && z.push(P("bias", a.dataType, a.dims, g)), z.push(M("output", e[0].dataType, u, g)), $ && z.push(M("mean_data_output", 1, b)), v && z.push(M("inv_std_output", 1, b)); + let O = [{ name: "norm_count", type: "u32" }, { name: "norm_size", type: "f32" }, { name: "norm_size_vectorized", type: "u32" }, { name: "epsilon", type: "f32" }]; + return ` + ${E.registerUniforms(O).declareVariables(...z)} + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${ao("f32", g)}; + var mean_square_vector = ${ao("f32", g)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${Ct(I, g, "x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${He("mean_vector", g)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${He("mean_square_vector", g)} / uniforms.norm_size ${n ? "" : "- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${Ct(I, g, "x[j + offset]")}; + let f32scale = ${Ct(I, g, "scale[j]")}; + output[j + offset] = ${z[0].type.value}((f32input ${n ? "" : "- mean"}) * inv_std_dev * f32scale + ${a ? `+ ${Ct(I, g, "bias[j]")}` : ""} + ); + } + + ${$ ? "mean_data_output[global_idx] = mean" : ""}; + ${v ? "inv_std_output[global_idx] = inv_std_dev" : ""}; + }`; + }, T = [{ dims: u, dataType: e[0].dataType }]; + return $ && T.push({ dims: b, dataType: 1 }), v && T.push({ dims: b, dataType: 1 }), { name: "LayerNormalization", shaderCache: { hint: `${g};${r};${n}`, inputDependencies: _ }, getRunData: () => ({ outputs: T, dispatchGroup: { x: Math.ceil(c / 64) }, programUniforms: S }), getShaderSource: x }; + }, Zd = (e, t) => { + mh(e.inputs), e.compute(fh(e.inputs, t, e.outputCount)); + }; + }); + var hh; + var Yd; + var Xd = U(() => { + "use strict"; + ne(); + Yr(); + Xr(); + hh = (e) => { + if (!e || e.length !== 2) throw new Error("MatMul requires 2 inputs."); + if (e[0].dims[e[0].dims.length - 1] !== e[1].dims[e[1].dims.length - 2]) throw new Error("shared dimension does not match."); + }, Yd = (e) => { + hh(e.inputs); + let t = Je.calcShape(e.inputs[0].dims, e.inputs[1].dims, true); + if (!t) throw new Error("Can't use matmul on the given tensors"); + let r = t[t.length - 1], n = e.inputs[0].dims[e.inputs[0].dims.length - 1]; + if (r < 8 && n < 8) e.compute(Qr(e.inputs, { activation: "" }, t)); + else { + let o = t[t.length - 2], i = k.size(e.inputs[0].dims.slice(0, -2)), a = k.size(e.inputs[1].dims.slice(0, -2)); + if (i !== 1 && o === 1 && a === 1) { + let u = e.inputs[0].reshape([1, i, n]), d = e.inputs[1].reshape([1, n, r]), c = [1, i, r], p = [u, d]; + e.compute(Jt(p, { activation: "" }, t, c), { inputs: p }); + } else e.compute(Jt(e.inputs, { activation: "" }, t)); + } + }; + }); + var gh; + var bh; + var yh; + var Jd; + var el; + var tl = U(() => { + "use strict"; + ee(); + ne(); + Se(); + ie(); + gh = (e, t) => { + if (e.length < 3 || e.length > 4) throw new Error("MatMulNBits requires 3 or 4 inputs"); + let r = e[0], n = r.dims.length; + if (r.dims[n - 1] !== t.k) throw new Error("The last dim of input shape does not match the k value"); + let o = Math.floor((t.k + t.blockSize - 1) / t.blockSize), i = t.blockSize / 8 * t.bits, a = e[1]; + if (!k.areEqual(a.dims, [t.n, o, i])) throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize"); + let d = e[2].dims; + if (k.size(d) !== t.n * o) throw new Error("scales input size error."); + if (e.length === 4) { + let p = e[3].dims, m = t.bits > 4 ? t.n * o : t.n * Math.floor((o + 1) / 2); + if (k.size(p) !== m) throw new Error("zeroPoints input size error."); + } + }, bh = (e, t) => { + let r = e[0].dims, n = r.length, o = r[n - 2], i = t.k, a = t.n, u = r.slice(0, n - 2), d = k.size(u), p = e[1].dims[2] / 4, m = e[0].dataType, f = ce(t.k), b = ce(p), g = ce(a), _ = u.concat([o, a]), S = o > 1 && a / g % 2 === 0 ? 2 : 1, $ = k.size(_) / g / S, v = 64, x = [], T = [d, o, i / f], E = k.convertShape(e[1].dims).slice(); + E.splice(-1, 1, p / b), x.push(...N(T)), x.push(...N(E)), x.push(...N(e[2].dims)), e.length === 4 && x.push(...N(k.convertShape(e[3].dims))); + let I = [d, o, a / g]; + x.push(...N(I)); + let z = (O) => { + let D = T.length, L = P("a", e[0].dataType, D, f), q = P("b", 12, E.length, b), Q = P("scales", e[2].dataType, e[2].dims.length), W = [L, q, Q], Z = e.length === 4 ? P("zero_points", 12, e[3].dims.length) : void 0; + Z && W.push(Z); + let we = I.length, H = M("output", e[0].dataType, we, g), j = be(e[0].dataType), te = (() => { + switch (f) { + case 1: + return `array<${j}, 8>`; + case 2: + return `mat4x2<${j}>`; + case 4: + return `mat2x4<${j}>`; + default: + throw new Error(`${f}-component is not supported.`); + } + })(), X = () => { + let ye = ` + // reuse a data + var input_offset = ${L.indicesToOffset(`${L.type.indices}(batch, row, word_offset)`)}; + var a_data: ${te}; + for (var j: u32 = 0; j < ${8 / f}; j++) { + a_data[j] = ${L.getByOffset("input_offset")}; + input_offset++; + } + `; + for (let re = 0; re < g * S; re++) ye += ` + b_value = ${b === 1 ? `b${re}_data` : `b${re}_data[i]`}; + b_value_lower = unpack4xU8(b_value & b_mask); + b_value_upper = unpack4xU8((b_value >> 4) & b_mask); + b_quantized_values = ${te}(${Array.from({ length: 4 }, (C, V) => `${j}(b_value_lower[${V}]), ${j}(b_value_upper[${V}])`).join(", ")}); + b_dequantized_values = ${f === 1 ? `${te}(${Array.from({ length: 8 }, (C, V) => `(b_quantized_values[${V}] - ${Z ? `zero_point${re}` : "zero_point"}) * scale${re}`).join(", ")});` : `(b_quantized_values - ${te}(${Array(8).fill(`${Z ? `zero_point${re}` : "zero_point"}`).join(",")})) * scale${re};`}; + workgroup_shared[local_id.x * ${S} + ${Math.floor(re / g)}]${g > 1 ? `[${re % g}]` : ""} += ${Array.from({ length: 8 / f }, (C, V) => `${f === 1 ? `a_data[${V}] * b_dequantized_values[${V}]` : `dot(a_data[${V}], b_dequantized_values[${V}])`}`).join(" + ")}; + `; + return ye; + }, ue = () => { + let ye = ` + var col_index = col * ${g}; + ${Z ? ` + let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; + var zero_point_byte_count: u32; + var zero_point_word_index: u32; + var zero_point_byte_offset: u32; + let zero_point_nibble_offset: u32 = block & 0x1u; + var zero_point_bits_offset: u32; + var zero_point_word: u32;` : ` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${j}(8);`} + `; + for (let re = 0; re < g * S; re++) ye += ` + let scale${re} = ${Q.getByOffset("col_index * nBlocksPerCol + block")}; + ${Z ? ` + zero_point_byte_count = col_index * zero_point_bytes_per_col + (block >> 0x1u); + zero_point_word_index = zero_point_byte_count >> 0x2u; + zero_point_byte_offset = zero_point_byte_count & 0x3u; + zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + zero_point_word = ${Z.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point${re} = ${j}((zero_point_word) & 0xFu);` : ""} + col_index += 1;`; + return ye; + }, he = () => { + let ye = `col_index = col * ${g};`; + for (let re = 0; re < g * S; re++) ye += ` + let b${re}_data = ${q.getByIndices(`${q.type.indices}(col_index, block, word)`)}; + col_index += 1;`; + return ye += ` + var b_value: u32; + let b_mask: u32 = 0x0F0F0F0Fu; + var b_value_lower: vec4; + var b_value_upper: vec4; + var b_quantized_values: ${te}; + var b_dequantized_values: ${te};`, ye; + }; + return ` + var workgroup_shared: array<${H.type.value}, ${S * v}>; + ${O.declareVariables(...W, H)} + ${O.mainStart([v, 1, 1])} + let output_indices = ${H.offsetToIndices(`(global_idx / ${v}) * ${S}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let nBlocksPerCol = uniforms.b_shape[1]; + + for (var block = local_id.x; block < nBlocksPerCol; block += ${v}) { + //process one block + var word_offset: u32 = block * ${t.blockSize / f}; + ${ue()} + for (var word: u32 = 0; word < ${p}; word += ${b}) { + ${he()} + for (var i: u32 = 0; i < ${b}; i++) { + ${X()} + word_offset += ${8 / f}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${S}) { + var output_value: ${H.type.value} = ${H.type.value}(0); + var workgroup_shared_offset: u32 = local_id.x; + for (var b: u32 = 0u; b < ${v}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${S}; + } + ${H.setByIndices(`${H.type.indices}(batch, row, col + local_id.x)`, "output_value")}; + } + }`; + }; + return { name: "MatMulNBits", shaderCache: { hint: `${t.blockSize};${t.bits};${f};${b};${g};${S};${v}`, inputDependencies: Array(e.length).fill("rank") }, getRunData: () => ({ outputs: [{ dims: _, dataType: m }], dispatchGroup: { x: $ }, programUniforms: x }), getShaderSource: z }; + }, yh = (e, t) => { + let r = e[0].dims, n = r.length, o = r[n - 2], i = t.k, a = t.n, u = r.slice(0, n - 2), d = k.size(u), p = e[1].dims[2] / 4, m = e[0].dataType, f = ce(t.k), b = ce(p), g = u.concat([o, a]), _ = 128, S = a % 8 === 0 ? 8 : a % 4 === 0 ? 4 : 1, $ = _ / S, v = $ * b * 8, x = v / f, T = v / t.blockSize, E = k.size(g) / S, I = [], z = [d, o, i / f], O = k.convertShape(e[1].dims).slice(); + O.splice(-1, 1, p / b), I.push(...N(z)), I.push(...N(O)), I.push(...N(e[2].dims)), e.length === 4 && I.push(...N(k.convertShape(e[3].dims))); + let D = [d, o, a]; + I.push(...N(D)); + let L = (q) => { + let Q = z.length, W = P("a", e[0].dataType, Q, f), Z = P("b", 12, O.length, b), we = P("scales", e[2].dataType, e[2].dims.length), H = [W, Z, we], j = e.length === 4 ? P("zero_points", 12, e[3].dims.length) : void 0; + j && H.push(j); + let te = D.length, X = M("output", e[0].dataType, te), ue = be(e[0].dataType), he = () => { + switch (f) { + case 1: + return ` + let a_data0 = vec4<${ue}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); + let a_data1 = vec4<${ue}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`; + case 2: + return ` + let a_data0 = vec4<${ue}>(sub_a[word_offset], sub_a[word_offset + 1]); + let a_data1 = vec4<${ue}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`; + case 4: + return ` + let a_data0 = sub_a[word_offset]; + let a_data1 = sub_a[word_offset + 1];`; + default: + throw new Error(`${f}-component is not supported.`); + } + }; + return ` + var sub_a: array<${W.type.value}, ${x}>; + var inter_results: array, ${S}>; + ${q.declareVariables(...H, X)} + ${q.mainStart([$, S, 1])} + let output_indices = ${X.offsetToIndices(`workgroup_index * ${S}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let n_blocks_per_col = uniforms.b_shape[1]; + let num_tiles = (n_blocks_per_col - 1) / ${T} + 1; + + // Loop over shared dimension. + for (var tile: u32 = 0; tile < num_tiles; tile += 1) { + let a_col_start = tile * ${x}; + // load one tile A data into shared memory. + for (var a_offset = local_idx; a_offset < ${x}; a_offset += ${_}) + { + let a_col = a_col_start + a_offset; + if (a_col < uniforms.a_shape[2]) + { + sub_a[a_offset] = ${W.getByIndices(`${W.type.indices}(batch, row, a_col)`)}; + } else { + sub_a[a_offset] = ${W.type.value}(0); + } + } + workgroupBarrier(); + + // each thread process one block + let b_row = col + local_id.y; + let block = tile * ${T} + local_id.x; + ${j ? ` + let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2; + let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u); + let zero_point_word_index = zero_point_byte_count >> 0x2u; + let zero_point_byte_offset = zero_point_byte_count & 0x3u; + let zero_point_nibble_offset: u32 = block & 0x1u; + let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + let zero_point_word = ${j.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point = ${ue}((zero_point_word) & 0xFu);` : ` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${ue}(8);`} + let scale = ${we.getByOffset("b_row * n_blocks_per_col + block")}; + let b_data = ${Z.getByIndices(`${Z.type.indices}(b_row, block, 0)`)}; + var word_offset = local_id.x * ${t.blockSize / f}; + for (var i: u32 = 0; i < ${b}; i++) { + ${he()} + let b_value = ${b === 1 ? "b_data" : "b_data[i]"}; + let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu); + let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu); + let b_quantized_values = mat2x4<${ue}>(${Array.from({ length: 4 }, (ye, re) => `${ue}(b_value_lower[${re}]), ${ue}(b_value_upper[${re}])`).join(", ")}); + let b_dequantized_values = (b_quantized_values - mat2x4<${ue}>(${Array(8).fill("zero_point").join(",")})) * scale; + inter_results[local_id.y][local_id.x] += ${Array.from({ length: 2 }, (ye, re) => `${`dot(a_data${re}, b_dequantized_values[${re}])`}`).join(" + ")}; + word_offset += ${8 / f}; + } + workgroupBarrier(); + } + + if (local_idx < ${S}) { + var output_value: ${X.type.value} = ${X.type.value}(0); + for (var b = 0u; b < ${$}; b++) { + output_value += inter_results[local_idx][b]; + } + if (col + local_idx < uniforms.output_shape[2]) + { + ${X.setByIndices(`${X.type.indices}(batch, row, col + local_idx)`, "output_value")} + } + } + }`; + }; + return { name: "BlockwiseMatMulNBits32", shaderCache: { hint: `${t.blockSize};${f};${b};${$};${S}`, inputDependencies: Array(e.length).fill("rank") }, getRunData: () => ({ outputs: [{ dims: g, dataType: m }], dispatchGroup: { x: E }, programUniforms: I }), getShaderSource: L }; + }, Jd = (e, t) => { + gh(e.inputs, t), t.blockSize === 32 && e.adapterInfo.isVendor("intel") && e.adapterInfo.isArchitecture("gen-12lp") ? e.compute(yh(e.inputs, t)) : e.compute(bh(e.inputs, t)); + }, el = (e) => J(e); + }); + var _h; + var wh; + var vh; + var $h; + var xh; + var Sh; + var Th; + var Ih; + var rl; + var nl = U(() => { + "use strict"; + ee(); + ne(); + ie(); + _h = (e) => { + if (!e || e.length < 1) throw new Error("Too few inputs"); + if (e[0].dataType !== 1 && e[0].dataType !== 10) throw new Error("Input type must be float or float16."); + if (e.length >= 2) { + let t = e[0].dims.length * 2 === e[1].dims[0]; + if (e.length === 4 && (t = e[3].dims[0] * 2 === e[1].dims[0]), !t) throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes]."); + } + }, wh = (e, t, r) => { + let n = ""; + for (let o = t - 1; o >= 0; --o) n += ` + k = i32(${e.indicesGet("indices", o)}) - ${F("uniforms.pads", o, r)}; + if (k < 0) { + break; + } + if (k >= i32(${F("uniforms.x_shape", o, t)})) { + break; + } + offset += k * i32(${F("uniforms.x_strides", o, t)}); + `; + return ` + value = ${e.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + } + `; + }, vh = (e, t, r) => { + let n = ""; + for (let o = t - 1; o >= 0; --o) n += ` + k = i32(${e.indicesGet("indices", o)}) - ${F("uniforms.pads", o, r)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${F("uniforms.x_shape", o, t)}) - 1); + k = k % _2n_1; + if(k >= i32(${F("uniforms.x_shape", o, t)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${F("uniforms.x_strides", o, t)}); + `; + return ` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `; + }, $h = (e, t, r) => { + let n = ""; + for (let o = t - 1; o >= 0; --o) n += ` + k = i32(${e.indicesGet("indices", o)}) - ${F("uniforms.pads", o, r)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${F("uniforms.x_shape", o, t)})) { + k = i32(${F("uniforms.x_shape", o, t)}) - 1; + } + offset += k * i32(${F("uniforms.x_strides", o, t)}); + `; + return ` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `; + }, xh = (e, t, r) => { + let n = ""; + for (let o = t - 1; o >= 0; --o) n += ` + k = i32(${e.indicesGet("indices", o)}) - ${F("uniforms.pads", o, r)}; + if (k < 0) { + k += i32(${F("uniforms.x_shape", o, t)}]); + } + if (k >= i32(${F("uniforms.x_shape", o, t)})) { + k -= i32(${F("uniforms.x_shape", o, t)}); + } + offset += k * i32(${F("uniforms.x_strides", o, t)}); + `; + return ` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `; + }, Sh = (e, t, r) => { + switch (r.mode) { + case 0: + return wh(e, t, r.pads.length); + case 1: + return vh(e, t, r.pads.length); + case 2: + return $h(e, t, r.pads.length); + case 3: + return xh(e, t, r.pads.length); + default: + throw new Error("Invalid mode"); + } + }, Th = (e, t) => { + let r = k.padShape(e[0].dims.slice(), t.pads), n = e[0].dims, o = k.size(r), i = [{ type: 12, data: o }, { type: 6, data: t.pads }], a = e.length >= 3 && e[2].data; + t.mode === 0 && i.push({ type: a ? e[2].dataType : 1, data: t.value }), i.push(...N(e[0].dims, r)); + let u = ["rank"], d = (c) => { + let p = M("output", e[0].dataType, r.length), m = P("x", e[0].dataType, n.length), f = m.type.value, b = Sh(p, n.length, t), g = [{ name: "output_size", type: "u32" }, { name: "pads", type: "i32", length: t.pads.length }]; + return t.mode === 0 && g.push({ name: "constant_value", type: a ? f : "f32" }), ` + ${c.registerUniforms(g).declareVariables(m, p)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${p.offsetToIndices("global_idx")}; + + var value = ${f}(0); + ${b} + output[global_idx] = value; + }`; + }; + return { name: "Pad", shaderCache: { hint: `${t.mode}${a}`, inputDependencies: u }, getRunData: () => ({ outputs: [{ dims: r, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(k.size(r) / 64) }, programUniforms: i }), getShaderSource: d }; + }, Ih = (e, t) => { + if (e.length > 1) { + let r = e[1].getBigInt64Array(), n = e.length >= 3 && e[2].data ? e[2].dataType === 10 ? e[2].getUint16Array()[0] : e[2].getFloat32Array()[0] : 0, o = e[0].dims.length, i = new Int32Array(2 * o).fill(0); + if (e.length >= 4) { + let u = e[3].getBigInt64Array(); + for (let d = 0; d < u.length; d++) i[Number(u[d])] = Number(r[d]), i[Number(u[d]) + o] = Number(r[d + u.length]); + } else r.forEach((u, d) => i[Number(d)] = Number(u)); + let a = []; + return i.forEach((u) => a.push(u)), { mode: t.mode, value: n, pads: a }; + } else return t; + }, rl = (e, t) => { + _h(e.inputs); + let r = Ih(e.inputs, t); + e.compute(Th(e.inputs, r), { inputs: [0] }); + }; + }); + var rn; + var ol; + var il; + var al; + var sl; + var Ch; + var Ah; + var ul; + var dl; + var ll; + var cl; + var pl; + var ml; + var fl; + var hl; + var gl; + var bl; + var yl; + var _l; + var wl = U(() => { + "use strict"; + We(); + ee(); + ne(); + ie(); + rn = (e) => { + if (ge.webgpu.validateInputContent && (!e || e.length !== 1)) throw new Error("Pool ops requires 1 input."); + }, ol = (e, t, r) => { + let n = t.format === "NHWC", o = e.dims.slice(); + n && o.splice(1, 0, o.pop()); + let i = Object.hasOwnProperty.call(t, "dilations"), a = t.kernelShape.slice(), u = t.strides.slice(), d = i ? t.dilations.slice() : [], c = t.pads.slice(); + Tt.adjustPoolAttributes(r, o, a, u, d, c); + let p = Tt.computePoolOutputShape(r, o, u, d, a, c, t.autoPad), m = Object.assign({}, t); + i ? Object.assign(m, { kernelShape: a, strides: u, pads: c, dilations: d, cacheKey: t.cacheKey }) : Object.assign(m, { kernelShape: a, strides: u, pads: c, cacheKey: t.cacheKey }); + let f = p.slice(); + return f.push(f.splice(1, 1)[0]), [m, n ? f : p]; + }, il = (e, t) => { + let r = t.format === "NHWC", n = k.size(e), o = k.size(t.kernelShape), i = [{ type: 12, data: n }, { type: 12, data: o }], a = [{ name: "outputSize", type: "u32" }, { name: "kernelSize", type: "u32" }]; + if (t.kernelShape.length <= 2) { + let u = t.kernelShape[t.kernelShape.length - 1], d = t.strides[t.strides.length - 1], c = t.pads[t.pads.length / 2 - 1], p = t.pads[t.pads.length - 1], m = !!(c + p); + i.push({ type: 12, data: u }, { type: 12, data: d }, { type: 12, data: c }, { type: 12, data: p }), a.push({ name: "kw", type: "u32" }, { name: "sw", type: "u32" }, { name: "pwStart", type: "u32" }, { name: "pwEnd", type: "u32" }); + let f = false; + if (t.kernelShape.length === 2) { + let b = t.kernelShape[t.kernelShape.length - 2], g = t.strides[t.strides.length - 2], _ = t.pads[t.pads.length / 2 - 2], S = t.pads[t.pads.length - 2]; + f = !!(_ + S), i.push({ type: 12, data: b }, { type: 12, data: g }, { type: 12, data: _ }, { type: 12, data: S }), a.push({ name: "kh", type: "u32" }, { name: "sh", type: "u32" }, { name: "phStart", type: "u32" }, { name: "phEnd", type: "u32" }); + } + return [i, a, true, m, f]; + } else { + if (r) throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format."); + let u = k.computeStrides(t.kernelShape); + i.push({ type: 12, data: u }, { type: 12, data: t.pads }, { type: 12, data: t.strides }), a.push({ name: "kernelStrides", type: "u32", length: u.length }, { name: "pads", type: "u32", length: t.pads.length }, { name: "strides", type: "u32", length: t.strides.length }); + let d = t.pads.reduce((c, p) => c + p); + return [i, a, !!d, false, false]; + } + }, al = (e, t, r, n, o, i, a, u, d, c, p, m) => { + let f = o.format === "NHWC", b = t.type.value, g = M("output", t.type.tensor, n); + if (o.kernelShape.length <= 2) { + let _ = "", S = "", $ = "", v = r - (f ? 2 : 1); + if (p ? _ = ` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${v}] < 0 || xIndices[${v}] + >= uniforms.x_shape[${v}]) { + pad++; + continue; + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${i} + }` : _ = ` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${i} + }`, o.kernelShape.length === 2) { + let T = r - (f ? 3 : 2); + m ? S = ` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${T}] = indices[${T}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${T}] < 0 || xIndices[${T}] >= uniforms.x_shape[${T}]) { + pad += i32(uniforms.kw); + continue; + } + ` : S = ` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${T}] = indices[${T}] * uniforms.sh - uniforms.phStart + j; + `, $ = ` + } + `; + } + return ` + ${e.registerUniforms(d).declareVariables(t, g)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${g.offsetToIndices("global_idx")}; + var xIndices = ${g.offsetToIndices("global_idx")}; + + var value = ${b}(${u}); + var pad = 0; + ${S} + ${_} + ${$} + ${a} + + output[global_idx] = value; + }`; + } else { + if (f) throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format."); + let _ = o.kernelShape.length, S = o.pads.length, $ = ""; + return c ? $ = ` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${i} + }` : $ = ` + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${i} + `, ` + ${e.registerUniforms(d).declareVariables(t, g)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${g.offsetToIndices("global_idx")}; + var xIndices = ${g.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${b}(${u}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${_ - 1}u; j++) { + offsets[j] = offset / ${F("uniforms.kernelStrides", "j", _)}; + offset -= offsets[j] * ${F("uniforms.kernelStrides", "j", _)}; + } + offsets[${_ - 1}] = offset; + + isPad = false; + for (var j = ${r - _}u; j < ${r}u; j++) { + xIndices[j] = indices[j] * ${F("uniforms.strides", `j - ${r - _}u`, _)} + + offsets[j - ${r - _}u] - ${F("uniforms.pads", "j - 2u", S)}; + ${$} + } + ${a} + + output[global_idx] = value; + }`; + } + }, sl = (e) => `${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`, Ch = (e) => `${sl(e)};${e.countIncludePad}`, Ah = (e) => `${sl(e)};${e.storageOrder};${e.dilations}`, ul = (e) => ({ format: e.format, autoPad: ["NOTSET", "VALID", "SAME_UPPER", "SAME_LOWER"][e.auto_pad], ceilMode: e.ceil_mode, kernelShape: e.kernel_shape, strides: e.strides, pads: e.pads }), dl = (e, t, r, n) => { + let [o, i] = ol(t, n, r), a = P("x", t.dataType, t.dims.length), u = a.type.value, d = "value += x_val;", c = ""; + o.countIncludePad ? c += `value /= ${u}(uniforms.kernelSize);` : c += `value /= ${u}(i32(uniforms.kernelSize) - pad);`; + let [p, m, f, b, g] = il(i, o); + p.push(...N(t.dims, i)); + let _ = ["rank"]; + return { name: e, shaderCache: { hint: `${n.cacheKey};${f};${b};${g}`, inputDependencies: _ }, getRunData: () => ({ outputs: [{ dims: i, dataType: t.dataType }], dispatchGroup: { x: Math.ceil(k.size(i) / 64) }, programUniforms: p }), getShaderSource: (S) => al(S, a, t.dims.length, i.length, o, d, c, 0, m, f, b, g) }; + }, ll = (e) => { + let t = e.count_include_pad !== 0, r = ul(e); + if (r.ceilMode !== 0) throw new Error("using ceil() in shape computation is not yet supported for AveragePool"); + let n = { countIncludePad: t, ...r, cacheKey: "" }; + return { ...n, cacheKey: Ch(n) }; + }, cl = (e, t) => { + rn(e.inputs), e.compute(dl("AveragePool", e.inputs[0], false, t)); + }, pl = { autoPad: "", ceilMode: 0, countIncludePad: false, kernelShape: [], strides: [], pads: [], storageOrder: 0, dilations: [] }, ml = (e) => { + let t = e.format; + return { format: t, ...pl, cacheKey: t }; + }, fl = (e, t) => { + rn(e.inputs), e.compute(dl("GlobalAveragePool", e.inputs[0], true, t)); + }, hl = (e, t, r, n) => { + let [o, i] = ol(t, n, r), a = ` + value = max(x_val, value); + `, u = "", d = P("x", t.dataType, t.dims.length), c = ["rank"], [p, m, f, b, g] = il(i, o); + return p.push(...N(t.dims, i)), { name: e, shaderCache: { hint: `${n.cacheKey};${f};${b};${g}`, inputDependencies: c }, getRunData: () => ({ outputs: [{ dims: i, dataType: t.dataType }], dispatchGroup: { x: Math.ceil(k.size(i) / 64) }, programUniforms: p }), getShaderSource: (_) => al(_, d, t.dims.length, i.length, o, a, u, t.dataType === 10 ? -65504 : -1e5, m, f, b, g) }; + }, gl = (e, t) => { + rn(e.inputs), e.compute(hl("MaxPool", e.inputs[0], false, t)); + }, bl = (e) => { + let t = e.storage_order, r = e.dilations, n = ul(e); + if (t !== 0) throw new Error("column major storage order is not yet supported for MaxPool"); + if (n.ceilMode !== 0) throw new Error("using ceil() in shape computation is not yet supported for MaxPool"); + let o = { storageOrder: t, dilations: r, ...n, cacheKey: "" }; + return { ...o, cacheKey: Ah(o) }; + }, yl = (e) => { + let t = e.format; + return { format: t, ...pl, cacheKey: t }; + }, _l = (e, t) => { + rn(e.inputs), e.compute(hl("GlobalMaxPool", e.inputs[0], true, t)); + }; + }); + var kh; + var Ph; + var vl; + var $l; + var xl = U(() => { + "use strict"; + ee(); + ne(); + Se(); + ie(); + kh = (e, t) => { + if (e.length < 2 || e.length > 3) throw new Error("DequantizeLinear requires 2 or 3 inputs."); + if (e.length === 3 && e[1].dims === e[2].dims) throw new Error("x-scale and x-zero-point must have the same shape."); + if (e.length === 3 && e[0].dataType !== e[2].dataType) throw new Error("x and x-zero-point must have the same data type."); + if (e[0].dataType === 6 && e.length > 2) throw new Error("In the case of dequantizing int32 there is no zero point."); + if (e[1].dims.length !== 0 && e[1].dims.length !== 1 && e[1].dims.length !== e[0].dims.length) throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor."); + if (e.length > 2) { + if (e[0].dataType !== e[2].dataType) throw new Error("x and x-zero-point must have the same data type."); + if (e[1].dims.length !== e[2].dims.length) throw new Error("scale and zero-point inputs must have the same rank."); + if (!e[1].dims.map((r, n) => r === e[2].dims[n]).reduce((r, n) => r && n, true)) throw new Error("scale and zero-point inputs must have the same shape."); + } + if (t.blockSize > 0) { + if (e[1].dims.length === 0 || e[1].dims.length === 1 && e[1].dims[0] === 1) throw new Error("blockSize must be set only for block quantization."); + if (!e[1].dims.map((o, i) => i === t.axis || o === e[0].dims[i]).reduce((o, i) => o && i, true)) throw new Error("For block qunatization, scale input shape to match the input shape except for the axis"); + if (e[1].dims.length !== e[0].dims.length) throw new Error("For block qunatization the scale input rank must be the same as the x rank."); + let r = e[0].dims[t.axis], n = e[1].dims[t.axis]; + if (t.blockSize < Math.ceil(r / n) || t.blockSize > Math.ceil(r / (n - 1) - 1)) throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)]."); + } + }, Ph = (e, t) => { + let r = k.normalizeAxis(t.axis, e[0].dims.length), n = e[0].dataType, o = n === 3, i = e[0].dims, a = e[1].dataType, u = k.size(i), d = n === 3 || n === 2, c = d ? [Math.ceil(k.size(e[0].dims) / 4)] : e[0].dims, p = e[1].dims, m = e.length > 2 ? e[2] : void 0, f = m ? d ? [Math.ceil(k.size(m.dims) / 4)] : m.dims : void 0, b = p.length === 0 || p.length === 1 && p[0] === 1, g = b === false && p.length === 1, _ = ce(u), S = b && (!d || _ === 4), $ = S ? _ : 1, v = S && !d ? _ : 1, x = P("input", d ? 12 : n, c.length, v), T = P("scale", a, p.length), E = m ? P("zero_point", d ? 12 : n, f.length) : void 0, I = M("output", a, i.length, $), z = [x, T]; + E && z.push(E); + let O = [c, p]; + m && O.push(f); + let D = [{ type: 12, data: u / $ }, { type: 12, data: r }, { type: 12, data: t.blockSize }, ...N(...O, i)], L = (q) => { + let Q = [{ name: "output_size", type: "u32" }, { name: "axis", type: "u32" }, { name: "block_size", type: "u32" }]; + return ` + ${q.registerUniforms(Q).declareVariables(...z, I)} + ${q.mainStart()} + ${q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${I.offsetToIndices("global_idx")}; + + // Set input x + ${d ? ` + let input = ${x.getByOffset("global_idx / 4")}; + let x_vec = ${o ? "unpack4xI8(input)" : "unpack4xU8(input)"}; + let x_value = ${$ === 1 ? "x_vec[global_idx % 4]" : "x_vec"};` : `let x_value = ${x.getByOffset("global_idx")};`}; + + // Set scale input + ${b ? `let scale_value= ${T.getByOffset("0")}` : g ? ` + let scale_index = ${I.indicesGet("output_indices", "uniforms.axis")}; + let scale_value= ${T.getByOffset("scale_index")};` : ` + var scale_indices: ${T.type.indices} = output_indices; + let index = ${T.indicesGet("scale_indices", "uniforms.axis")} / uniforms.block_size; + ${T.indicesSet("scale_indices", "uniforms.axis", "index")}; + let scale_value= ${T.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${E ? b ? d ? ` + let zero_point_input = ${E.getByOffset("0")}; + let zero_point_vec = ${o ? "unpack4xI8(zero_point_input)" : "unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]` : `let zero_point_value = ${E.getByOffset("0")}` : g ? d ? ` + let zero_point_index = ${I.indicesGet("output_indices", "uniforms.axis")}; + let zero_point_input = ${E.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${o ? "unpack4xI8(zero_point_input)" : "unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_index % 4]` : ` + let zero_point_index = ${I.indicesGet("output_indices", "uniforms.axis")}; + let zero_point_value = ${E.getByOffset("zero_point_index")};` : d ? ` + let zero_point_offset = ${T.indicesToOffset("scale_indices")}; + let zero_point_input = ${E.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${o ? "unpack4xI8(zero_point_input)" : "unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];` : `let zero_point_value = ${E.getByIndices("scale_indices")};` : `let zero_point_value = ${d ? o ? "i32" : "u32" : x.type.value}(0);`}; + // Compute and write output + ${I.setByOffset("global_idx", `${I.type.value}(x_value - zero_point_value) * scale_value`)}; + }`; + }; + return { name: "DequantizeLinear", shaderCache: { hint: t.cacheKey, inputDependencies: E ? ["rank", "rank", "rank"] : ["rank", "rank"] }, getShaderSource: L, getRunData: () => ({ outputs: [{ dims: i, dataType: a }], dispatchGroup: { x: Math.ceil(u / $ / 64), y: 1, z: 1 }, programUniforms: D }) }; + }, vl = (e, t) => { + kh(e.inputs, t), e.compute(Ph(e.inputs, t)); + }, $l = (e) => J({ axis: e.axis, blockSize: e.blockSize }); + }); + var zh; + var Oh; + var Sl; + var Tl = U(() => { + "use strict"; + We(); + ee(); + ie(); + zh = (e, t, r) => { + let n = e === t, o = e < t && r < 0, i = e > t && r > 0; + if (n || o || i) throw new Error("Range these inputs' contents are invalid."); + }, Oh = (e, t, r, n) => { + let o = Math.abs(Math.ceil((t - e) / r)), i = [o], a = o, u = [{ type: 12, data: a }, { type: n, data: e }, { type: n, data: r }, ...N(i)], d = (c) => { + let p = M("output", n, i.length), m = p.type.value, f = [{ name: "outputSize", type: "u32" }, { name: "start", type: m }, { name: "delta", type: m }]; + return ` + ${c.registerUniforms(f).declareVariables(p)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${m}(global_idx) * uniforms.delta; + }`; + }; + return { name: "Range", shaderCache: { hint: `${n}` }, getShaderSource: d, getRunData: () => ({ outputs: [{ dims: i, dataType: n }], dispatchGroup: { x: Math.ceil(a / 64) }, programUniforms: u }) }; + }, Sl = (e) => { + let t = 0, r = 0, n = 0; + e.inputs[0].dataType === 6 ? (t = e.inputs[0].getInt32Array()[0], r = e.inputs[1].getInt32Array()[0], n = e.inputs[2].getInt32Array()[0]) : e.inputs[0].dataType === 1 && (t = e.inputs[0].getFloat32Array()[0], r = e.inputs[1].getFloat32Array()[0], n = e.inputs[2].getFloat32Array()[0]), ge.webgpu.validateInputContent && zh(t, r, n), e.compute(Oh(t, r, n, e.inputs[0].dataType), { inputs: [] }); + }; + }); + var Bh; + var Il; + var Cl; + var Dh; + var Al; + var El; + var kl = U(() => { + "use strict"; + ee(); + ne(); + Se(); + ie(); + Bh = (e, t, r, n) => { + if (e !== "none" && n !== "i32" && n !== "u32" && n !== "f32") throw new Error(`Input ${n} is not supported with reduction ${e}.`); + let o = `{ + var oldValue = 0; + loop { + let newValueF32 =`, i = `; + let newValue = bitcast(newValueF32); + let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue); + if res.exchanged { + break; + } + oldValue = res.old_value; + } + }`; + switch (e) { + case "none": + return `${t}=${r};`; + case "add": + return n === "i32" || n === "u32" ? `atomicAdd(&${t}, bitcast<${n}>(${r}));` : ` + ${o}bitcast<${n}>(oldValue) + (${r})${i}`; + case "max": + return n === "i32" || n === "u32" ? `atomicMax(&${t}, bitcast<${n}>(${r}));` : ` + ${o}max(bitcast(oldValue), (${r}))${i}`; + case "min": + return n === "i32" || n === "u32" ? `atomicMin(&${t}, bitcast<${n}>(${r}));` : `${o}min(bitcast<${n}>(oldValue), (${r}))${i}`; + case "mul": + return `${o}(bitcast<${n}>(oldValue) * (${r}))${i}`; + default: + throw new Error(`Reduction ${e} is not supported.`); + } + }, Il = (e, t) => `${e === 1 ? ` + let element_count_dim = uniforms.output_strides; + let dim_value = uniforms.output_shape;` : ` + let element_count_dim = uniforms.output_strides[${t ? "i - indices_start" : "i"}]; + let dim_value = uniforms.output_shape[${t ? "i - indices_start" : "i"} + uniforms.last_index_dimension];`} + + if (index >= 0) { + if (index >= i32(dim_value)) { + index = i32(dim_value - 1); + } + } else { + if (index < -i32(dim_value)) { + index = 0; + } else { + index += i32(dim_value); + } + } + data_offset += u32((u32(index) * element_count_dim));`, Cl = (e, t, r) => `for (var i = 0u; i < uniforms.num_updates_elements; i++) { + let value = updates[uniforms.num_updates_elements * ${r ? "global_idx" : "idx"} + i]; + ${Bh(e.reduction, "output[data_offset + i]", "value", t)} + }`, Dh = (e, t) => { + let r = e[0].dims, n = e[1].dims, o = r, i = 1, a = Math.ceil(k.size(n) / i), u = n[n.length - 1], d = k.sizeFromDimension(r, u), c = k.sizeFromDimension(n, 0) / u, p = [{ type: 12, data: a }, { type: 12, data: u }, { type: 12, data: d }, ...N(e[1].dims, e[2].dims, o)], m = (f) => { + let b = P("indices", e[1].dataType, e[1].dims.length), g = P("updates", e[2].dataType, e[2].dims.length, i), _ = t.reduction !== "none" && t.reduction !== "" ? es("output", e[0].dataType, o.length) : M("output", e[0].dataType, o.length, i); + return ` + ${f.registerUniform("output_size", "u32").registerUniform("last_index_dimension", "u32").registerUniform("num_updates_elements", "u32").declareVariables(b, g, _)} + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var hasDuplicates = false; + if (${t.reduction === "none"}) { + for (var i = 0; i < ${c}; i = i + 1) { + for (var j = i + 1; j < ${c}; j = j + 1) { + var index_i = i32(indices[i].x); + var index_j = i32(indices[j].x); + if (index_i == index_j) { + hasDuplicates = true; + break; + } + } + if (hasDuplicates) { + break; + } + } + } + + if (${t.reduction === "none"} && hasDuplicates) { + if (global_idx != 0u) { + return; + } + // Process each index-update pair individually when duplicates exist + for (var idx = 0u; idx < ${c}u; idx++) { + var data_offset = 0u; + for (var i = 0u; i < uniforms.last_index_dimension; i++) { + var index = i32(indices[idx * uniforms.last_index_dimension + i].x); + ${Il(r.length, false)} + } + ${Cl(t, _.type.value, false)} + } + return; + } + + var data_offset = 0u; + var indices_start = uniforms.last_index_dimension * global_idx; + var indices_end = indices_start + uniforms.last_index_dimension; + for (var i = indices_start; i < indices_end; i++) { + var index = i32(indices[i].x); + ${Il(r.length, true)} + } + ${Cl(t, _.type.value, true)} + }`; + }; + return { name: "ScatterND", shaderCache: { hint: `${t.cacheKey}_${t.reduction}`, inputDependencies: ["rank", "rank"] }, getRunData: () => ({ outputs: [{ dims: o, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(a / 64) }, programUniforms: p }), getShaderSource: m }; + }, Al = (e) => J({ reduction: e.reduction }), El = (e, t) => { + e.compute(Dh(e.inputs, t), { inputs: [e.inputs[1], e.inputs[2]], outputs: [] }); + }; + }); + var Mh; + var Rh; + var Uh; + var Pl; + var Nh; + var Vh; + var Wh; + var Lh; + var Gh; + var Hh; + var Fh; + var qh; + var zl; + var jh; + var Kh; + var Zh; + var Qh; + var Yh; + var Ol; + var Bl; + var Dl = U(() => { + "use strict"; + ee(); + ne(); + Se(); + ie(); + Mh = (e, t) => { + if (e.every((r) => r > 0 || (() => { + throw new Error("Resize requires scales input values to be positive"); + })), e.length > 0) { + if (t.mode === "linear") { + if (!(e.length === 2 || e.length === 3 || e.length === 4 && e[0] === 1 && e[1] === 1 || e.length === 4 && e[0] === 1 && e[3] === 1 || e.length === 5 && e[0] === 1 && e[1] === 1)) throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and + one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`); + } else if (t.mode === "cubic" && !(e.length === 2 || e.length === 4 && e[0] === 1 && e[1] === 1 || e.length === 4 && e[0] === 1 && e[3] === 1)) throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode"); + } + }, Rh = (e, t, r) => { + t.every((o) => o >= 0 && o < r || (() => { + throw new Error("Resize requires axes input values to be positive and less than rank"); + })); + let n = new Array(r).fill(1); + return t.forEach((o, i) => n[o] = e[i]), n; + }, Uh = (e, t, r, n, o, i) => { + let [a, u, d] = r > 10 ? [1, 2, 3] : [-1, e.length > 1 ? 1 : -1, -1], c = e[0].dims.length; + if (a > 0 && e.length > a && e[a].dims.length > 0) e[a].getFloat32Array().forEach((p) => i.push(p)); + else if (t.coordinateTransformMode === "tf_crop_and_resize") throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize"); + if (u > 0 && e.length > u && e[u].dims.length === 1 && e[u].dims[0] > 0) { + if (e[u].getFloat32Array().forEach((p) => n.push(p)), n.length !== 0 && n.length !== c && r >= 18 && n.length !== t.axes.length) throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up"); + Mh(n, t), t.axes.length > 0 && Rh(n, t.axes, c).forEach((p, m) => n[m] = p); + } + if (d > 0 && e.length > d && e[d].dims.length === 1 && e[d].dims[0] > 0 && (e[d].getBigInt64Array().forEach((p) => o.push(Number(p))), o.length !== 0 && o.length !== c && r >= 18 && o.length !== t.axes.length)) throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up"); + if (t.axes.length > 0) { + if (n.length !== 0 && n.length !== t.axes.length) throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified'); + if (o.length !== 0 && o.length !== t.axes.length) throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified'); + } + if (typeof n < "u" && typeof o < "u" && n.length > 0 && o.length > c) throw new Error("Resize requires only of scales or sizes to be specified"); + }, Pl = (e, t, r, n) => ` + // The whole part and the fractional part are calculated separately due to inaccuracy of floating + // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an + // offset-by-one error later in floor(). + let big = (${e}) * (${t}); + let whole = ${n}(big / (${r})); + let fract = ${n}(big % (${r})) / ${n}(${r}); + return whole + fract; +`, Nh = (e, t) => `fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, + lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { ` + (() => { + switch (e) { + case "asymmetric": + return ` + if (xScale < 1.0 || floor(xScale) != xScale) { + return ${t}(xResized) / ${t}(xScale); + } else { + ${Pl("xResized", "lengthOriginal", "lengthResized", t)} + } + `; + case "pytorch_half_pixel": + return `if (lengthResized > 1) { + return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5; + } else { + return 0.0; + }`; + case "tf_half_pixel_for_nn": + return `return (${t}(xResized) + 0.5) / ${t}(xScale);`; + case "align_corners": + return `if (lengthResized == 1) { + return 0.0; + } else { + ${Pl("xResized", "lengthOriginal - 1", "lengthResized - 1", t)} + }`; + case "tf_crop_and_resize": + return `if (lengthResized > 1) { + return ${t}(roiStart) * ${t}(lengthOriginal - 1) + + (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) / + ${t}(lengthResized - 1); + } else { + return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1); + }`; + case "half_pixel_symmetric": + return `const outputWidth = ${t}xScale * ${t}(lengthResized); + const adjustment = ${t}(lengthResized) / outputWidth; + const center = ${t}(lengthOriginal) / 2; + const offset = center * (1 - adjustment); + return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`; + case "half_pixel": + return `return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`; + default: + throw new Error(`Coordinate transform mode ${e} is not supported`); + } + })() + "}", Vh = (e, t, r) => `fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {` + (() => { + switch (e) { + case "round_prefer_ceil": + return "if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }"; + case "floor": + return "return floor(xOriginal);"; + case "ceil": + return "return ceil(xOriginal);"; + case "round_prefer_floor": + return "if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }"; + case "simple": + default: + if (t < 11) return "if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }"; + throw new Error(`Nearest mode ${e} is not supported`); + } + })() + "}", Wh = (e, t, r) => { + let n = new Array(r).fill(0).concat(new Array(r).fill(1)), o = e.length === 0 ? n : e.slice(); + return t.length > 0 ? (t.forEach((i, a) => { + n[i] = o[a], n[a + r] = o[t.length + a]; + }), n) : o; + }, Lh = (e, t, r, n) => { + let o = []; + if (r.length > 0) if (n.length > 0) { + if (e.forEach((i) => o.push(i)), Math.max(...n) > e.length) throw new Error("axes is out of bound"); + n.forEach((i, a) => o[i] = r[a]); + } else r.forEach((i) => o.push(i)); + else { + if (t.length === 0) throw new Error("Resize requires either scales or sizes."); + o = e.map((i, a) => Math.round(i * t[a])); + } + return o; + }, Gh = (e, t, r) => { + let n = (() => { + switch (r.keepAspectRatioPolicy) { + case "not_larger": + return r.axes.length > 0 ? Math.min(...r.axes.map((i) => t[i]), Number.MAX_VALUE) : Math.min(...t, Number.MAX_VALUE); + case "not_smaller": + return r.axes.length > 0 ? Math.max(...r.axes.map((i) => t[i]), Number.MIN_VALUE) : Math.max(...t, Number.MIN_VALUE); + default: + throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`); + } + })(); + t.fill(1, 0, t.length); + let o = e.slice(); + return r.axes.length > 0 ? (r.axes.forEach((i) => t[i] = n), r.axes.forEach((i) => o[i] = Math.round(e[i] * t[i]))) : (t.fill(n, 0, t.length), o.forEach((i, a) => o[a] = Math.round(i * t[a]))), o; + }, Hh = (e, t, r, n, o) => ` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> { + var original_indices: array<${e.type.value}, ${r.length}>; + for (var i:u32 = 0; i < ${r.length}; i++) { + var output_index = ${e.indicesGet("output_indices", "i")}; + var scale = ${F("uniforms.scales", "i", n)}; + var roi_low = ${F("uniforms.roi", "i", o)}; + var roi_hi = ${F("uniforms.roi", `i + ${t.length}`, o)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${F("uniforms.input_shape", "i", t.length)}; + var output_shape_i = ${F("uniforms.output_shape", "i", r.length)}; + original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + } + } + return original_indices; + }`, Fh = (e, t, r, n, o, i, a) => ` + fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + for (var i:u32 = 0; i < ${n.length}; i++) { + var output_index = ${t.indicesGet("output_indices", "i")}; + var input_index: u32; + var scale = ${F("uniforms.scales", "i", o)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${F("uniforms.roi", "i", i)}; + var roi_hi = ${F("uniforms.roi", `i + ${r.length}`, i)}; + var input_shape_i = ${F("uniforms.input_shape", "i", r.length)}; + var output_shape_i = ${F("uniforms.output_shape", "i", n.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${a} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) { + if (original_idx < 0) { + input_index = 0; + } else if (original_idx > ${t.type.value}(input_shape_i - 1)) { + input_index = input_shape_i - 1; + } else { + input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); + } + } else { + input_index = u32(original_idx); + } + } + ${e.indicesSet("input_indices", "i", "input_index")} + } + return input_indices; + }`, qh = (e, t) => ` + fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { + for (var i:u32 = 0; i < ${t.length}; i++) { + var input_index = ${e.indicesGet("input_indices", "i")}; + if (input_index < 0 || input_index >= ${F("uniforms.input_shape", "i", t.length)}) { + return false; + } + } + return true; + }`, zl = (e, t, r, n) => e.rank > n ? ` + ${e.indicesSet("input_indices", t, "channel")}; + ${e.indicesSet("input_indices", r, "batch")}; +` : "", jh = (e, t, r, n, o) => { + let [a, u, d, c] = r.length === 2 ? [-1, 0, 1, -1] : [0, 2, 3, 1], p = e.type.value; + return ` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${p} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices", u, `max(0, min(row, ${r[u]} - 1))`)}; + ${e.indicesSet("input_indices", d, `max(0, min(col, ${r[d]} - 1))`)}; + ${zl(e, c, a, 2)} + return ${e.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${p} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${p} = originalIndices[${u}]; + var col:${p} = originalIndices[${d}]; + ${n ? `if (row < 0 || row > (${r[u]} - 1) || col < 0 || col > (${r[d]} - 1)) { + return ${o}; + }` : ""}; + row = max(0, min(row, ${r[u]} - 1)); + col = max(0, min(col, ${r[d]} - 1)); + var row1: u32 = u32(row); + var col1: u32 = u32(col); + var row2: u32 = u32(row + 1); + var col2: u32 = u32(col + 1); + var channel: u32 = ${r.length > 2 ? `u32(originalIndices[${c}])` : "0"}; + var batch: u32 = ${r.length > 2 ? `u32(originalIndices[${a}])` : "0"}; + var x11: ${p} = getInputValue(batch, channel, row1, col1); + var x12: ${p} = getInputValue(batch, channel, row1, col2); + var x21: ${p} = getInputValue(batch, channel, row2, col1); + var x22: ${p} = getInputValue(batch, channel, row2, col2); + var dx1: ${p} = abs(row - ${p}(row1)); + var dx2: ${p} = abs(${p}(row2) - row); + var dy1: ${p} = abs(col - ${p}(col1)); + var dy2: ${p} = abs(${p}(col2) - col); + if (row1 == row2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (col1 == col2) { + dy1 = 0.5; + dy2 = 0.5; + } + return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); + }`; + }, Kh = (e, t, r, n, o, i, a, u, d, c) => { + let p = r.length === 2, m = true, [f, b] = p ? [0, 1] : m ? [2, 3] : [1, 2], g = e.type.value, _ = (S) => { + let $ = S === f ? "row" : "col"; + return ` + fn ${$}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${g} { + var output_index = ${t.indicesGet("output_indices", S)}; + var originalIdx: ${g} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[S]}, + ${n[S]}, ${r[S]}, ${i[S]}, ${i[S]} + ${r.length}); + var fractOriginalIdx: ${g} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${u} && (originalIdx < 0 || originalIdx > (${r[S]} - 1))) { + return ${d}; + } + var data: array<${g}, 4> = array<${g}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${$}: ${g} = originalIdx + ${g}(i); + if (${$} < 0 || ${$} >= ${r[S]}) { + ${c ? `coefs[i + 1] = 0.0; + continue;` : u ? `return ${d};` : `${$} = max(0, min(${$}, ${r[S]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy", S, `u32(${$})`)}; + data[i + 1] = ${S === f ? e.getByIndices("input_indices_copy") : "rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`; + }; + return ` + ${_(f)}; + ${_(b)}; + fn getCubicInterpolationCoefs(s: ${g}) -> array<${g}, 4> { + var absS = abs(s); + var coeffs: array<${g}, 4> = array<${g}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${g} = 1.0 - absS; + var twoMinusAbsS: ${g} = 2.0 - absS; + var onePlusAbsS: ${g} = 1.0 + absS; + coeffs[0] = ((${a} * onePlusAbsS - 5 * ${a}) * onePlusAbsS + 8 * ${a}) * onePlusAbsS - 4 * ${a}; + coeffs[1] = ((${a} + 2) * absS - (${a} + 3)) * absS * absS + 1; + coeffs[2] = ((${a} + 2) * oneMinusAbsS - (${a} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${a} * twoMinusAbsS - 5 * ${a}) * twoMinusAbsS + 8 * ${a}) * twoMinusAbsS - 4 * ${a}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${g}, 4>, coefs: array<${g}, 4>) -> ${g} { + var coefsSum: ${g} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; + return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; + } + + fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${g} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `; + }, Zh = (e, t, r, n, o) => { + let [a, u, d, c, p] = r.length === 3 ? [-1, 0, 1, 2, -1] : [0, 2, 3, 4, 1], m = e.type.value; + return ` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${m} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices", u, `max(0, min(depth, ${r[u]} - 1))`)}; + ${e.indicesSet("input_indices", d, `max(0, min(height, ${r[d]} - 1))`)}; + ${e.indicesSet("input_indices", c, `max(0, min(width, ${r[c]} - 1))`)}; + ${zl(e, p, a, 3)} + return ${e.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${m} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${m} = originalIndices[${u}]; + var height:${m} = originalIndices[${d}]; + var width:${m} = originalIndices[${c}]; + ${n ? `if (depth < 0 || depth > (${r[u]} - 1) || height < 0 || height > (${r[d]} - 1) || width < 0 || (width > ${r[c]} - 1)) { + return ${o}; + }` : ""}; + + depth = max(0, min(depth, ${r[u]} - 1)); + height = max(0, min(height, ${r[d]} - 1)); + width = max(0, min(width, ${r[c]} - 1)); + var depth1: u32 = u32(depth); + var height1: u32 = u32(height); + var width1: u32 = u32(width); + var depth2: u32 = u32(depth + 1); + var height2: u32 = u32(height + 1); + var width2: u32 = u32(width + 1); + var channel: u32 = ${r.length > 3 ? `u32(originalIndices[${p}])` : "0"}; + var batch: u32 = ${r.length > 3 ? `u32(originalIndices[${a}])` : "0"}; + + var x111: ${m} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${m} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${m} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${m} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${m} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${m} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${m} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${m} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${m} = abs(depth - ${m}(depth1)); + var dx2: ${m} = abs(${m}(depth2) - depth); + var dy1: ${m} = abs(height - ${m}(height1)); + var dy2: ${m} = abs(${m}(height2) - height); + var dz1: ${m} = abs(width - ${m}(width1)); + var dz2: ${m} = abs(${m}(width2) - width); + if (depth1 == depth2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (height1 == height2) { + dy1 = 0.5; + dy2 = 0.5; + } + if (width1 == width2) { + dz1 = 0.5; + dz2 = 0.5; + } + return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + + x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); + }`; + }, Qh = (e, t, r, n, o, i) => { + let a = e.dims, u = Wh(i, t.axes, a.length), d = Lh(a, n, o, t.axes), c = n.slice(); + n.length === 0 && (c = a.map((v, x) => v === 0 ? 1 : d[x] / v), t.keepAspectRatioPolicy !== "stretch" && (d = Gh(a, c, t))); + let p = M("output", e.dataType, d.length), m = P("input", e.dataType, a.length), f = k.size(d), b = a.length === d.length && a.every((v, x) => v === d[x]), g = t.coordinateTransformMode === "tf_crop_and_resize", _ = t.extrapolationValue, S = m.type.value, $ = (v) => ` + ${b ? "" : ` + ${Nh(t.coordinateTransformMode, S)}; + ${(() => { + switch (t.mode) { + case "nearest": + return ` + ${qh(m, a)}; + ${Vh(t.nearestMode, r, S)}; + ${Fh(m, p, a, d, c.length, u.length, g)}; + `; + case "linear": + return ` + ${Hh(p, a, d, c.length, u.length)}; + ${(() => { + if (a.length === 2 || a.length === 4) return `${jh(m, p, a, g, _)}`; + if (a.length === 3 || a.length === 5) return `${Zh(m, p, a, g, _)}`; + throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode."); + })()}; + `; + case "cubic": + return ` + ${(() => { + if (a.length === 2 || a.length === 4) return `${Kh(m, p, a, d, c, u, t.cubicCoeffA, g, t.extrapolationValue, t.excludeOutside)}`; + throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode."); + })()}; + `; + default: + throw Error("Invalid resize mode"); + } + })()}; + `} + ${v.registerUniform("output_size", "u32").registerUniform("scales", "f32", c.length).registerUniform("roi", "f32", u.length).declareVariables(m, p)} + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${b ? "output[global_idx] = input[global_idx];" : ` + let output_indices = ${p.offsetToIndices("global_idx")}; + var input_indices: ${m.type.indices}; + ${(() => { + switch (t.mode) { + case "nearest": + return `input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${m.getByIndices("input_indices")}; + } else { + output[global_idx] = ${t.extrapolationValue}; + }`; + case "linear": + return `output[global_idx] = ${a.length === 2 || a.length === 4 ? "bilinearInterpolation" : "trilinearInterpolation"}(output_indices);`; + case "cubic": + return "output[global_idx] = bicubicInterpolation(output_indices);"; + default: + throw Error(`Unsupported resize mode: ${t.mode}`); + } + })()}; +`} + }`; + return { name: "Resize", shaderCache: { hint: `${t.cacheKey}|${r}|${c.length > 0 ? t.mode === "cubic" ? c : c.length : ""}|${o.length > 0 ? o : ""}|${u.length > 0 ? u : ""}|${b}|${t.mode === "nearest" ? a.length : a}`, inputDependencies: ["rank"] }, getShaderSource: $, getRunData: () => ({ outputs: [{ dims: d, dataType: e.dataType }], dispatchGroup: { x: Math.ceil(f / 64) }, programUniforms: [{ type: 12, data: f }, { type: 1, data: c }, { type: 1, data: u }, ...N(a, d)] }) }; + }, Yh = (e) => { + let t = e.customDataBuffer; + return new Uint32Array(t, t.byteOffset, 1)[0]; + }, Ol = (e, t) => { + let r = [], n = [], o = [], i = Yh(e); + if (t.antialias !== 0) throw Error("Only default value (0) for Antialias attribute is supported"); + Uh(e.inputs, t, i, r, n, o), e.compute(Qh(e.inputs[0], t, i, r, n, o), { inputs: [0] }); + }, Bl = (e) => { + let t = e.antialias, r = e.axes, n = e.coordinateTransformMode, o = e.cubicCoeffA, i = e.excludeOutside !== 0, a = e.extrapolationValue, u = e.keepAspectRatioPolicy, d = e.mode, c = e.nearestMode === "" ? "simple" : e.nearestMode; + return J({ antialias: t, axes: r, coordinateTransformMode: n, cubicCoeffA: o, excludeOutside: i, extrapolationValue: a, keepAspectRatioPolicy: u, mode: d, nearestMode: c }); + }; + }); + var Xh; + var Jh; + var Ml; + var Rl = U(() => { + "use strict"; + ee(); + ne(); + ie(); + Xh = (e) => { + if (!e || e.length < 3) throw new Error("layerNorm requires at least 3 inputs."); + let t = e[0], r = e[1], n = e[2]; + if (t.dataType !== r.dataType || t.dataType !== n.dataType) throw new Error("All inputs must have the same data type"); + if (t.dims.length !== 3 && t.dims.length !== 2) throw new Error("Input must be 2D or 3D"); + if (r.dims.length !== 3 && r.dims.length !== 2) throw new Error("Skip must be 2D or 3D"); + let o = t.dims[t.dims.length - 1], i = t.dims[t.dims.length - 2]; + if (r.dims[r.dims.length - 1] !== o) throw new Error("Skip must have the same hidden size as input"); + if (r.dims[r.dims.length - 2] !== i) throw new Error("Skip must have the same sequence length as input"); + if (n.dims.length !== 1) throw new Error("Gamma must be 1D"); + if (n.dims[n.dims.length - 1] !== o) throw new Error("Gamma must have the same hidden size as input"); + if (e.length > 3) { + let a = e[3]; + if (a.dims.length !== 1) throw new Error("Beta must be 1D"); + if (a.dims[a.dims.length - 1] !== o) throw new Error("Beta must have the same hidden size as input"); + } + if (e.length > 4) { + let a = e[4]; + if (a.dims.length !== 1) throw new Error("Bias must be 1D"); + if (a.dims[a.dims.length - 1] !== o) throw new Error("Bias must have the same hidden size as input"); + } + }, Jh = (e, t, r, n) => { + let o = t.simplified, i = e[0].dims, a = k.size(i), u = i, d = a, c = i.slice(-1)[0], p = n ? i.slice(0, -1).concat(1) : [], m = !o && e.length > 3, f = e.length > 4, b = n && r > 1, g = n && r > 2, _ = r > 3, S = 64, $ = ce(c), v = [{ type: 12, data: d }, { type: 12, data: $ }, { type: 12, data: c }, { type: 1, data: t.epsilon }], x = (E) => { + let I = [{ name: "output_size", type: "u32" }, { name: "components", type: "u32" }, { name: "hidden_size", type: "u32" }, { name: "epsilon", type: "f32" }], z = [P("x", e[0].dataType, e[0].dims, $), P("skip", e[1].dataType, e[1].dims, $), P("gamma", e[2].dataType, e[2].dims, $)]; + m && z.push(P("beta", e[3].dataType, e[3].dims, $)), f && z.push(P("bias", e[4].dataType, e[4].dims, $)), z.push(M("output", e[0].dataType, u, $)), b && z.push(M("mean_output", 1, p)), g && z.push(M("inv_std_output", 1, p)), _ && z.push(M("input_skip_bias_sum", e[0].dataType, u, $)); + let O = be(e[0].dataType), D = be(1, $); + return ` + + ${E.registerUniforms(I).declareVariables(...z)} + var sum_shared : array<${D}, ${S}>; + var sum_squared_shared : array<${D}, ${S}>; + + ${E.mainStart([S, 1, 1])} + let ix = local_id.x; + let iy = global_id.x / ${S}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${S}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${S - 1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${f ? "bias[offset1d + i]" : O + "(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${_ ? "input_skip_bias_sum[offset + i] = value;" : ""} + output[offset + i] = value; + let f32_value = ${Ct(O, $, "value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${S}; + for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) { + reduce_size = curr_size + (reduce_size & 1); + if (ix < curr_size) { + sum_shared[ix] += sum_shared[ix + reduce_size]; + sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size]; + } + workgroupBarrier(); + } + + let sum = sum_shared[0]; + let square_sum = sum_squared_shared[0]; + let mean = ${He("sum", $)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${He("square_sum", $)} / f32(uniforms.hidden_size) ${o ? "" : "- mean * mean"} + uniforms.epsilon); + ${b ? "mean_output[global_idx] = mean;" : ""} + ${g ? "inv_std_output[global_idx] = inv_std_dev;" : ""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${o ? "" : `- ${O}(mean)`}) * + ${O}(inv_std_dev) * gamma[offset1d + i] + ${m ? "+ beta[offset1d + i]" : ""}; + } + }`; + }, T = [{ dims: u, dataType: e[0].dataType }]; + return r > 1 && T.push({ dims: p, dataType: 1 }), r > 2 && T.push({ dims: p, dataType: 1 }), r > 3 && T.push({ dims: i, dataType: e[0].dataType }), { name: "SkipLayerNormalization", shaderCache: { hint: `${$};${b};${g};${_}`, inputDependencies: e.map((E, I) => "type") }, getShaderSource: x, getRunData: () => ({ outputs: T, dispatchGroup: { x: Math.ceil(d / c) }, programUniforms: v }) }; + }, Ml = (e, t) => { + Xh(e.inputs); + let n = [0]; + e.outputCount > 1 && n.push(-3), e.outputCount > 2 && n.push(-3), e.outputCount > 3 && n.push(3), e.compute(Jh(e.inputs, t, e.outputCount, false), { outputs: n }); + }; + }); + var eg; + var nn; + var tg; + var Ul; + var rg; + var ng; + var Nl; + var Vl; + var Wl = U(() => { + "use strict"; + ee(); + ne(); + Se(); + ie(); + eg = (e, t) => { + if (!e || e.length < 1) throw new Error("too few inputs"); + if (t.axes.length !== 0) { + if (t.axes.length !== t.starts.length || t.axes.length !== t.ends.length) throw new Error("axes, starts and ends must have the same length"); + } else if (t.starts.length !== t.ends.length) throw new Error("starts and ends must have the same length"); + e.slice(1).forEach((r, n) => { + if (e[n + 1].dataType !== 6 && e[n + 1].dataType !== 7) throw new Error(`Input ${n} must be an array of int32 or int64`); + }); + }, nn = (e, t) => { + let r = []; + if (e.length > t) if (e[t].dataType === 7) e[t].getBigInt64Array().forEach((n) => r.push(Number(n))); + else if (e[t].dataType === 6) e[t].getInt32Array().forEach((n) => r.push(Number(n))); + else throw new Error(`Input ${t} must be an array of int32 or int64`); + return r; + }, tg = (e, t) => { + if (e.length > 1) { + let r = nn(e, 1), n = nn(e, 2), o = nn(e, 3); + return o.length === 0 && (o = [...Array(e[0].dims.length).keys()]), J({ starts: r, ends: n, axes: o }); + } else return t; + }, Ul = (e, t, r, n, o) => { + let i = e; + return e < 0 && (i += r[n[t]]), o[t] < 0 ? Math.max(0, Math.min(i, r[n[t]] - 1)) : Math.max(0, Math.min(i, r[n[t]])); + }, rg = (e, t, r) => `fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + var carry = 0u; + for (var i = ${r.length}; i >= 0; i--) { + let input_shape_i = ${F("uniforms.input_shape", "i", r.length)}; + let steps_i = ${F("uniforms.steps", "i", r.length)}; + let signs_i = ${F("uniforms.signs", "i", r.length)}; + let starts_i = ${F("uniforms.starts", "i", r.length)}; + var output_index = ${t.indicesGet("output_indices", "i")}; + var input_index = output_index * steps_i + starts_i + carry; + carry = input_index / input_shape_i; + input_index = input_index % input_shape_i; + if (signs_i < 0) { + input_index = input_shape_i - input_index - 1u + starts_i; + } + ${e.indicesSet("input_indices", "i", "input_index")}; + } + return input_indices; + }`, ng = (e, t) => { + let r = e[0].dims, n = k.size(r), o = t.axes.length > 0 ? k.normalizeAxes(t.axes, r.length) : [...Array(r.length).keys()], i = nn(e, 4); + i.forEach(($) => $ !== 0 || (() => { + throw new Error("step cannot be 0"); + })), i.length === 0 && (i = Array(o.length).fill(1)); + let a = t.starts.map(($, v) => Ul($, v, r, o, i)), u = t.ends.map(($, v) => Ul($, v, r, o, i)); + if (o.length !== a.length || o.length !== u.length) throw new Error("start, ends and axes should have the same number of elements"); + if (o.length !== r.length) for (let $ = 0; $ < r.length; ++$) o.includes($) || (a.splice($, 0, 0), u.splice($, 0, r[$]), i.splice($, 0, 1)); + let d = i.map(($) => Math.sign($)); + i.forEach(($, v, x) => { + if ($ < 0) { + let T = (u[v] - a[v]) / $, E = a[v], I = E + T * i[v]; + a[v] = I, u[v] = E, x[v] = -$; + } + }); + let c = r.slice(0); + o.forEach(($, v) => { + c[$] = Math.ceil((u[$] - a[$]) / i[$]); + }); + let p = { dims: c, dataType: e[0].dataType }, m = M("output", e[0].dataType, c.length), f = P("input", e[0].dataType, e[0].dims.length), b = k.size(c), g = [{ name: "outputSize", type: "u32" }, { name: "starts", type: "u32", length: a.length }, { name: "signs", type: "i32", length: d.length }, { name: "steps", type: "u32", length: i.length }], _ = [{ type: 12, data: b }, { type: 12, data: a }, { type: 6, data: d }, { type: 12, data: i }, ...N(e[0].dims, c)], S = ($) => ` + ${$.registerUniforms(g).declareVariables(f, m)} + ${rg(f, m, r)} + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${m.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${m.setByOffset("global_idx", f.getByIndices("input_indices"))} + }`; + return { name: "Slice", shaderCache: { hint: `${d.length}_${a.length}_${i.length}`, inputDependencies: ["rank"] }, getShaderSource: S, getRunData: () => ({ outputs: [p], dispatchGroup: { x: Math.ceil(n / 64) }, programUniforms: _ }) }; + }, Nl = (e, t) => { + eg(e.inputs, t); + let r = tg(e.inputs, t); + e.compute(ng(e.inputs, r), { inputs: [0] }); + }, Vl = (e) => { + let t = e.starts, r = e.ends, n = e.axes; + return J({ starts: t, ends: r, axes: n }); + }; + }); + var og; + var ig; + var Ll; + var Gl; + var Hl = U(() => { + "use strict"; + ee(); + ne(); + Se(); + st(); + ie(); + og = (e) => { + if (!e || e.length !== 1) throw new Error("Softmax op requires 1 input."); + }, ig = (e, t) => { + let r = e.inputs[0], n = r.dims, o = k.size(n), i = n.length, a = k.normalizeAxis(t.axis, i), u = a < n.length - 1, d, c = []; + u ? (c = Array.from({ length: i }, (z, O) => O), c[a] = i - 1, c[i - 1] = a, d = e.compute(Ee(r, c), { inputs: [r], outputs: [-1] })[0]) : d = r; + let p = d.dims, m = p[i - 1], f = o / m, b = ce(m), g = m / b, _ = 64; + f === 1 && (_ = 256); + let S = (z, O) => O === 4 ? `max(max(${z}.x, ${z}.y), max(${z}.z, ${z}.w))` : O === 2 ? `max(${z}.x, ${z}.y)` : O === 3 ? `max(max(${z}.x, ${z}.y), ${z}.z)` : z, $ = P("x", d.dataType, d.dims, b), v = M("result", d.dataType, d.dims, b), x = $.type.value, T = be(d.dataType) === "f32" ? `var threadMax = ${x}(-3.402823e+38f);` : `var threadMax = ${x}(-65504.0h);`, E = (z) => ` + var rowMaxShared : ${x}; + var rowSumShared : ${x}; + var threadShared : array<${x}, ${_}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${x} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${x}) { + let index = row * row_stride + col; + result[index] = value; + } + ${z.registerUniform("packedCols", "i32").declareVariables($, v)} + ${z.mainStart(_)} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${_}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${T} + for (var col = lindex; col < cols; col += wg) { + let value = getValue(row, col, row_stride); + threadMax = max(threadMax, value); + } + if (lindex < cols) { + threadShared[lindex] = threadMax; + } + workgroupBarrier(); + + var reduceSize = min(cols, wg); + for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { + reduceSize = currSize + (reduceSize & 1); + if (lindex < currSize) { + threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); + } + workgroupBarrier(); + } + if (lindex == 0) { + rowMaxShared = ${x}(${S("threadShared[0]", b)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${x}(0.0); + for (var col = lindex; col < cols; col += wg) { + let subExp = exp(getValue(row, col, row_stride) - rowMaxShared); + threadSum += subExp; + } + threadShared[lindex] = threadSum; + workgroupBarrier(); + + for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) { + if (lindex < currSize) { + threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize]; + } + workgroupBarrier(); + } + if (lindex == 0) { + rowSumShared = ${x}(${He("threadShared[0]", b)}); + } + workgroupBarrier(); + + // calculate final value for each element in the row + for (var col = lindex; col < cols; col += wg) { + let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; + setValue(row, col, row_stride, value); + } + }`, I = e.compute({ name: "Softmax", shaderCache: { hint: `${b};${_}`, inputDependencies: ["type"] }, getRunData: () => ({ outputs: [{ dims: p, dataType: d.dataType }], dispatchGroup: { x: f }, programUniforms: [{ type: 6, data: g }] }), getShaderSource: E }, { inputs: [d], outputs: [u ? -1 : 0] })[0]; + u && e.compute(Ee(I, c), { inputs: [I] }); + }, Ll = (e, t) => { + og(e.inputs), ig(e, t); + }, Gl = (e) => J({ axis: e.axis }); + }); + var Fl; + var ag; + var sg; + var ug; + var ql; + var jl = U(() => { + "use strict"; + ee(); + ne(); + ie(); + Fl = (e) => Array.from(e.getBigInt64Array(), Number), ag = (e) => { + if (!e || e.length !== 2) throw new Error("Tile requires 2 inputs."); + if (e[0].dataType !== 1 && e[0].dataType !== 10 && e[0].dataType !== 6 && e[0].dataType !== 12) throw new Error("Tile only support float, float16, int32, and uint32 data types"); + if (e[1].dataType !== 7) throw new Error("Tile `repeats` input should be of int64 data type"); + if (e[1].dims.length !== 1) throw new Error("Tile `repeats` input should be 1-D"); + if (Fl(e[1]).length !== e[0].dims.length) throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor"); + }, sg = (e, t) => { + let r = []; + for (let n = 0; n < e.length; ++n) r.push(e[n] * t[n]); + return r; + }, ug = (e, t) => { + let r = e[0].dims, n = t ?? Fl(e[1]), o = sg(r, n), i = k.size(o), a = e[0].dataType, u = P("input", a, r.length), d = M("output", a, o.length), c = (p) => ` + const inputShape = ${u.indices(...r)}; + ${p.registerUniform("output_size", "u32").declareVariables(u, d)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${d.offsetToIndices("global_idx")}; + var input_indices: ${u.type.indices}; + for (var i = 0; i < ${r.length}; i++) { + let input_dim_i = ${u.indicesGet("uniforms.input_shape", "i")}; + let input_dim_value = ${d.indicesGet("output_indices", "i")} % input_dim_i; + + ${u.indicesSet("input_indices", "i", "input_dim_value")} + } + ${d.setByOffset("global_idx", u.getByIndices("input_indices"))} + }`; + return { name: "Tile", shaderCache: { hint: `${n}`, inputDependencies: ["rank"] }, getRunData: () => ({ outputs: [{ dims: o, dataType: e[0].dataType }], dispatchGroup: { x: Math.ceil(i / 64) }, programUniforms: [{ type: 12, data: i }, ...N(e[0].dims, o)] }), getShaderSource: c }; + }, ql = (e) => { + ag(e.inputs), e.compute(ug(e.inputs), { inputs: [0] }); + }; + }); + var dg; + var lg; + var Kl; + var Zl = U(() => { + "use strict"; + ee(); + ne(); + ie(); + dg = (e, t, r, n, o) => { + let i = M("output_data", o, r.length, 4), a = P("a_data", t[1].dataType, t[1].dims.length, 4), u = P("b_data", t[2].dataType, t[2].dims.length, 4), d = P("c_data", t[0].dataType, t[0].dims.length, 4), c, p = (m, f, b) => `select(${f}, ${m}, ${b})`; + if (!n) c = i.setByOffset("global_idx", p(a.getByOffset("global_idx"), u.getByOffset("global_idx"), d.getByOffset("global_idx"))); + else { + let m = (f, b, g = "") => { + let _ = `a_data[index_a${b}][component_a${b}]`, S = `b_data[index_b${b}][component_b${b}]`, $ = `bool(c_data[index_c${b}] & (0xffu << (component_c${b} * 8)))`; + return ` + let output_indices${b} = ${i.offsetToIndices(`global_idx * 4u + ${b}u`)}; + let offset_a${b} = ${a.broadcastedIndicesToOffset(`output_indices${b}`, i)}; + let offset_b${b} = ${u.broadcastedIndicesToOffset(`output_indices${b}`, i)}; + let offset_c${b} = ${d.broadcastedIndicesToOffset(`output_indices${b}`, i)}; + let index_a${b} = offset_a${b} / 4u; + let index_b${b} = offset_b${b} / 4u; + let index_c${b} = offset_c${b} / 4u; + let component_a${b} = offset_a${b} % 4u; + let component_b${b} = offset_b${b} % 4u; + let component_c${b} = offset_c${b} % 4u; + ${f}[${b}] = ${g}(${p(_, S, $)}); + `; + }; + o === 9 ? c = ` + var data = vec4(0); + ${m("data", 0, "u32")} + ${m("data", 1, "u32")} + ${m("data", 2, "u32")} + ${m("data", 3, "u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));` : c = ` + ${m("output_data[global_idx]", 0)} + ${m("output_data[global_idx]", 1)} + ${m("output_data[global_idx]", 2)} + ${m("output_data[global_idx]", 3)} + `; + } + return ` + ${e.registerUniform("vec_size", "u32").declareVariables(d, a, u, i)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${c} + }`; + }, lg = (e) => { + let t = e[1].dims, r = e[2].dims, n = e[0].dims, o = e[1].dataType, i = !(k.areEqual(t, r) && k.areEqual(r, n)), a = t, u = k.size(t); + if (i) { + let c = Je.calcShape(Je.calcShape(t, r, false), n, false); + if (!c) throw new Error("Can't perform where op on the given tensors"); + a = c, u = k.size(a); + } + let d = Math.ceil(u / 4); + return { name: "Where", shaderCache: { inputDependencies: ["rank", "rank", "rank"] }, getShaderSource: (c) => dg(c, e, a, i, o), getRunData: () => ({ outputs: [{ dims: a, dataType: o }], dispatchGroup: { x: Math.ceil(u / 64 / 4) }, programUniforms: [{ type: 12, data: d }, ...N(n, t, r, a)] }) }; + }, Kl = (e) => { + e.compute(lg(e.inputs)); + }; + }); + var Ql; + var Yl = U(() => { + "use strict"; + Es(); + Fr(); + zs(); + Bs(); + _u(); + ku(); + Ou(); + Zu(); + rd(); + id(); + ud(); + md(); + gd(); + yd(); + vd(); + Sd(); + Cd(); + kd(); + Od(); + Md(); + Fd(); + Kd(); + Qd(); + Xd(); + tl(); + $o(); + nl(); + wl(); + xl(); + Tl(); + kl(); + Gr(); + Dl(); + To(); + Rl(); + Wl(); + Hl(); + So(); + jl(); + st(); + jr(); + Zl(); + Ql = /* @__PURE__ */ new Map([["Abs", [Ds]], ["Acos", [Ms]], ["Acosh", [Rs]], ["Add", [wu]], ["ArgMax", [As, uo]], ["ArgMin", [Cs, uo]], ["Asin", [Us]], ["Asinh", [Ns]], ["Atan", [Vs]], ["Atanh", [Ws]], ["Attention", [ks]], ["AveragePool", [cl, ll]], ["BatchNormalization", [Ps]], ["BiasAdd", [Os]], ["BiasSplitGelu", [yu]], ["Cast", [Gs, Ls]], ["Ceil", [Fs]], ["Clip", [Hs]], ["Concat", [Pu, zu]], ["Conv", [yo, bo]], ["ConvTranspose", [td, Ju]], ["Cos", [qs]], ["Cosh", [js]], ["CumSum", [nd, od]], ["DepthToSpace", [ad, sd]], ["DequantizeLinear", [vl, $l]], ["Div", [vu]], ["Einsum", [cd, pd]], ["Elu", [Ks, Yt]], ["Equal", [$u]], ["Erf", [Zs]], ["Exp", [Qs]], ["Expand", [hd]], ["FastGelu", [bd]], ["Floor", [Ys]], ["FusedConv", [yo, bo]], ["Gather", [wd, _d]], ["GatherElements", [Ed, Ad]], ["GatherBlockQuantized", [Td, Id]], ["GatherND", [$d, xd]], ["Gelu", [Xs]], ["Gemm", [zd, Pd]], ["GlobalAveragePool", [fl, ml]], ["GlobalMaxPool", [_l, yl]], ["Greater", [Iu]], ["GreaterOrEqual", [Au]], ["GridSample", [Bd, Dd]], ["GroupQueryAttention", [Hd]], ["HardSigmoid", [au, iu]], ["InstanceNormalization", [jd]], ["LayerNormalization", [Zd]], ["LeakyRelu", [Js, Yt]], ["Less", [Cu]], ["LessOrEqual", [Eu]], ["Log", [hu]], ["MatMul", [Yd]], ["MatMulNBits", [Jd, el]], ["MaxPool", [gl, bl]], ["Mul", [xu]], ["MultiHeadAttention", [Nd, Ud]], ["Neg", [tu]], ["Not", [eu]], ["Pad", [rl]], ["Pow", [Su]], ["QuickGelu", [gu, Yt]], ["Range", [Sl]], ["Reciprocal", [ru]], ["ReduceMin", [vs]], ["ReduceMean", [gs]], ["ReduceMax", [ws]], ["ReduceSum", [xs]], ["ReduceProd", [$s]], ["ReduceL1", [bs]], ["ReduceL2", [ys]], ["ReduceLogSum", [Ts]], ["ReduceLogSumExp", [_s]], ["ReduceSumSquare", [Ss]], ["Relu", [nu]], ["Resize", [Ol, Bl]], ["RotaryEmbedding", [Ld]], ["ScatterND", [El, Al]], ["Sigmoid", [ou]], ["Sin", [su]], ["Sinh", [uu]], ["Slice", [Nl, Vl]], ["SkipLayerNormalization", [Ml]], ["Split", [Vd, Wd]], ["Sqrt", [du]], ["Softmax", [Ll, Gl]], ["Sub", [Tu]], ["Tan", [lu]], ["Tanh", [pu]], ["ThresholdedRelu", [fu, Yt]], ["Tile", [ql]], ["Transpose", [ns, os]], ["Where", [Kl]]]); + }); + var on; + var Xl = U(() => { + "use strict"; + We(); + Xe(); + ie(); + on = class { + constructor(t) { + this.backend = t; + this.repo = /* @__PURE__ */ new Map(), this.attributesBound = false; + } + getArtifact(t) { + return this.repo.get(t); + } + setArtifact(t, r) { + this.repo.set(t, r); + } + run(t, r, n, o, i) { + Re(t.programInfo.name); + let a = this.backend.device, u = this.backend.getComputePassEncoder(); + this.backend.writeTimestamp(this.backend.pendingDispatchNumber * 2); + let d = []; + for (let p of r) d.push({ binding: d.length, resource: { buffer: p.buffer } }); + for (let p of n) d.push({ binding: d.length, resource: { buffer: p.buffer } }); + i && d.push({ binding: d.length, resource: i }); + let c = a.createBindGroup({ layout: t.computePipeline.getBindGroupLayout(0), entries: d, label: t.programInfo.name }); + if (this.backend.sessionStatus === "capturing") { + let p = { kernelId: this.backend.currentKernelId, computePipeline: t.computePipeline, bindGroup: c, dispatchGroup: o }; + this.backend.capturedCommandList.get(this.backend.currentSessionId).push(p); + } + u.setPipeline(t.computePipeline), u.setBindGroup(0, c), u.dispatchWorkgroups(...o), this.backend.writeTimestamp(this.backend.pendingDispatchNumber * 2 + 1), this.backend.pendingDispatchNumber++, (this.backend.pendingDispatchNumber >= this.backend.maxDispatchNumber || this.backend.queryType === "at-passes") && this.backend.endComputePass(), this.backend.pendingDispatchNumber >= this.backend.maxDispatchNumber && this.backend.flush(), Oe(t.programInfo.name); + } + dispose() { + } + build(t, r) { + Re(t.name); + let n = this.backend.device, o = []; + [{ feature: "shader-f16", extension: "f16" }, { feature: "subgroups", extension: "subgroups" }].forEach((m) => { + n.features.has(m.feature) && o.push(`enable ${m.extension};`); + }); + let a = ts(r, this.backend.device.limits), u = t.getShaderSource(a), d = `${o.join(` +`)} +${a.additionalImplementations} +${u}`, c = n.createShaderModule({ code: d, label: t.name }); + se("verbose", () => `[WebGPU] ${t.name} shader code: ${d}`); + let p = n.createComputePipeline({ compute: { module: c, entryPoint: "main" }, layout: "auto", label: t.name }); + return Oe(t.name), { programInfo: t, computePipeline: p, uniformVariablesInfo: a.variablesInfo }; + } + normalizeDispatchGroupSize(t) { + let r = typeof t == "number" ? t : t.x, n = typeof t == "number" ? 1 : t.y || 1, o = typeof t == "number" ? 1 : t.z || 1, i = this.backend.device.limits.maxComputeWorkgroupsPerDimension; + if (r <= i && n <= i && o <= i) return [r, n, o]; + let a = r * n * o, u = Math.ceil(Math.sqrt(a)); + if (u > i) { + if (u = Math.ceil(Math.cbrt(a)), u > i) throw new Error("Total dispatch size exceeds WebGPU maximum."); + return [u, u, u]; + } else return [u, u, 1]; + } + }; + }); + var Jl = {}; + Dt(Jl, { WebGpuBackend: () => Co }); + var cg; + var pg; + var Io; + var Co; + var ec = U(() => { + "use strict"; + We(); + ee(); + Xe(); + Zn(); + Ja(); + Yl(); + Xl(); + cg = (e, t) => { + if (t.length !== e.length) throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`); + let r = []; + for (let n = 0; n < e.length; ++n) { + let o = e[n].dataType; + switch (t[n]) { + case "none": { + r.push(""); + break; + } + case "type": { + r.push(`${o}`); + break; + } + case "rank": { + let i = e[n].dims.length; + r.push(`${o};${i}`); + break; + } + case "dims": { + let i = e[n].dims.join(","); + r.push(`${o};${i}`); + break; + } + default: + throw new Error(`unsupported input dependency: ${t[n]}`); + } + } + return r.join("|"); + }, pg = (e, t, r) => { + let n = e.name; + return e.shaderCache?.hint && (n += "[" + e.shaderCache.hint + "]"), n += ":" + r + `:${cg(t, e.shaderCache?.inputDependencies ?? new Array(t.length).fill("dims"))}`, n; + }, Io = class { + constructor(t) { + t && (this.architecture = t.architecture, this.vendor = t.vendor); + } + isArchitecture(t) { + return this.architecture === t; + } + isVendor(t) { + return this.vendor === t; + } + }, Co = class { + constructor() { + this.currentSessionId = null; + this.currentKernelId = null; + this.commandEncoder = null; + this.computePassEncoder = null; + this.maxDispatchNumber = 16; + this.pendingDispatchNumber = 0; + this.pendingKernels = []; + this.pendingQueries = /* @__PURE__ */ new Map(); + this.sessionStatus = "default"; + this.capturedCommandList = /* @__PURE__ */ new Map(); + this.capturedPendingKernels = /* @__PURE__ */ new Map(); + this.sessionExternalDataMapping = /* @__PURE__ */ new Map(); + } + get currentKernelCustomData() { + if (this.currentKernelId === null) throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)"); + let t = this.kernelCustomData.get(this.currentKernelId); + return t || (t = {}, this.kernelCustomData.set(this.currentKernelId, t)), t; + } + async initialize(t, r) { + this.env = t; + let n = [], o = { requiredLimits: { maxComputeWorkgroupStorageSize: r.limits.maxComputeWorkgroupStorageSize, maxComputeWorkgroupsPerDimension: r.limits.maxComputeWorkgroupsPerDimension, maxStorageBufferBindingSize: r.limits.maxStorageBufferBindingSize, maxBufferSize: r.limits.maxBufferSize, maxComputeInvocationsPerWorkgroup: r.limits.maxComputeInvocationsPerWorkgroup, maxComputeWorkgroupSizeX: r.limits.maxComputeWorkgroupSizeX, maxComputeWorkgroupSizeY: r.limits.maxComputeWorkgroupSizeY, maxComputeWorkgroupSizeZ: r.limits.maxComputeWorkgroupSizeZ }, requiredFeatures: n }, i = (a) => r.features.has(a) && n.push(a) && true; + i("chromium-experimental-timestamp-query-inside-passes") || i("timestamp-query"), i("shader-f16"), i("subgroups"), this.device = await r.requestDevice(o), this.adapterInfo = new Io(r.info || await r.requestAdapterInfo()), this.gpuDataManager = Xa(this), this.programManager = new on(this), this.kernels = /* @__PURE__ */ new Map(), this.kernelPersistentData = /* @__PURE__ */ new Map(), this.kernelCustomData = /* @__PURE__ */ new Map(), Br(t.logLevel, !!t.debug), this.device.onuncapturederror = (a) => { + a.error instanceof GPUValidationError && console.error(`An uncaught WebGPU validation error was raised: ${a.error.message}`); + }, Object.defineProperty(this.env.webgpu, "device", { value: this.device, writable: false, enumerable: true, configurable: false }), Object.defineProperty(this.env.webgpu, "adapter", { value: r, writable: false, enumerable: true, configurable: false }), this.setQueryType(); + } + dispose() { + typeof this.querySet < "u" && this.querySet.destroy(), this.gpuDataManager.dispose(); + } + getCommandEncoder() { + return this.commandEncoder || (this.commandEncoder = this.device.createCommandEncoder()), this.commandEncoder; + } + getComputePassEncoder() { + if (!this.computePassEncoder) { + let t = this.getCommandEncoder(), r = {}; + this.queryType === "at-passes" && (r.timestampWrites = { querySet: this.querySet, beginningOfPassWriteIndex: this.pendingDispatchNumber * 2, endOfPassWriteIndex: this.pendingDispatchNumber * 2 + 1 }), this.computePassEncoder = t.beginComputePass(r); + } + return this.computePassEncoder; + } + endComputePass() { + this.computePassEncoder && (this.computePassEncoder.end(), this.computePassEncoder = null); + } + flush() { + if (!this.commandEncoder) return; + Re(), this.endComputePass(); + let t; + this.queryType !== "none" && (this.commandEncoder.resolveQuerySet(this.querySet, 0, this.pendingDispatchNumber * 2, this.queryResolveBuffer, 0), t = this.device.createBuffer({ size: this.pendingDispatchNumber * 2 * 8, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }), this.pendingQueries.set(t, this.pendingKernels), this.pendingKernels = [], this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer, 0, t, 0, this.pendingDispatchNumber * 2 * 8)), this.device.queue.submit([this.commandEncoder.finish()]), this.gpuDataManager.refreshPendingBuffers(), this.commandEncoder = null, this.pendingDispatchNumber = 0, this.queryType !== "none" && t.mapAsync(GPUMapMode.READ).then(() => { + let r = new BigUint64Array(t.getMappedRange()), n = this.pendingQueries.get(t); + for (let o = 0; o < r.length / 2; o++) { + let i = n[o], a = i.kernelId, u = this.kernels.get(a), d = u.kernelType, c = u.kernelName, p = i.programName, m = i.inputTensorViews, f = i.outputTensorViews, b = r[o * 2], g = r[o * 2 + 1]; + typeof this.queryTimeBase > "u" && (this.queryTimeBase = b); + let _ = Number(b - this.queryTimeBase), S = Number(g - this.queryTimeBase); + if (!Number.isSafeInteger(_) || !Number.isSafeInteger(S)) throw new RangeError("incorrect timestamp range"); + if (this.env.webgpu.profiling?.ondata) this.env.webgpu.profiling.ondata({ version: 1, inputsMetadata: m.map(($) => ({ dims: $.dims, dataType: Ye($.dataType) })), outputsMetadata: f.map(($) => ({ dims: $.dims, dataType: Ye($.dataType) })), kernelId: a, kernelType: d, kernelName: c, programName: p, startTime: _, endTime: S }); + else { + let $ = ""; + m.forEach((x, T) => { + $ += `input[${T}]: [${x.dims}] | ${Ye(x.dataType)}, `; + }); + let v = ""; + f.forEach((x, T) => { + v += `output[${T}]: [${x.dims}] | ${Ye(x.dataType)}, `; + }), console.log(`[profiling] kernel "${a}|${d}|${c}|${p}" ${$}${v}execution time: ${S - _} ns`); + } + gr("GPU", `${p}::${b}::${g}`); + } + t.unmap(), this.pendingQueries.delete(t); + }), Oe(); + } + run(t, r, n, o, i, a) { + Re(t.name); + let u = []; + for (let x = 0; x < r.length; ++x) { + let T = r[x].data; + if (T === 0) continue; + let E = this.gpuDataManager.get(T); + if (!E) throw new Error(`no GPU data for input: ${T}`); + u.push(E); + } + let { outputs: d, dispatchGroup: c, programUniforms: p } = t.getRunData(r), m = n.length === 0 ? d.map((x, T) => T) : n; + if (m.length !== d.length) throw new Error(`Output size ${m.length} must be equal to ${d.length}.`); + let f = [], b = []; + for (let x = 0; x < d.length; ++x) { + if (!Number.isInteger(m[x]) || m[x] < -3 || m[x] >= a) throw new Error(`Invalid output index: ${m[x]}`); + if (m[x] === -3) continue; + let T = m[x] === -1, E = m[x] === -2, I = T || E ? i(d[x].dataType, d[x].dims) : o(m[x], d[x].dataType, d[x].dims); + if (f.push(I), I.data === 0) continue; + let z = this.gpuDataManager.get(I.data); + if (!z) throw new Error(`no GPU data for output: ${I.data}`); + if (T && this.temporaryData.push(z), E) { + let O = this.kernelPersistentData.get(this.currentKernelId); + O || (O = [], this.kernelPersistentData.set(this.currentKernelId, O)), O.push(z); + } + b.push(z); + } + if (u.length !== r.length || b.length !== f.length) { + if (b.length === 0) return Oe(t.name), f; + throw new Error(`Program ${t.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`); + } + let g; + if (p) { + let x = 0, T = []; + p.forEach((O) => { + let D = typeof O.data == "number" ? [O.data] : O.data; + if (D.length === 0) return; + let L = O.type === 10 ? 2 : 4, q, Q; + O.type === 10 ? (Q = D.length > 4 ? 16 : D.length > 2 ? 8 : D.length * L, q = D.length > 4 ? 16 : L * D.length) : (Q = D.length <= 2 ? D.length * L : 16, q = 16), x = Math.ceil(x / Q) * Q, T.push(x); + let W = O.type === 10 ? 8 : 4; + x += D.length > 4 ? Math.ceil(D.length / W) * q : D.length * L; + }); + let E = 16; + x = Math.ceil(x / E) * E; + let I = new ArrayBuffer(x); + p.forEach((O, D) => { + let L = T[D], q = typeof O.data == "number" ? [O.data] : O.data; + if (O.type === 6) new Int32Array(I, L, q.length).set(q); + else if (O.type === 12) new Uint32Array(I, L, q.length).set(q); + else if (O.type === 10) new Uint16Array(I, L, q.length).set(q); + else if (O.type === 1) new Float32Array(I, L, q.length).set(q); + else throw new Error(`Unsupported uniform type: ${Ye(O.type)}`); + }); + let z = this.gpuDataManager.create(x, GPUBufferUsage.COPY_DST | GPUBufferUsage.UNIFORM); + this.device.queue.writeBuffer(z.buffer, 0, I, 0, x), this.gpuDataManager.release(z.id), g = { offset: 0, size: x, buffer: z.buffer }; + } + let _ = this.programManager.normalizeDispatchGroupSize(c), S = _[1] === 1 && _[2] === 1, $ = pg(t, r, S), v = this.programManager.getArtifact($); + if (v || (v = this.programManager.build(t, _), this.programManager.setArtifact($, v), se("info", () => `[artifact] key: ${$}, programName: ${t.name}`)), p && v.uniformVariablesInfo) { + if (p.length !== v.uniformVariablesInfo.length) throw new Error(`Uniform variables count mismatch: expect ${v.uniformVariablesInfo.length}, got ${p.length} in program "${v.programInfo.name}".`); + for (let x = 0; x < p.length; x++) { + let T = p[x], E = T.type, I = typeof T.data == "number" ? 1 : T.data.length, [z, O] = v.uniformVariablesInfo[x]; + if (E !== z || I !== O) throw new Error(`Uniform variable ${x} mismatch: expect type ${z} with size ${O}, got type ${E} with size ${I} in program "${v.programInfo.name}".`); + } + } + if (se("info", () => `[ProgramManager] run "${t.name}" (key=${$}) with ${_[0]}x${_[1]}x${_[2]}`), this.queryType !== "none" || this.sessionStatus === "capturing") { + let x = { kernelId: this.currentKernelId, programName: v.programInfo.name, inputTensorViews: r, outputTensorViews: f }; + this.pendingKernels.push(x), this.sessionStatus === "capturing" && this.capturedPendingKernels.get(this.currentSessionId).push(x); + } + return this.programManager.run(v, u, b, _, g), Oe(t.name), f; + } + upload(t, r) { + this.gpuDataManager.upload(t, r); + } + memcpy(t, r) { + this.gpuDataManager.memcpy(t, r); + } + async download(t, r) { + await this.gpuDataManager.download(t, r); + } + alloc(t) { + return this.gpuDataManager.create(t).id; + } + free(t) { + return this.gpuDataManager.release(t); + } + createKernel(t, r, n, o) { + let i = Ql.get(t); + if (!i) throw new Error(`kernel not implemented: ${t}`); + let a = { kernelType: t, kernelName: o, kernelEntry: i[0], attributes: [i[1], n] }; + this.kernels.set(r, a); + } + releaseKernel(t) { + let r = this.kernelPersistentData.get(t); + if (r) { + for (let n of r) this.gpuDataManager.release(n.id); + this.kernelPersistentData.delete(t); + } + this.kernelCustomData.delete(t), this.kernels.delete(t); + } + computeKernel(t, r, n) { + let o = this.kernels.get(t); + if (!o) throw new Error(`kernel not created: ${t}`); + let i = o.kernelType, a = o.kernelName, u = o.kernelEntry, d = o.attributes; + if (this.currentKernelId !== null) throw new Error(`kernel "[${i}] ${a}" is not allowed to be called recursively`); + this.currentKernelId = t, d[0] && (d[1] = d[0](d[1]), d[0] = void 0), se("info", () => `[WebGPU] Start to run kernel "[${i}] ${a}"...`); + let c = this.env.debug; + this.temporaryData = []; + try { + return c && this.device.pushErrorScope("validation"), u(r, d[1]), 0; + } catch (p) { + return n.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${a}" failed. ${p}`)), 1; + } finally { + c && n.push(this.device.popErrorScope().then((p) => p ? `GPU validation error for kernel "[${i}] ${a}": ${p.message}` : null)); + for (let p of this.temporaryData) this.gpuDataManager.release(p.id); + this.temporaryData = [], this.currentKernelId = null; + } + } + registerBuffer(t, r, n, o) { + let i = this.sessionExternalDataMapping.get(t); + i || (i = /* @__PURE__ */ new Map(), this.sessionExternalDataMapping.set(t, i)); + let a = i.get(r), u = this.gpuDataManager.registerExternalBuffer(n, o, a); + return i.set(r, [u, n]), u; + } + unregisterBuffers(t) { + let r = this.sessionExternalDataMapping.get(t); + r && (r.forEach((n) => this.gpuDataManager.unregisterExternalBuffer(n[0])), this.sessionExternalDataMapping.delete(t)); + } + getBuffer(t) { + let r = this.gpuDataManager.get(t); + if (!r) throw new Error(`no GPU data for buffer: ${t}`); + return r.buffer; + } + createDownloader(t, r, n) { + return async () => { + let o = await ro(this, t, r); + return Mr(o.buffer, n); + }; + } + writeTimestamp(t) { + this.queryType === "inside-passes" && this.computePassEncoder.writeTimestamp(this.querySet, t); + } + setQueryType() { + this.queryType = "none", (this.env.webgpu.profiling?.mode === "default" || (typeof this.env.trace > "u" ? this.env.wasm.trace : this.env.trace)) && (this.device.features.has("chromium-experimental-timestamp-query-inside-passes") ? this.queryType = "inside-passes" : this.device.features.has("timestamp-query") && (this.queryType = "at-passes"), this.queryType !== "none" && typeof this.querySet > "u" && (this.querySet = this.device.createQuerySet({ type: "timestamp", count: this.maxDispatchNumber * 2 }), this.queryResolveBuffer = this.device.createBuffer({ size: this.maxDispatchNumber * 2 * 8, usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.QUERY_RESOLVE }))); + } + captureBegin() { + se("info", "captureBegin"), this.capturedCommandList.get(this.currentSessionId) || this.capturedCommandList.set(this.currentSessionId, []), this.capturedPendingKernels.get(this.currentSessionId) || this.capturedPendingKernels.set(this.currentSessionId, []), this.flush(), this.sessionStatus = "capturing"; + } + captureEnd() { + se("info", "captureEnd"), this.flush(), this.sessionStatus = "default"; + } + replay() { + se("info", "replay"), this.sessionStatus = "replaying"; + let t = this.capturedCommandList.get(this.currentSessionId), r = this.capturedPendingKernels.get(this.currentSessionId), n = t.length; + this.pendingKernels = []; + for (let o = 0; o < n; o++) { + let i = this.getComputePassEncoder(), a = t[o]; + this.writeTimestamp(this.pendingDispatchNumber * 2), i.setPipeline(a.computePipeline), i.setBindGroup(0, a.bindGroup), i.dispatchWorkgroups(...a.dispatchGroup), this.writeTimestamp(this.pendingDispatchNumber * 2 + 1), this.pendingDispatchNumber++, this.queryType !== "none" && this.pendingKernels.push(r[o]), (this.pendingDispatchNumber >= this.maxDispatchNumber || this.queryType === "at-passes") && this.endComputePass(), this.pendingDispatchNumber >= this.maxDispatchNumber && this.flush(); + } + this.flush(), this.sessionStatus = "default"; + } + onCreateSession() { + this.gpuDataManager.onCreateSession(); + } + onReleaseSession(t) { + this.unregisterBuffers(t), this.capturedCommandList.has(t) && this.capturedCommandList.delete(t), this.capturedPendingKernels.has(t) && this.capturedPendingKernels.delete(t), this.gpuDataManager.onReleaseSession(t); + } + onRunStart(t) { + this.currentSessionId = t, this.setQueryType(); + } + }; + }); + var tc = {}; + Dt(tc, { init: () => mg }); + var tr; + var Ao; + var mg; + var rc = U(() => { + "use strict"; + ee(); + Xe(); + ne(); + Ka(); + tr = class e { + constructor(t, r, n, o) { + this.module = t; + this.dataType = r; + this.data = n; + this.dims = o; + } + getFloat32Array() { + if (this.dataType !== 1) throw new Error("Invalid data type"); + let t = k.size(this.dims); + return t === 0 ? new Float32Array() : new Float32Array(this.module.HEAP8.buffer, this.data, t); + } + getBigInt64Array() { + if (this.dataType !== 7) throw new Error("Invalid data type"); + let t = k.size(this.dims); + return t === 0 ? new BigInt64Array() : new BigInt64Array(this.module.HEAP8.buffer, this.data, t); + } + getInt32Array() { + if (this.dataType !== 6) throw new Error("Invalid data type"); + let t = k.size(this.dims); + return t === 0 ? new Int32Array() : new Int32Array(this.module.HEAP8.buffer, this.data, t); + } + getUint16Array() { + if (this.dataType !== 10 && this.dataType !== 4) throw new Error("Invalid data type"); + let t = k.size(this.dims); + return t === 0 ? new Uint16Array() : new Uint16Array(this.module.HEAP8.buffer, this.data, t); + } + reshape(t) { + if (k.size(t) !== k.size(this.dims)) throw new Error("Invalid new shape"); + return new e(this.module, this.dataType, this.data, t); + } + }, Ao = class { + constructor(t, r, n) { + this.module = t; + this.backend = r; + this.customDataOffset = 0; + this.customDataSize = 0; + this.adapterInfo = r.adapterInfo; + let o = t.PTR_SIZE, i = n / t.PTR_SIZE, a = o === 4 ? "i32" : "i64"; + this.opKernelContext = Number(t.getValue(o * i++, a)); + let u = Number(t.getValue(o * i++, a)); + this.outputCount = Number(t.getValue(o * i++, a)), this.customDataOffset = Number(t.getValue(o * i++, "*")), this.customDataSize = Number(t.getValue(o * i++, a)); + let d = []; + for (let c = 0; c < u; c++) { + let p = Number(t.getValue(o * i++, a)), m = Number(t.getValue(o * i++, "*")), f = Number(t.getValue(o * i++, a)), b = []; + for (let g = 0; g < f; g++) b.push(Number(t.getValue(o * i++, a))); + d.push(new tr(t, p, m, b)); + } + this.inputs = d; + } + get kernelCustomData() { + return this.backend.currentKernelCustomData; + } + get customDataBuffer() { + return this.module.HEAPU8.subarray(this.customDataOffset, this.customDataOffset + this.customDataSize); + } + compute(t, r) { + let n = r?.inputs?.map((u) => typeof u == "number" ? this.inputs[u] : u) ?? this.inputs, o = r?.outputs ?? [], i = (u, d, c) => new tr(this.module, d, this.output(u, c), c), a = (u, d) => { + let c = gt(u, d); + if (!c) throw new Error(`Unsupported data type: ${u}`); + let p = c > 0 ? this.backend.gpuDataManager.create(c).id : 0; + return new tr(this.module, u, p, d); + }; + return this.backend.run(t, n, o, i, a, this.outputCount); + } + output(t, r) { + let n = this.module.stackSave(); + try { + let o = this.module.PTR_SIZE, i = o === 4 ? "i32" : "i64", a = this.module.stackAlloc((1 + r.length) * o); + this.module.setValue(a, r.length, i); + for (let u = 0; u < r.length; u++) this.module.setValue(a + o * (u + 1), r[u], i); + return this.module._JsepOutput(this.opKernelContext, t, a); + } catch (o) { + throw new Error(`Failed to generate kernel's output[${t}] with dims [${r}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${o}`); + } finally { + this.module.stackRestore(n); + } + } + }, mg = async (e, t, r, n) => { + let o = t.jsepInit; + if (!o) throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support."); + if (e === "webgpu") { + let i = (ec(), Ft(Jl)).WebGpuBackend, a = new i(); + await a.initialize(r, n), o("webgpu", [a, (u) => a.alloc(Number(u)), (u) => a.free(u), (u, d, c, p = false) => { + if (p) se("verbose", () => `[WebGPU] jsepCopyGpuToGpu: src=${Number(u)}, dst=${Number(d)}, size=${Number(c)}`), a.memcpy(Number(u), Number(d)); + else { + se("verbose", () => `[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(u)}, gpuDataId=${Number(d)}, size=${Number(c)}`); + let m = t.HEAPU8.subarray(Number(u >>> 0), Number(u >>> 0) + Number(c)); + a.upload(Number(d), m); + } + }, async (u, d, c) => { + se("verbose", () => `[WebGPU] jsepCopyGpuToCpu: gpuDataId=${u}, dataOffset=${d}, size=${c}`), await a.download(Number(u), () => t.HEAPU8.subarray(Number(d) >>> 0, Number(d + c) >>> 0)); + }, (u, d, c) => a.createKernel(u, Number(d), c, t.UTF8ToString(t._JsepGetNodeName(Number(d)))), (u) => a.releaseKernel(u), (u, d, c, p) => { + se("verbose", () => `[WebGPU] jsepRun: sessionHandle=${c}, kernel=${u}, contextDataOffset=${d}`); + let m = new Ao(t, a, Number(d)); + return a.computeKernel(Number(u), m, p); + }, () => a.captureBegin(), () => a.captureEnd(), () => a.replay()]); + } else { + let i = new Nr(r); + o("webnn", [i, () => i.reserveTensorId(), (a) => i.releaseTensorId(a), async (a, u, d, c, p) => i.ensureTensor(a, u, d, c, p), (a, u) => { + i.uploadTensor(a, u); + }, async (a, u) => i.downloadTensor(a, u)]); + } + }; + }); + var fg; + var vr; + var $r; + var At; + var hg; + var nc; + var jt; + var xr; + var Sr; + var oc; + var Tr; + var Ir; + var Cr; + var Vn = U(() => { + "use strict"; + Ma(); + Ua(); + ee(); + ht(); + Er(); + jn(); + fg = (e, t) => { + fe()._OrtInit(e, t) !== 0 && pe("Can't initialize onnxruntime."); + }, vr = async (e) => { + fg(e.wasm.numThreads, Zt(e.logLevel)); + }, $r = async (e, t) => { + fe().asyncInit?.(); + { + let r = (rc(), Ft(tc)).init; + if (t === "webgpu") { + if (typeof navigator > "u" || !navigator.gpu) throw new Error("WebGPU is not supported in current environment"); + let n = e.webgpu.adapter; + if (n) { + if (typeof n.limits != "object" || typeof n.features != "object" || typeof n.requestDevice != "function") throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object."); + } else { + let o = e.webgpu.powerPreference; + if (o !== void 0 && o !== "low-power" && o !== "high-performance") throw new Error(`Invalid powerPreference setting: "${o}"`); + let i = e.webgpu.forceFallbackAdapter; + if (i !== void 0 && typeof i != "boolean") throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`); + if (n = await navigator.gpu.requestAdapter({ powerPreference: o, forceFallbackAdapter: i }), !n) throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.'); + } + await r("webgpu", fe(), e, n); + } + if (t === "webnn") { + if (typeof navigator > "u" || !navigator.ml) throw new Error("WebNN is not supported in current environment"); + await r("webnn", fe(), e); + } + } + }, At = /* @__PURE__ */ new Map(), hg = (e) => { + let t = fe(), r = t.stackSave(); + try { + let n = t.PTR_SIZE, o = t.stackAlloc(2 * n); + t._OrtGetInputOutputCount(e, o, o + n) !== 0 && pe("Can't get session input/output count."); + let a = n === 4 ? "i32" : "i64"; + return [Number(t.getValue(o, a)), Number(t.getValue(o + n, a))]; + } finally { + t.stackRestore(r); + } + }, nc = (e, t) => { + let r = fe(), n = r.stackSave(), o = 0; + try { + let i = r.PTR_SIZE, a = r.stackAlloc(2 * i); + r._OrtGetInputOutputMetadata(e, t, a, a + i) !== 0 && pe("Can't get session input/output metadata."); + let d = Number(r.getValue(a, "*")); + o = Number(r.getValue(a + i, "*")); + let c = r.HEAP32[o / 4]; + if (c === 0) return [d, 0]; + let p = r.HEAPU32[o / 4 + 1], m = []; + for (let f = 0; f < p; f++) { + let b = Number(r.getValue(o + 8 + f * i, "*")); + m.push(b !== 0 ? r.UTF8ToString(b) : Number(r.getValue(o + 8 + (f + p) * i, "*"))); + } + return [d, c, m]; + } finally { + r.stackRestore(n), o !== 0 && r._OrtFree(o); + } + }, jt = (e) => { + let t = fe(), r = t._malloc(e.byteLength); + if (r === 0) throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`); + return t.HEAPU8.set(e, r), [r, e.byteLength]; + }, xr = async (e, t) => { + let r, n, o = fe(); + Array.isArray(e) ? [r, n] = e : e.buffer === o.HEAPU8.buffer ? [r, n] = [e.byteOffset, e.byteLength] : [r, n] = jt(e); + let i = 0, a = 0, u = 0, d = [], c = [], p = []; + try { + if ([a, d] = await Ra(t), t?.externalData && o.mountExternalData) { + let T = []; + for (let E of t.externalData) { + let I = typeof E == "string" ? E : E.path; + T.push(Qt(typeof E == "string" ? E : E.data).then((z) => { + o.mountExternalData(I, z); + })); + } + await Promise.all(T); + } + for (let T of t?.executionProviders ?? []) if ((typeof T == "string" ? T : T.name) === "webnn") { + if (o.shouldTransferToMLTensor = false, typeof T != "string") { + let I = T, z = I?.context, O = I?.gpuDevice, D = I?.deviceType, L = I?.powerPreference; + z ? o.currentContext = z : O ? o.currentContext = await o.webnnCreateMLContext(O) : o.currentContext = await o.webnnCreateMLContext({ deviceType: D, powerPreference: L }); + } else o.currentContext = await o.webnnCreateMLContext(); + break; + } + i = await o._OrtCreateSession(r, n, a), o.webgpuOnCreateSession?.(i), i === 0 && pe("Can't create a session."), o.jsepOnCreateSession?.(), o.currentContext && (o.webnnRegisterMLContext(i, o.currentContext), o.currentContext = void 0, o.shouldTransferToMLTensor = true); + let [m, f] = hg(i), b = !!t?.enableGraphCapture, g = [], _ = [], S = [], $ = [], v = []; + for (let T = 0; T < m; T++) { + let [E, I, z] = nc(i, T); + E === 0 && pe("Can't get an input name."), c.push(E); + let O = o.UTF8ToString(E); + g.push(O), S.push(I === 0 ? { name: O, isTensor: false } : { name: O, isTensor: true, type: Ye(I), shape: z }); + } + for (let T = 0; T < f; T++) { + let [E, I, z] = nc(i, T + m); + E === 0 && pe("Can't get an output name."), p.push(E); + let O = o.UTF8ToString(E); + _.push(O), $.push(I === 0 ? { name: O, isTensor: false } : { name: O, isTensor: true, type: Ye(I), shape: z }); + { + if (b && t?.preferredOutputLocation === void 0) { + v.push("gpu-buffer"); + continue; + } + let D = typeof t?.preferredOutputLocation == "string" ? t.preferredOutputLocation : t?.preferredOutputLocation?.[O] ?? "cpu"; + if (D !== "cpu" && D !== "cpu-pinned" && D !== "gpu-buffer" && D !== "ml-tensor") throw new Error(`Not supported preferred output location: ${D}.`); + if (b && D !== "gpu-buffer") throw new Error(`Not supported preferred output location: ${D}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`); + v.push(D); + } + } + let x = null; + return v.some((T) => T === "gpu-buffer" || T === "ml-tensor") && (u = o._OrtCreateBinding(i), u === 0 && pe("Can't create IO binding."), x = { handle: u, outputPreferredLocations: v, outputPreferredLocationsEncoded: v.map((T) => qn(T)) }), At.set(i, [i, c, p, x, b, false]), [i, g, _, S, $]; + } catch (m) { + throw c.forEach((f) => o._OrtFree(f)), p.forEach((f) => o._OrtFree(f)), u !== 0 && o._OrtReleaseBinding(u) !== 0 && pe("Can't release IO binding."), i !== 0 && o._OrtReleaseSession(i) !== 0 && pe("Can't release session."), m; + } finally { + o._free(r), a !== 0 && o._OrtReleaseSessionOptions(a) !== 0 && pe("Can't release session options."), d.forEach((m) => o._free(m)), o.unmountExternalData?.(); + } + }, Sr = (e) => { + let t = fe(), r = At.get(e); + if (!r) throw new Error(`cannot release session. invalid session id: ${e}`); + let [n, o, i, a, u] = r; + a && (u && t._OrtClearBoundOutputs(a.handle) !== 0 && pe("Can't clear bound outputs."), t._OrtReleaseBinding(a.handle) !== 0 && pe("Can't release IO binding.")), t.jsepOnReleaseSession?.(e), t.webnnOnReleaseSession?.(e), t.webgpuOnReleaseSession?.(e), o.forEach((d) => t._OrtFree(d)), i.forEach((d) => t._OrtFree(d)), t._OrtReleaseSession(n) !== 0 && pe("Can't release session."), At.delete(e); + }, oc = async (e, t, r, n, o, i, a = false) => { + if (!e) { + t.push(0); + return; + } + let u = fe(), d = u.PTR_SIZE, c = e[0], p = e[1], m = e[3], f = m, b, g; + if (c === "string" && (m === "gpu-buffer" || m === "ml-tensor")) throw new Error("String tensor is not supported on GPU."); + if (a && m !== "gpu-buffer") throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`); + if (m === "gpu-buffer") { + let $ = e[2].gpuBuffer; + g = gt(Mt(c), p); + { + let v = u.jsepRegisterBuffer; + if (!v) throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.'); + b = v(n, i, $, g); + } + } else if (m === "ml-tensor") { + let $ = e[2].mlTensor; + g = gt(Mt(c), p); + let v = u.webnnRegisterMLTensor; + if (!v) throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.'); + b = v(n, $, Mt(c), p); + } else { + let $ = e[2]; + if (Array.isArray($)) { + g = d * $.length, b = u._malloc(g), r.push(b); + for (let v = 0; v < $.length; v++) { + if (typeof $[v] != "string") throw new TypeError(`tensor data at index ${v} is not a string`); + u.setValue(b + v * d, Ne($[v], r), "*"); + } + } else { + let v = u.webnnIsGraphInput; + if (c !== "string" && v) { + let x = u.UTF8ToString(o); + if (v(n, x)) { + let T = Mt(c); + g = gt(T, p), f = "ml-tensor"; + let E = u.webnnCreateTemporaryTensor, I = u.webnnUploadTensor; + if (!E || !I) throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.'); + let z = await E(n, T, p); + I(z, new Uint8Array($.buffer, $.byteOffset, $.byteLength)), b = z; + } else g = $.byteLength, b = u._malloc(g), r.push(b), u.HEAPU8.set(new Uint8Array($.buffer, $.byteOffset, g), b); + } else g = $.byteLength, b = u._malloc(g), r.push(b), u.HEAPU8.set(new Uint8Array($.buffer, $.byteOffset, g), b); + } + } + let _ = u.stackSave(), S = u.stackAlloc(4 * p.length); + try { + p.forEach((v, x) => u.setValue(S + x * d, v, d === 4 ? "i32" : "i64")); + let $ = u._OrtCreateTensor(Mt(c), b, g, S, p.length, qn(f)); + $ === 0 && pe(`Can't create tensor for input/output. session=${n}, index=${i}.`), t.push($); + } finally { + u.stackRestore(_); + } + }, Tr = async (e, t, r, n, o, i) => { + let a = fe(), u = a.PTR_SIZE, d = At.get(e); + if (!d) throw new Error(`cannot run inference. invalid session id: ${e}`); + let c = d[0], p = d[1], m = d[2], f = d[3], b = d[4], g = d[5], _ = t.length, S = n.length, $ = 0, v = [], x = [], T = [], E = [], I = a.stackSave(), z = a.stackAlloc(_ * u), O = a.stackAlloc(_ * u), D = a.stackAlloc(S * u), L = a.stackAlloc(S * u); + try { + [$, v] = Da(i); + for (let W = 0; W < _; W++) await oc(r[W], x, E, e, p[t[W]], t[W], b); + for (let W = 0; W < S; W++) await oc(o[W], T, E, e, m[n[W]], _ + n[W], b); + for (let W = 0; W < _; W++) a.setValue(z + W * u, x[W], "*"), a.setValue(O + W * u, p[t[W]], "*"); + for (let W = 0; W < S; W++) a.setValue(D + W * u, T[W], "*"), a.setValue(L + W * u, m[n[W]], "*"); + if (f && !g) { + let { handle: W, outputPreferredLocations: Z, outputPreferredLocationsEncoded: we } = f; + if (p.length !== _) throw new Error(`input count from feeds (${_}) is expected to be always equal to model's input count (${p.length}).`); + for (let H = 0; H < _; H++) { + let j = t[H]; + await a._OrtBindInput(W, p[j], x[H]) !== 0 && pe(`Can't bind input[${H}] for session=${e}.`); + } + for (let H = 0; H < S; H++) { + let j = n[H]; + o[H]?.[3] ? a._OrtBindOutput(W, m[j], T[H], 0) !== 0 && pe(`Can't bind pre-allocated output[${H}] for session=${e}.`) : a._OrtBindOutput(W, m[j], 0, we[j]) !== 0 && pe(`Can't bind output[${H}] to ${Z[H]} for session=${e}.`); + } + At.set(e, [c, p, m, f, b, true]); + } + a.jsepOnRunStart?.(c), a.webnnOnRunStart?.(c); + let q; + f ? q = await a._OrtRunWithBinding(c, f.handle, S, D, $) : q = await a._OrtRun(c, O, z, _, L, S, D, $), q !== 0 && pe("failed to call OrtRun()."); + let Q = []; + for (let W = 0; W < S; W++) { + let Z = Number(a.getValue(D + W * u, "*")); + if (Z === T[W]) { + Q.push(o[W]); + continue; + } + let we = a.stackSave(), H = a.stackAlloc(4 * u), j = false, te, X = 0; + try { + a._OrtGetTensorData(Z, H, H + u, H + 2 * u, H + 3 * u) !== 0 && pe(`Can't access output tensor data on index ${W}.`); + let he = u === 4 ? "i32" : "i64", ye = Number(a.getValue(H, he)); + X = a.getValue(H + u, "*"); + let re = a.getValue(H + u * 2, "*"), C = Number(a.getValue(H + u * 3, he)), V = []; + for (let ve = 0; ve < C; ve++) V.push(Number(a.getValue(re + ve * u, he))); + a._OrtFree(re) !== 0 && pe("Can't free memory for tensor dims."); + let de = V.reduce((ve, $e) => ve * $e, 1); + te = Ye(ye); + let ze = f?.outputPreferredLocations[n[W]]; + if (te === "string") { + if (ze === "gpu-buffer" || ze === "ml-tensor") throw new Error("String tensor is not supported on GPU."); + let ve = []; + for (let $e = 0; $e < de; $e++) { + let Ce = a.getValue(X + $e * u, "*"), _t = a.getValue(X + ($e + 1) * u, "*"), kt = $e === de - 1 ? void 0 : _t - Ce; + ve.push(a.UTF8ToString(Ce, kt)); + } + Q.push([te, V, ve, "cpu"]); + } else if (ze === "gpu-buffer" && de > 0) { + let ve = a.jsepGetBuffer; + if (!ve) throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.'); + let $e = ve(X), Ce = gt(ye, de); + if (Ce === void 0 || !zr(te)) throw new Error(`Unsupported data type: ${te}`); + j = true, Q.push([te, V, { gpuBuffer: $e, download: a.jsepCreateDownloader($e, Ce, te), dispose: () => { + a._OrtReleaseTensor(Z) !== 0 && pe("Can't release tensor."); + } }, "gpu-buffer"]); + } else if (ze === "ml-tensor" && de > 0) { + let ve = a.webnnEnsureTensor, $e = a.webnnIsInt64Supported; + if (!ve || !$e) throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.'); + if (gt(ye, de) === void 0 || !Or(te)) throw new Error(`Unsupported data type: ${te}`); + if (te === "int64" && !$e(e)) throw new Error('preferredLocation "ml-tensor" for int64 output is not supported by current WebNN Context.'); + let _t = await ve(e, X, ye, V, false); + j = true, Q.push([te, V, { mlTensor: _t, download: a.webnnCreateMLTensorDownloader(X, te), dispose: () => { + a.webnnReleaseTensorId(X), a._OrtReleaseTensor(Z); + } }, "ml-tensor"]); + } else { + let ve = Pr(te), $e = new ve(de); + new Uint8Array($e.buffer, $e.byteOffset, $e.byteLength).set(a.HEAPU8.subarray(X, X + $e.byteLength)), Q.push([te, V, $e, "cpu"]); + } + } finally { + a.stackRestore(we), te === "string" && X && a._free(X), j || a._OrtReleaseTensor(Z), a.webnnOnRunEnd?.(c); + } + } + return f && !b && (a._OrtClearBoundOutputs(f.handle) !== 0 && pe("Can't clear bound outputs."), At.set(e, [c, p, m, f, b, false])), Q; + } finally { + a.stackRestore(I), x.forEach((q) => a._OrtReleaseTensor(q)), T.forEach((q) => a._OrtReleaseTensor(q)), E.forEach((q) => a._free(q)), $ !== 0 && a._OrtReleaseRunOptions($), v.forEach((q) => a._free(q)); + } + }, Ir = (e) => { + let t = fe(), r = At.get(e); + if (!r) throw new Error("invalid session id"); + let n = r[0], o = t._OrtEndProfiling(n); + o === 0 && pe("Can't get an profile file name."), t._OrtFree(o); + }, Cr = (e) => { + let t = []; + for (let r of e) { + let n = r[2]; + !Array.isArray(n) && "buffer" in n && t.push(n.buffer); + } + return t; + }; + }); + var Et; + var Le; + var rr; + var sn; + var un; + var an; + var Eo; + var ko; + var Vt; + var Wt; + var bg; + var ic; + var ac; + var sc; + var uc; + var dc; + var lc; + var cc; + var Po = U(() => { + "use strict"; + We(); + Vn(); + ht(); + _r(); + Et = () => !!ge.wasm.proxy && typeof document < "u", rr = false, sn = false, un = false, ko = /* @__PURE__ */ new Map(), Vt = (e, t) => { + let r = ko.get(e); + r ? r.push(t) : ko.set(e, [t]); + }, Wt = () => { + if (rr || !sn || un || !Le) throw new Error("worker not ready"); + }, bg = (e) => { + switch (e.data.type) { + case "init-wasm": + rr = false, e.data.err ? (un = true, Eo[1](e.data.err)) : (sn = true, Eo[0]()), an && (URL.revokeObjectURL(an), an = void 0); + break; + case "init-ep": + case "copy-from": + case "create": + case "release": + case "run": + case "end-profiling": { + let t = ko.get(e.data.type); + e.data.err ? t.shift()[1](e.data.err) : t.shift()[0](e.data.out); + break; + } + default: + } + }, ic = async () => { + if (!sn) { + if (rr) throw new Error("multiple calls to 'initWasm()' detected."); + if (un) throw new Error("previous call to 'initWasm()' failed."); + if (rr = true, Et()) return new Promise((e, t) => { + Le?.terminate(), za().then(([r, n]) => { + try { + Le = n, Le.onerror = (i) => t(i), Le.onmessage = bg, Eo = [e, t]; + let o = { type: "init-wasm", in: ge }; + !o.in.wasm.wasmPaths && (r || Gn) && (o.in.wasm.wasmPaths = { wasm: new URL("ort-wasm-simd-threaded.jsep.wasm", import_meta.url).href }), Le.postMessage(o), an = r; + } catch (o) { + t(o); + } + }, t); + }); + try { + await wr(ge.wasm), await vr(ge), sn = true; + } catch (e) { + throw un = true, e; + } finally { + rr = false; + } + } + }, ac = async (e) => { + if (Et()) return Wt(), new Promise((t, r) => { + Vt("init-ep", [t, r]); + let n = { type: "init-ep", in: { epName: e, env: ge } }; + Le.postMessage(n); + }); + await $r(ge, e); + }, sc = async (e) => Et() ? (Wt(), new Promise((t, r) => { + Vt("copy-from", [t, r]); + let n = { type: "copy-from", in: { buffer: e } }; + Le.postMessage(n, [e.buffer]); + })) : jt(e), uc = async (e, t) => { + if (Et()) { + if (t?.preferredOutputLocation) throw new Error('session option "preferredOutputLocation" is not supported for proxy.'); + return Wt(), new Promise((r, n) => { + Vt("create", [r, n]); + let o = { type: "create", in: { model: e, options: { ...t } } }, i = []; + e instanceof Uint8Array && i.push(e.buffer), Le.postMessage(o, i); + }); + } else return xr(e, t); + }, dc = async (e) => { + if (Et()) return Wt(), new Promise((t, r) => { + Vt("release", [t, r]); + let n = { type: "release", in: e }; + Le.postMessage(n); + }); + Sr(e); + }, lc = async (e, t, r, n, o, i) => { + if (Et()) { + if (r.some((a) => a[3] !== "cpu")) throw new Error("input tensor on GPU is not supported for proxy."); + if (o.some((a) => a)) throw new Error("pre-allocated output tensor is not supported for proxy."); + return Wt(), new Promise((a, u) => { + Vt("run", [a, u]); + let d = r, c = { type: "run", in: { sessionId: e, inputIndices: t, inputs: d, outputIndices: n, options: i } }; + Le.postMessage(c, Cr(d)); + }); + } else return Tr(e, t, r, n, o, i); + }, cc = async (e) => { + if (Et()) return Wt(), new Promise((t, r) => { + Vt("end-profiling", [t, r]); + let n = { type: "end-profiling", in: e }; + Le.postMessage(n); + }); + Ir(e); + }; + }); + var pc; + var yg; + var dn; + var mc = U(() => { + "use strict"; + We(); + Po(); + ee(); + yr(); + jn(); + pc = (e, t) => { + switch (e.location) { + case "cpu": + return [e.type, e.dims, e.data, "cpu"]; + case "gpu-buffer": + return [e.type, e.dims, { gpuBuffer: e.gpuBuffer }, "gpu-buffer"]; + case "ml-tensor": + return [e.type, e.dims, { mlTensor: e.mlTensor }, "ml-tensor"]; + default: + throw new Error(`invalid data location: ${e.location} for ${t()}`); + } + }, yg = (e) => { + switch (e[3]) { + case "cpu": + return new Ge(e[0], e[2], e[1]); + case "gpu-buffer": { + let t = e[0]; + if (!zr(t)) throw new Error(`not supported data type: ${t} for deserializing GPU tensor`); + let { gpuBuffer: r, download: n, dispose: o } = e[2]; + return Ge.fromGpuBuffer(r, { dataType: t, dims: e[1], download: n, dispose: o }); + } + case "ml-tensor": { + let t = e[0]; + if (!Or(t)) throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`); + let { mlTensor: r, download: n, dispose: o } = e[2]; + return Ge.fromMLTensor(r, { dataType: t, dims: e[1], download: n, dispose: o }); + } + default: + throw new Error(`invalid data location: ${e[3]}`); + } + }, dn = class { + async fetchModelAndCopyToWasmMemory(t) { + return sc(await Qt(t)); + } + async loadModel(t, r) { + Re(); + let n; + typeof t == "string" ? n = await this.fetchModelAndCopyToWasmMemory(t) : n = t, [this.sessionId, this.inputNames, this.outputNames, this.inputMetadata, this.outputMetadata] = await uc(n, r), Oe(); + } + async dispose() { + return dc(this.sessionId); + } + async run(t, r, n) { + Re(); + let o = [], i = []; + Object.entries(t).forEach((f) => { + let b = f[0], g = f[1], _ = this.inputNames.indexOf(b); + if (_ === -1) throw new Error(`invalid input '${b}'`); + o.push(g), i.push(_); + }); + let a = [], u = []; + Object.entries(r).forEach((f) => { + let b = f[0], g = f[1], _ = this.outputNames.indexOf(b); + if (_ === -1) throw new Error(`invalid output '${b}'`); + a.push(g), u.push(_); + }); + let d = o.map((f, b) => pc(f, () => `input "${this.inputNames[i[b]]}"`)), c = a.map((f, b) => f ? pc(f, () => `output "${this.outputNames[u[b]]}"`) : null), p = await lc(this.sessionId, i, d, u, c, n), m = {}; + for (let f = 0; f < p.length; f++) m[this.outputNames[u[f]]] = a[f] ?? yg(p[f]); + return Oe(), m; + } + startProfiling() { + } + endProfiling() { + cc(this.sessionId); + } + }; + }); + var hc = {}; + Dt(hc, { OnnxruntimeWebAssemblyBackend: () => ln, initializeFlags: () => fc, wasmBackend: () => _g }); + var fc; + var ln; + var _g; + var gc = U(() => { + "use strict"; + We(); + Po(); + mc(); + fc = () => { + (typeof ge.wasm.initTimeout != "number" || ge.wasm.initTimeout < 0) && (ge.wasm.initTimeout = 0); + let e = ge.wasm.simd; + if (typeof e != "boolean" && e !== void 0 && e !== "fixed" && e !== "relaxed" && (console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`), ge.wasm.simd = false), typeof ge.wasm.proxy != "boolean" && (ge.wasm.proxy = false), typeof ge.wasm.trace != "boolean" && (ge.wasm.trace = false), typeof ge.wasm.numThreads != "number" || !Number.isInteger(ge.wasm.numThreads) || ge.wasm.numThreads <= 0) if (typeof self < "u" && !self.crossOriginIsolated) ge.wasm.numThreads = 1; + else { + let t = typeof navigator > "u" ? On("node:os").cpus().length : navigator.hardwareConcurrency; + ge.wasm.numThreads = Math.min(4, Math.ceil((t || 1) / 2)); + } + }, ln = class { + async init(t) { + fc(), await ic(), await ac(t); + } + async createInferenceSessionHandler(t, r) { + let n = new dn(); + return await n.loadModel(t, r), n; + } + }, _g = new ln(); + }); + We(); + We(); + We(); + var _a = "1.22.0-dev.20250409-89f8206ba4"; + var IS = Nn; + { + let e = (gc(), Ft(hc)).wasmBackend; + $t("webgpu", e, 5), $t("webnn", e, 5), $t("cpu", e, 10), $t("wasm", e, 10); + } + Object.defineProperty(ge.versions, "web", { value: _a, enumerable: true }); + + // node_modules/@huggingface/transformers/dist/transformers.web.js + var import_meta2 = {}; + var __webpack_modules__ = { + /***/ + "onnxruntime-common": ( + /*!*************************************!*\ + !*** external "onnxruntime-common" ***! + \*************************************/ + /***/ + ((module) => { + module.exports = esm_exports; + }) + ), + /***/ + "onnxruntime-web": ( + /*!**********************************!*\ + !*** external "onnxruntime-web" ***! + \**********************************/ + /***/ + ((module) => { + module.exports = ort_bundle_min_exports; + }) + ), + /***/ + "?2ce3": ( + /*!**********************************!*\ + !*** onnxruntime-node (ignored) ***! + \**********************************/ + /***/ + (() => { + }) + ), + /***/ + "?7992": ( + /*!*************************!*\ + !*** node:fs (ignored) ***! + \*************************/ + /***/ + (() => { + }) + ), + /***/ + "?5af5": ( + /*!***************************!*\ + !*** node:path (ignored) ***! + \***************************/ + /***/ + (() => { + }) + ), + /***/ + "?2b25": ( + /*!***********************!*\ + !*** sharp (ignored) ***! + \***********************/ + /***/ + (() => { + }) + ), + /***/ + "?db59": ( + /*!*************************!*\ + !*** node:fs (ignored) ***! + \*************************/ + /***/ + (() => { + }) + ), + /***/ + "?383f": ( + /*!***************************!*\ + !*** node:path (ignored) ***! + \***************************/ + /***/ + (() => { + }) + ), + /***/ + "?fa4b": ( + /*!**************************!*\ + !*** node:url (ignored) ***! + \**************************/ + /***/ + (() => { + }) + ), + /***/ + "./node_modules/@huggingface/jinja/dist/index.js": ( + /*!*******************************************************!*\ + !*** ./node_modules/@huggingface/jinja/dist/index.js ***! + \*******************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + Environment: () => ( + /* binding */ + Environment + ), + /* harmony export */ + Interpreter: () => ( + /* binding */ + Interpreter + ), + /* harmony export */ + Template: () => ( + /* binding */ + Template + ), + /* harmony export */ + parse: () => ( + /* binding */ + parse + ), + /* harmony export */ + tokenize: () => ( + /* binding */ + tokenize + ) + /* harmony export */ + }); + var TOKEN_TYPES = Object.freeze({ + Text: "Text", + // The text between Jinja statements or expressions + NumericLiteral: "NumericLiteral", + // e.g., 123, 1.0 + StringLiteral: "StringLiteral", + // 'string' + Identifier: "Identifier", + // Variables, functions, statements, booleans, etc. + Equals: "Equals", + // = + OpenParen: "OpenParen", + // ( + CloseParen: "CloseParen", + // ) + OpenStatement: "OpenStatement", + // {% + CloseStatement: "CloseStatement", + // %} + OpenExpression: "OpenExpression", + // {{ + CloseExpression: "CloseExpression", + // }} + OpenSquareBracket: "OpenSquareBracket", + // [ + CloseSquareBracket: "CloseSquareBracket", + // ] + OpenCurlyBracket: "OpenCurlyBracket", + // { + CloseCurlyBracket: "CloseCurlyBracket", + // } + Comma: "Comma", + // , + Dot: "Dot", + // . + Colon: "Colon", + // : + Pipe: "Pipe", + // | + CallOperator: "CallOperator", + // () + AdditiveBinaryOperator: "AdditiveBinaryOperator", + // + - ~ + MultiplicativeBinaryOperator: "MultiplicativeBinaryOperator", + // * / % + ComparisonBinaryOperator: "ComparisonBinaryOperator", + // < > <= >= == != + UnaryOperator: "UnaryOperator", + // ! - + + Comment: "Comment" + // {# ... #} + }); + var Token = class { + /** + * Constructs a new Token. + * @param {string} value The raw value as seen inside the source code. + * @param {TokenType} type The type of token. + */ + constructor(value, type) { + this.value = value; + this.type = type; + } + }; + function isWord(char) { + return /\w/.test(char); + } + function isInteger(char) { + return /[0-9]/.test(char); + } + function isWhitespace(char) { + return /\s/.test(char); + } + var ORDERED_MAPPING_TABLE = [ + // Control sequences + ["{%", TOKEN_TYPES.OpenStatement], + ["%}", TOKEN_TYPES.CloseStatement], + ["{{", TOKEN_TYPES.OpenExpression], + ["}}", TOKEN_TYPES.CloseExpression], + // Single character tokens + ["(", TOKEN_TYPES.OpenParen], + [")", TOKEN_TYPES.CloseParen], + ["{", TOKEN_TYPES.OpenCurlyBracket], + ["}", TOKEN_TYPES.CloseCurlyBracket], + ["[", TOKEN_TYPES.OpenSquareBracket], + ["]", TOKEN_TYPES.CloseSquareBracket], + [",", TOKEN_TYPES.Comma], + [".", TOKEN_TYPES.Dot], + [":", TOKEN_TYPES.Colon], + ["|", TOKEN_TYPES.Pipe], + // Comparison operators + ["<=", TOKEN_TYPES.ComparisonBinaryOperator], + [">=", TOKEN_TYPES.ComparisonBinaryOperator], + ["==", TOKEN_TYPES.ComparisonBinaryOperator], + ["!=", TOKEN_TYPES.ComparisonBinaryOperator], + ["<", TOKEN_TYPES.ComparisonBinaryOperator], + [">", TOKEN_TYPES.ComparisonBinaryOperator], + // Arithmetic operators + ["+", TOKEN_TYPES.AdditiveBinaryOperator], + ["-", TOKEN_TYPES.AdditiveBinaryOperator], + ["~", TOKEN_TYPES.AdditiveBinaryOperator], + ["*", TOKEN_TYPES.MultiplicativeBinaryOperator], + ["/", TOKEN_TYPES.MultiplicativeBinaryOperator], + ["%", TOKEN_TYPES.MultiplicativeBinaryOperator], + // Assignment operator + ["=", TOKEN_TYPES.Equals] + ]; + var ESCAPE_CHARACTERS = /* @__PURE__ */ new Map([ + ["n", "\n"], + // New line + ["t", " "], + // Horizontal tab + ["r", "\r"], + // Carriage return + ["b", "\b"], + // Backspace + ["f", "\f"], + // Form feed + ["v", "\v"], + // Vertical tab + ["'", "'"], + // Single quote + ['"', '"'], + // Double quote + ["\\", "\\"] + // Backslash + ]); + function preprocess(template, options = {}) { + if (template.endsWith("\n")) { + template = template.slice(0, -1); + } + if (options.lstrip_blocks) { + template = template.replace(/^[ \t]*({[#%-])/gm, "$1"); + } + if (options.trim_blocks) { + template = template.replace(/([#%-]})\n/g, "$1"); + } + return template.replace(/{%\s*(end)?generation\s*%}/gs, ""); + } + function tokenize(source, options = {}) { + const tokens = []; + const src = preprocess(source, options); + let cursorPosition = 0; + let curlyBracketDepth = 0; + const consumeWhile = (predicate) => { + let str = ""; + while (predicate(src[cursorPosition])) { + if (src[cursorPosition] === "\\") { + ++cursorPosition; + if (cursorPosition >= src.length) + throw new SyntaxError("Unexpected end of input"); + const escaped = src[cursorPosition++]; + const unescaped = ESCAPE_CHARACTERS.get(escaped); + if (unescaped === void 0) { + throw new SyntaxError(`Unexpected escaped character: ${escaped}`); + } + str += unescaped; + continue; + } + str += src[cursorPosition++]; + if (cursorPosition >= src.length) + throw new SyntaxError("Unexpected end of input"); + } + return str; + }; + const stripTrailingWhitespace = () => { + const lastToken = tokens.at(-1); + if (lastToken && lastToken.type === TOKEN_TYPES.Text) { + lastToken.value = lastToken.value.trimEnd(); + if (lastToken.value === "") { + tokens.pop(); + } + } + }; + const skipLeadingWhitespace = () => { + while (cursorPosition < src.length && isWhitespace(src[cursorPosition])) { + ++cursorPosition; + } + }; + main: + while (cursorPosition < src.length) { + const lastTokenType = tokens.at(-1)?.type; + if (lastTokenType === void 0 || lastTokenType === TOKEN_TYPES.CloseStatement || lastTokenType === TOKEN_TYPES.CloseExpression || lastTokenType === TOKEN_TYPES.Comment) { + let text = ""; + while (cursorPosition < src.length && // Keep going until we hit the next Jinja statement or expression + !(src[cursorPosition] === "{" && (src[cursorPosition + 1] === "%" || src[cursorPosition + 1] === "{" || src[cursorPosition + 1] === "#"))) { + text += src[cursorPosition++]; + } + if (text.length > 0) { + tokens.push(new Token(text, TOKEN_TYPES.Text)); + continue; + } + } + if (src[cursorPosition] === "{" && src[cursorPosition + 1] === "#") { + cursorPosition += 2; + const stripBefore = src[cursorPosition] === "-"; + if (stripBefore) { + ++cursorPosition; + } + let comment = ""; + while (src[cursorPosition] !== "#" || src[cursorPosition + 1] !== "}") { + if (cursorPosition + 2 >= src.length) { + throw new SyntaxError("Missing end of comment tag"); + } + comment += src[cursorPosition++]; + } + const stripAfter = comment.endsWith("-"); + if (stripAfter) { + comment = comment.slice(0, -1); + } + if (stripBefore) { + stripTrailingWhitespace(); + } + tokens.push(new Token(comment, TOKEN_TYPES.Comment)); + cursorPosition += 2; + if (stripAfter) { + skipLeadingWhitespace(); + } + continue; + } + if (src.slice(cursorPosition, cursorPosition + 3) === "{%-") { + stripTrailingWhitespace(); + tokens.push(new Token("{%", TOKEN_TYPES.OpenStatement)); + cursorPosition += 3; + continue; + } + if (src.slice(cursorPosition, cursorPosition + 3) === "{{-") { + stripTrailingWhitespace(); + tokens.push(new Token("{{", TOKEN_TYPES.OpenExpression)); + curlyBracketDepth = 0; + cursorPosition += 3; + continue; + } + consumeWhile(isWhitespace); + if (src.slice(cursorPosition, cursorPosition + 3) === "-%}") { + tokens.push(new Token("%}", TOKEN_TYPES.CloseStatement)); + cursorPosition += 3; + skipLeadingWhitespace(); + continue; + } + if (src.slice(cursorPosition, cursorPosition + 3) === "-}}") { + tokens.push(new Token("}}", TOKEN_TYPES.CloseExpression)); + cursorPosition += 3; + skipLeadingWhitespace(); + continue; + } + const char = src[cursorPosition]; + if (char === "-" || char === "+") { + const lastTokenType2 = tokens.at(-1)?.type; + if (lastTokenType2 === TOKEN_TYPES.Text || lastTokenType2 === void 0) { + throw new SyntaxError(`Unexpected character: ${char}`); + } + switch (lastTokenType2) { + case TOKEN_TYPES.Identifier: + case TOKEN_TYPES.NumericLiteral: + case TOKEN_TYPES.StringLiteral: + case TOKEN_TYPES.CloseParen: + case TOKEN_TYPES.CloseSquareBracket: + break; + default: { + ++cursorPosition; + const num = consumeWhile(isInteger); + tokens.push( + new Token(`${char}${num}`, num.length > 0 ? TOKEN_TYPES.NumericLiteral : TOKEN_TYPES.UnaryOperator) + ); + continue; + } + } + } + for (const [seq, type] of ORDERED_MAPPING_TABLE) { + if (seq === "}}" && curlyBracketDepth > 0) { + continue; + } + const slice2 = src.slice(cursorPosition, cursorPosition + seq.length); + if (slice2 === seq) { + tokens.push(new Token(seq, type)); + if (type === TOKEN_TYPES.OpenExpression) { + curlyBracketDepth = 0; + } else if (type === TOKEN_TYPES.OpenCurlyBracket) { + ++curlyBracketDepth; + } else if (type === TOKEN_TYPES.CloseCurlyBracket) { + --curlyBracketDepth; + } + cursorPosition += seq.length; + continue main; + } + } + if (char === "'" || char === '"') { + ++cursorPosition; + const str = consumeWhile((c) => c !== char); + tokens.push(new Token(str, TOKEN_TYPES.StringLiteral)); + ++cursorPosition; + continue; + } + if (isInteger(char)) { + let num = consumeWhile(isInteger); + if (src[cursorPosition] === "." && isInteger(src[cursorPosition + 1])) { + ++cursorPosition; + const frac = consumeWhile(isInteger); + num = `${num}.${frac}`; + } + tokens.push(new Token(num, TOKEN_TYPES.NumericLiteral)); + continue; + } + if (isWord(char)) { + const word = consumeWhile(isWord); + tokens.push(new Token(word, TOKEN_TYPES.Identifier)); + continue; + } + throw new SyntaxError(`Unexpected character: ${char}`); + } + return tokens; + } + var Statement = class { + type = "Statement"; + }; + var Program = class extends Statement { + constructor(body) { + super(); + this.body = body; + } + type = "Program"; + }; + var If2 = class extends Statement { + constructor(test, body, alternate) { + super(); + this.test = test; + this.body = body; + this.alternate = alternate; + } + type = "If"; + }; + var For = class extends Statement { + constructor(loopvar, iterable, body, defaultBlock) { + super(); + this.loopvar = loopvar; + this.iterable = iterable; + this.body = body; + this.defaultBlock = defaultBlock; + } + type = "For"; + }; + var Break = class extends Statement { + type = "Break"; + }; + var Continue = class extends Statement { + type = "Continue"; + }; + var SetStatement = class extends Statement { + constructor(assignee, value, body) { + super(); + this.assignee = assignee; + this.value = value; + this.body = body; + } + type = "Set"; + }; + var Macro = class extends Statement { + constructor(name, args, body) { + super(); + this.name = name; + this.args = args; + this.body = body; + } + type = "Macro"; + }; + var Comment = class extends Statement { + constructor(value) { + super(); + this.value = value; + } + type = "Comment"; + }; + var Expression = class extends Statement { + type = "Expression"; + }; + var MemberExpression = class extends Expression { + constructor(object, property, computed) { + super(); + this.object = object; + this.property = property; + this.computed = computed; + } + type = "MemberExpression"; + }; + var CallExpression = class extends Expression { + constructor(callee, args) { + super(); + this.callee = callee; + this.args = args; + } + type = "CallExpression"; + }; + var Identifier = class extends Expression { + /** + * @param {string} value The name of the identifier + */ + constructor(value) { + super(); + this.value = value; + } + type = "Identifier"; + }; + var Literal = class extends Expression { + constructor(value) { + super(); + this.value = value; + } + type = "Literal"; + }; + var IntegerLiteral = class extends Literal { + type = "IntegerLiteral"; + }; + var FloatLiteral = class extends Literal { + type = "FloatLiteral"; + }; + var StringLiteral = class extends Literal { + type = "StringLiteral"; + }; + var ArrayLiteral = class extends Literal { + type = "ArrayLiteral"; + }; + var TupleLiteral = class extends Literal { + type = "TupleLiteral"; + }; + var ObjectLiteral = class extends Literal { + type = "ObjectLiteral"; + }; + var BinaryExpression = class extends Expression { + constructor(operator, left, right) { + super(); + this.operator = operator; + this.left = left; + this.right = right; + } + type = "BinaryExpression"; + }; + var FilterExpression = class extends Expression { + constructor(operand, filter) { + super(); + this.operand = operand; + this.filter = filter; + } + type = "FilterExpression"; + }; + var FilterStatement = class extends Statement { + constructor(filter, body) { + super(); + this.filter = filter; + this.body = body; + } + type = "FilterStatement"; + }; + var SelectExpression = class extends Expression { + constructor(lhs, test) { + super(); + this.lhs = lhs; + this.test = test; + } + type = "SelectExpression"; + }; + var TestExpression = class extends Expression { + constructor(operand, negate, test) { + super(); + this.operand = operand; + this.negate = negate; + this.test = test; + } + type = "TestExpression"; + }; + var UnaryExpression = class extends Expression { + constructor(operator, argument) { + super(); + this.operator = operator; + this.argument = argument; + } + type = "UnaryExpression"; + }; + var SliceExpression = class extends Expression { + constructor(start = void 0, stop = void 0, step = void 0) { + super(); + this.start = start; + this.stop = stop; + this.step = step; + } + type = "SliceExpression"; + }; + var KeywordArgumentExpression = class extends Expression { + constructor(key, value) { + super(); + this.key = key; + this.value = value; + } + type = "KeywordArgumentExpression"; + }; + var SpreadExpression = class extends Expression { + constructor(argument) { + super(); + this.argument = argument; + } + type = "SpreadExpression"; + }; + var CallStatement = class extends Statement { + constructor(call, callerArgs, body) { + super(); + this.call = call; + this.callerArgs = callerArgs; + this.body = body; + } + type = "CallStatement"; + }; + var Ternary = class extends Expression { + constructor(condition, trueExpr, falseExpr) { + super(); + this.condition = condition; + this.trueExpr = trueExpr; + this.falseExpr = falseExpr; + } + type = "Ternary"; + }; + function parse(tokens) { + const program = new Program([]); + let current = 0; + function expect(type, error) { + const prev = tokens[current++]; + if (!prev || prev.type !== type) { + throw new Error(`Parser Error: ${error}. ${prev.type} !== ${type}.`); + } + return prev; + } + function expectIdentifier(name) { + if (!isIdentifier(name)) { + throw new SyntaxError(`Expected ${name}`); + } + ++current; + } + function parseAny() { + switch (tokens[current].type) { + case TOKEN_TYPES.Comment: + return new Comment(tokens[current++].value); + case TOKEN_TYPES.Text: + return parseText(); + case TOKEN_TYPES.OpenStatement: + return parseJinjaStatement(); + case TOKEN_TYPES.OpenExpression: + return parseJinjaExpression(); + default: + throw new SyntaxError(`Unexpected token type: ${tokens[current].type}`); + } + } + function is2(...types) { + return current + types.length <= tokens.length && types.every((type, i) => type === tokens[current + i].type); + } + function isStatement(...names) { + return tokens[current]?.type === TOKEN_TYPES.OpenStatement && tokens[current + 1]?.type === TOKEN_TYPES.Identifier && names.includes(tokens[current + 1]?.value); + } + function isIdentifier(...names) { + return current + names.length <= tokens.length && names.every((name, i) => tokens[current + i].type === "Identifier" && name === tokens[current + i].value); + } + function parseText() { + return new StringLiteral(expect(TOKEN_TYPES.Text, "Expected text token").value); + } + function parseJinjaStatement() { + expect(TOKEN_TYPES.OpenStatement, "Expected opening statement token"); + if (tokens[current].type !== TOKEN_TYPES.Identifier) { + throw new SyntaxError(`Unknown statement, got ${tokens[current].type}`); + } + const name = tokens[current].value; + let result; + switch (name) { + case "set": + ++current; + result = parseSetStatement(); + break; + case "if": + ++current; + result = parseIfStatement(); + expect(TOKEN_TYPES.OpenStatement, "Expected {% token"); + expectIdentifier("endif"); + expect(TOKEN_TYPES.CloseStatement, "Expected %} token"); + break; + case "macro": + ++current; + result = parseMacroStatement(); + expect(TOKEN_TYPES.OpenStatement, "Expected {% token"); + expectIdentifier("endmacro"); + expect(TOKEN_TYPES.CloseStatement, "Expected %} token"); + break; + case "for": + ++current; + result = parseForStatement(); + expect(TOKEN_TYPES.OpenStatement, "Expected {% token"); + expectIdentifier("endfor"); + expect(TOKEN_TYPES.CloseStatement, "Expected %} token"); + break; + case "call": { + ++current; + let callerArgs = null; + if (is2(TOKEN_TYPES.OpenParen)) { + callerArgs = parseArgs(); + } + const callee = parsePrimaryExpression(); + if (callee.type !== "Identifier") { + throw new SyntaxError(`Expected identifier following call statement`); + } + const callArgs = parseArgs(); + expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); + const body = []; + while (!isStatement("endcall")) { + body.push(parseAny()); + } + expect(TOKEN_TYPES.OpenStatement, "Expected '{%'"); + expectIdentifier("endcall"); + expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); + const callExpr = new CallExpression(callee, callArgs); + result = new CallStatement(callExpr, callerArgs, body); + break; + } + case "break": + ++current; + expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); + result = new Break(); + break; + case "continue": + ++current; + expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); + result = new Continue(); + break; + case "filter": { + ++current; + let filterNode = parsePrimaryExpression(); + if (filterNode instanceof Identifier && is2(TOKEN_TYPES.OpenParen)) { + filterNode = parseCallExpression(filterNode); + } + expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); + const filterBody = []; + while (!isStatement("endfilter")) { + filterBody.push(parseAny()); + } + expect(TOKEN_TYPES.OpenStatement, "Expected '{%'"); + expectIdentifier("endfilter"); + expect(TOKEN_TYPES.CloseStatement, "Expected '%}'"); + result = new FilterStatement(filterNode, filterBody); + break; + } + default: + throw new SyntaxError(`Unknown statement type: ${name}`); + } + return result; + } + function parseJinjaExpression() { + expect(TOKEN_TYPES.OpenExpression, "Expected opening expression token"); + const result = parseExpression(); + expect(TOKEN_TYPES.CloseExpression, "Expected closing expression token"); + return result; + } + function parseSetStatement() { + const left = parseExpressionSequence(); + let value = null; + const body = []; + if (is2(TOKEN_TYPES.Equals)) { + ++current; + value = parseExpressionSequence(); + } else { + expect(TOKEN_TYPES.CloseStatement, "Expected %} token"); + while (!isStatement("endset")) { + body.push(parseAny()); + } + expect(TOKEN_TYPES.OpenStatement, "Expected {% token"); + expectIdentifier("endset"); + } + expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); + return new SetStatement(left, value, body); + } + function parseIfStatement() { + const test = parseExpression(); + expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); + const body = []; + const alternate = []; + while (!isStatement("elif", "else", "endif")) { + body.push(parseAny()); + } + if (isStatement("elif")) { + ++current; + ++current; + const result = parseIfStatement(); + alternate.push(result); + } else if (isStatement("else")) { + ++current; + ++current; + expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); + while (!isStatement("endif")) { + alternate.push(parseAny()); + } + } + return new If2(test, body, alternate); + } + function parseMacroStatement() { + const name = parsePrimaryExpression(); + if (name.type !== "Identifier") { + throw new SyntaxError(`Expected identifier following macro statement`); + } + const args = parseArgs(); + expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); + const body = []; + while (!isStatement("endmacro")) { + body.push(parseAny()); + } + return new Macro(name, args, body); + } + function parseExpressionSequence(primary = false) { + const fn = primary ? parsePrimaryExpression : parseExpression; + const expressions = [fn()]; + const isTuple = is2(TOKEN_TYPES.Comma); + while (isTuple) { + ++current; + expressions.push(fn()); + if (!is2(TOKEN_TYPES.Comma)) { + break; + } + } + return isTuple ? new TupleLiteral(expressions) : expressions[0]; + } + function parseForStatement() { + const loopVariable = parseExpressionSequence(true); + if (!(loopVariable instanceof Identifier || loopVariable instanceof TupleLiteral)) { + throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${loopVariable.type} instead`); + } + if (!isIdentifier("in")) { + throw new SyntaxError("Expected `in` keyword following loop variable"); + } + ++current; + const iterable = parseExpression(); + expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); + const body = []; + while (!isStatement("endfor", "else")) { + body.push(parseAny()); + } + const alternative = []; + if (isStatement("else")) { + ++current; + ++current; + expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); + while (!isStatement("endfor")) { + alternative.push(parseAny()); + } + } + return new For(loopVariable, iterable, body, alternative); + } + function parseExpression() { + return parseIfExpression(); + } + function parseIfExpression() { + const a = parseLogicalOrExpression(); + if (isIdentifier("if")) { + ++current; + const test = parseLogicalOrExpression(); + if (isIdentifier("else")) { + ++current; + const falseExpr = parseIfExpression(); + return new Ternary(test, a, falseExpr); + } else { + return new SelectExpression(a, test); + } + } + return a; + } + function parseLogicalOrExpression() { + let left = parseLogicalAndExpression(); + while (isIdentifier("or")) { + const operator = tokens[current]; + ++current; + const right = parseLogicalAndExpression(); + left = new BinaryExpression(operator, left, right); + } + return left; + } + function parseLogicalAndExpression() { + let left = parseLogicalNegationExpression(); + while (isIdentifier("and")) { + const operator = tokens[current]; + ++current; + const right = parseLogicalNegationExpression(); + left = new BinaryExpression(operator, left, right); + } + return left; + } + function parseLogicalNegationExpression() { + let right; + while (isIdentifier("not")) { + const operator = tokens[current]; + ++current; + const arg = parseLogicalNegationExpression(); + right = new UnaryExpression(operator, arg); + } + return right ?? parseComparisonExpression(); + } + function parseComparisonExpression() { + let left = parseAdditiveExpression(); + while (true) { + let operator; + if (isIdentifier("not", "in")) { + operator = new Token("not in", TOKEN_TYPES.Identifier); + current += 2; + } else if (isIdentifier("in")) { + operator = tokens[current++]; + } else if (is2(TOKEN_TYPES.ComparisonBinaryOperator)) { + operator = tokens[current++]; + } else { + break; + } + const right = parseAdditiveExpression(); + left = new BinaryExpression(operator, left, right); + } + return left; + } + function parseAdditiveExpression() { + let left = parseMultiplicativeExpression(); + while (is2(TOKEN_TYPES.AdditiveBinaryOperator)) { + const operator = tokens[current]; + ++current; + const right = parseMultiplicativeExpression(); + left = new BinaryExpression(operator, left, right); + } + return left; + } + function parseCallMemberExpression() { + const member = parseMemberExpression(parsePrimaryExpression()); + if (is2(TOKEN_TYPES.OpenParen)) { + return parseCallExpression(member); + } + return member; + } + function parseCallExpression(callee) { + let expression = new CallExpression(callee, parseArgs()); + expression = parseMemberExpression(expression); + if (is2(TOKEN_TYPES.OpenParen)) { + expression = parseCallExpression(expression); + } + return expression; + } + function parseArgs() { + expect(TOKEN_TYPES.OpenParen, "Expected opening parenthesis for arguments list"); + const args = parseArgumentsList(); + expect(TOKEN_TYPES.CloseParen, "Expected closing parenthesis for arguments list"); + return args; + } + function parseArgumentsList() { + const args = []; + while (!is2(TOKEN_TYPES.CloseParen)) { + let argument; + if (tokens[current].type === TOKEN_TYPES.MultiplicativeBinaryOperator && tokens[current].value === "*") { + ++current; + const expr = parseExpression(); + argument = new SpreadExpression(expr); + } else { + argument = parseExpression(); + if (is2(TOKEN_TYPES.Equals)) { + ++current; + if (!(argument instanceof Identifier)) { + throw new SyntaxError(`Expected identifier for keyword argument`); + } + const value = parseExpression(); + argument = new KeywordArgumentExpression(argument, value); + } + } + args.push(argument); + if (is2(TOKEN_TYPES.Comma)) { + ++current; + } + } + return args; + } + function parseMemberExpressionArgumentsList() { + const slices = []; + let isSlice = false; + while (!is2(TOKEN_TYPES.CloseSquareBracket)) { + if (is2(TOKEN_TYPES.Colon)) { + slices.push(void 0); + ++current; + isSlice = true; + } else { + slices.push(parseExpression()); + if (is2(TOKEN_TYPES.Colon)) { + ++current; + isSlice = true; + } + } + } + if (slices.length === 0) { + throw new SyntaxError(`Expected at least one argument for member/slice expression`); + } + if (isSlice) { + if (slices.length > 3) { + throw new SyntaxError(`Expected 0-3 arguments for slice expression`); + } + return new SliceExpression(...slices); + } + return slices[0]; + } + function parseMemberExpression(object) { + while (is2(TOKEN_TYPES.Dot) || is2(TOKEN_TYPES.OpenSquareBracket)) { + const operator = tokens[current]; + ++current; + let property; + const computed = operator.type === TOKEN_TYPES.OpenSquareBracket; + if (computed) { + property = parseMemberExpressionArgumentsList(); + expect(TOKEN_TYPES.CloseSquareBracket, "Expected closing square bracket"); + } else { + property = parsePrimaryExpression(); + if (property.type !== "Identifier") { + throw new SyntaxError(`Expected identifier following dot operator`); + } + } + object = new MemberExpression(object, property, computed); + } + return object; + } + function parseMultiplicativeExpression() { + let left = parseTestExpression(); + while (is2(TOKEN_TYPES.MultiplicativeBinaryOperator)) { + const operator = tokens[current++]; + const right = parseTestExpression(); + left = new BinaryExpression(operator, left, right); + } + return left; + } + function parseTestExpression() { + let operand = parseFilterExpression(); + while (isIdentifier("is")) { + ++current; + const negate = isIdentifier("not"); + if (negate) { + ++current; + } + const filter = parsePrimaryExpression(); + if (!(filter instanceof Identifier)) { + throw new SyntaxError(`Expected identifier for the test`); + } + operand = new TestExpression(operand, negate, filter); + } + return operand; + } + function parseFilterExpression() { + let operand = parseCallMemberExpression(); + while (is2(TOKEN_TYPES.Pipe)) { + ++current; + let filter = parsePrimaryExpression(); + if (!(filter instanceof Identifier)) { + throw new SyntaxError(`Expected identifier for the filter`); + } + if (is2(TOKEN_TYPES.OpenParen)) { + filter = parseCallExpression(filter); + } + operand = new FilterExpression(operand, filter); + } + return operand; + } + function parsePrimaryExpression() { + const token = tokens[current++]; + switch (token.type) { + case TOKEN_TYPES.NumericLiteral: { + const num = token.value; + return num.includes(".") ? new FloatLiteral(Number(num)) : new IntegerLiteral(Number(num)); + } + case TOKEN_TYPES.StringLiteral: { + let value = token.value; + while (is2(TOKEN_TYPES.StringLiteral)) { + value += tokens[current++].value; + } + return new StringLiteral(value); + } + case TOKEN_TYPES.Identifier: + return new Identifier(token.value); + case TOKEN_TYPES.OpenParen: { + const expression = parseExpressionSequence(); + expect(TOKEN_TYPES.CloseParen, "Expected closing parenthesis, got ${tokens[current].type} instead."); + return expression; + } + case TOKEN_TYPES.OpenSquareBracket: { + const values = []; + while (!is2(TOKEN_TYPES.CloseSquareBracket)) { + values.push(parseExpression()); + if (is2(TOKEN_TYPES.Comma)) { + ++current; + } + } + ++current; + return new ArrayLiteral(values); + } + case TOKEN_TYPES.OpenCurlyBracket: { + const values = /* @__PURE__ */ new Map(); + while (!is2(TOKEN_TYPES.CloseCurlyBracket)) { + const key = parseExpression(); + expect(TOKEN_TYPES.Colon, "Expected colon between key and value in object literal"); + const value = parseExpression(); + values.set(key, value); + if (is2(TOKEN_TYPES.Comma)) { + ++current; + } + } + ++current; + return new ObjectLiteral(values); + } + default: + throw new SyntaxError(`Unexpected token: ${token.type}`); + } + } + while (current < tokens.length) { + program.body.push(parseAny()); + } + return program; + } + function range(start, stop, step = 1) { + if (stop === void 0) { + stop = start; + start = 0; + } + const result = []; + for (let i = start; i < stop; i += step) { + result.push(i); + } + return result; + } + function slice(array, start, stop, step = 1) { + const direction = Math.sign(step); + if (direction >= 0) { + start = (start ??= 0) < 0 ? Math.max(array.length + start, 0) : Math.min(start, array.length); + stop = (stop ??= array.length) < 0 ? Math.max(array.length + stop, 0) : Math.min(stop, array.length); + } else { + start = (start ??= array.length - 1) < 0 ? Math.max(array.length + start, -1) : Math.min(start, array.length - 1); + stop = (stop ??= -1) < -1 ? Math.max(array.length + stop, -1) : Math.min(stop, array.length - 1); + } + const result = []; + for (let i = start; direction * i < direction * stop; i += step) { + result.push(array[i]); + } + return result; + } + function titleCase(value) { + return value.replace(/\b\w/g, (c) => c.toUpperCase()); + } + function strftime_now(format2) { + return strftime(/* @__PURE__ */ new Date(), format2); + } + function strftime(date, format2) { + const monthFormatterLong = new Intl.DateTimeFormat(void 0, { month: "long" }); + const monthFormatterShort = new Intl.DateTimeFormat(void 0, { month: "short" }); + const pad2 = (n) => n < 10 ? "0" + n : n.toString(); + return format2.replace(/%[YmdbBHM%]/g, (token) => { + switch (token) { + case "%Y": + return date.getFullYear().toString(); + case "%m": + return pad2(date.getMonth() + 1); + case "%d": + return pad2(date.getDate()); + case "%b": + return monthFormatterShort.format(date); + case "%B": + return monthFormatterLong.format(date); + case "%H": + return pad2(date.getHours()); + case "%M": + return pad2(date.getMinutes()); + case "%%": + return "%"; + default: + return token; + } + }); + } + function escapeRegExp(s) { + return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + } + function replace(str, oldvalue, newvalue, count) { + if (count === 0) + return str; + let remaining = count == null || count < 0 ? Infinity : count; + const pattern = oldvalue.length === 0 ? new RegExp("(?=)", "gu") : new RegExp(escapeRegExp(oldvalue), "gu"); + return str.replaceAll(pattern, (match) => { + if (remaining > 0) { + --remaining; + return newvalue; + } + return match; + }); + } + var BreakControl = class extends Error { + }; + var ContinueControl = class extends Error { + }; + var RuntimeValue = class { + type = "RuntimeValue"; + value; + /** + * A collection of built-in functions for this type. + */ + builtins = /* @__PURE__ */ new Map(); + /** + * Creates a new RuntimeValue. + */ + constructor(value = void 0) { + this.value = value; + } + /** + * Determines truthiness or falsiness of the runtime value. + * This function should be overridden by subclasses if it has custom truthiness criteria. + * @returns {BooleanValue} BooleanValue(true) if the value is truthy, BooleanValue(false) otherwise. + */ + __bool__() { + return new BooleanValue(!!this.value); + } + toString() { + return String(this.value); + } + }; + var IntegerValue = class extends RuntimeValue { + type = "IntegerValue"; + }; + var FloatValue = class extends RuntimeValue { + type = "FloatValue"; + toString() { + return this.value % 1 === 0 ? this.value.toFixed(1) : this.value.toString(); + } + }; + var StringValue = class extends RuntimeValue { + type = "StringValue"; + builtins = /* @__PURE__ */ new Map([ + [ + "upper", + new FunctionValue(() => { + return new StringValue(this.value.toUpperCase()); + }) + ], + [ + "lower", + new FunctionValue(() => { + return new StringValue(this.value.toLowerCase()); + }) + ], + [ + "strip", + new FunctionValue(() => { + return new StringValue(this.value.trim()); + }) + ], + [ + "title", + new FunctionValue(() => { + return new StringValue(titleCase(this.value)); + }) + ], + [ + "capitalize", + new FunctionValue(() => { + return new StringValue(this.value.charAt(0).toUpperCase() + this.value.slice(1)); + }) + ], + ["length", new IntegerValue(this.value.length)], + [ + "rstrip", + new FunctionValue(() => { + return new StringValue(this.value.trimEnd()); + }) + ], + [ + "lstrip", + new FunctionValue(() => { + return new StringValue(this.value.trimStart()); + }) + ], + [ + "startswith", + new FunctionValue((args) => { + if (args.length === 0) { + throw new Error("startswith() requires at least one argument"); + } + const pattern = args[0]; + if (pattern instanceof StringValue) { + return new BooleanValue(this.value.startsWith(pattern.value)); + } else if (pattern instanceof ArrayValue) { + for (const item of pattern.value) { + if (!(item instanceof StringValue)) { + throw new Error("startswith() tuple elements must be strings"); + } + if (this.value.startsWith(item.value)) { + return new BooleanValue(true); + } + } + return new BooleanValue(false); + } + throw new Error("startswith() argument must be a string or tuple of strings"); + }) + ], + [ + "endswith", + new FunctionValue((args) => { + if (args.length === 0) { + throw new Error("endswith() requires at least one argument"); + } + const pattern = args[0]; + if (pattern instanceof StringValue) { + return new BooleanValue(this.value.endsWith(pattern.value)); + } else if (pattern instanceof ArrayValue) { + for (const item of pattern.value) { + if (!(item instanceof StringValue)) { + throw new Error("endswith() tuple elements must be strings"); + } + if (this.value.endsWith(item.value)) { + return new BooleanValue(true); + } + } + return new BooleanValue(false); + } + throw new Error("endswith() argument must be a string or tuple of strings"); + }) + ], + [ + "split", + // follows Python's `str.split(sep=None, maxsplit=-1)` function behavior + // https://docs.python.org/3.13/library/stdtypes.html#str.split + new FunctionValue((args) => { + const sep = args[0] ?? new NullValue(); + if (!(sep instanceof StringValue || sep instanceof NullValue)) { + throw new Error("sep argument must be a string or null"); + } + const maxsplit = args[1] ?? new IntegerValue(-1); + if (!(maxsplit instanceof IntegerValue)) { + throw new Error("maxsplit argument must be a number"); + } + let result = []; + if (sep instanceof NullValue) { + const text = this.value.trimStart(); + for (const { 0: match, index } of text.matchAll(/\S+/g)) { + if (maxsplit.value !== -1 && result.length >= maxsplit.value && index !== void 0) { + result.push(match + text.slice(index + match.length)); + break; + } + result.push(match); + } + } else { + if (sep.value === "") { + throw new Error("empty separator"); + } + result = this.value.split(sep.value); + if (maxsplit.value !== -1 && result.length > maxsplit.value) { + result.push(result.splice(maxsplit.value).join(sep.value)); + } + } + return new ArrayValue(result.map((part) => new StringValue(part))); + }) + ], + [ + "replace", + new FunctionValue((args) => { + if (args.length < 2) { + throw new Error("replace() requires at least two arguments"); + } + const oldValue = args[0]; + const newValue = args[1]; + if (!(oldValue instanceof StringValue && newValue instanceof StringValue)) { + throw new Error("replace() arguments must be strings"); + } + let count; + if (args.length > 2) { + if (args[2].type === "KeywordArgumentsValue") { + count = args[2].value.get("count") ?? new NullValue(); + } else { + count = args[2]; + } + } else { + count = new NullValue(); + } + if (!(count instanceof IntegerValue || count instanceof NullValue)) { + throw new Error("replace() count argument must be a number or null"); + } + return new StringValue(replace(this.value, oldValue.value, newValue.value, count.value)); + }) + ] + ]); + }; + var BooleanValue = class extends RuntimeValue { + type = "BooleanValue"; + }; + function toJSON(input, indent, depth, convertUndefinedToNull = true) { + const currentDepth = depth ?? 0; + switch (input.type) { + case "NullValue": + return "null"; + case "UndefinedValue": + return convertUndefinedToNull ? "null" : "undefined"; + case "IntegerValue": + case "FloatValue": + case "StringValue": + case "BooleanValue": + return JSON.stringify(input.value); + case "ArrayValue": + case "ObjectValue": { + const indentValue = indent ? " ".repeat(indent) : ""; + const basePadding = "\n" + indentValue.repeat(currentDepth); + const childrenPadding = basePadding + indentValue; + if (input.type === "ArrayValue") { + const core = input.value.map( + (x) => toJSON(x, indent, currentDepth + 1, convertUndefinedToNull) + ); + return indent ? `[${childrenPadding}${core.join(`,${childrenPadding}`)}${basePadding}]` : `[${core.join(", ")}]`; + } else { + const core = Array.from(input.value.entries()).map(([key, value]) => { + const v = `"${key}": ${toJSON(value, indent, currentDepth + 1, convertUndefinedToNull)}`; + return indent ? `${childrenPadding}${v}` : v; + }); + return indent ? `{${core.join(",")}${basePadding}}` : `{${core.join(", ")}}`; + } + } + default: + throw new Error(`Cannot convert to JSON: ${input.type}`); + } + } + var ObjectValue = class extends RuntimeValue { + type = "ObjectValue"; + /** + * NOTE: necessary to override since all JavaScript arrays are considered truthy, + * while only non-empty Python arrays are consider truthy. + * + * e.g., + * - JavaScript: {} && 5 -> 5 + * - Python: {} and 5 -> {} + */ + __bool__() { + return new BooleanValue(this.value.size > 0); + } + builtins = /* @__PURE__ */ new Map([ + [ + "get", + new FunctionValue(([key, defaultValue]) => { + if (!(key instanceof StringValue)) { + throw new Error(`Object key must be a string: got ${key.type}`); + } + return this.value.get(key.value) ?? defaultValue ?? new NullValue(); + }) + ], + ["items", new FunctionValue(() => this.items())], + ["keys", new FunctionValue(() => this.keys())], + ["values", new FunctionValue(() => this.values())], + [ + "dictsort", + new FunctionValue((args) => { + let kwargs = /* @__PURE__ */ new Map(); + const positionalArgs = args.filter((arg) => { + if (arg instanceof KeywordArgumentsValue) { + kwargs = arg.value; + return false; + } + return true; + }); + const caseSensitive = positionalArgs.at(0) ?? kwargs.get("case_sensitive") ?? new BooleanValue(false); + if (!(caseSensitive instanceof BooleanValue)) { + throw new Error("case_sensitive must be a boolean"); + } + const by = positionalArgs.at(1) ?? kwargs.get("by") ?? new StringValue("key"); + if (!(by instanceof StringValue)) { + throw new Error("by must be a string"); + } + if (!["key", "value"].includes(by.value)) { + throw new Error("by must be either 'key' or 'value'"); + } + const reverse = positionalArgs.at(2) ?? kwargs.get("reverse") ?? new BooleanValue(false); + if (!(reverse instanceof BooleanValue)) { + throw new Error("reverse must be a boolean"); + } + const items = Array.from(this.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value])).sort((a, b) => { + const index = by.value === "key" ? 0 : 1; + const aVal = a.value[index]; + const bVal = b.value[index]; + const result = compareRuntimeValues(aVal, bVal, caseSensitive.value); + return reverse.value ? -result : result; + }); + return new ArrayValue(items); + }) + ] + ]); + items() { + return new ArrayValue( + Array.from(this.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value])) + ); + } + keys() { + return new ArrayValue(Array.from(this.value.keys()).map((key) => new StringValue(key))); + } + values() { + return new ArrayValue(Array.from(this.value.values())); + } + toString() { + return toJSON(this, null, 0, false); + } + }; + var KeywordArgumentsValue = class extends ObjectValue { + type = "KeywordArgumentsValue"; + }; + var ArrayValue = class extends RuntimeValue { + type = "ArrayValue"; + builtins = /* @__PURE__ */ new Map([["length", new IntegerValue(this.value.length)]]); + /** + * NOTE: necessary to override since all JavaScript arrays are considered truthy, + * while only non-empty Python arrays are consider truthy. + * + * e.g., + * - JavaScript: [] && 5 -> 5 + * - Python: [] and 5 -> [] + */ + __bool__() { + return new BooleanValue(this.value.length > 0); + } + toString() { + return toJSON(this, null, 0, false); + } + }; + var TupleValue = class extends ArrayValue { + type = "TupleValue"; + }; + var FunctionValue = class extends RuntimeValue { + type = "FunctionValue"; + }; + var NullValue = class extends RuntimeValue { + type = "NullValue"; + }; + var UndefinedValue = class extends RuntimeValue { + type = "UndefinedValue"; + }; + var Environment = class { + constructor(parent) { + this.parent = parent; + } + /** + * The variables declared in this environment. + */ + variables = /* @__PURE__ */ new Map([ + [ + "namespace", + new FunctionValue((args) => { + if (args.length === 0) { + return new ObjectValue(/* @__PURE__ */ new Map()); + } + if (args.length !== 1 || !(args[0] instanceof ObjectValue)) { + throw new Error("`namespace` expects either zero arguments or a single object argument"); + } + return args[0]; + }) + ] + ]); + /** + * The tests available in this environment. + */ + tests = /* @__PURE__ */ new Map([ + ["boolean", (operand) => operand.type === "BooleanValue"], + ["callable", (operand) => operand instanceof FunctionValue], + [ + "odd", + (operand) => { + if (!(operand instanceof IntegerValue)) { + throw new Error(`cannot odd on ${operand.type}`); + } + return operand.value % 2 !== 0; + } + ], + [ + "even", + (operand) => { + if (!(operand instanceof IntegerValue)) { + throw new Error(`cannot even on ${operand.type}`); + } + return operand.value % 2 === 0; + } + ], + ["false", (operand) => operand.type === "BooleanValue" && !operand.value], + ["true", (operand) => operand.type === "BooleanValue" && operand.value], + ["none", (operand) => operand.type === "NullValue"], + ["string", (operand) => operand.type === "StringValue"], + ["number", (operand) => operand instanceof IntegerValue || operand instanceof FloatValue], + ["integer", (operand) => operand instanceof IntegerValue], + ["iterable", (operand) => operand.type === "ArrayValue" || operand.type === "StringValue"], + ["mapping", (operand) => operand.type === "ObjectValue"], + [ + "lower", + (operand) => { + const str = operand.value; + return operand.type === "StringValue" && str === str.toLowerCase(); + } + ], + [ + "upper", + (operand) => { + const str = operand.value; + return operand.type === "StringValue" && str === str.toUpperCase(); + } + ], + ["none", (operand) => operand.type === "NullValue"], + ["defined", (operand) => operand.type !== "UndefinedValue"], + ["undefined", (operand) => operand.type === "UndefinedValue"], + ["equalto", (a, b) => a.value === b.value], + ["eq", (a, b) => a.value === b.value] + ]); + /** + * Set the value of a variable in the current environment. + */ + set(name, value) { + return this.declareVariable(name, convertToRuntimeValues(value)); + } + declareVariable(name, value) { + if (this.variables.has(name)) { + throw new SyntaxError(`Variable already declared: ${name}`); + } + this.variables.set(name, value); + return value; + } + // private assignVariable(name: string, value: AnyRuntimeValue): AnyRuntimeValue { + // const env = this.resolve(name); + // env.variables.set(name, value); + // return value; + // } + /** + * Set variable in the current scope. + * See https://jinja.palletsprojects.com/en/3.0.x/templates/#assignments for more information. + */ + setVariable(name, value) { + this.variables.set(name, value); + return value; + } + /** + * Resolve the environment in which the variable is declared. + * @param {string} name The name of the variable. + * @returns {Environment} The environment in which the variable is declared. + */ + resolve(name) { + if (this.variables.has(name)) { + return this; + } + if (this.parent) { + return this.parent.resolve(name); + } + throw new Error(`Unknown variable: ${name}`); + } + lookupVariable(name) { + try { + return this.resolve(name).variables.get(name) ?? new UndefinedValue(); + } catch { + return new UndefinedValue(); + } + } + }; + function setupGlobals(env3) { + env3.set("false", false); + env3.set("true", true); + env3.set("none", null); + env3.set("raise_exception", (args) => { + throw new Error(args); + }); + env3.set("range", range); + env3.set("strftime_now", strftime_now); + env3.set("True", true); + env3.set("False", false); + env3.set("None", null); + } + function getAttributeValue(item, attributePath) { + const parts = attributePath.split("."); + let value = item; + for (const part of parts) { + if (value instanceof ObjectValue) { + value = value.value.get(part) ?? new UndefinedValue(); + } else if (value instanceof ArrayValue) { + const index = parseInt(part, 10); + if (!isNaN(index) && index >= 0 && index < value.value.length) { + value = value.value[index]; + } else { + return new UndefinedValue(); + } + } else { + return new UndefinedValue(); + } + } + return value; + } + function compareRuntimeValues(a, b, caseSensitive = false) { + if (a instanceof NullValue && b instanceof NullValue) { + return 0; + } + if (a instanceof NullValue || b instanceof NullValue) { + throw new Error(`Cannot compare ${a.type} with ${b.type}`); + } + if (a instanceof UndefinedValue && b instanceof UndefinedValue) { + return 0; + } + if (a instanceof UndefinedValue || b instanceof UndefinedValue) { + throw new Error(`Cannot compare ${a.type} with ${b.type}`); + } + const isNumericLike = (v) => v instanceof IntegerValue || v instanceof FloatValue || v instanceof BooleanValue; + const getNumericValue = (v) => { + if (v instanceof BooleanValue) { + return v.value ? 1 : 0; + } + return v.value; + }; + if (isNumericLike(a) && isNumericLike(b)) { + const aNum = getNumericValue(a); + const bNum = getNumericValue(b); + return aNum < bNum ? -1 : aNum > bNum ? 1 : 0; + } + if (a.type !== b.type) { + throw new Error(`Cannot compare different types: ${a.type} and ${b.type}`); + } + switch (a.type) { + case "StringValue": { + let aStr = a.value; + let bStr = b.value; + if (!caseSensitive) { + aStr = aStr.toLowerCase(); + bStr = bStr.toLowerCase(); + } + return aStr < bStr ? -1 : aStr > bStr ? 1 : 0; + } + default: + throw new Error(`Cannot compare type: ${a.type}`); + } + } + var Interpreter = class { + global; + constructor(env3) { + this.global = env3 ?? new Environment(); + } + /** + * Run the program. + */ + run(program) { + return this.evaluate(program, this.global); + } + /** + * Evaluates expressions following the binary operation type. + */ + evaluateBinaryExpression(node, environment) { + const left = this.evaluate(node.left, environment); + switch (node.operator.value) { + case "and": + return left.__bool__().value ? this.evaluate(node.right, environment) : left; + case "or": + return left.__bool__().value ? left : this.evaluate(node.right, environment); + } + const right = this.evaluate(node.right, environment); + switch (node.operator.value) { + case "==": + return new BooleanValue(left.value == right.value); + case "!=": + return new BooleanValue(left.value != right.value); + } + if (left instanceof UndefinedValue || right instanceof UndefinedValue) { + if (right instanceof UndefinedValue && ["in", "not in"].includes(node.operator.value)) { + return new BooleanValue(node.operator.value === "not in"); + } + throw new Error(`Cannot perform operation ${node.operator.value} on undefined values`); + } else if (left instanceof NullValue || right instanceof NullValue) { + throw new Error("Cannot perform operation on null values"); + } else if (node.operator.value === "~") { + return new StringValue(left.value.toString() + right.value.toString()); + } else if ((left instanceof IntegerValue || left instanceof FloatValue) && (right instanceof IntegerValue || right instanceof FloatValue)) { + const a = left.value, b = right.value; + switch (node.operator.value) { + case "+": + case "-": + case "*": { + const res = node.operator.value === "+" ? a + b : node.operator.value === "-" ? a - b : a * b; + const isFloat = left instanceof FloatValue || right instanceof FloatValue; + return isFloat ? new FloatValue(res) : new IntegerValue(res); + } + case "/": + return new FloatValue(a / b); + case "%": { + const rem = a % b; + const isFloat = left instanceof FloatValue || right instanceof FloatValue; + return isFloat ? new FloatValue(rem) : new IntegerValue(rem); + } + case "<": + return new BooleanValue(a < b); + case ">": + return new BooleanValue(a > b); + case ">=": + return new BooleanValue(a >= b); + case "<=": + return new BooleanValue(a <= b); + } + } else if (left instanceof ArrayValue && right instanceof ArrayValue) { + switch (node.operator.value) { + case "+": + return new ArrayValue(left.value.concat(right.value)); + } + } else if (right instanceof ArrayValue) { + const member = right.value.find((x) => x.value === left.value) !== void 0; + switch (node.operator.value) { + case "in": + return new BooleanValue(member); + case "not in": + return new BooleanValue(!member); + } + } + if (left instanceof StringValue || right instanceof StringValue) { + switch (node.operator.value) { + case "+": + return new StringValue(left.value.toString() + right.value.toString()); + } + } + if (left instanceof StringValue && right instanceof StringValue) { + switch (node.operator.value) { + case "in": + return new BooleanValue(right.value.includes(left.value)); + case "not in": + return new BooleanValue(!right.value.includes(left.value)); + } + } + if (left instanceof StringValue && right instanceof ObjectValue) { + switch (node.operator.value) { + case "in": + return new BooleanValue(right.value.has(left.value)); + case "not in": + return new BooleanValue(!right.value.has(left.value)); + } + } + throw new SyntaxError(`Unknown operator "${node.operator.value}" between ${left.type} and ${right.type}`); + } + evaluateArguments(args, environment) { + const positionalArguments = []; + const keywordArguments = /* @__PURE__ */ new Map(); + for (const argument of args) { + if (argument.type === "SpreadExpression") { + const spreadNode = argument; + const val = this.evaluate(spreadNode.argument, environment); + if (!(val instanceof ArrayValue)) { + throw new Error(`Cannot unpack non-iterable type: ${val.type}`); + } + for (const item of val.value) { + positionalArguments.push(item); + } + } else if (argument.type === "KeywordArgumentExpression") { + const kwarg = argument; + keywordArguments.set(kwarg.key.value, this.evaluate(kwarg.value, environment)); + } else { + if (keywordArguments.size > 0) { + throw new Error("Positional arguments must come before keyword arguments"); + } + positionalArguments.push(this.evaluate(argument, environment)); + } + } + return [positionalArguments, keywordArguments]; + } + applyFilter(operand, filterNode, environment) { + if (filterNode.type === "Identifier") { + const filter = filterNode; + if (filter.value === "tojson") { + return new StringValue(toJSON(operand)); + } + if (operand instanceof ArrayValue) { + switch (filter.value) { + case "list": + return operand; + case "first": + return operand.value[0]; + case "last": + return operand.value[operand.value.length - 1]; + case "length": + return new IntegerValue(operand.value.length); + case "reverse": + return new ArrayValue(operand.value.slice().reverse()); + case "sort": { + return new ArrayValue(operand.value.slice().sort((a, b) => compareRuntimeValues(a, b, false))); + } + case "join": + return new StringValue(operand.value.map((x) => x.value).join("")); + case "string": + return new StringValue(toJSON(operand, null, 0, false)); + case "unique": { + const seen = /* @__PURE__ */ new Set(); + const output = []; + for (const item of operand.value) { + if (!seen.has(item.value)) { + seen.add(item.value); + output.push(item); + } + } + return new ArrayValue(output); + } + default: + throw new Error(`Unknown ArrayValue filter: ${filter.value}`); + } + } else if (operand instanceof StringValue) { + switch (filter.value) { + case "length": + case "upper": + case "lower": + case "title": + case "capitalize": { + const builtin = operand.builtins.get(filter.value); + if (builtin instanceof FunctionValue) { + return builtin.value( + /* no arguments */ + [], + environment + ); + } else if (builtin instanceof IntegerValue) { + return builtin; + } else { + throw new Error(`Unknown StringValue filter: ${filter.value}`); + } + } + case "trim": + return new StringValue(operand.value.trim()); + case "indent": + return new StringValue( + operand.value.split("\n").map( + (x, i) => ( + // By default, don't indent the first line or empty lines + i === 0 || x.length === 0 ? x : " " + x + ) + ).join("\n") + ); + case "join": + case "string": + return operand; + case "int": { + const val = parseInt(operand.value, 10); + return new IntegerValue(isNaN(val) ? 0 : val); + } + case "float": { + const val = parseFloat(operand.value); + return new FloatValue(isNaN(val) ? 0 : val); + } + default: + throw new Error(`Unknown StringValue filter: ${filter.value}`); + } + } else if (operand instanceof IntegerValue || operand instanceof FloatValue) { + switch (filter.value) { + case "abs": + return operand instanceof IntegerValue ? new IntegerValue(Math.abs(operand.value)) : new FloatValue(Math.abs(operand.value)); + case "int": + return new IntegerValue(Math.floor(operand.value)); + case "float": + return new FloatValue(operand.value); + default: + throw new Error(`Unknown NumericValue filter: ${filter.value}`); + } + } else if (operand instanceof ObjectValue) { + switch (filter.value) { + case "items": + return new ArrayValue( + Array.from(operand.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value])) + ); + case "length": + return new IntegerValue(operand.value.size); + default: { + const builtin = operand.builtins.get(filter.value); + if (builtin) { + if (builtin instanceof FunctionValue) { + return builtin.value([], environment); + } + return builtin; + } + throw new Error(`Unknown ObjectValue filter: ${filter.value}`); + } + } + } else if (operand instanceof BooleanValue) { + switch (filter.value) { + case "bool": + return new BooleanValue(operand.value); + case "int": + return new IntegerValue(operand.value ? 1 : 0); + case "float": + return new FloatValue(operand.value ? 1 : 0); + case "string": + return new StringValue(operand.value ? "true" : "false"); + default: + throw new Error(`Unknown BooleanValue filter: ${filter.value}`); + } + } + throw new Error(`Cannot apply filter "${filter.value}" to type: ${operand.type}`); + } else if (filterNode.type === "CallExpression") { + const filter = filterNode; + if (filter.callee.type !== "Identifier") { + throw new Error(`Unknown filter: ${filter.callee.type}`); + } + const filterName = filter.callee.value; + if (filterName === "tojson") { + const [, kwargs] = this.evaluateArguments(filter.args, environment); + const indent = kwargs.get("indent") ?? new NullValue(); + if (!(indent instanceof IntegerValue || indent instanceof NullValue)) { + throw new Error("If set, indent must be a number"); + } + return new StringValue(toJSON(operand, indent.value)); + } else if (filterName === "join") { + let value; + if (operand instanceof StringValue) { + value = Array.from(operand.value); + } else if (operand instanceof ArrayValue) { + value = operand.value.map((x) => x.value); + } else { + throw new Error(`Cannot apply filter "${filterName}" to type: ${operand.type}`); + } + const [args, kwargs] = this.evaluateArguments(filter.args, environment); + const separator = args.at(0) ?? kwargs.get("separator") ?? new StringValue(""); + if (!(separator instanceof StringValue)) { + throw new Error("separator must be a string"); + } + return new StringValue(value.join(separator.value)); + } else if (filterName === "int" || filterName === "float") { + const [args, kwargs] = this.evaluateArguments(filter.args, environment); + const defaultValue = args.at(0) ?? kwargs.get("default") ?? (filterName === "int" ? new IntegerValue(0) : new FloatValue(0)); + if (operand instanceof StringValue) { + const val = filterName === "int" ? parseInt(operand.value, 10) : parseFloat(operand.value); + return isNaN(val) ? defaultValue : filterName === "int" ? new IntegerValue(val) : new FloatValue(val); + } else if (operand instanceof IntegerValue || operand instanceof FloatValue) { + return operand; + } else if (operand instanceof BooleanValue) { + return filterName === "int" ? new IntegerValue(operand.value ? 1 : 0) : new FloatValue(operand.value ? 1 : 0); + } else { + throw new Error(`Cannot apply filter "${filterName}" to type: ${operand.type}`); + } + } else if (filterName === "default") { + const [args, kwargs] = this.evaluateArguments(filter.args, environment); + const defaultValue = args[0] ?? new StringValue(""); + const booleanValue = args[1] ?? kwargs.get("boolean") ?? new BooleanValue(false); + if (!(booleanValue instanceof BooleanValue)) { + throw new Error("`default` filter flag must be a boolean"); + } + if (operand instanceof UndefinedValue || booleanValue.value && !operand.__bool__().value) { + return defaultValue; + } + return operand; + } + if (operand instanceof ArrayValue) { + switch (filterName) { + case "sort": { + const [args, kwargs] = this.evaluateArguments(filter.args, environment); + const reverse = args.at(0) ?? kwargs.get("reverse") ?? new BooleanValue(false); + if (!(reverse instanceof BooleanValue)) { + throw new Error("reverse must be a boolean"); + } + const caseSensitive = args.at(1) ?? kwargs.get("case_sensitive") ?? new BooleanValue(false); + if (!(caseSensitive instanceof BooleanValue)) { + throw new Error("case_sensitive must be a boolean"); + } + const attribute = args.at(2) ?? kwargs.get("attribute") ?? new NullValue(); + if (!(attribute instanceof StringValue || attribute instanceof IntegerValue || attribute instanceof NullValue)) { + throw new Error("attribute must be a string, integer, or null"); + } + const getSortValue = (item) => { + if (attribute instanceof NullValue) { + return item; + } + const attrPath = attribute instanceof IntegerValue ? String(attribute.value) : attribute.value; + return getAttributeValue(item, attrPath); + }; + return new ArrayValue( + operand.value.slice().sort((a, b) => { + const aVal = getSortValue(a); + const bVal = getSortValue(b); + const result = compareRuntimeValues(aVal, bVal, caseSensitive.value); + return reverse.value ? -result : result; + }) + ); + } + case "selectattr": + case "rejectattr": { + const select = filterName === "selectattr"; + if (operand.value.some((x) => !(x instanceof ObjectValue))) { + throw new Error(`\`${filterName}\` can only be applied to array of objects`); + } + if (filter.args.some((x) => x.type !== "StringLiteral")) { + throw new Error(`arguments of \`${filterName}\` must be strings`); + } + const [attr, testName, value] = filter.args.map((x) => this.evaluate(x, environment)); + let testFunction; + if (testName) { + const test = environment.tests.get(testName.value); + if (!test) { + throw new Error(`Unknown test: ${testName.value}`); + } + testFunction = test; + } else { + testFunction = (...x) => x[0].__bool__().value; + } + const filtered = operand.value.filter((item) => { + const a = item.value.get(attr.value); + const result = a ? testFunction(a, value) : false; + return select ? result : !result; + }); + return new ArrayValue(filtered); + } + case "map": { + const [, kwargs] = this.evaluateArguments(filter.args, environment); + if (kwargs.has("attribute")) { + const attr = kwargs.get("attribute"); + if (!(attr instanceof StringValue)) { + throw new Error("attribute must be a string"); + } + const defaultValue = kwargs.get("default"); + const mapped = operand.value.map((item) => { + if (!(item instanceof ObjectValue)) { + throw new Error("items in map must be an object"); + } + const value = getAttributeValue(item, attr.value); + return value instanceof UndefinedValue ? defaultValue ?? new UndefinedValue() : value; + }); + return new ArrayValue(mapped); + } else { + throw new Error("`map` expressions without `attribute` set are not currently supported."); + } + } + } + throw new Error(`Unknown ArrayValue filter: ${filterName}`); + } else if (operand instanceof StringValue) { + switch (filterName) { + case "indent": { + const [args, kwargs] = this.evaluateArguments(filter.args, environment); + const width = args.at(0) ?? kwargs.get("width") ?? new IntegerValue(4); + if (!(width instanceof IntegerValue)) { + throw new Error("width must be a number"); + } + const first = args.at(1) ?? kwargs.get("first") ?? new BooleanValue(false); + const blank = args.at(2) ?? kwargs.get("blank") ?? new BooleanValue(false); + const lines = operand.value.split("\n"); + const indent = " ".repeat(width.value); + const indented = lines.map( + (x, i) => !first.value && i === 0 || !blank.value && x.length === 0 ? x : indent + x + ); + return new StringValue(indented.join("\n")); + } + case "replace": { + const replaceFn = operand.builtins.get("replace"); + if (!(replaceFn instanceof FunctionValue)) { + throw new Error("replace filter not available"); + } + const [args, kwargs] = this.evaluateArguments(filter.args, environment); + return replaceFn.value([...args, new KeywordArgumentsValue(kwargs)], environment); + } + } + throw new Error(`Unknown StringValue filter: ${filterName}`); + } else if (operand instanceof ObjectValue) { + const builtin = operand.builtins.get(filterName); + if (builtin && builtin instanceof FunctionValue) { + const [args, kwargs] = this.evaluateArguments(filter.args, environment); + if (kwargs.size > 0) { + args.push(new KeywordArgumentsValue(kwargs)); + } + return builtin.value(args, environment); + } + throw new Error(`Unknown ObjectValue filter: ${filterName}`); + } else { + throw new Error(`Cannot apply filter "${filterName}" to type: ${operand.type}`); + } + } + throw new Error(`Unknown filter: ${filterNode.type}`); + } + /** + * Evaluates expressions following the filter operation type. + */ + evaluateFilterExpression(node, environment) { + const operand = this.evaluate(node.operand, environment); + return this.applyFilter(operand, node.filter, environment); + } + /** + * Evaluates expressions following the test operation type. + */ + evaluateTestExpression(node, environment) { + const operand = this.evaluate(node.operand, environment); + const test = environment.tests.get(node.test.value); + if (!test) { + throw new Error(`Unknown test: ${node.test.value}`); + } + const result = test(operand); + return new BooleanValue(node.negate ? !result : result); + } + /** + * Evaluates expressions following the select operation type. + */ + evaluateSelectExpression(node, environment) { + const predicate = this.evaluate(node.test, environment); + if (!predicate.__bool__().value) { + return new UndefinedValue(); + } + return this.evaluate(node.lhs, environment); + } + /** + * Evaluates expressions following the unary operation type. + */ + evaluateUnaryExpression(node, environment) { + const argument = this.evaluate(node.argument, environment); + switch (node.operator.value) { + case "not": + return new BooleanValue(!argument.value); + default: + throw new SyntaxError(`Unknown operator: ${node.operator.value}`); + } + } + evaluateTernaryExpression(node, environment) { + const cond = this.evaluate(node.condition, environment); + return cond.__bool__().value ? this.evaluate(node.trueExpr, environment) : this.evaluate(node.falseExpr, environment); + } + evalProgram(program, environment) { + return this.evaluateBlock(program.body, environment); + } + evaluateBlock(statements, environment) { + let result = ""; + for (const statement of statements) { + const lastEvaluated = this.evaluate(statement, environment); + if (lastEvaluated.type !== "NullValue" && lastEvaluated.type !== "UndefinedValue") { + result += lastEvaluated.toString(); + } + } + return new StringValue(result); + } + evaluateIdentifier(node, environment) { + return environment.lookupVariable(node.value); + } + evaluateCallExpression(expr, environment) { + const [args, kwargs] = this.evaluateArguments(expr.args, environment); + if (kwargs.size > 0) { + args.push(new KeywordArgumentsValue(kwargs)); + } + const fn = this.evaluate(expr.callee, environment); + if (fn.type !== "FunctionValue") { + throw new Error(`Cannot call something that is not a function: got ${fn.type}`); + } + return fn.value(args, environment); + } + evaluateSliceExpression(object, expr, environment) { + if (!(object instanceof ArrayValue || object instanceof StringValue)) { + throw new Error("Slice object must be an array or string"); + } + const start = this.evaluate(expr.start, environment); + const stop = this.evaluate(expr.stop, environment); + const step = this.evaluate(expr.step, environment); + if (!(start instanceof IntegerValue || start instanceof UndefinedValue)) { + throw new Error("Slice start must be numeric or undefined"); + } + if (!(stop instanceof IntegerValue || stop instanceof UndefinedValue)) { + throw new Error("Slice stop must be numeric or undefined"); + } + if (!(step instanceof IntegerValue || step instanceof UndefinedValue)) { + throw new Error("Slice step must be numeric or undefined"); + } + if (object instanceof ArrayValue) { + return new ArrayValue(slice(object.value, start.value, stop.value, step.value)); + } else { + return new StringValue(slice(Array.from(object.value), start.value, stop.value, step.value).join("")); + } + } + evaluateMemberExpression(expr, environment) { + const object = this.evaluate(expr.object, environment); + let property; + if (expr.computed) { + if (expr.property.type === "SliceExpression") { + return this.evaluateSliceExpression(object, expr.property, environment); + } else { + property = this.evaluate(expr.property, environment); + } + } else { + property = new StringValue(expr.property.value); + } + let value; + if (object instanceof ObjectValue) { + if (!(property instanceof StringValue)) { + throw new Error(`Cannot access property with non-string: got ${property.type}`); + } + value = object.value.get(property.value) ?? object.builtins.get(property.value); + } else if (object instanceof ArrayValue || object instanceof StringValue) { + if (property instanceof IntegerValue) { + value = object.value.at(property.value); + if (object instanceof StringValue) { + value = new StringValue(object.value.at(property.value)); + } + } else if (property instanceof StringValue) { + value = object.builtins.get(property.value); + } else { + throw new Error(`Cannot access property with non-string/non-number: got ${property.type}`); + } + } else { + if (!(property instanceof StringValue)) { + throw new Error(`Cannot access property with non-string: got ${property.type}`); + } + value = object.builtins.get(property.value); + } + return value instanceof RuntimeValue ? value : new UndefinedValue(); + } + evaluateSet(node, environment) { + const rhs = node.value ? this.evaluate(node.value, environment) : this.evaluateBlock(node.body, environment); + if (node.assignee.type === "Identifier") { + const variableName = node.assignee.value; + environment.setVariable(variableName, rhs); + } else if (node.assignee.type === "TupleLiteral") { + const tuple = node.assignee; + if (!(rhs instanceof ArrayValue)) { + throw new Error(`Cannot unpack non-iterable type in set: ${rhs.type}`); + } + const arr = rhs.value; + if (arr.length !== tuple.value.length) { + throw new Error(`Too ${tuple.value.length > arr.length ? "few" : "many"} items to unpack in set`); + } + for (let i = 0; i < tuple.value.length; ++i) { + const elem = tuple.value[i]; + if (elem.type !== "Identifier") { + throw new Error(`Cannot unpack to non-identifier in set: ${elem.type}`); + } + environment.setVariable(elem.value, arr[i]); + } + } else if (node.assignee.type === "MemberExpression") { + const member = node.assignee; + const object = this.evaluate(member.object, environment); + if (!(object instanceof ObjectValue)) { + throw new Error("Cannot assign to member of non-object"); + } + if (member.property.type !== "Identifier") { + throw new Error("Cannot assign to member with non-identifier property"); + } + object.value.set(member.property.value, rhs); + } else { + throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(node.assignee)}`); + } + return new NullValue(); + } + evaluateIf(node, environment) { + const test = this.evaluate(node.test, environment); + return this.evaluateBlock(test.__bool__().value ? node.body : node.alternate, environment); + } + evaluateFor(node, environment) { + const scope = new Environment(environment); + let test, iterable; + if (node.iterable.type === "SelectExpression") { + const select = node.iterable; + iterable = this.evaluate(select.lhs, scope); + test = select.test; + } else { + iterable = this.evaluate(node.iterable, scope); + } + if (!(iterable instanceof ArrayValue || iterable instanceof ObjectValue)) { + throw new Error(`Expected iterable or object type in for loop: got ${iterable.type}`); + } + if (iterable instanceof ObjectValue) { + iterable = iterable.keys(); + } + const items = []; + const scopeUpdateFunctions = []; + for (let i = 0; i < iterable.value.length; ++i) { + const loopScope = new Environment(scope); + const current = iterable.value[i]; + let scopeUpdateFunction; + if (node.loopvar.type === "Identifier") { + scopeUpdateFunction = (scope2) => scope2.setVariable(node.loopvar.value, current); + } else if (node.loopvar.type === "TupleLiteral") { + const loopvar = node.loopvar; + if (current.type !== "ArrayValue") { + throw new Error(`Cannot unpack non-iterable type: ${current.type}`); + } + const c = current; + if (loopvar.value.length !== c.value.length) { + throw new Error(`Too ${loopvar.value.length > c.value.length ? "few" : "many"} items to unpack`); + } + scopeUpdateFunction = (scope2) => { + for (let j = 0; j < loopvar.value.length; ++j) { + if (loopvar.value[j].type !== "Identifier") { + throw new Error(`Cannot unpack non-identifier type: ${loopvar.value[j].type}`); + } + scope2.setVariable(loopvar.value[j].value, c.value[j]); + } + }; + } else { + throw new Error(`Invalid loop variable(s): ${node.loopvar.type}`); + } + if (test) { + scopeUpdateFunction(loopScope); + const testValue = this.evaluate(test, loopScope); + if (!testValue.__bool__().value) { + continue; + } + } + items.push(current); + scopeUpdateFunctions.push(scopeUpdateFunction); + } + let result = ""; + let noIteration = true; + for (let i = 0; i < items.length; ++i) { + const loop = /* @__PURE__ */ new Map([ + ["index", new IntegerValue(i + 1)], + ["index0", new IntegerValue(i)], + ["revindex", new IntegerValue(items.length - i)], + ["revindex0", new IntegerValue(items.length - i - 1)], + ["first", new BooleanValue(i === 0)], + ["last", new BooleanValue(i === items.length - 1)], + ["length", new IntegerValue(items.length)], + ["previtem", i > 0 ? items[i - 1] : new UndefinedValue()], + ["nextitem", i < items.length - 1 ? items[i + 1] : new UndefinedValue()] + ]); + scope.setVariable("loop", new ObjectValue(loop)); + scopeUpdateFunctions[i](scope); + try { + const evaluated = this.evaluateBlock(node.body, scope); + result += evaluated.value; + } catch (err) { + if (err instanceof ContinueControl) { + continue; + } + if (err instanceof BreakControl) { + break; + } + throw err; + } + noIteration = false; + } + if (noIteration) { + const defaultEvaluated = this.evaluateBlock(node.defaultBlock, scope); + result += defaultEvaluated.value; + } + return new StringValue(result); + } + /** + * See https://jinja.palletsprojects.com/en/3.1.x/templates/#macros for more information. + */ + evaluateMacro(node, environment) { + environment.setVariable( + node.name.value, + new FunctionValue((args, scope) => { + const macroScope = new Environment(scope); + args = args.slice(); + let kwargs; + if (args.at(-1)?.type === "KeywordArgumentsValue") { + kwargs = args.pop(); + } + for (let i = 0; i < node.args.length; ++i) { + const nodeArg = node.args[i]; + const passedArg = args[i]; + if (nodeArg.type === "Identifier") { + const identifier = nodeArg; + if (!passedArg) { + throw new Error(`Missing positional argument: ${identifier.value}`); + } + macroScope.setVariable(identifier.value, passedArg); + } else if (nodeArg.type === "KeywordArgumentExpression") { + const kwarg = nodeArg; + const value = passedArg ?? // Try positional arguments first + kwargs?.value.get(kwarg.key.value) ?? // Look in user-passed kwargs + this.evaluate(kwarg.value, macroScope); + macroScope.setVariable(kwarg.key.value, value); + } else { + throw new Error(`Unknown argument type: ${nodeArg.type}`); + } + } + return this.evaluateBlock(node.body, macroScope); + }) + ); + return new NullValue(); + } + evaluateCallStatement(node, environment) { + const callerFn = new FunctionValue((callerArgs, callerEnv) => { + const callBlockEnv = new Environment(callerEnv); + if (node.callerArgs) { + for (let i = 0; i < node.callerArgs.length; ++i) { + const param = node.callerArgs[i]; + if (param.type !== "Identifier") { + throw new Error(`Caller parameter must be an identifier, got ${param.type}`); + } + callBlockEnv.setVariable(param.value, callerArgs[i] ?? new UndefinedValue()); + } + } + return this.evaluateBlock(node.body, callBlockEnv); + }); + const [macroArgs, macroKwargs] = this.evaluateArguments(node.call.args, environment); + macroArgs.push(new KeywordArgumentsValue(macroKwargs)); + const fn = this.evaluate(node.call.callee, environment); + if (fn.type !== "FunctionValue") { + throw new Error(`Cannot call something that is not a function: got ${fn.type}`); + } + const newEnv = new Environment(environment); + newEnv.setVariable("caller", callerFn); + return fn.value(macroArgs, newEnv); + } + evaluateFilterStatement(node, environment) { + const rendered = this.evaluateBlock(node.body, environment); + return this.applyFilter(rendered, node.filter, environment); + } + evaluate(statement, environment) { + if (!statement) + return new UndefinedValue(); + switch (statement.type) { + case "Program": + return this.evalProgram(statement, environment); + case "Set": + return this.evaluateSet(statement, environment); + case "If": + return this.evaluateIf(statement, environment); + case "For": + return this.evaluateFor(statement, environment); + case "Macro": + return this.evaluateMacro(statement, environment); + case "CallStatement": + return this.evaluateCallStatement(statement, environment); + case "Break": + throw new BreakControl(); + case "Continue": + throw new ContinueControl(); + case "IntegerLiteral": + return new IntegerValue(statement.value); + case "FloatLiteral": + return new FloatValue(statement.value); + case "StringLiteral": + return new StringValue(statement.value); + case "ArrayLiteral": + return new ArrayValue(statement.value.map((x) => this.evaluate(x, environment))); + case "TupleLiteral": + return new TupleValue(statement.value.map((x) => this.evaluate(x, environment))); + case "ObjectLiteral": { + const mapping = /* @__PURE__ */ new Map(); + for (const [key, value] of statement.value) { + const evaluatedKey = this.evaluate(key, environment); + if (!(evaluatedKey instanceof StringValue)) { + throw new Error(`Object keys must be strings: got ${evaluatedKey.type}`); + } + mapping.set(evaluatedKey.value, this.evaluate(value, environment)); + } + return new ObjectValue(mapping); + } + case "Identifier": + return this.evaluateIdentifier(statement, environment); + case "CallExpression": + return this.evaluateCallExpression(statement, environment); + case "MemberExpression": + return this.evaluateMemberExpression(statement, environment); + case "UnaryExpression": + return this.evaluateUnaryExpression(statement, environment); + case "BinaryExpression": + return this.evaluateBinaryExpression(statement, environment); + case "FilterExpression": + return this.evaluateFilterExpression(statement, environment); + case "FilterStatement": + return this.evaluateFilterStatement(statement, environment); + case "TestExpression": + return this.evaluateTestExpression(statement, environment); + case "SelectExpression": + return this.evaluateSelectExpression(statement, environment); + case "Ternary": + return this.evaluateTernaryExpression(statement, environment); + case "Comment": + return new NullValue(); + default: + throw new SyntaxError(`Unknown node type: ${statement.type}`); + } + } + }; + function convertToRuntimeValues(input) { + switch (typeof input) { + case "number": + return Number.isInteger(input) ? new IntegerValue(input) : new FloatValue(input); + case "string": + return new StringValue(input); + case "boolean": + return new BooleanValue(input); + case "undefined": + return new UndefinedValue(); + case "object": + if (input === null) { + return new NullValue(); + } else if (Array.isArray(input)) { + return new ArrayValue(input.map(convertToRuntimeValues)); + } else { + return new ObjectValue( + new Map(Object.entries(input).map(([key, value]) => [key, convertToRuntimeValues(value)])) + ); + } + case "function": + return new FunctionValue((args, _scope) => { + const result = input(...args.map((x) => x.value)) ?? null; + return convertToRuntimeValues(result); + }); + default: + throw new Error(`Cannot convert to runtime value: ${input}`); + } + } + var NEWLINE = "\n"; + var OPEN_STATEMENT = "{%- "; + var CLOSE_STATEMENT = " -%}"; + function getBinaryOperatorPrecedence(expr) { + switch (expr.operator.type) { + case "MultiplicativeBinaryOperator": + return 4; + case "AdditiveBinaryOperator": + return 3; + case "ComparisonBinaryOperator": + return 2; + case "Identifier": + if (expr.operator.value === "and") + return 1; + if (expr.operator.value === "in" || expr.operator.value === "not in") + return 2; + return 0; + } + return 0; + } + function format(program, indent = " ") { + const indentStr = typeof indent === "number" ? " ".repeat(indent) : indent; + const body = formatStatements(program.body, 0, indentStr); + return body.replace(/\n$/, ""); + } + function createStatement(...text) { + return OPEN_STATEMENT + text.join(" ") + CLOSE_STATEMENT; + } + function formatStatements(stmts, depth, indentStr) { + return stmts.map((stmt) => formatStatement(stmt, depth, indentStr)).join(NEWLINE); + } + function formatStatement(node, depth, indentStr) { + const pad = indentStr.repeat(depth); + switch (node.type) { + case "Program": + return formatStatements(node.body, depth, indentStr); + case "If": + return formatIf(node, depth, indentStr); + case "For": + return formatFor(node, depth, indentStr); + case "Set": + return formatSet(node, depth, indentStr); + case "Macro": + return formatMacro(node, depth, indentStr); + case "Break": + return pad + createStatement("break"); + case "Continue": + return pad + createStatement("continue"); + case "CallStatement": + return formatCallStatement(node, depth, indentStr); + case "FilterStatement": + return formatFilterStatement(node, depth, indentStr); + case "Comment": + return pad + "{# " + node.value + " #}"; + default: + return pad + "{{- " + formatExpression(node) + " -}}"; + } + } + function formatIf(node, depth, indentStr) { + const pad = indentStr.repeat(depth); + const clauses = []; + let current = node; + while (current) { + clauses.push({ test: current.test, body: current.body }); + if (current.alternate.length === 1 && current.alternate[0].type === "If") { + current = current.alternate[0]; + } else { + break; + } + } + let out = pad + createStatement("if", formatExpression(clauses[0].test)) + NEWLINE + formatStatements(clauses[0].body, depth + 1, indentStr); + for (let i = 1; i < clauses.length; ++i) { + out += NEWLINE + pad + createStatement("elif", formatExpression(clauses[i].test)) + NEWLINE + formatStatements(clauses[i].body, depth + 1, indentStr); + } + if (current && current.alternate.length > 0) { + out += NEWLINE + pad + createStatement("else") + NEWLINE + formatStatements(current.alternate, depth + 1, indentStr); + } + out += NEWLINE + pad + createStatement("endif"); + return out; + } + function formatFor(node, depth, indentStr) { + const pad = indentStr.repeat(depth); + let formattedIterable = ""; + if (node.iterable.type === "SelectExpression") { + const n = node.iterable; + formattedIterable = `${formatExpression(n.lhs)} if ${formatExpression(n.test)}`; + } else { + formattedIterable = formatExpression(node.iterable); + } + let out = pad + createStatement("for", formatExpression(node.loopvar), "in", formattedIterable) + NEWLINE + formatStatements(node.body, depth + 1, indentStr); + if (node.defaultBlock.length > 0) { + out += NEWLINE + pad + createStatement("else") + NEWLINE + formatStatements(node.defaultBlock, depth + 1, indentStr); + } + out += NEWLINE + pad + createStatement("endfor"); + return out; + } + function formatSet(node, depth, indentStr) { + const pad = indentStr.repeat(depth); + const left = formatExpression(node.assignee); + const right = node.value ? formatExpression(node.value) : ""; + const value = pad + createStatement("set", `${left}${node.value ? " = " + right : ""}`); + if (node.body.length === 0) { + return value; + } + return value + NEWLINE + formatStatements(node.body, depth + 1, indentStr) + NEWLINE + pad + createStatement("endset"); + } + function formatMacro(node, depth, indentStr) { + const pad = indentStr.repeat(depth); + const args = node.args.map(formatExpression).join(", "); + return pad + createStatement("macro", `${node.name.value}(${args})`) + NEWLINE + formatStatements(node.body, depth + 1, indentStr) + NEWLINE + pad + createStatement("endmacro"); + } + function formatCallStatement(node, depth, indentStr) { + const pad = indentStr.repeat(depth); + const params = node.callerArgs && node.callerArgs.length > 0 ? `(${node.callerArgs.map(formatExpression).join(", ")})` : ""; + const callExpr = formatExpression(node.call); + let out = pad + createStatement(`call${params}`, callExpr) + NEWLINE; + out += formatStatements(node.body, depth + 1, indentStr) + NEWLINE; + out += pad + createStatement("endcall"); + return out; + } + function formatFilterStatement(node, depth, indentStr) { + const pad = indentStr.repeat(depth); + const spec = node.filter.type === "Identifier" ? node.filter.value : formatExpression(node.filter); + let out = pad + createStatement("filter", spec) + NEWLINE; + out += formatStatements(node.body, depth + 1, indentStr) + NEWLINE; + out += pad + createStatement("endfilter"); + return out; + } + function formatExpression(node, parentPrec = -1) { + switch (node.type) { + case "SpreadExpression": { + const n = node; + return `*${formatExpression(n.argument)}`; + } + case "Identifier": + return node.value; + case "IntegerLiteral": + return `${node.value}`; + case "FloatLiteral": + return `${node.value}`; + case "StringLiteral": + return JSON.stringify(node.value); + case "BinaryExpression": { + const n = node; + const thisPrecedence = getBinaryOperatorPrecedence(n); + const left = formatExpression(n.left, thisPrecedence); + const right = formatExpression(n.right, thisPrecedence + 1); + const expr = `${left} ${n.operator.value} ${right}`; + return thisPrecedence < parentPrec ? `(${expr})` : expr; + } + case "UnaryExpression": { + const n = node; + const val = n.operator.value + (n.operator.value === "not" ? " " : "") + formatExpression(n.argument, Infinity); + return val; + } + case "CallExpression": { + const n = node; + const args = n.args.map(formatExpression).join(", "); + return `${formatExpression(n.callee)}(${args})`; + } + case "MemberExpression": { + const n = node; + let obj = formatExpression(n.object); + if (![ + "Identifier", + "MemberExpression", + "CallExpression", + "StringLiteral", + "IntegerLiteral", + "FloatLiteral", + "ArrayLiteral", + "TupleLiteral", + "ObjectLiteral" + ].includes(n.object.type)) { + obj = `(${obj})`; + } + let prop = formatExpression(n.property); + if (!n.computed && n.property.type !== "Identifier") { + prop = `(${prop})`; + } + return n.computed ? `${obj}[${prop}]` : `${obj}.${prop}`; + } + case "FilterExpression": { + const n = node; + const operand = formatExpression(n.operand, Infinity); + if (n.filter.type === "CallExpression") { + return `${operand} | ${formatExpression(n.filter)}`; + } + return `${operand} | ${n.filter.value}`; + } + case "SelectExpression": { + const n = node; + return `${formatExpression(n.lhs)} if ${formatExpression(n.test)}`; + } + case "TestExpression": { + const n = node; + return `${formatExpression(n.operand)} is${n.negate ? " not" : ""} ${n.test.value}`; + } + case "ArrayLiteral": + case "TupleLiteral": { + const elems = node.value.map(formatExpression); + const brackets = node.type === "ArrayLiteral" ? "[]" : "()"; + return `${brackets[0]}${elems.join(", ")}${brackets[1]}`; + } + case "ObjectLiteral": { + const entries = Array.from(node.value.entries()).map( + ([k2, v]) => `${formatExpression(k2)}: ${formatExpression(v)}` + ); + return `{${entries.join(", ")}}`; + } + case "SliceExpression": { + const n = node; + const s = n.start ? formatExpression(n.start) : ""; + const t = n.stop ? formatExpression(n.stop) : ""; + const st2 = n.step ? `:${formatExpression(n.step)}` : ""; + return `${s}:${t}${st2}`; + } + case "KeywordArgumentExpression": { + const n = node; + return `${n.key.value}=${formatExpression(n.value)}`; + } + case "Ternary": { + const n = node; + const expr = `${formatExpression(n.trueExpr)} if ${formatExpression(n.condition, 0)} else ${formatExpression( + n.falseExpr + )}`; + return parentPrec > -1 ? `(${expr})` : expr; + } + default: + throw new Error(`Unknown expression type: ${node.type}`); + } + } + var Template = class { + parsed; + /** + * @param {string} template The template string + */ + constructor(template) { + const tokens = tokenize(template, { + lstrip_blocks: true, + trim_blocks: true + }); + this.parsed = parse(tokens); + } + render(items) { + const env3 = new Environment(); + setupGlobals(env3); + if (items) { + for (const [key, value] of Object.entries(items)) { + env3.set(key, value); + } + } + const interpreter = new Interpreter(env3); + const result = interpreter.run(this.parsed); + return result.value; + } + format(options) { + return format(this.parsed, options?.indent || " "); + } + }; + }) + ), + /***/ + "./src/backends/onnx.js": ( + /*!******************************!*\ + !*** ./src/backends/onnx.js ***! + \******************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + var onnxruntime_node__WEBPACK_IMPORTED_MODULE_1___namespace_cache; + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + Tensor: () => ( + /* reexport safe */ + onnxruntime_common__WEBPACK_IMPORTED_MODULE_3__.Tensor + ), + /* harmony export */ + createInferenceSession: () => ( + /* binding */ + createInferenceSession + ), + /* harmony export */ + deviceToExecutionProviders: () => ( + /* binding */ + deviceToExecutionProviders + ), + /* harmony export */ + isONNXProxy: () => ( + /* binding */ + isONNXProxy + ), + /* harmony export */ + isONNXTensor: () => ( + /* binding */ + isONNXTensor + ), + /* harmony export */ + runInferenceSession: () => ( + /* binding */ + runInferenceSession + ) + /* harmony export */ + }); + var _env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../env.js */ + "./src/env.js" + ); + var onnxruntime_node__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! onnxruntime-node */ + "?2ce3" + ); + var onnxruntime_web__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! onnxruntime-web */ + "onnxruntime-web" + ); + var onnxruntime_common__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! onnxruntime-common */ + "onnxruntime-common" + ); + const DEVICE_TO_EXECUTION_PROVIDER_MAPPING = Object.freeze({ + auto: null, + // Auto-detect based on device and environment + gpu: null, + // Auto-detect GPU + cpu: "cpu", + // CPU + wasm: "wasm", + // WebAssembly + webgpu: "webgpu", + // WebGPU + cuda: "cuda", + // CUDA + dml: "dml", + // DirectML + webnn: { name: "webnn", deviceType: "cpu" }, + // WebNN (default) + "webnn-npu": { name: "webnn", deviceType: "npu" }, + // WebNN NPU + "webnn-gpu": { name: "webnn", deviceType: "gpu" }, + // WebNN GPU + "webnn-cpu": { name: "webnn", deviceType: "cpu" } + // WebNN CPU + }); + const supportedDevices = []; + let defaultDevices; + let ONNX; + const ORT_SYMBOL = Symbol.for("onnxruntime"); + if (ORT_SYMBOL in globalThis) { + ONNX = globalThis[ORT_SYMBOL]; + } else if (_env_js__WEBPACK_IMPORTED_MODULE_0__.apis.IS_NODE_ENV) { + ONNX = onnxruntime_node__WEBPACK_IMPORTED_MODULE_1__ ?? (onnxruntime_node__WEBPACK_IMPORTED_MODULE_1___namespace_cache || (onnxruntime_node__WEBPACK_IMPORTED_MODULE_1___namespace_cache = __webpack_require__2.t(onnxruntime_node__WEBPACK_IMPORTED_MODULE_1__, 2))); + switch (process.platform) { + case "win32": + supportedDevices.push("dml"); + break; + case "linux": + if (process.arch === "x64") { + supportedDevices.push("cuda"); + } + break; + case "darwin": + break; + } + supportedDevices.push("cpu"); + defaultDevices = ["cpu"]; + } else { + ONNX = onnxruntime_web__WEBPACK_IMPORTED_MODULE_2__; + if (_env_js__WEBPACK_IMPORTED_MODULE_0__.apis.IS_WEBNN_AVAILABLE) { + supportedDevices.push("webnn-npu", "webnn-gpu", "webnn-cpu", "webnn"); + } + if (_env_js__WEBPACK_IMPORTED_MODULE_0__.apis.IS_WEBGPU_AVAILABLE) { + supportedDevices.push("webgpu"); + } + supportedDevices.push("wasm"); + defaultDevices = ["wasm"]; + } + const InferenceSession3 = ONNX.InferenceSession; + function deviceToExecutionProviders(device = null) { + if (!device) return defaultDevices; + switch (device) { + case "auto": + return supportedDevices; + case "gpu": + return supportedDevices.filter( + (x) => ["webgpu", "cuda", "dml", "webnn-gpu"].includes(x) + ); + } + if (supportedDevices.includes(device)) { + return [DEVICE_TO_EXECUTION_PROVIDER_MAPPING[device] ?? device]; + } + throw new Error(`Unsupported device: "${device}". Should be one of: ${supportedDevices.join(", ")}.`); + } + let wasmInitPromise = null; + async function createInferenceSession(buffer_or_path, session_options, session_config) { + if (wasmInitPromise) { + await wasmInitPromise; + } + const sessionPromise = InferenceSession3.create(buffer_or_path, session_options); + wasmInitPromise ??= sessionPromise; + const session = await sessionPromise; + session.config = session_config; + return session; + } + let webInferenceChain = Promise.resolve(); + const IS_WEB_ENV = _env_js__WEBPACK_IMPORTED_MODULE_0__.apis.IS_BROWSER_ENV || _env_js__WEBPACK_IMPORTED_MODULE_0__.apis.IS_WEBWORKER_ENV; + async function runInferenceSession(session, ortFeed) { + const run = () => session.run(ortFeed); + const output = await (IS_WEB_ENV ? webInferenceChain = webInferenceChain.then(run) : run()); + return output; + } + function isONNXTensor(x) { + return x instanceof ONNX.Tensor; + } + const ONNX_ENV = ONNX?.env; + if (ONNX_ENV?.wasm) { + if ( + // @ts-ignore Cannot find name 'ServiceWorkerGlobalScope'.ts(2304) + !(typeof ServiceWorkerGlobalScope !== "undefined" && self instanceof ServiceWorkerGlobalScope) && !ONNX_ENV.wasm.wasmPaths + ) { + ONNX_ENV.wasm.wasmPaths = `https://cdn.jsdelivr.net/npm/@huggingface/transformers@${_env_js__WEBPACK_IMPORTED_MODULE_0__.env.version}/dist/`; + } + ONNX_ENV.wasm.proxy = false; + } + if (ONNX_ENV?.webgpu) { + ONNX_ENV.webgpu.powerPreference = "high-performance"; + } + function isONNXProxy() { + return ONNX_ENV?.wasm?.proxy; + } + _env_js__WEBPACK_IMPORTED_MODULE_0__.env.backends.onnx = ONNX_ENV; + }) + ), + /***/ + "./src/base/feature_extraction_utils.js": ( + /*!**********************************************!*\ + !*** ./src/base/feature_extraction_utils.js ***! + \**********************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + FeatureExtractor: () => ( + /* binding */ + FeatureExtractor + ), + /* harmony export */ + validate_audio_inputs: () => ( + /* binding */ + validate_audio_inputs + ) + /* harmony export */ + }); + var _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../utils/constants.js */ + "./src/utils/constants.js" + ); + var _utils_generic_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../utils/generic.js */ + "./src/utils/generic.js" + ); + var _utils_hub_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../utils/hub.js */ + "./src/utils/hub.js" + ); + class FeatureExtractor extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_1__.Callable { + /** + * Constructs a new FeatureExtractor instance. + * + * @param {Object} config The configuration for the feature extractor. + */ + constructor(config) { + super(); + this.config = config; + } + /** + * Instantiate one of the feature extractor classes of the library from a pretrained model. + * + * The feature extractor class to instantiate is selected based on the `feature_extractor_type` property of + * the config object (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) + * + * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: + * - A string, the *model id* of a pretrained feature_extractor hosted inside a model repo on huggingface.co. + * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a + * user or organization name, like `dbmdz/bert-base-german-cased`. + * - A path to a *directory* containing feature_extractor files, e.g., `./my_model_directory/`. + * @param {import('../utils/hub.js').PretrainedOptions} options Additional options for loading the feature_extractor. + * + * @returns {Promise} A new instance of the Feature Extractor class. + */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + const config = await (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_2__.getModelJSON)(pretrained_model_name_or_path, _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__.FEATURE_EXTRACTOR_NAME, true, options); + return new this(config); + } + } + function validate_audio_inputs(audio, feature_extractor) { + if (!(audio instanceof Float32Array || audio instanceof Float64Array)) { + throw new Error( + `${feature_extractor} expects input to be a Float32Array or a Float64Array, but got ${audio?.constructor?.name ?? typeof audio} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.` + ); + } + } + }) + ), + /***/ + "./src/base/image_processors_utils.js": ( + /*!********************************************!*\ + !*** ./src/base/image_processors_utils.js ***! + \********************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + ImageProcessor: () => ( + /* binding */ + ImageProcessor + ), + /* harmony export */ + center_to_corners_format: () => ( + /* binding */ + center_to_corners_format + ), + /* harmony export */ + post_process_instance_segmentation: () => ( + /* binding */ + post_process_instance_segmentation + ), + /* harmony export */ + post_process_object_detection: () => ( + /* binding */ + post_process_object_detection + ), + /* harmony export */ + post_process_panoptic_segmentation: () => ( + /* binding */ + post_process_panoptic_segmentation + ), + /* harmony export */ + post_process_semantic_segmentation: () => ( + /* binding */ + post_process_semantic_segmentation + ) + /* harmony export */ + }); + var _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../utils/generic.js */ + "./src/utils/generic.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../utils/tensor.js */ + "./src/utils/tensor.js" + ); + var _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../utils/maths.js */ + "./src/utils/maths.js" + ); + var _utils_image_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! ../utils/image.js */ + "./src/utils/image.js" + ); + var _utils_core_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__2( + /*! ../utils/core.js */ + "./src/utils/core.js" + ); + var _utils_hub_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__2( + /*! ../utils/hub.js */ + "./src/utils/hub.js" + ); + var _utils_constants_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__2( + /*! ../utils/constants.js */ + "./src/utils/constants.js" + ); + function constraint_to_multiple_of(val, multiple, minVal = 0, maxVal = null) { + const a = val / multiple; + let x = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.bankers_round)(a) * multiple; + if (maxVal !== null && x > maxVal) { + x = Math.floor(a) * multiple; + } + if (x < minVal) { + x = Math.ceil(a) * multiple; + } + return x; + } + function enforce_size_divisibility([width, height], divisor) { + return [ + Math.max(Math.floor(width / divisor), 1) * divisor, + Math.max(Math.floor(height / divisor), 1) * divisor + ]; + } + function center_to_corners_format([centerX, centerY, width, height]) { + return [ + centerX - width / 2, + centerY - height / 2, + centerX + width / 2, + centerY + height / 2 + ]; + } + function post_process_object_detection(outputs, threshold = 0.5, target_sizes = null, is_zero_shot = false) { + const out_logits = outputs.logits; + const out_bbox = outputs.pred_boxes; + const [batch_size, num_boxes, num_classes] = out_logits.dims; + if (target_sizes !== null && target_sizes.length !== batch_size) { + throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits"); + } + let toReturn = []; + for (let i = 0; i < batch_size; ++i) { + let target_size = target_sizes !== null ? target_sizes[i] : null; + let info = { + boxes: [], + classes: [], + scores: [] + }; + let logits = out_logits[i]; + let bbox = out_bbox[i]; + for (let j = 0; j < num_boxes; ++j) { + let logit = logits[j]; + let indices = []; + let probs; + if (is_zero_shot) { + probs = logit.sigmoid().data; + for (let k2 = 0; k2 < probs.length; ++k2) { + if (probs[k2] > threshold) { + indices.push(k2); + } + } + } else { + let maxIndex = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(logit.data)[1]; + if (maxIndex === num_classes - 1) { + continue; + } + probs = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.softmax)(logit.data); + if (probs[maxIndex] < threshold) { + continue; + } + indices.push(maxIndex); + } + for (const index of indices) { + let box = bbox[j].data; + box = center_to_corners_format(box); + if (target_size !== null) { + box = box.map((x, i2) => x * target_size[(i2 + 1) % 2]); + } + info.boxes.push(box); + info.classes.push(index); + info.scores.push(probs[index]); + } + } + toReturn.push(info); + } + return toReturn; + } + function post_process_semantic_segmentation(outputs, target_sizes = null) { + const logits = outputs.logits; + const batch_size = logits.dims[0]; + if (target_sizes !== null && target_sizes.length !== batch_size) { + throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits"); + } + const toReturn = []; + for (let i = 0; i < batch_size; ++i) { + const target_size = target_sizes !== null ? target_sizes[i] : null; + let data = logits[i]; + if (target_size !== null) { + data = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.interpolate)(data, target_size, "bilinear", false); + } + const [height, width] = target_size ?? data.dims.slice(-2); + const segmentation = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor( + "int32", + new Int32Array(height * width), + [height, width] + ); + const buffer = data[0].data; + const segmentation_data = segmentation.data; + for (let j = 1; j < data.dims[0]; ++j) { + const row = data[j].data; + for (let k2 = 0; k2 < row.length; ++k2) { + if (row[k2] > buffer[k2]) { + buffer[k2] = row[k2]; + segmentation_data[k2] = j; + } + } + } + const hasLabel = new Array(data.dims[0]); + for (let j = 0; j < segmentation_data.length; ++j) { + const index = segmentation_data[j]; + hasLabel[index] = index; + } + const labels = hasLabel.filter((x) => x !== void 0); + toReturn.push({ segmentation, labels }); + } + return toReturn; + } + function remove_low_and_no_objects(class_logits, mask_logits, object_mask_threshold, num_labels) { + const mask_probs_item = []; + const pred_scores_item = []; + const pred_labels_item = []; + for (let j = 0; j < class_logits.dims[0]; ++j) { + const cls = class_logits[j]; + const mask = mask_logits[j]; + const pred_label = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(cls.data)[1]; + if (pred_label === num_labels) { + continue; + } + const scores = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.softmax)(cls.data); + const pred_score = scores[pred_label]; + if (pred_score > object_mask_threshold) { + mask_probs_item.push(mask); + pred_scores_item.push(pred_score); + pred_labels_item.push(pred_label); + } + } + return [mask_probs_item, pred_scores_item, pred_labels_item]; + } + function check_segment_validity(mask_labels, mask_probs, k2, mask_threshold = 0.5, overlap_mask_area_threshold = 0.8) { + const mask_k = []; + let mask_k_area = 0; + let original_area = 0; + const mask_probs_k_data = mask_probs[k2].data; + for (let i = 0; i < mask_labels.length; ++i) { + if (mask_labels[i] === k2) { + mask_k.push(i); + ++mask_k_area; + } + if (mask_probs_k_data[i] >= mask_threshold) { + ++original_area; + } + } + let mask_exists = mask_k_area > 0 && original_area > 0; + if (mask_exists) { + let area_ratio = mask_k_area / original_area; + mask_exists = area_ratio > overlap_mask_area_threshold; + } + return [mask_exists, mask_k]; + } + function compute_segments(mask_probs, pred_scores, pred_labels, mask_threshold, overlap_mask_area_threshold, label_ids_to_fuse = null, target_size = null) { + const [height, width] = target_size ?? mask_probs[0].dims; + const segmentation = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor( + "int32", + new Int32Array(height * width), + [height, width] + ); + const segments = []; + if (target_size !== null) { + for (let i = 0; i < mask_probs.length; ++i) { + mask_probs[i] = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.interpolate)(mask_probs[i], target_size, "bilinear", false); + } + } + const mask_labels = new Int32Array(mask_probs[0].data.length); + const bestScores = new Float32Array(mask_probs[0].data.length); + for (let i = 0; i < mask_probs.length; ++i) { + let score = pred_scores[i]; + const mask_probs_i_data = mask_probs[i].data; + for (let j = 0; j < mask_probs_i_data.length; ++j) { + mask_probs_i_data[j] *= score; + if (mask_probs_i_data[j] > bestScores[j]) { + mask_labels[j] = i; + bestScores[j] = mask_probs_i_data[j]; + } + } + } + let current_segment_id = 0; + const segmentation_data = segmentation.data; + for (let k2 = 0; k2 < pred_labels.length; ++k2) { + const pred_class = pred_labels[k2]; + const [mask_exists, mask_k] = check_segment_validity( + mask_labels, + mask_probs, + k2, + mask_threshold, + overlap_mask_area_threshold + ); + if (!mask_exists) { + continue; + } + ++current_segment_id; + for (const index of mask_k) { + segmentation_data[index] = current_segment_id; + } + segments.push({ + id: current_segment_id, + label_id: pred_class, + // was_fused: should_fuse, TODO + score: pred_scores[k2] + }); + } + return [segmentation, segments]; + } + function smart_resize(height, width, factor = 28, min_pixels = 56 * 56, max_pixels = 14 * 14 * 4 * 1280) { + if (height < factor || width < factor) { + throw new Error(`height:${height} or width:${width} must be larger than factor:${factor}`); + } else if (Math.max(height, width) / Math.min(height, width) > 200) { + throw new Error( + `absolute aspect ratio must be smaller than 200, got ${Math.max(height, width) / Math.min(height, width)}` + ); + } + let h_bar = Math.round(height / factor) * factor; + let w_bar = Math.round(width / factor) * factor; + if (h_bar * w_bar > max_pixels) { + const beta = Math.sqrt(height * width / max_pixels); + h_bar = Math.floor(height / beta / factor) * factor; + w_bar = Math.floor(width / beta / factor) * factor; + } else if (h_bar * w_bar < min_pixels) { + const beta = Math.sqrt(min_pixels / (height * width)); + h_bar = Math.ceil(height * beta / factor) * factor; + w_bar = Math.ceil(width * beta / factor) * factor; + } + return [h_bar, w_bar]; + } + function post_process_panoptic_segmentation(outputs, threshold = 0.5, mask_threshold = 0.5, overlap_mask_area_threshold = 0.8, label_ids_to_fuse = null, target_sizes = null) { + if (label_ids_to_fuse === null) { + console.warn("`label_ids_to_fuse` unset. No instance will be fused."); + label_ids_to_fuse = /* @__PURE__ */ new Set(); + } + const class_queries_logits = outputs.class_queries_logits ?? outputs.logits; + const masks_queries_logits = outputs.masks_queries_logits ?? outputs.pred_masks; + const mask_probs = masks_queries_logits.sigmoid(); + let [batch_size, num_queries, num_labels] = class_queries_logits.dims; + num_labels -= 1; + if (target_sizes !== null && target_sizes.length !== batch_size) { + throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits"); + } + let toReturn = []; + for (let i = 0; i < batch_size; ++i) { + let target_size = target_sizes !== null ? target_sizes[i] : null; + let class_logits = class_queries_logits[i]; + let mask_logits = mask_probs[i]; + let [mask_probs_item, pred_scores_item, pred_labels_item] = remove_low_and_no_objects(class_logits, mask_logits, threshold, num_labels); + if (pred_labels_item.length === 0) { + let [height, width] = target_size ?? mask_logits.dims.slice(-2); + let segmentation2 = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor( + "int32", + new Int32Array(height * width).fill(-1), + [height, width] + ); + toReturn.push({ + segmentation: segmentation2, + segments_info: [] + }); + continue; + } + let [segmentation, segments] = compute_segments( + mask_probs_item, + pred_scores_item, + pred_labels_item, + mask_threshold, + overlap_mask_area_threshold, + label_ids_to_fuse, + target_size + ); + toReturn.push({ + segmentation, + segments_info: segments + }); + } + return toReturn; + } + function post_process_instance_segmentation(outputs, threshold = 0.5, target_sizes = null) { + throw new Error("`post_process_instance_segmentation` is not yet implemented."); + } + class ImageProcessor extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { + /** + * Constructs a new `ImageProcessor`. + * @param {ImageProcessorConfig} config The configuration object. + */ + constructor(config) { + super(); + this.image_mean = config.image_mean ?? config.mean; + this.image_std = config.image_std ?? config.std; + this.resample = config.resample ?? 2; + this.do_rescale = config.do_rescale ?? true; + this.rescale_factor = config.rescale_factor ?? 1 / 255; + this.do_normalize = config.do_normalize; + this.do_thumbnail = config.do_thumbnail; + this.size = config.size ?? config.image_size; + this.do_resize = config.do_resize ?? this.size !== void 0; + this.size_divisibility = config.size_divisibility ?? config.size_divisor; + this.do_center_crop = config.do_center_crop; + this.crop_size = config.crop_size; + this.do_convert_rgb = config.do_convert_rgb ?? true; + this.do_crop_margin = config.do_crop_margin; + this.pad_size = config.pad_size; + this.do_pad = config.do_pad; + this.min_pixels = config.min_pixels; + this.max_pixels = config.max_pixels; + if (this.do_pad && !this.pad_size && this.size && this.size.width !== void 0 && this.size.height !== void 0) { + this.pad_size = this.size; + } + this.do_flip_channel_order = config.do_flip_channel_order ?? false; + this.config = config; + } + /** + * Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any + * corresponding dimension of the specified size. + * @param {RawImage} image The image to be resized. + * @param {{height:number, width:number}} size The size `{"height": h, "width": w}` to resize the image to. + * @param {string | 0 | 1 | 2 | 3 | 4 | 5} [resample=2] The resampling filter to use. + * @returns {Promise} The resized image. + */ + async thumbnail(image, size, resample = 2) { + const input_height = image.height; + const input_width = image.width; + const output_height = size.height; + const output_width = size.width; + let height = Math.min(input_height, output_height); + let width = Math.min(input_width, output_width); + if (height === input_height && width === input_width) { + return image; + } + if (input_height > input_width) { + width = Math.floor(input_width * height / input_height); + } else if (input_width > input_height) { + height = Math.floor(input_height * width / input_width); + } + return await image.resize(width, height, { resample }); + } + /** + * Crops the margin of the image. Gray pixels are considered margin (i.e., pixels with a value below the threshold). + * @param {RawImage} image The image to be cropped. + * @param {number} gray_threshold Value below which pixels are considered to be gray. + * @returns {Promise} The cropped image. + */ + async crop_margin(image, gray_threshold = 200) { + const gray_image = image.clone().grayscale(); + const minValue = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.min)(gray_image.data)[0]; + const maxValue = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(gray_image.data)[0]; + const diff = maxValue - minValue; + if (diff === 0) { + return image; + } + const threshold = gray_threshold / 255; + let x_min = gray_image.width, y_min = gray_image.height, x_max = 0, y_max = 0; + const gray_image_data = gray_image.data; + for (let j = 0; j < gray_image.height; ++j) { + const row = j * gray_image.width; + for (let i = 0; i < gray_image.width; ++i) { + if ((gray_image_data[row + i] - minValue) / diff < threshold) { + x_min = Math.min(x_min, i); + y_min = Math.min(y_min, j); + x_max = Math.max(x_max, i); + y_max = Math.max(y_max, j); + } + } + } + image = await image.crop([x_min, y_min, x_max, y_max]); + return image; + } + /** + * Pad the image by a certain amount. + * @param {Float32Array} pixelData The pixel data to pad. + * @param {number[]} imgDims The dimensions of the image (height, width, channels). + * @param {{width:number; height:number}|number|'square'} padSize The dimensions of the padded image. + * @param {Object} options The options for padding. + * @param {'constant'|'symmetric'} [options.mode='constant'] The type of padding to add. + * @param {boolean} [options.center=false] Whether to center the image. + * @param {number|number[]} [options.constant_values=0] The constant value to use for padding. + * @returns {[Float32Array, number[]]} The padded pixel data and image dimensions. + */ + pad_image(pixelData, imgDims, padSize, { + mode = "constant", + center = false, + constant_values = 0 + } = {}) { + const [imageHeight, imageWidth, imageChannels] = imgDims; + let paddedImageWidth, paddedImageHeight; + if (typeof padSize === "number") { + paddedImageWidth = padSize; + paddedImageHeight = padSize; + } else if (padSize === "square") { + paddedImageWidth = paddedImageHeight = Math.max(imageHeight, imageWidth); + } else { + paddedImageWidth = padSize.width; + paddedImageHeight = padSize.height; + } + if (paddedImageWidth !== imageWidth || paddedImageHeight !== imageHeight) { + const paddedPixelData = new Float32Array(paddedImageWidth * paddedImageHeight * imageChannels); + if (Array.isArray(constant_values)) { + for (let i = 0; i < paddedPixelData.length; ++i) { + paddedPixelData[i] = constant_values[i % imageChannels]; + } + } else if (constant_values !== 0) { + paddedPixelData.fill(constant_values); + } + const [left, top] = center ? [Math.floor((paddedImageWidth - imageWidth) / 2), Math.floor((paddedImageHeight - imageHeight) / 2)] : [0, 0]; + for (let i = 0; i < imageHeight; ++i) { + const a = (i + top) * paddedImageWidth; + const b = i * imageWidth; + for (let j = 0; j < imageWidth; ++j) { + const c = (a + j + left) * imageChannels; + const d = (b + j) * imageChannels; + for (let k2 = 0; k2 < imageChannels; ++k2) { + paddedPixelData[c + k2] = pixelData[d + k2]; + } + } + } + if (mode === "symmetric") { + if (center) { + throw new Error("`center` padding is not supported when `mode` is set to `symmetric`."); + } + const h1 = imageHeight - 1; + const w1 = imageWidth - 1; + for (let i = 0; i < paddedImageHeight; ++i) { + const a = i * paddedImageWidth; + const b = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_4__.calculateReflectOffset)(i, h1) * imageWidth; + for (let j = 0; j < paddedImageWidth; ++j) { + if (i < imageHeight && j < imageWidth) continue; + const c = (a + j) * imageChannels; + const d = (b + (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_4__.calculateReflectOffset)(j, w1)) * imageChannels; + for (let k2 = 0; k2 < imageChannels; ++k2) { + paddedPixelData[c + k2] = pixelData[d + k2]; + } + } + } + } + pixelData = paddedPixelData; + imgDims = [paddedImageHeight, paddedImageWidth, imageChannels]; + } + return [pixelData, imgDims]; + } + /** + * Rescale the image' pixel values by `this.rescale_factor`. + * @param {Float32Array} pixelData The pixel data to rescale. + * @returns {void} + */ + rescale(pixelData) { + for (let i = 0; i < pixelData.length; ++i) { + pixelData[i] = this.rescale_factor * pixelData[i]; + } + } + /** + * Find the target (width, height) dimension of the output image after + * resizing given the input image and the desired size. + * @param {RawImage} image The image to resize. + * @param {any} size The size to use for resizing the image. + * @returns {[number, number]} The target (width, height) dimension of the output image after resizing. + */ + get_resize_output_image_size(image, size) { + const [srcWidth, srcHeight] = image.size; + let shortest_edge; + let longest_edge; + if (this.do_thumbnail) { + const { height, width } = size; + shortest_edge = Math.min(height, width); + } else if (Number.isInteger(size)) { + shortest_edge = size; + longest_edge = this.config.max_size ?? shortest_edge; + } else if (size !== void 0) { + shortest_edge = size.shortest_edge; + longest_edge = size.longest_edge; + } + if (shortest_edge !== void 0 || longest_edge !== void 0) { + const shortResizeFactor = shortest_edge === void 0 ? 1 : Math.max(shortest_edge / srcWidth, shortest_edge / srcHeight); + const newWidth = srcWidth * shortResizeFactor; + const newHeight = srcHeight * shortResizeFactor; + const longResizeFactor = longest_edge === void 0 ? 1 : Math.min(longest_edge / newWidth, longest_edge / newHeight); + let finalWidth = Math.floor(Number((newWidth * longResizeFactor).toFixed(2))); + let finalHeight = Math.floor(Number((newHeight * longResizeFactor).toFixed(2))); + if (this.size_divisibility !== void 0) { + [finalWidth, finalHeight] = enforce_size_divisibility([finalWidth, finalHeight], this.size_divisibility); + } + return [finalWidth, finalHeight]; + } else if (size !== void 0 && size.width !== void 0 && size.height !== void 0) { + let newWidth = size.width; + let newHeight = size.height; + if (this.config.keep_aspect_ratio && this.config.ensure_multiple_of) { + let scale_height = newHeight / srcHeight; + let scale_width = newWidth / srcWidth; + if (Math.abs(1 - scale_width) < Math.abs(1 - scale_height)) { + scale_height = scale_width; + } else { + scale_width = scale_height; + } + newHeight = constraint_to_multiple_of(scale_height * srcHeight, this.config.ensure_multiple_of); + newWidth = constraint_to_multiple_of(scale_width * srcWidth, this.config.ensure_multiple_of); + } + return [newWidth, newHeight]; + } else if (this.size_divisibility !== void 0) { + return enforce_size_divisibility([srcWidth, srcHeight], this.size_divisibility); + } else if (this.min_pixels !== void 0 && this.max_pixels !== void 0) { + const factor = this.config.patch_size * this.config.merge_size; + return smart_resize(srcHeight, srcWidth, factor, this.min_pixels, this.max_pixels); + } else { + throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(size)}`); + } + } + /** + * Resizes the image. + * @param {RawImage} image The image to resize. + * @returns {Promise} The resized image. + */ + async resize(image) { + const [newWidth, newHeight] = this.get_resize_output_image_size(image, this.size); + return await image.resize(newWidth, newHeight, { + // @ts-expect-error TS2322 + resample: this.resample + }); + } + /** + * @typedef {object} PreprocessedImage + * @property {HeightWidth} original_size The original size of the image. + * @property {HeightWidth} reshaped_input_size The reshaped input size of the image. + * @property {Tensor} pixel_values The pixel values of the preprocessed image. + */ + /** + * Preprocesses the given image. + * + * @param {RawImage} image The image to preprocess. + * @param {Object} overrides The overrides for the preprocessing options. + * @returns {Promise} The preprocessed image. + */ + async preprocess(image, { + do_normalize = null, + do_pad = null, + do_convert_rgb = null, + do_convert_grayscale = null, + do_flip_channel_order = null + } = {}) { + if (this.do_crop_margin) { + image = await this.crop_margin(image); + } + const [srcWidth, srcHeight] = image.size; + if (do_convert_rgb ?? this.do_convert_rgb) { + image = image.rgb(); + } else if (do_convert_grayscale) { + image = image.grayscale(); + } + if (this.do_resize) { + image = await this.resize(image); + } + if (this.do_thumbnail) { + image = await this.thumbnail(image, this.size, this.resample); + } + if (this.do_center_crop) { + let crop_width; + let crop_height; + if (Number.isInteger(this.crop_size)) { + crop_width = this.crop_size; + crop_height = this.crop_size; + } else { + crop_width = this.crop_size.width; + crop_height = this.crop_size.height; + } + image = await image.center_crop(crop_width, crop_height); + } + const reshaped_input_size = [image.height, image.width]; + let pixelData = Float32Array.from(image.data); + let imgDims = [image.height, image.width, image.channels]; + if (this.do_rescale) { + this.rescale(pixelData); + } + if (do_normalize ?? this.do_normalize) { + let image_mean = this.image_mean; + if (!Array.isArray(this.image_mean)) { + image_mean = new Array(image.channels).fill(image_mean); + } + let image_std = this.image_std; + if (!Array.isArray(this.image_std)) { + image_std = new Array(image.channels).fill(image_std); + } + if (image_mean.length !== image.channels || image_std.length !== image.channels) { + throw new Error(`When set to arrays, the length of \`image_mean\` (${image_mean.length}) and \`image_std\` (${image_std.length}) must match the number of channels in the image (${image.channels}).`); + } + for (let i = 0; i < pixelData.length; i += image.channels) { + for (let j = 0; j < image.channels; ++j) { + pixelData[i + j] = (pixelData[i + j] - image_mean[j]) / image_std[j]; + } + } + } + if (do_pad ?? this.do_pad) { + if (this.pad_size) { + const padded = this.pad_image(pixelData, [image.height, image.width, image.channels], this.pad_size); + [pixelData, imgDims] = padded; + } else if (this.size_divisibility) { + const [paddedWidth, paddedHeight] = enforce_size_divisibility([imgDims[1], imgDims[0]], this.size_divisibility); + [pixelData, imgDims] = this.pad_image(pixelData, imgDims, { width: paddedWidth, height: paddedHeight }); + } + } + if (do_flip_channel_order ?? this.do_flip_channel_order) { + if (imgDims[2] !== 3) { + throw new Error("Flipping channel order is only supported for RGB images."); + } + for (let i = 0; i < pixelData.length; i += 3) { + const temp = pixelData[i]; + pixelData[i] = pixelData[i + 2]; + pixelData[i + 2] = temp; + } + } + const pixel_values = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor("float32", pixelData, imgDims).permute(2, 0, 1); + return { + original_size: [srcHeight, srcWidth], + reshaped_input_size, + pixel_values + }; + } + /** + * Calls the feature extraction process on an array of images, + * preprocesses each image, and concatenates the resulting + * features into a single Tensor. + * @param {RawImage[]} images The image(s) to extract features from. + * @param {...any} args Additional arguments. + * @returns {Promise} An object containing the concatenated pixel values (and other metadata) of the preprocessed images. + */ + async _call(images, ...args) { + if (!Array.isArray(images)) { + images = [images]; + } + const imageData = await Promise.all(images.map((x) => this.preprocess(x))); + const pixel_values = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.stack)(imageData.map((x) => x.pixel_values), 0); + return { + pixel_values, + // Original sizes of images + original_sizes: imageData.map((x) => x.original_size), + // Reshaped sizes of images, before padding or cropping + reshaped_input_sizes: imageData.map((x) => x.reshaped_input_size) + }; + } + /** + * Instantiate one of the processor classes of the library from a pretrained model. + * + * The processor class to instantiate is selected based on the `image_processor_type` (or `feature_extractor_type`; legacy) + * property of the config object (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) + * + * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: + * - A string, the *model id* of a pretrained processor hosted inside a model repo on huggingface.co. + * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a + * user or organization name, like `dbmdz/bert-base-german-cased`. + * - A path to a *directory* containing processor files, e.g., `./my_model_directory/`. + * @param {import('../utils/hub.js').PretrainedOptions} options Additional options for loading the processor. + * + * @returns {Promise} A new instance of the Processor class. + */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + const preprocessorConfig = await (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.getModelJSON)(pretrained_model_name_or_path, _utils_constants_js__WEBPACK_IMPORTED_MODULE_6__.IMAGE_PROCESSOR_NAME, true, options); + return new this(preprocessorConfig); + } + } + }) + ), + /***/ + "./src/base/processing_utils.js": ( + /*!**************************************!*\ + !*** ./src/base/processing_utils.js ***! + \**************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + Processor: () => ( + /* binding */ + Processor + ) + /* harmony export */ + }); + var _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../utils/constants.js */ + "./src/utils/constants.js" + ); + var _utils_generic_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../utils/generic.js */ + "./src/utils/generic.js" + ); + var _utils_hub_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../utils/hub.js */ + "./src/utils/hub.js" + ); + class Processor extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_1__.Callable { + static classes = [ + "image_processor_class", + "tokenizer_class", + "feature_extractor_class" + ]; + static uses_processor_config = false; + static uses_chat_template_file = false; + /** + * Creates a new Processor with the given components + * @param {Object} config + * @param {Record} components + * @param {string} chat_template + */ + constructor(config, components, chat_template) { + super(); + this.config = config; + this.components = components; + this.chat_template = chat_template; + } + /** + * @returns {import('./image_processors_utils.js').ImageProcessor|undefined} The image processor of the processor, if it exists. + */ + get image_processor() { + return this.components.image_processor; + } + /** + * @returns {PreTrainedTokenizer|undefined} The tokenizer of the processor, if it exists. + */ + get tokenizer() { + return this.components.tokenizer; + } + /** + * @returns {import('./feature_extraction_utils.js').FeatureExtractor|undefined} The feature extractor of the processor, if it exists. + */ + get feature_extractor() { + return this.components.feature_extractor; + } + /** + * @param {Parameters[0]} messages + * @param {Parameters[1]} options + * @returns {ReturnType} + */ + apply_chat_template(messages, options = {}) { + if (!this.tokenizer) { + throw new Error("Unable to apply chat template without a tokenizer."); + } + return this.tokenizer.apply_chat_template(messages, { + tokenize: false, + // default to false + chat_template: this.chat_template ?? void 0, + ...options + }); + } + /** + * @param {Parameters} args + * @returns {ReturnType} + */ + batch_decode(...args) { + if (!this.tokenizer) { + throw new Error("Unable to decode without a tokenizer."); + } + return this.tokenizer.batch_decode(...args); + } + /** + * @param {Parameters} args + * @returns {ReturnType} + */ + decode(...args) { + if (!this.tokenizer) { + throw new Error("Unable to decode without a tokenizer."); + } + return this.tokenizer.decode(...args); + } + /** + * Calls the feature_extractor function with the given input. + * @param {any} input The input to extract features from. + * @param {...any} args Additional arguments. + * @returns {Promise} A Promise that resolves with the extracted features. + */ + async _call(input, ...args) { + for (const item of [this.image_processor, this.feature_extractor, this.tokenizer]) { + if (item) { + return item(input, ...args); + } + } + throw new Error("No image processor, feature extractor, or tokenizer found."); + } + /** + * Instantiate one of the processor classes of the library from a pretrained model. + * + * The processor class to instantiate is selected based on the `image_processor_type` (or `feature_extractor_type`; legacy) + * property of the config object (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) + * + * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: + * - A string, the *model id* of a pretrained processor hosted inside a model repo on huggingface.co. + * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a + * user or organization name, like `dbmdz/bert-base-german-cased`. + * - A path to a *directory* containing processor files, e.g., `./my_model_directory/`. + * @param {PretrainedProcessorOptions} options Additional options for loading the processor. + * + * @returns {Promise} A new instance of the Processor class. + */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + const [config, components, chat_template] = await Promise.all([ + // TODO: + this.uses_processor_config ? (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_2__.getModelJSON)(pretrained_model_name_or_path, _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__.PROCESSOR_NAME, true, options) : {}, + Promise.all( + this.classes.filter((cls) => cls in this).map(async (cls) => { + const component = await this[cls].from_pretrained(pretrained_model_name_or_path, options); + return [cls.replace(/_class$/, ""), component]; + }) + ).then(Object.fromEntries), + this.uses_chat_template_file ? (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_2__.getModelText)(pretrained_model_name_or_path, _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__.CHAT_TEMPLATE_NAME, true, options) : null + ]); + return new this(config, components, chat_template); + } + } + }) + ), + /***/ + "./src/configs.js": ( + /*!************************!*\ + !*** ./src/configs.js ***! + \************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + AutoConfig: () => ( + /* binding */ + AutoConfig + ), + /* harmony export */ + PretrainedConfig: () => ( + /* binding */ + PretrainedConfig + ), + /* harmony export */ + getCacheShapes: () => ( + /* binding */ + getCacheShapes + ) + /* harmony export */ + }); + var _utils_core_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ./utils/core.js */ + "./src/utils/core.js" + ); + var _utils_hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ./utils/hub.js */ + "./src/utils/hub.js" + ); + async function loadConfig(pretrained_model_name_or_path, options) { + return await (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_1__.getModelJSON)(pretrained_model_name_or_path, "config.json", true, options); + } + function getNormalizedConfig(config) { + const mapping = {}; + let init_normalized_config = {}; + switch (config.model_type) { + // Sub-configs + case "llava": + case "paligemma": + case "gemma3": + case "florence2": + case "llava_onevision": + case "idefics3": + case "ultravox": + case "voxtral": + case "smolvlm": + case "gemma3n": + case "mistral3": + init_normalized_config = getNormalizedConfig(config.text_config); + break; + case "moondream1": + init_normalized_config = getNormalizedConfig(config.phi_config); + break; + case "musicgen": + init_normalized_config = getNormalizedConfig(config.decoder); + break; + case "multi_modality": + init_normalized_config = getNormalizedConfig(config.language_config); + break; + // Decoder-only models + case "gpt2": + case "gptj": + case "jais": + case "codegen": + case "gpt_bigcode": + mapping["num_heads"] = "n_head"; + mapping["num_layers"] = "n_layer"; + mapping["hidden_size"] = "n_embd"; + break; + case "gpt_neox": + case "stablelm": + case "opt": + case "falcon": + case "modernbert-decoder": + mapping["num_heads"] = "num_attention_heads"; + mapping["num_layers"] = "num_hidden_layers"; + mapping["hidden_size"] = "hidden_size"; + break; + case "llama": + case "llama4_text": + case "nanochat": + case "arcee": + case "lfm2": + case "smollm3": + case "olmo": + case "olmo2": + case "mobilellm": + case "granite": + case "granitemoehybrid": + case "cohere": + case "mistral": + case "starcoder2": + case "qwen2": + case "qwen2_vl": + case "phi": + case "phi3": + case "phi3_v": + case "llava_qwen2": + mapping["num_heads"] = "num_key_value_heads"; + mapping["num_layers"] = "num_hidden_layers"; + mapping["hidden_size"] = "hidden_size"; + mapping["num_attention_heads"] = "num_attention_heads"; + mapping["dim_kv"] = "head_dim"; + break; + case "qwen3": + case "gemma": + case "gemma2": + case "vaultgemma": + case "gemma3_text": + case "gemma3n_text": + case "glm": + case "helium": + case "ernie4_5": + case "ministral": + case "ministral3": + mapping["num_heads"] = "num_key_value_heads"; + mapping["num_layers"] = "num_hidden_layers"; + mapping["dim_kv"] = "head_dim"; + break; + case "openelm": + mapping["num_heads"] = "num_kv_heads"; + mapping["num_layers"] = "num_transformer_layers"; + mapping["dim_kv"] = "head_dim"; + break; + case "gpt_neo": + case "donut-swin": + mapping["num_heads"] = "num_heads"; + mapping["num_layers"] = "num_layers"; + mapping["hidden_size"] = "hidden_size"; + break; + case "bloom": + mapping["num_heads"] = "n_head"; + mapping["num_layers"] = "n_layer"; + mapping["hidden_size"] = "hidden_size"; + break; + case "mpt": + mapping["num_heads"] = "n_heads"; + mapping["num_layers"] = "n_layers"; + mapping["hidden_size"] = "d_model"; + break; + case "exaone": + mapping["num_heads"] = "num_key_value_heads"; + mapping["num_layers"] = "num_layers"; + mapping["dim_kv"] = "head_dim"; + mapping["num_attention_heads"] = "num_attention_heads"; + break; + // Encoder-decoder models + case "t5": + case "mt5": + case "longt5": + mapping["num_decoder_layers"] = "num_decoder_layers"; + mapping["num_decoder_heads"] = "num_heads"; + mapping["decoder_dim_kv"] = "d_kv"; + mapping["num_encoder_layers"] = "num_layers"; + mapping["num_encoder_heads"] = "num_heads"; + mapping["encoder_dim_kv"] = "d_kv"; + break; + case "bart": + case "mbart": + case "marian": + case "whisper": + case "lite-whisper": + case "m2m_100": + case "blenderbot": + case "blenderbot-small": + case "florence2_language": + mapping["num_decoder_layers"] = "decoder_layers"; + mapping["num_decoder_heads"] = "decoder_attention_heads"; + mapping["decoder_hidden_size"] = "d_model"; + mapping["num_encoder_layers"] = "encoder_layers"; + mapping["num_encoder_heads"] = "encoder_attention_heads"; + mapping["encoder_hidden_size"] = "d_model"; + break; + case "speecht5": + mapping["num_decoder_layers"] = "decoder_layers"; + mapping["num_decoder_heads"] = "decoder_attention_heads"; + mapping["decoder_hidden_size"] = "hidden_size"; + mapping["num_encoder_layers"] = "encoder_layers"; + mapping["num_encoder_heads"] = "encoder_attention_heads"; + mapping["encoder_hidden_size"] = "hidden_size"; + break; + case "trocr": + mapping["num_encoder_layers"] = mapping["num_decoder_layers"] = "decoder_layers"; + mapping["num_encoder_heads"] = mapping["num_decoder_heads"] = "decoder_attention_heads"; + mapping["encoder_hidden_size"] = mapping["decoder_hidden_size"] = "d_model"; + break; + case "musicgen_decoder": + mapping["num_encoder_layers"] = mapping["num_decoder_layers"] = "num_hidden_layers"; + mapping["num_encoder_heads"] = mapping["num_decoder_heads"] = "num_attention_heads"; + mapping["encoder_hidden_size"] = mapping["decoder_hidden_size"] = "hidden_size"; + break; + case "moonshine": + mapping["num_decoder_layers"] = "decoder_num_hidden_layers"; + mapping["num_decoder_heads"] = "decoder_num_key_value_heads"; + mapping["num_encoder_layers"] = "encoder_num_hidden_layers"; + mapping["num_encoder_heads"] = "encoder_num_key_value_heads"; + mapping["encoder_hidden_size"] = mapping["decoder_hidden_size"] = "hidden_size"; + break; + case "vision-encoder-decoder": + const decoderConfig = getNormalizedConfig(config.decoder); + const add_encoder_pkv = "num_decoder_layers" in decoderConfig; + const result = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_0__.pick)(config, ["model_type", "is_encoder_decoder"]); + if (add_encoder_pkv) { + result.num_decoder_layers = decoderConfig.num_decoder_layers; + result.num_decoder_heads = decoderConfig.num_decoder_heads; + result.decoder_hidden_size = decoderConfig.decoder_hidden_size; + result.num_encoder_layers = decoderConfig.num_encoder_layers; + result.num_encoder_heads = decoderConfig.num_encoder_heads; + result.encoder_hidden_size = decoderConfig.encoder_hidden_size; + } else { + result.num_layers = decoderConfig.num_layers; + result.num_heads = decoderConfig.num_heads; + result.hidden_size = decoderConfig.hidden_size; + } + return result; + } + const normalized_config = { + ...init_normalized_config, + ...(0, _utils_core_js__WEBPACK_IMPORTED_MODULE_0__.pick)(config, ["model_type", "multi_query", "is_encoder_decoder"]) + }; + for (const key in mapping) { + normalized_config[key] = config[mapping[key]]; + } + return normalized_config; + } + function getCacheShapes(config, options) { + if (config.model_type === "lfm2") { + const pkv_prefix = options?.prefix ?? "past_key_values"; + const conv_prefix = pkv_prefix === "present" ? "present" : "past"; + const cache_values = {}; + const { layer_types, num_attention_heads, num_key_value_heads, hidden_size, conv_L_cache } = config; + const head_dim = hidden_size / num_attention_heads; + const batch_size = options?.batch_size ?? 1; + for (let i = 0; i < layer_types.length; ++i) { + if (layer_types[i] === "full_attention") { + for (const kv of ["key", "value"]) { + cache_values[`${pkv_prefix}.${i}.${kv}`] = [batch_size, num_key_value_heads, 0, head_dim]; + } + } else if (layer_types[i] === "conv") { + cache_values[`${conv_prefix}_conv.${i}`] = [batch_size, hidden_size, conv_L_cache]; + } else { + throw new Error(`Unsupported layer type: ${layer_types[i]}`); + } + } + return cache_values; + } + return getKeyValueShapes(config, options); + } + function getKeyValueShapes(config, { + prefix = "past_key_values", + batch_size = 1 + } = {}) { + const decoderFeeds = {}; + const normalized_config = config.normalized_config; + if (normalized_config.is_encoder_decoder && ("num_encoder_heads" in normalized_config && "num_decoder_heads" in normalized_config)) { + const encoder_dim_kv = normalized_config.encoder_dim_kv ?? normalized_config.encoder_hidden_size / normalized_config.num_encoder_heads; + const decoder_dim_kv = normalized_config.decoder_dim_kv ?? normalized_config.decoder_hidden_size / normalized_config.num_decoder_heads; + const encoder_dims = [batch_size, normalized_config.num_encoder_heads, 0, encoder_dim_kv]; + const decoder_dims = [batch_size, normalized_config.num_decoder_heads, 0, decoder_dim_kv]; + for (let i = 0; i < normalized_config.num_decoder_layers; ++i) { + decoderFeeds[`${prefix}.${i}.encoder.key`] = encoder_dims; + decoderFeeds[`${prefix}.${i}.encoder.value`] = encoder_dims; + decoderFeeds[`${prefix}.${i}.decoder.key`] = decoder_dims; + decoderFeeds[`${prefix}.${i}.decoder.value`] = decoder_dims; + } + } else { + const num_heads = normalized_config.num_heads; + const num_layers = normalized_config.num_layers; + const dim_kv = normalized_config.dim_kv ?? normalized_config.hidden_size / (normalized_config.num_attention_heads ?? num_heads); + if (normalized_config.model_type === "falcon") { + const dims = [batch_size * num_heads, 0, dim_kv]; + for (let i = 0; i < num_layers; ++i) { + decoderFeeds[`${prefix}.${i}.key`] = dims; + decoderFeeds[`${prefix}.${i}.value`] = dims; + } + } else if (normalized_config.multi_query) { + const dims = [batch_size * num_heads, 0, 2 * dim_kv]; + for (let i = 0; i < num_layers; ++i) { + decoderFeeds[`${prefix}.${i}.key_value`] = dims; + } + } else if (normalized_config.model_type === "bloom") { + const keyDims = [batch_size * num_heads, dim_kv, 0]; + const valueDims = [batch_size * num_heads, 0, dim_kv]; + for (let i = 0; i < num_layers; ++i) { + decoderFeeds[`${prefix}.${i}.key`] = keyDims; + decoderFeeds[`${prefix}.${i}.value`] = valueDims; + } + } else if (normalized_config.model_type === "openelm") { + for (let i = 0; i < num_layers; ++i) { + const dims = [batch_size, num_heads[i], 0, dim_kv]; + decoderFeeds[`${prefix}.${i}.key`] = dims; + decoderFeeds[`${prefix}.${i}.value`] = dims; + } + } else { + const dims = [batch_size, num_heads, 0, dim_kv]; + for (let i = 0; i < num_layers; ++i) { + decoderFeeds[`${prefix}.${i}.key`] = dims; + decoderFeeds[`${prefix}.${i}.value`] = dims; + } + } + } + return decoderFeeds; + } + class PretrainedConfig { + // NOTE: Typo in original + /** @type {string|null} */ + model_type = null; + /** @type {boolean} */ + is_encoder_decoder = false; + /** @type {number} */ + max_position_embeddings; + /** @type {TransformersJSConfig} */ + "transformers.js_config"; + /** + * Create a new PreTrainedTokenizer instance. + * @param {Object} configJSON The JSON of the config. + */ + constructor(configJSON) { + Object.assign(this, configJSON); + this.normalized_config = getNormalizedConfig(this); + } + /** + * Loads a pre-trained config from the given `pretrained_model_name_or_path`. + * + * @param {string} pretrained_model_name_or_path The path to the pre-trained config. + * @param {PretrainedOptions} options Additional options for loading the config. + * @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`. + * + * @returns {Promise} A new instance of the `PretrainedConfig` class. + */ + static async from_pretrained(pretrained_model_name_or_path, { + progress_callback = null, + config = null, + cache_dir = null, + local_files_only = false, + revision = "main" + } = {}) { + if (config && !(config instanceof PretrainedConfig)) { + config = new PretrainedConfig(config); + } + const data = config ?? await loadConfig(pretrained_model_name_or_path, { + progress_callback, + config, + cache_dir, + local_files_only, + revision + }); + return new this(data); + } + } + class AutoConfig { + /** @type {typeof PretrainedConfig.from_pretrained} */ + static async from_pretrained(...args) { + return PretrainedConfig.from_pretrained(...args); + } + } + }) + ), + /***/ + "./src/env.js": ( + /*!********************!*\ + !*** ./src/env.js ***! + \********************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + apis: () => ( + /* binding */ + apis + ), + /* harmony export */ + env: () => ( + /* binding */ + env3 + ) + /* harmony export */ + }); + var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! node:fs */ + "?db59" + ); + var node_path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! node:path */ + "?383f" + ); + var node_url__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! node:url */ + "?fa4b" + ); + const VERSION = "3.8.1"; + const IS_BROWSER_ENV = typeof window !== "undefined" && typeof window.document !== "undefined"; + const IS_WEBWORKER_ENV = typeof self !== "undefined" && ["DedicatedWorkerGlobalScope", "ServiceWorkerGlobalScope", "SharedWorkerGlobalScope"].includes(self.constructor?.name); + const IS_WEB_CACHE_AVAILABLE = typeof self !== "undefined" && "caches" in self; + const IS_WEBGPU_AVAILABLE = typeof navigator !== "undefined" && "gpu" in navigator; + const IS_WEBNN_AVAILABLE = typeof navigator !== "undefined" && "ml" in navigator; + const IS_PROCESS_AVAILABLE = typeof process !== "undefined"; + const IS_NODE_ENV = IS_PROCESS_AVAILABLE && process?.release?.name === "node"; + const IS_FS_AVAILABLE = !isEmpty(node_fs__WEBPACK_IMPORTED_MODULE_0__); + const IS_PATH_AVAILABLE = !isEmpty(node_path__WEBPACK_IMPORTED_MODULE_1__); + const IS_DENO_RUNTIME = typeof globalThis.Deno !== "undefined"; + const IS_BUN_RUNTIME = typeof globalThis.Bun !== "undefined"; + const apis = Object.freeze({ + /** Whether we are running in a browser environment (and not a web worker) */ + IS_BROWSER_ENV, + /** Whether we are running in a web worker environment */ + IS_WEBWORKER_ENV, + /** Whether the Cache API is available */ + IS_WEB_CACHE_AVAILABLE, + /** Whether the WebGPU API is available */ + IS_WEBGPU_AVAILABLE, + /** Whether the WebNN API is available */ + IS_WEBNN_AVAILABLE, + /** Whether the Node.js process API is available */ + IS_PROCESS_AVAILABLE, + /** Whether we are running in a Node.js-like environment (node, deno, bun) */ + IS_NODE_ENV, + /** Whether the filesystem API is available */ + IS_FS_AVAILABLE, + /** Whether the path API is available */ + IS_PATH_AVAILABLE + }); + const RUNNING_LOCALLY = IS_FS_AVAILABLE && IS_PATH_AVAILABLE; + let dirname__ = "./"; + if (RUNNING_LOCALLY) { + const _import_meta_url = Object(import_meta2).url; + if (_import_meta_url) { + dirname__ = node_path__WEBPACK_IMPORTED_MODULE_1__.dirname(node_path__WEBPACK_IMPORTED_MODULE_1__.dirname(node_url__WEBPACK_IMPORTED_MODULE_2__.fileURLToPath(_import_meta_url))); + } else if (typeof __dirname !== "undefined") { + dirname__ = node_path__WEBPACK_IMPORTED_MODULE_1__.dirname(__dirname); + } + } + const DEFAULT_CACHE_DIR = RUNNING_LOCALLY ? node_path__WEBPACK_IMPORTED_MODULE_1__.join(dirname__, "/.cache/") : null; + const DEFAULT_LOCAL_MODEL_PATH = "/models/"; + const localModelPath = RUNNING_LOCALLY ? node_path__WEBPACK_IMPORTED_MODULE_1__.join(dirname__, DEFAULT_LOCAL_MODEL_PATH) : DEFAULT_LOCAL_MODEL_PATH; + const env3 = { + version: VERSION, + /////////////////// Backends settings /////////////////// + // NOTE: These will be populated later by the backends themselves. + backends: { + // onnxruntime-web/onnxruntime-node + onnx: {} + }, + /////////////////// Model settings /////////////////// + allowRemoteModels: true, + remoteHost: "https://huggingface.co/", + remotePathTemplate: "{model}/resolve/{revision}/", + allowLocalModels: !(IS_BROWSER_ENV || IS_WEBWORKER_ENV), + localModelPath, + useFS: IS_FS_AVAILABLE, + /////////////////// Cache settings /////////////////// + useBrowserCache: IS_WEB_CACHE_AVAILABLE && !IS_DENO_RUNTIME, + useFSCache: IS_FS_AVAILABLE, + cacheDir: DEFAULT_CACHE_DIR, + useCustomCache: false, + customCache: null + ////////////////////////////////////////////////////// + }; + function isEmpty(obj) { + return Object.keys(obj).length === 0; + } + }) + ), + /***/ + "./src/generation/configuration_utils.js": ( + /*!***********************************************!*\ + !*** ./src/generation/configuration_utils.js ***! + \***********************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + GenerationConfig: () => ( + /* binding */ + GenerationConfig + ) + /* harmony export */ + }); + var _utils_core_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../utils/core.js */ + "./src/utils/core.js" + ); + class GenerationConfig { + // Parameters that control the length of the output + /** + * The maximum length the generated tokens can have. + * Corresponds to the length of the input prompt + `max_new_tokens`. + * Its effect is overridden by `max_new_tokens`, if also set. + * @type {number} + * @default 20 + */ + max_length = 20; + /** + * The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt. + * @type {number} + * @default null + */ + max_new_tokens = null; + /** + * The minimum length of the sequence to be generated. + * Corresponds to the length of the input prompt + `min_new_tokens`. + * Its effect is overridden by `min_new_tokens`, if also set. + * @type {number} + * @default 0 + */ + min_length = 0; + /** + * The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt. + * @type {number} + * @default null + */ + min_new_tokens = null; + /** + * Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values: + * - `true`, where the generation stops as soon as there are `num_beams` complete candidates; + * - `false`, where an heuristic is applied and the generation stops when is it very unlikely to find better candidates; + * - `"never"`, where the beam search procedure only stops when there cannot be better candidates (canonical beam search algorithm). + * @type {boolean|"never"} + * @default false + */ + early_stopping = false; + /** + * The maximum amount of time you allow the computation to run for in seconds. + * Generation will still finish the current pass after allocated time has been passed. + * @type {number} + * @default null + */ + max_time = null; + // Parameters that control the generation strategy used + /** + * Whether or not to use sampling; use greedy decoding otherwise. + * @type {boolean} + * @default false + */ + do_sample = false; + /** + * Number of beams for beam search. 1 means no beam search. + * @type {number} + * @default 1 + */ + num_beams = 1; + /** + * Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams. + * See [this paper](https://huggingface.co/papers/1610.02424) for more details. + * @type {number} + * @default 1 + */ + num_beam_groups = 1; + /** + * The values balance the model confidence and the degeneration penalty in contrastive search decoding. + * @type {number} + * @default null + */ + penalty_alpha = null; + /** + * Whether or not the model should use the past last key/values attentions (if applicable to the model) to speed up decoding. + * @type {boolean} + * @default true + */ + use_cache = true; + // Parameters for manipulation of the model output logits + /** + * The value used to modulate the next token probabilities. + * @type {number} + * @default 1.0 + */ + temperature = 1; + /** + * The number of highest probability vocabulary tokens to keep for top-k-filtering. + * @type {number} + * @default 50 + */ + top_k = 50; + /** + * If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or higher are kept for generation. + * @type {number} + * @default 1.0 + */ + top_p = 1; + /** + * Local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next, given the partial text already generated. + * If set to float < 1, the smallest set of the most locally typical tokens with probabilities that add up to `typical_p` or higher are kept for generation. + * See [this paper](https://huggingface.co/papers/2202.00666) for more details. + * @type {number} + * @default 1.0 + */ + typical_p = 1; + /** + * If set to float strictly between 0 and 1, only tokens with a conditional probability greater than `epsilon_cutoff` will be sampled. + * In the paper, suggested values range from 3e-4 to 9e-4, depending on the size of the model. + * See [Truncation Sampling as Language Model Desmoothing](https://huggingface.co/papers/2210.15191) for more details. + * @type {number} + * @default 0.0 + */ + epsilon_cutoff = 0; + /** + * Eta sampling is a hybrid of locally typical sampling and epsilon sampling. + * If set to float strictly between 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits)))`. + * The latter term is intuitively the expected next token probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model. + * See [Truncation Sampling as Language Model Desmoothing](https://huggingface.co/papers/2210.15191) for more details. + * @type {number} + * @default 0.0 + */ + eta_cutoff = 0; + /** + * This value is subtracted from a beam's score if it generates a token same as any beam from other group at a particular time. + * Note that `diversity_penalty` is only effective if `group beam search` is enabled. + * @type {number} + * @default 0.0 + */ + diversity_penalty = 0; + /** + * The parameter for repetition penalty. 1.0 means no penalty. + * See [this paper](https://huggingface.co/papers/1909.05858) for more details. + * @type {number} + * @default 1.0 + */ + repetition_penalty = 1; + /** + * The paramater for encoder_repetition_penalty. + * An exponential penalty on sequences that are not in the original input. + * 1.0 means no penalty. + * @type {number} + * @default 1.0 + */ + encoder_repetition_penalty = 1; + /** + * Exponential penalty to the length that is used with beam-based generation. + * It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence. + * Since the score is the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while `length_penalty` < 0.0 encourages shorter sequences. + * @type {number} + * @default 1.0 + */ + length_penalty = 1; + /** + * If set to int > 0, all ngrams of that size can only occur once. + * @type {number} + * @default 0 + */ + no_repeat_ngram_size = 0; + /** + * List of token ids that are not allowed to be generated. + * In order to get the token ids of the words that should not appear in the generated text, use + * `tokenizer(bad_words, { add_prefix_space: true, add_special_tokens: false }).input_ids`. + * @type {number[][]} + * @default null + */ + bad_words_ids = null; + /** + * List of token ids that must be generated. + * If given a `number[][]`, this is treated as a simple list of words that must be included, the opposite to `bad_words_ids`. + * If given `number[][][]`, this triggers a [disjunctive constraint](https://github.com/huggingface/transformers/issues/14081), where one can allow different forms of each word. + * @type {number[][]|number[][][]} + * @default null + */ + force_words_ids = null; + /** + * Whether to renormalize the logits after applying all the logits processors or warpers (including the custom ones). + * It's highly recommended to set this flag to `true` as the search algorithms suppose the score logits are normalized but some logit processors or warpers break the normalization. + * @type {boolean} + * @default false + */ + renormalize_logits = false; + /** + * Custom constraints that can be added to the generation to ensure that the output will contain the use of certain tokens as defined by `Constraint` objects, in the most sensible way possible. + * @type {Object[]} + * @default null + */ + constraints = null; + /** + * The id of the token to force as the first generated token after the `decoder_start_token_id`. + * Useful for multilingual models like mBART where the first generated token needs to be the target language token. + * @type {number} + * @default null + */ + forced_bos_token_id = null; + /** + * The id of the token to force as the last generated token when `max_length` is reached. + * Optionally, use a list to set multiple *end-of-sequence* tokens. + * @type {number|number[]} + * @default null + */ + forced_eos_token_id = null; + /** + * Whether to remove possible *nan* and *inf* outputs of the model to prevent the generation method to crash. Note that using `remove_invalid_values` can slow down generation. + * @type {boolean} + */ + remove_invalid_values = false; + /** + * This Tuple adds an exponentially increasing length penalty, after a certain amount of tokens have been generated. + * The tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty starts and `decay_factor` represents the factor of exponential decay. + * @type {[number, number]} + * @default null + */ + exponential_decay_length_penalty = null; + /** + * A list of tokens that will be suppressed at generation. + * The `SuppressTokens` logit processor will set their log probs to `-inf` so that they are not sampled. + * @type {number[]} + * @default null + */ + suppress_tokens = null; + /** + * A streamer that will be used to stream the generation. + * @type {import('./streamers.js').TextStreamer} + * @default null + */ + streamer = null; + /** + * A list of tokens that will be suppressed at the beginning of the generation. + * The `SuppressBeginTokens` logit processor will set their log probs to `-inf` so that they are not sampled. + * @type {number[]} + * @default null + */ + begin_suppress_tokens = null; + /** + * A list of pairs of integers which indicates a mapping from generation indices to token indices that will be forced before sampling. + * For example, `[[1, 123]]` means the second generated token will always be a token of index 123. + * @type {[number, number][]} + * @default null + */ + forced_decoder_ids = null; + /** + * The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`. + * Higher guidance scale encourages the model to generate samples that are more closely linked to the input + * prompt, usually at the expense of poorer quality. + * @type {number} + * @default null + */ + guidance_scale = null; + // Parameters that define the output variables of `generate` + /** + * The number of independently computed returned sequences for each element in the batch. + * @type {number} + * @default 1 + */ + num_return_sequences = 1; + /** + * Whether or not to return the attentions tensors of all attention layers. + * See `attentions` under returned tensors for more details. + * @type {boolean} + * @default false + */ + output_attentions = false; + /** + * Whether or not to return the hidden states of all layers. + * See `hidden_states` under returned tensors for more details. + * @type {boolean} + * @default false + */ + output_hidden_states = false; + /** + * Whether or not to return the prediction scores. + * See `scores` under returned tensors for more details. + * @type {boolean} + * @default false + */ + output_scores = false; + /** + * Whether or not to return a `ModelOutput` instead of a plain tuple. + * @type {boolean} + * @default false + */ + return_dict_in_generate = false; + // Special tokens that can be used at generation time + /** + * The id of the *padding* token. + * @type {number} + * @default null + */ + pad_token_id = null; + /** + * The id of the *beginning-of-sequence* token. + * @type {number} + * @default null + */ + bos_token_id = null; + /** + * The id of the *end-of-sequence* token. + * Optionally, use a list to set multiple *end-of-sequence* tokens. + * @type {number|number[]} + * @default null + */ + eos_token_id = null; + // Generation parameters exclusive to encoder-decoder models + /** + * If set to int > 0, all ngrams of that size that occur in the `encoder_input_ids` cannot occur in the `decoder_input_ids`. + * @type {number} + * @default 0 + */ + encoder_no_repeat_ngram_size = 0; + /** + * If an encoder-decoder model starts decoding with a different token than *bos*, the id of that token. + * @type {number} + * @default null + */ + decoder_start_token_id = null; + // Wild card + /** + * Additional generation kwargs will be forwarded to the `generate` function of the model. + * Kwargs that are not present in `generate`'s signature will be used in the model forward pass. + * @type {Object} + * @default {} + */ + generation_kwargs = {}; + /** + * + * @param {GenerationConfig|import('../configs.js').PretrainedConfig} config + */ + constructor(config) { + Object.assign(this, (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_0__.pick)(config, Object.getOwnPropertyNames(this))); + } + } + }) + ), + /***/ + "./src/generation/logits_process.js": ( + /*!******************************************!*\ + !*** ./src/generation/logits_process.js ***! + \******************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + ClassifierFreeGuidanceLogitsProcessor: () => ( + /* binding */ + ClassifierFreeGuidanceLogitsProcessor + ), + /* harmony export */ + ForcedBOSTokenLogitsProcessor: () => ( + /* binding */ + ForcedBOSTokenLogitsProcessor + ), + /* harmony export */ + ForcedEOSTokenLogitsProcessor: () => ( + /* binding */ + ForcedEOSTokenLogitsProcessor + ), + /* harmony export */ + LogitsProcessor: () => ( + /* binding */ + LogitsProcessor + ), + /* harmony export */ + LogitsProcessorList: () => ( + /* binding */ + LogitsProcessorList + ), + /* harmony export */ + LogitsWarper: () => ( + /* binding */ + LogitsWarper + ), + /* harmony export */ + MinLengthLogitsProcessor: () => ( + /* binding */ + MinLengthLogitsProcessor + ), + /* harmony export */ + MinNewTokensLengthLogitsProcessor: () => ( + /* binding */ + MinNewTokensLengthLogitsProcessor + ), + /* harmony export */ + NoBadWordsLogitsProcessor: () => ( + /* binding */ + NoBadWordsLogitsProcessor + ), + /* harmony export */ + NoRepeatNGramLogitsProcessor: () => ( + /* binding */ + NoRepeatNGramLogitsProcessor + ), + /* harmony export */ + RepetitionPenaltyLogitsProcessor: () => ( + /* binding */ + RepetitionPenaltyLogitsProcessor + ), + /* harmony export */ + SuppressTokensAtBeginLogitsProcessor: () => ( + /* binding */ + SuppressTokensAtBeginLogitsProcessor + ), + /* harmony export */ + TemperatureLogitsWarper: () => ( + /* binding */ + TemperatureLogitsWarper + ), + /* harmony export */ + TopKLogitsWarper: () => ( + /* binding */ + TopKLogitsWarper + ), + /* harmony export */ + TopPLogitsWarper: () => ( + /* binding */ + TopPLogitsWarper + ), + /* harmony export */ + WhisperTimeStampLogitsProcessor: () => ( + /* binding */ + WhisperTimeStampLogitsProcessor + ) + /* harmony export */ + }); + var _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../utils/generic.js */ + "./src/utils/generic.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../utils/tensor.js */ + "./src/utils/tensor.js" + ); + var _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../utils/maths.js */ + "./src/utils/maths.js" + ); + class LogitsProcessor extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { + /** + * Apply the processor to the input logits. + * + * @abstract + * @param {bigint[][]} input_ids The input ids. + * @param {Tensor} logits The logits to process. + * @throws {Error} Throws an error if `_call` is not implemented in the subclass. + */ + _call(input_ids, logits) { + throw Error("`_call` should be implemented in a subclass"); + } + } + class LogitsWarper extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { + /** + * Apply the processor to the input logits. + * + * @abstract + * @param {bigint[][]} input_ids The input ids. + * @param {Tensor} logits The logits to process. + * @throws {Error} Throws an error if `_call` is not implemented in the subclass. + */ + _call(input_ids, logits) { + throw Error("`_call` should be implemented in a subclass"); + } + } + class LogitsProcessorList extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { + /** + * Constructs a new instance of `LogitsProcessorList`. + */ + constructor() { + super(); + this.processors = []; + } + /** + * Adds a new logits processor to the list. + * + * @param {LogitsProcessor} item The logits processor function to add. + */ + push(item) { + this.processors.push(item); + } + /** + * Adds multiple logits processors to the list. + * + * @param {LogitsProcessor[]} items The logits processor functions to add. + */ + extend(items) { + this.processors.push(...items); + } + /** + * Applies all logits processors in the list to a batch of logits, modifying them in-place. + * + * @param {bigint[][]} input_ids The input IDs for the language model. + * @param {Tensor} logits + */ + _call(input_ids, logits) { + let toReturn = logits; + for (const processor of this.processors) { + toReturn = processor(input_ids, toReturn); + } + return toReturn; + } + [Symbol.iterator]() { + return this.processors.values(); + } + } + class ForcedBOSTokenLogitsProcessor extends LogitsProcessor { + /** + * Create a ForcedBOSTokenLogitsProcessor. + * @param {number} bos_token_id The ID of the beginning-of-sequence token to be forced. + */ + constructor(bos_token_id) { + super(); + this.bos_token_id = bos_token_id; + } + /** + * Apply the BOS token forcing to the logits. + * @param {bigint[][]} input_ids The input IDs. + * @param {Tensor} logits The logits. + * @returns {Tensor} The logits with BOS token forcing. + */ + _call(input_ids, logits) { + for (let i = 0; i < input_ids.length; ++i) { + if (input_ids[i].length === 1) { + const batch_logits_data = ( + /** @type {Float32Array} */ + logits[i].data + ); + batch_logits_data.fill(-Infinity); + batch_logits_data[this.bos_token_id] = 0; + } + } + return logits; + } + } + class ForcedEOSTokenLogitsProcessor extends LogitsProcessor { + /** + * Create a ForcedEOSTokenLogitsProcessor. + * @param {number} max_length The maximum length of the sequence to be generated. + * @param {number|number[]} eos_token_id The id(s) of the *end-of-sequence* token. + */ + constructor(max_length, eos_token_id) { + super(); + this.max_length = max_length; + this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; + } + /** + * Apply the processor to input_ids and logits. + * + * @param {bigint[][]} input_ids The input ids. + * @param {Tensor} logits The logits tensor. + */ + _call(input_ids, logits) { + for (let i = 0; i < input_ids.length; ++i) { + if (input_ids[i].length === this.max_length - 1) { + const batch_logits_data = ( + /** @type {Float32Array} */ + logits[i].data + ); + batch_logits_data.fill(-Infinity); + for (const eos_token of this.eos_token_id) { + batch_logits_data[eos_token] = 0; + } + } + } + return logits; + } + } + class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor { + /** + * Create a SuppressTokensAtBeginLogitsProcessor. + * @param {number[]} begin_suppress_tokens The IDs of the tokens to suppress. + * @param {number} begin_index The number of tokens to generate before suppressing tokens. + */ + constructor(begin_suppress_tokens, begin_index) { + super(); + this.begin_suppress_tokens = begin_suppress_tokens; + this.begin_index = begin_index; + } + /** + * Apply the BOS token forcing to the logits. + * @param {bigint[][]} input_ids The input IDs. + * @param {Tensor} logits The logits. + * @returns {Tensor} The logits with BOS token forcing. + */ + _call(input_ids, logits) { + for (let i = 0; i < input_ids.length; ++i) { + if (input_ids[i].length === this.begin_index) { + const batch_logits_data = ( + /** @type {Float32Array} */ + logits[i].data + ); + for (const token_id of this.begin_suppress_tokens) { + batch_logits_data[token_id] = -Infinity; + } + } + } + return logits; + } + } + class WhisperTimeStampLogitsProcessor extends LogitsProcessor { + /** + * Constructs a new WhisperTimeStampLogitsProcessor. + * @param {import('../models/whisper/generation_whisper.js').WhisperGenerationConfig} generate_config The config object passed to the `generate()` method of a transformer model. + * @param {number[]} init_tokens The initial tokens of the input sequence. + */ + constructor(generate_config, init_tokens) { + super(); + this.eos_token_id = Array.isArray(generate_config.eos_token_id) ? generate_config.eos_token_id[0] : generate_config.eos_token_id; + this.no_timestamps_token_id = generate_config.no_timestamps_token_id; + this.timestamp_begin = this.no_timestamps_token_id + 1; + this.begin_index = init_tokens.length; + if (init_tokens.at(-1) === this.no_timestamps_token_id) { + this.begin_index -= 1; + } + this.max_initial_timestamp_index = generate_config.max_initial_timestamp_index; + } + /** + * Modify the logits to handle timestamp tokens. + * @param {bigint[][]} input_ids The input sequence of tokens. + * @param {Tensor} logits The logits output by the model. + * @returns {Tensor} The modified logits. + */ + _call(input_ids, logits) { + for (let i = 0; i < input_ids.length; ++i) { + const batch_logits_data = ( + /** @type {Float32Array} */ + logits[i].data + ); + batch_logits_data[this.no_timestamps_token_id] = -Infinity; + if (input_ids[i].length === this.begin_index - 1) { + batch_logits_data.fill(-Infinity); + batch_logits_data[this.timestamp_begin] = 0; + continue; + } + const seq = input_ids[i].slice(this.begin_index); + const last_was_timestamp = seq.length >= 1 && seq[seq.length - 1] >= this.timestamp_begin; + const penultimate_was_timestamp = seq.length < 2 || seq[seq.length - 2] >= this.timestamp_begin; + if (last_was_timestamp) { + if (penultimate_was_timestamp) { + batch_logits_data.subarray(this.timestamp_begin).fill(-Infinity); + } else { + batch_logits_data.subarray(0, this.eos_token_id).fill(-Infinity); + } + } + if (input_ids[i].length === this.begin_index && this.max_initial_timestamp_index !== null) { + const last_allowed = this.timestamp_begin + this.max_initial_timestamp_index; + batch_logits_data.subarray(last_allowed + 1).fill(-Infinity); + } + const logprobs = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.log_softmax)(batch_logits_data); + const timestamp_logprob = Math.log(logprobs.subarray(this.timestamp_begin).map(Math.exp).reduce((a, b) => a + b)); + const max_text_token_logprob = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(logprobs.subarray(0, this.timestamp_begin))[0]; + if (timestamp_logprob > max_text_token_logprob) { + batch_logits_data.subarray(0, this.timestamp_begin).fill(-Infinity); + } + } + return logits; + } + } + class NoRepeatNGramLogitsProcessor extends LogitsProcessor { + /** + * Create a NoRepeatNGramLogitsProcessor. + * @param {number} no_repeat_ngram_size The no-repeat-ngram size. All ngrams of this size can only occur once. + */ + constructor(no_repeat_ngram_size) { + super(); + this.no_repeat_ngram_size = no_repeat_ngram_size; + } + /** + * Generate n-grams from a sequence of token ids. + * @param {bigint[]} prevInputIds List of previous input ids + * @returns {Map} Map of generated n-grams + */ + getNgrams(prevInputIds) { + const curLen = prevInputIds.length; + const ngrams = []; + for (let j = 0; j < curLen + 1 - this.no_repeat_ngram_size; ++j) { + const ngram = []; + for (let k2 = 0; k2 < this.no_repeat_ngram_size; ++k2) { + ngram.push(prevInputIds[j + k2]); + } + ngrams.push(ngram.map(Number)); + } + const generatedNgram = /* @__PURE__ */ new Map(); + for (const ngram of ngrams) { + const prevNgram = ngram.slice(0, ngram.length - 1); + const prevNgramKey = JSON.stringify(prevNgram); + const prevNgramValue = generatedNgram.get(prevNgramKey) ?? []; + prevNgramValue.push(ngram[ngram.length - 1]); + generatedNgram.set(prevNgramKey, prevNgramValue); + } + return generatedNgram; + } + /** + * Generate n-grams from a sequence of token ids. + * @param {Map} bannedNgrams Map of banned n-grams + * @param {bigint[]} prevInputIds List of previous input ids + * @returns {number[]} Map of generated n-grams + */ + getGeneratedNgrams(bannedNgrams, prevInputIds) { + const ngramIdx = prevInputIds.slice(prevInputIds.length + 1 - this.no_repeat_ngram_size, prevInputIds.length); + const banned = bannedNgrams.get(JSON.stringify(ngramIdx.map(Number))) ?? []; + return banned; + } + /** + * Calculate banned n-gram tokens + * @param {bigint[]} prevInputIds List of previous input ids + * @returns {number[]} Map of generated n-grams + */ + calcBannedNgramTokens(prevInputIds) { + const bannedTokens = []; + if (prevInputIds.length + 1 < this.no_repeat_ngram_size) { + return bannedTokens; + } else { + const generatedNgrams = this.getNgrams(prevInputIds); + const bannedTokens2 = this.getGeneratedNgrams(generatedNgrams, prevInputIds); + return bannedTokens2; + } + } + /** + * Apply the no-repeat-ngram processor to the logits. + * @param {bigint[][]} input_ids The input IDs. + * @param {Tensor} logits The logits. + * @returns {Tensor} The logits with no-repeat-ngram processing. + */ + _call(input_ids, logits) { + for (let i = 0; i < input_ids.length; ++i) { + const batch_logits_data = ( + /** @type {Float32Array} */ + logits[i].data + ); + const bannedTokens = this.calcBannedNgramTokens(input_ids[i]); + for (const token of bannedTokens) { + batch_logits_data[token] = -Infinity; + } + } + return logits; + } + } + class RepetitionPenaltyLogitsProcessor extends LogitsProcessor { + /** + * Create a RepetitionPenaltyLogitsProcessor. + * @param {number} penalty The parameter for repetition penalty. + * - 1.0 means no penalty. Above 1.0 penalizes previously generated tokens. + * - Between 0.0 and 1.0 rewards previously generated tokens. + */ + constructor(penalty) { + super(); + this.penalty = penalty; + } + /** + * Apply the repetition penalty to the logits. + * @param {bigint[][]} input_ids The input IDs. + * @param {Tensor} logits The logits. + * @returns {Tensor} The logits with repetition penalty processing. + */ + _call(input_ids, logits) { + for (let i = 0; i < input_ids.length; ++i) { + const batch_logits_data = ( + /** @type {Float32Array} */ + logits[i].data + ); + for (const input_id of new Set(input_ids[i])) { + const token = Number(input_id); + if (batch_logits_data[token] < 0) { + batch_logits_data[token] *= this.penalty; + } else { + batch_logits_data[token] /= this.penalty; + } + } + } + return logits; + } + } + class MinLengthLogitsProcessor extends LogitsProcessor { + /** + * Create a MinLengthLogitsProcessor. + * @param {number} min_length The minimum length below which the score of `eos_token_id` is set to negative infinity. + * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token. + */ + constructor(min_length, eos_token_id) { + super(); + this.min_length = min_length; + this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; + } + /** + * Apply logit processor. + * @param {bigint[][]} input_ids The input IDs. + * @param {Tensor} logits The logits. + * @returns {Tensor} The processed logits. + */ + _call(input_ids, logits) { + for (let i = 0; i < input_ids.length; ++i) { + if (input_ids[i].length < this.min_length) { + const batch_logits_data = ( + /** @type {Float32Array} */ + logits[i].data + ); + for (const eos_token of this.eos_token_id) { + batch_logits_data[eos_token] = -Infinity; + } + } + } + return logits; + } + } + class MinNewTokensLengthLogitsProcessor extends LogitsProcessor { + /** + * Create a MinNewTokensLengthLogitsProcessor. + * @param {number} prompt_length_to_skip The input tokens length. + * @param {number} min_new_tokens The minimum *new* tokens length below which the score of `eos_token_id` is set to negative infinity. + * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token. + */ + constructor(prompt_length_to_skip, min_new_tokens, eos_token_id) { + super(); + this.prompt_length_to_skip = prompt_length_to_skip; + this.min_new_tokens = min_new_tokens; + this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; + } + /** + * Apply logit processor. + * @param {bigint[][]} input_ids The input IDs. + * @param {Tensor} logits The logits. + * @returns {Tensor} The processed logits. + */ + _call(input_ids, logits) { + for (let i = 0; i < input_ids.length; ++i) { + const new_tokens_length = input_ids[i].length - this.prompt_length_to_skip; + if (new_tokens_length < this.min_new_tokens) { + const batch_logits_data = ( + /** @type {Float32Array} */ + logits[i].data + ); + for (const eos_token of this.eos_token_id) { + batch_logits_data[eos_token] = -Infinity; + } + } + } + return logits; + } + } + class NoBadWordsLogitsProcessor extends LogitsProcessor { + /** + * Create a `NoBadWordsLogitsProcessor`. + * @param {number[][]} bad_words_ids List of list of token ids that are not allowed to be generated. + * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens. + */ + constructor(bad_words_ids, eos_token_id) { + super(); + this.bad_words_ids = bad_words_ids; + this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; + } + /** + * Apply logit processor. + * @param {bigint[][]} input_ids The input IDs. + * @param {Tensor} logits The logits. + * @returns {Tensor} The processed logits. + */ + _call(input_ids, logits) { + for (let i = 0; i < input_ids.length; ++i) { + const batch_logits_data = ( + /** @type {Float32Array} */ + logits[i].data + ); + const ids = input_ids[i]; + for (const bad_word_ids of this.bad_words_ids) { + if (ids.length < bad_word_ids.length - 1) continue; + let mark = true; + for (let j = 1; j <= bad_word_ids.length - 1; ++j) { + if (bad_word_ids.at(-j - 1) != ids.at(-j)) { + mark = false; + break; + } + } + if (mark) { + batch_logits_data[bad_word_ids.at(-1)] = -Infinity; + } + } + } + return logits; + } + } + class ClassifierFreeGuidanceLogitsProcessor extends LogitsProcessor { + /** + * Create a `ClassifierFreeGuidanceLogitsProcessor`. + * @param {number} guidance_scale The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`. + * Higher guidance scale encourages the model to generate samples that are more closely linked to the input + * prompt, usually at the expense of poorer quality. + */ + constructor(guidance_scale) { + super(); + if (guidance_scale <= 1) { + throw new Error( + `Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${guidance_scale}.` + ); + } + this.guidance_scale = guidance_scale; + } + /** + * Apply logit processor. + * @param {bigint[][]} input_ids The input IDs. + * @param {Tensor} logits The logits. + * @returns {Tensor} The processed logits. + */ + _call(input_ids, logits) { + if (logits.dims[0] !== 2 * input_ids.length) { + throw new Error( + `Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${logits.dims[0]} for the logits and ${input_ids.length} for the input ids.` + ); + } + const unguided_bsz = input_ids.length; + const cond_logits = logits.slice([0, unguided_bsz], null); + const uncond_logits = logits.slice([unguided_bsz, logits.dims[0]], null); + for (let i = 0; i < uncond_logits.data.length; ++i) { + uncond_logits.data[i] += (cond_logits.data[i] - uncond_logits.data[i]) * this.guidance_scale; + } + return uncond_logits; + } + } + class TemperatureLogitsWarper extends LogitsWarper { + /** + * Create a `TemperatureLogitsWarper`. + * @param {number} temperature Strictly positive float value used to modulate the logits distribution. + * A value smaller than `1` decreases randomness (and vice versa), with `0` being equivalent to shifting + * all probability mass to the most likely token. + */ + constructor(temperature) { + super(); + if (typeof temperature !== "number" || temperature <= 0) { + let errorMessage = `\`temperature\` (=${temperature}) must be a strictly positive float, otherwise your next token scores will be invalid.`; + if (temperature === 0) { + errorMessage += " If you're looking for greedy decoding strategies, set `do_sample=false`."; + } + } + this.temperature = temperature; + } + /** + * Apply logit warper. + * @param {bigint[][]} input_ids The input IDs. + * @param {Tensor} logits The logits. + * @returns {Tensor} The processed logits. + */ + _call(input_ids, logits) { + const batch_logits_data = ( + /** @type {Float32Array} */ + logits.data + ); + for (let i = 0; i < batch_logits_data.length; ++i) { + batch_logits_data[i] /= this.temperature; + } + return logits; + } + } + class TopPLogitsWarper extends LogitsWarper { + /** + * Create a `TopPLogitsWarper`. + * @param {number} top_p If set to < 1, only the smallest set of most probable tokens with + * probabilities that add up to `top_p` or higher are kept for generation. + * @param {Object} options Additional options for the top-p sampling. + * @param {number} [options.filter_value=-Infinity] All filtered values will be set to this float value. + * @param {number} [options.min_tokens_to_keep=1] Minimum number of tokens that cannot be filtered. + */ + constructor(top_p, { + filter_value = -Infinity, + min_tokens_to_keep = 1 + } = {}) { + super(); + if (top_p < 0 || top_p > 1) { + throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${top_p}`); + } + if (!Number.isInteger(min_tokens_to_keep) || min_tokens_to_keep < 1) { + throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${min_tokens_to_keep}`); + } + this.top_p = top_p; + this.filter_value = filter_value; + this.min_tokens_to_keep = min_tokens_to_keep; + } + } + class TopKLogitsWarper extends LogitsWarper { + /** + * Create a `TopKLogitsWarper`. + * @param {number} top_k If set to > 0, only the top `top_k` tokens are kept for generation. + * @param {Object} options Additional options for the top-k sampling. + * @param {number} [options.filter_value=-Infinity] All filtered values will be set to this float value. + * @param {number} [options.min_tokens_to_keep=1] Minimum number of tokens that cannot be filtered. + */ + constructor(top_k, { + filter_value = -Infinity, + min_tokens_to_keep = 1 + } = {}) { + super(); + if (!Number.isInteger(top_k) || top_k < 0) { + throw new Error(`\`top_k\` must be a positive integer, but is ${top_k}`); + } + this.top_k = Math.max(top_k, min_tokens_to_keep); + this.filter_value = filter_value; + } + } + }) + ), + /***/ + "./src/generation/logits_sampler.js": ( + /*!******************************************!*\ + !*** ./src/generation/logits_sampler.js ***! + \******************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + LogitsSampler: () => ( + /* binding */ + LogitsSampler + ) + /* harmony export */ + }); + var _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../utils/generic.js */ + "./src/utils/generic.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../utils/tensor.js */ + "./src/utils/tensor.js" + ); + var _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../utils/maths.js */ + "./src/utils/maths.js" + ); + var _generation_configuration_utils_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! ../generation/configuration_utils.js */ + "./src/generation/configuration_utils.js" + ); + class LogitsSampler extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { + /** + * Creates a new Sampler object with the specified generation config. + * @param {GenerationConfig} generation_config The generation config. + */ + constructor(generation_config) { + super(); + this.generation_config = generation_config; + } + /** + * Executes the sampler, using the specified logits. + * @param {Tensor} logits + * @returns {Promise<[bigint, number][]>} + */ + async _call(logits) { + return this.sample(logits); + } + /** + * Abstract method for sampling the logits. + * @param {Tensor} logits + * @throws {Error} If not implemented in subclass. + * @returns {Promise<[bigint, number][]>} + */ + async sample(logits) { + throw Error("sample should be implemented in subclasses."); + } + /** + * Returns the specified logits as an array, with temperature applied. + * @param {Tensor} logits + * @param {number} index + * @returns {Float32Array} + */ + getLogits(logits, index) { + let vocabSize = logits.dims.at(-1); + let logs = ( + /** @type {Float32Array} */ + logits.data + ); + if (index === -1) { + logs = logs.slice(-vocabSize); + } else { + let startIndex = index * vocabSize; + logs = logs.slice(startIndex, startIndex + vocabSize); + } + return logs; + } + /** + * Selects an item randomly based on the specified probabilities. + * @param {import("../transformers.js").DataArray} probabilities An array of probabilities to use for selection. + * @returns {number} The index of the selected item. + */ + randomSelect(probabilities) { + let sumProbabilities = 0; + for (let i = 0; i < probabilities.length; ++i) { + sumProbabilities += probabilities[i]; + } + let r = Math.random() * sumProbabilities; + for (let i = 0; i < probabilities.length; ++i) { + r -= probabilities[i]; + if (r <= 0) { + return i; + } + } + return 0; + } + /** + * Returns a Sampler object based on the specified options. + * @param {GenerationConfig} generation_config An object containing options for the sampler. + * @returns {LogitsSampler} A Sampler object. + */ + static getSampler(generation_config) { + if (generation_config.do_sample) { + return new MultinomialSampler(generation_config); + } else if (generation_config.num_beams > 1) { + return new BeamSearchSampler(generation_config); + } else { + if (generation_config.num_return_sequences > 1) { + throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${generation_config.num_return_sequences}.`); + } + return new GreedySampler(generation_config); + } + } + } + class GreedySampler extends LogitsSampler { + /** + * Sample the maximum probability of a given logits tensor. + * @param {Tensor} logits + * @returns {Promise<[bigint, number][]>} An array with a single tuple, containing the index of the maximum value and a meaningless score (since this is a greedy search). + */ + async sample(logits) { + const argmax = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(logits.data)[1]; + return [ + [BigInt(argmax), 0] + ]; + } + } + class MultinomialSampler extends LogitsSampler { + /** + * Sample from the logits. + * @param {Tensor} logits + * @returns {Promise<[bigint, number][]>} + */ + async sample(logits) { + let k2 = logits.dims.at(-1); + if (this.generation_config.top_k > 0) { + k2 = Math.min(this.generation_config.top_k, k2); + } + const [v, i] = await (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.topk)(logits, k2); + const probabilities = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.softmax)( + /** @type {Float32Array} */ + v.data + ); + return Array.from({ length: this.generation_config.num_beams }, () => { + const sampledIndex = this.randomSelect(probabilities); + return [ + i.data[sampledIndex], + // token id + Math.log(probabilities[sampledIndex]) + // score + ]; + }); + } + } + class BeamSearchSampler extends LogitsSampler { + /** + * Sample from the logits. + * @param {Tensor} logits + * @returns {Promise<[bigint, number][]>} + */ + async sample(logits) { + let k2 = logits.dims.at(-1); + if (this.generation_config.top_k > 0) { + k2 = Math.min(this.generation_config.top_k, k2); + } + const [v, i] = await (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.topk)(logits, k2); + const probabilities = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.softmax)( + /** @type {Float32Array} */ + v.data + ); + return Array.from({ length: this.generation_config.num_beams }, (_, x) => { + return [ + i.data[x], + // token id + Math.log(probabilities[x]) + // score + ]; + }); + } + } + }) + ), + /***/ + "./src/generation/stopping_criteria.js": ( + /*!*********************************************!*\ + !*** ./src/generation/stopping_criteria.js ***! + \*********************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + EosTokenCriteria: () => ( + /* binding */ + EosTokenCriteria + ), + /* harmony export */ + InterruptableStoppingCriteria: () => ( + /* binding */ + InterruptableStoppingCriteria + ), + /* harmony export */ + MaxLengthCriteria: () => ( + /* binding */ + MaxLengthCriteria + ), + /* harmony export */ + StoppingCriteria: () => ( + /* binding */ + StoppingCriteria + ), + /* harmony export */ + StoppingCriteriaList: () => ( + /* binding */ + StoppingCriteriaList + ) + /* harmony export */ + }); + var _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../utils/generic.js */ + "./src/utils/generic.js" + ); + class StoppingCriteria extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { + /** + * + * @param {number[][]} input_ids (`number[][]` of shape `(batch_size, sequence_length)`): + * Indices of input sequence tokens in the vocabulary. + * @param {number[][]} scores scores (`number[][]` of shape `(batch_size, config.vocab_size)`): + * Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax + * or scores for each vocabulary token after SoftMax. + * @returns {boolean[]} A list of booleans indicating whether each sequence should be stopped. + */ + _call(input_ids, scores) { + throw Error("StoppingCriteria needs to be subclassed"); + } + } + class StoppingCriteriaList extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { + /** + * Constructs a new instance of `StoppingCriteriaList`. + */ + constructor() { + super(); + this.criteria = []; + } + /** + * Adds a new stopping criterion to the list. + * + * @param {StoppingCriteria} item The stopping criterion to add. + */ + push(item) { + this.criteria.push(item); + } + /** + * Adds multiple stopping criteria to the list. + * + * @param {StoppingCriteria|StoppingCriteriaList|StoppingCriteria[]} items The stopping criteria to add. + */ + extend(items) { + if (items instanceof StoppingCriteriaList) { + items = items.criteria; + } else if (items instanceof StoppingCriteria) { + items = [items]; + } + this.criteria.push(...items); + } + _call(input_ids, scores) { + const is_done = new Array(input_ids.length).fill(false); + for (const criterion of this.criteria) { + const criterion_done = criterion(input_ids, scores); + for (let i = 0; i < is_done.length; ++i) { + is_done[i] ||= criterion_done[i]; + } + } + return is_done; + } + [Symbol.iterator]() { + return this.criteria.values(); + } + } + class MaxLengthCriteria extends StoppingCriteria { + /** + * + * @param {number} max_length The maximum length that the output sequence can have in number of tokens. + * @param {number} [max_position_embeddings=null] The maximum model length, as defined by the model's `config.max_position_embeddings` attribute. + */ + constructor(max_length, max_position_embeddings = null) { + super(); + this.max_length = max_length; + this.max_position_embeddings = max_position_embeddings; + } + _call(input_ids) { + return input_ids.map((ids) => ids.length >= this.max_length); + } + } + class EosTokenCriteria extends StoppingCriteria { + /** + * + * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. + * Optionally, use a list to set multiple *end-of-sequence* tokens. + */ + constructor(eos_token_id) { + super(); + if (!Array.isArray(eos_token_id)) { + eos_token_id = [eos_token_id]; + } + this.eos_token_id = eos_token_id; + } + /** + * + * @param {number[][]} input_ids + * @param {number[][]} scores + * @returns {boolean[]} + */ + _call(input_ids, scores) { + return input_ids.map((ids) => { + const last = ids.at(-1); + return this.eos_token_id.some((eos_id) => last == eos_id); + }); + } + } + class InterruptableStoppingCriteria extends StoppingCriteria { + constructor() { + super(); + this.interrupted = false; + } + interrupt() { + this.interrupted = true; + } + reset() { + this.interrupted = false; + } + _call(input_ids, scores) { + return new Array(input_ids.length).fill(this.interrupted); + } + } + }) + ), + /***/ + "./src/generation/streamers.js": ( + /*!*************************************!*\ + !*** ./src/generation/streamers.js ***! + \*************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + BaseStreamer: () => ( + /* binding */ + BaseStreamer + ), + /* harmony export */ + TextStreamer: () => ( + /* binding */ + TextStreamer + ), + /* harmony export */ + WhisperTextStreamer: () => ( + /* binding */ + WhisperTextStreamer + ) + /* harmony export */ + }); + var _utils_core_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../utils/core.js */ + "./src/utils/core.js" + ); + var _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../tokenizers.js */ + "./src/tokenizers.js" + ); + var _env_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../env.js */ + "./src/env.js" + ); + class BaseStreamer { + /** + * Function that is called by `.generate()` to push new tokens + * @param {bigint[][]} value + */ + put(value) { + throw Error("Not implemented"); + } + /** + * Function that is called by `.generate()` to signal the end of generation + */ + end() { + throw Error("Not implemented"); + } + } + const stdout_write = _env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_PROCESS_AVAILABLE ? (x) => process.stdout.write(x) : (x) => console.log(x); + class TextStreamer extends BaseStreamer { + /** + * + * @param {import('../tokenizers.js').PreTrainedTokenizer} tokenizer + * @param {Object} options + * @param {boolean} [options.skip_prompt=false] Whether to skip the prompt tokens + * @param {boolean} [options.skip_special_tokens=true] Whether to skip special tokens when decoding + * @param {function(string): void} [options.callback_function=null] Function to call when a piece of text is ready to display + * @param {function(bigint[]): void} [options.token_callback_function=null] Function to call when a new token is generated + * @param {Object} [options.decode_kwargs={}] Additional keyword arguments to pass to the tokenizer's decode method + */ + constructor(tokenizer, { + skip_prompt = false, + callback_function = null, + token_callback_function = null, + skip_special_tokens = true, + decode_kwargs = {}, + ...kwargs + } = {}) { + super(); + this.tokenizer = tokenizer; + this.skip_prompt = skip_prompt; + this.callback_function = callback_function ?? stdout_write; + this.token_callback_function = token_callback_function; + this.decode_kwargs = { skip_special_tokens, ...decode_kwargs, ...kwargs }; + this.token_cache = []; + this.print_len = 0; + this.next_tokens_are_prompt = true; + } + /** + * Receives tokens, decodes them, and prints them to stdout as soon as they form entire words. + * @param {bigint[][]} value + */ + put(value) { + if (value.length > 1) { + throw Error("TextStreamer only supports batch size of 1"); + } + const is_prompt = this.next_tokens_are_prompt; + if (is_prompt) { + this.next_tokens_are_prompt = false; + if (this.skip_prompt) return; + } + const tokens = value[0]; + this.token_callback_function?.(tokens); + this.token_cache = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_0__.mergeArrays)(this.token_cache, tokens); + const text = this.tokenizer.decode(this.token_cache, this.decode_kwargs); + let printable_text; + if (is_prompt || text.endsWith("\n")) { + printable_text = text.slice(this.print_len); + this.token_cache = []; + this.print_len = 0; + } else if (text.length > 0 && (0, _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__.is_chinese_char)(text.charCodeAt(text.length - 1))) { + printable_text = text.slice(this.print_len); + this.print_len += printable_text.length; + } else { + printable_text = text.slice(this.print_len, text.lastIndexOf(" ") + 1); + this.print_len += printable_text.length; + } + this.on_finalized_text(printable_text, false); + } + /** + * Flushes any remaining cache and prints a newline to stdout. + */ + end() { + let printable_text; + if (this.token_cache.length > 0) { + const text = this.tokenizer.decode(this.token_cache, this.decode_kwargs); + printable_text = text.slice(this.print_len); + this.token_cache = []; + this.print_len = 0; + } else { + printable_text = ""; + } + this.next_tokens_are_prompt = true; + this.on_finalized_text(printable_text, true); + } + /** + * Prints the new text to stdout. If the stream is ending, also prints a newline. + * @param {string} text + * @param {boolean} stream_end + */ + on_finalized_text(text, stream_end) { + if (text.length > 0) { + this.callback_function?.(text); + } + if (stream_end && this.callback_function === stdout_write && _env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_PROCESS_AVAILABLE) { + this.callback_function?.("\n"); + } + } + } + class WhisperTextStreamer extends TextStreamer { + /** + * @param {import('../tokenizers.js').WhisperTokenizer} tokenizer + * @param {Object} options + * @param {boolean} [options.skip_prompt=false] Whether to skip the prompt tokens + * @param {function(string): void} [options.callback_function=null] Function to call when a piece of text is ready to display + * @param {function(bigint[]): void} [options.token_callback_function=null] Function to call when a new token is generated + * @param {function(number): void} [options.on_chunk_start=null] Function to call when a new chunk starts + * @param {function(number): void} [options.on_chunk_end=null] Function to call when a chunk ends + * @param {function(): void} [options.on_finalize=null] Function to call when the stream is finalized + * @param {number} [options.time_precision=0.02] Precision of the timestamps + * @param {boolean} [options.skip_special_tokens=true] Whether to skip special tokens when decoding + * @param {Object} [options.decode_kwargs={}] Additional keyword arguments to pass to the tokenizer's decode method + */ + constructor(tokenizer, { + skip_prompt = false, + callback_function = null, + token_callback_function = null, + on_chunk_start = null, + on_chunk_end = null, + on_finalize = null, + time_precision = 0.02, + skip_special_tokens = true, + decode_kwargs = {} + } = {}) { + super(tokenizer, { + skip_prompt, + skip_special_tokens, + callback_function, + token_callback_function, + decode_kwargs + }); + this.timestamp_begin = tokenizer.timestamp_begin; + this.on_chunk_start = on_chunk_start; + this.on_chunk_end = on_chunk_end; + this.on_finalize = on_finalize; + this.time_precision = time_precision; + this.waiting_for_timestamp = false; + } + /** + * @param {bigint[][]} value + */ + put(value) { + if (value.length > 1) { + throw Error("WhisperTextStreamer only supports batch size of 1"); + } + const tokens = value[0]; + if (tokens.length === 1) { + const offset = Number(tokens[0]) - this.timestamp_begin; + if (offset >= 0) { + const time = offset * this.time_precision; + if (this.waiting_for_timestamp) { + this.on_chunk_end?.(time); + } else { + this.on_chunk_start?.(time); + } + this.waiting_for_timestamp = !this.waiting_for_timestamp; + this.token_callback_function?.(tokens); + return; + } + } + return super.put(value); + } + end() { + super.end(); + this.on_finalize?.(); + } + } + }) + ), + /***/ + "./src/models.js": ( + /*!***********************!*\ + !*** ./src/models.js ***! + \***********************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + ASTForAudioClassification: () => ( + /* binding */ + ASTForAudioClassification + ), + /* harmony export */ + ASTModel: () => ( + /* binding */ + ASTModel + ), + /* harmony export */ + ASTPreTrainedModel: () => ( + /* binding */ + ASTPreTrainedModel + ), + /* harmony export */ + AlbertForMaskedLM: () => ( + /* binding */ + AlbertForMaskedLM + ), + /* harmony export */ + AlbertForQuestionAnswering: () => ( + /* binding */ + AlbertForQuestionAnswering + ), + /* harmony export */ + AlbertForSequenceClassification: () => ( + /* binding */ + AlbertForSequenceClassification + ), + /* harmony export */ + AlbertModel: () => ( + /* binding */ + AlbertModel + ), + /* harmony export */ + AlbertPreTrainedModel: () => ( + /* binding */ + AlbertPreTrainedModel + ), + /* harmony export */ + ArceeForCausalLM: () => ( + /* binding */ + ArceeForCausalLM + ), + /* harmony export */ + ArceeModel: () => ( + /* binding */ + ArceeModel + ), + /* harmony export */ + ArceePreTrainedModel: () => ( + /* binding */ + ArceePreTrainedModel + ), + /* harmony export */ + AutoModel: () => ( + /* binding */ + AutoModel + ), + /* harmony export */ + AutoModelForAudioClassification: () => ( + /* binding */ + AutoModelForAudioClassification + ), + /* harmony export */ + AutoModelForAudioFrameClassification: () => ( + /* binding */ + AutoModelForAudioFrameClassification + ), + /* harmony export */ + AutoModelForAudioTextToText: () => ( + /* binding */ + AutoModelForAudioTextToText + ), + /* harmony export */ + AutoModelForCTC: () => ( + /* binding */ + AutoModelForCTC + ), + /* harmony export */ + AutoModelForCausalLM: () => ( + /* binding */ + AutoModelForCausalLM + ), + /* harmony export */ + AutoModelForDepthEstimation: () => ( + /* binding */ + AutoModelForDepthEstimation + ), + /* harmony export */ + AutoModelForDocumentQuestionAnswering: () => ( + /* binding */ + AutoModelForDocumentQuestionAnswering + ), + /* harmony export */ + AutoModelForImageClassification: () => ( + /* binding */ + AutoModelForImageClassification + ), + /* harmony export */ + AutoModelForImageFeatureExtraction: () => ( + /* binding */ + AutoModelForImageFeatureExtraction + ), + /* harmony export */ + AutoModelForImageMatting: () => ( + /* binding */ + AutoModelForImageMatting + ), + /* harmony export */ + AutoModelForImageSegmentation: () => ( + /* binding */ + AutoModelForImageSegmentation + ), + /* harmony export */ + AutoModelForImageTextToText: () => ( + /* binding */ + AutoModelForImageTextToText + ), + /* harmony export */ + AutoModelForImageToImage: () => ( + /* binding */ + AutoModelForImageToImage + ), + /* harmony export */ + AutoModelForMaskGeneration: () => ( + /* binding */ + AutoModelForMaskGeneration + ), + /* harmony export */ + AutoModelForMaskedLM: () => ( + /* binding */ + AutoModelForMaskedLM + ), + /* harmony export */ + AutoModelForNormalEstimation: () => ( + /* binding */ + AutoModelForNormalEstimation + ), + /* harmony export */ + AutoModelForObjectDetection: () => ( + /* binding */ + AutoModelForObjectDetection + ), + /* harmony export */ + AutoModelForPoseEstimation: () => ( + /* binding */ + AutoModelForPoseEstimation + ), + /* harmony export */ + AutoModelForQuestionAnswering: () => ( + /* binding */ + AutoModelForQuestionAnswering + ), + /* harmony export */ + AutoModelForSemanticSegmentation: () => ( + /* binding */ + AutoModelForSemanticSegmentation + ), + /* harmony export */ + AutoModelForSeq2SeqLM: () => ( + /* binding */ + AutoModelForSeq2SeqLM + ), + /* harmony export */ + AutoModelForSequenceClassification: () => ( + /* binding */ + AutoModelForSequenceClassification + ), + /* harmony export */ + AutoModelForSpeechSeq2Seq: () => ( + /* binding */ + AutoModelForSpeechSeq2Seq + ), + /* harmony export */ + AutoModelForTextToSpectrogram: () => ( + /* binding */ + AutoModelForTextToSpectrogram + ), + /* harmony export */ + AutoModelForTextToWaveform: () => ( + /* binding */ + AutoModelForTextToWaveform + ), + /* harmony export */ + AutoModelForTokenClassification: () => ( + /* binding */ + AutoModelForTokenClassification + ), + /* harmony export */ + AutoModelForUniversalSegmentation: () => ( + /* binding */ + AutoModelForUniversalSegmentation + ), + /* harmony export */ + AutoModelForVision2Seq: () => ( + /* binding */ + AutoModelForVision2Seq + ), + /* harmony export */ + AutoModelForXVector: () => ( + /* binding */ + AutoModelForXVector + ), + /* harmony export */ + AutoModelForZeroShotObjectDetection: () => ( + /* binding */ + AutoModelForZeroShotObjectDetection + ), + /* harmony export */ + BartForConditionalGeneration: () => ( + /* binding */ + BartForConditionalGeneration + ), + /* harmony export */ + BartForSequenceClassification: () => ( + /* binding */ + BartForSequenceClassification + ), + /* harmony export */ + BartModel: () => ( + /* binding */ + BartModel + ), + /* harmony export */ + BartPretrainedModel: () => ( + /* binding */ + BartPretrainedModel + ), + /* harmony export */ + BaseModelOutput: () => ( + /* binding */ + BaseModelOutput + ), + /* harmony export */ + BeitForImageClassification: () => ( + /* binding */ + BeitForImageClassification + ), + /* harmony export */ + BeitModel: () => ( + /* binding */ + BeitModel + ), + /* harmony export */ + BeitPreTrainedModel: () => ( + /* binding */ + BeitPreTrainedModel + ), + /* harmony export */ + BertForMaskedLM: () => ( + /* binding */ + BertForMaskedLM + ), + /* harmony export */ + BertForQuestionAnswering: () => ( + /* binding */ + BertForQuestionAnswering + ), + /* harmony export */ + BertForSequenceClassification: () => ( + /* binding */ + BertForSequenceClassification + ), + /* harmony export */ + BertForTokenClassification: () => ( + /* binding */ + BertForTokenClassification + ), + /* harmony export */ + BertModel: () => ( + /* binding */ + BertModel + ), + /* harmony export */ + BertPreTrainedModel: () => ( + /* binding */ + BertPreTrainedModel + ), + /* harmony export */ + BlenderbotForConditionalGeneration: () => ( + /* binding */ + BlenderbotForConditionalGeneration + ), + /* harmony export */ + BlenderbotModel: () => ( + /* binding */ + BlenderbotModel + ), + /* harmony export */ + BlenderbotPreTrainedModel: () => ( + /* binding */ + BlenderbotPreTrainedModel + ), + /* harmony export */ + BlenderbotSmallForConditionalGeneration: () => ( + /* binding */ + BlenderbotSmallForConditionalGeneration + ), + /* harmony export */ + BlenderbotSmallModel: () => ( + /* binding */ + BlenderbotSmallModel + ), + /* harmony export */ + BlenderbotSmallPreTrainedModel: () => ( + /* binding */ + BlenderbotSmallPreTrainedModel + ), + /* harmony export */ + BloomForCausalLM: () => ( + /* binding */ + BloomForCausalLM + ), + /* harmony export */ + BloomModel: () => ( + /* binding */ + BloomModel + ), + /* harmony export */ + BloomPreTrainedModel: () => ( + /* binding */ + BloomPreTrainedModel + ), + /* harmony export */ + CLIPModel: () => ( + /* binding */ + CLIPModel + ), + /* harmony export */ + CLIPPreTrainedModel: () => ( + /* binding */ + CLIPPreTrainedModel + ), + /* harmony export */ + CLIPSegForImageSegmentation: () => ( + /* binding */ + CLIPSegForImageSegmentation + ), + /* harmony export */ + CLIPSegModel: () => ( + /* binding */ + CLIPSegModel + ), + /* harmony export */ + CLIPSegPreTrainedModel: () => ( + /* binding */ + CLIPSegPreTrainedModel + ), + /* harmony export */ + CLIPTextModel: () => ( + /* binding */ + CLIPTextModel + ), + /* harmony export */ + CLIPTextModelWithProjection: () => ( + /* binding */ + CLIPTextModelWithProjection + ), + /* harmony export */ + CLIPVisionModel: () => ( + /* binding */ + CLIPVisionModel + ), + /* harmony export */ + CLIPVisionModelWithProjection: () => ( + /* binding */ + CLIPVisionModelWithProjection + ), + /* harmony export */ + CamembertForMaskedLM: () => ( + /* binding */ + CamembertForMaskedLM + ), + /* harmony export */ + CamembertForQuestionAnswering: () => ( + /* binding */ + CamembertForQuestionAnswering + ), + /* harmony export */ + CamembertForSequenceClassification: () => ( + /* binding */ + CamembertForSequenceClassification + ), + /* harmony export */ + CamembertForTokenClassification: () => ( + /* binding */ + CamembertForTokenClassification + ), + /* harmony export */ + CamembertModel: () => ( + /* binding */ + CamembertModel + ), + /* harmony export */ + CamembertPreTrainedModel: () => ( + /* binding */ + CamembertPreTrainedModel + ), + /* harmony export */ + CausalLMOutput: () => ( + /* binding */ + CausalLMOutput + ), + /* harmony export */ + CausalLMOutputWithPast: () => ( + /* binding */ + CausalLMOutputWithPast + ), + /* harmony export */ + ChineseCLIPModel: () => ( + /* binding */ + ChineseCLIPModel + ), + /* harmony export */ + ChineseCLIPPreTrainedModel: () => ( + /* binding */ + ChineseCLIPPreTrainedModel + ), + /* harmony export */ + ClapAudioModelWithProjection: () => ( + /* binding */ + ClapAudioModelWithProjection + ), + /* harmony export */ + ClapModel: () => ( + /* binding */ + ClapModel + ), + /* harmony export */ + ClapPreTrainedModel: () => ( + /* binding */ + ClapPreTrainedModel + ), + /* harmony export */ + ClapTextModelWithProjection: () => ( + /* binding */ + ClapTextModelWithProjection + ), + /* harmony export */ + CodeGenForCausalLM: () => ( + /* binding */ + CodeGenForCausalLM + ), + /* harmony export */ + CodeGenModel: () => ( + /* binding */ + CodeGenModel + ), + /* harmony export */ + CodeGenPreTrainedModel: () => ( + /* binding */ + CodeGenPreTrainedModel + ), + /* harmony export */ + CohereForCausalLM: () => ( + /* binding */ + CohereForCausalLM + ), + /* harmony export */ + CohereModel: () => ( + /* binding */ + CohereModel + ), + /* harmony export */ + CoherePreTrainedModel: () => ( + /* binding */ + CoherePreTrainedModel + ), + /* harmony export */ + ConvBertForMaskedLM: () => ( + /* binding */ + ConvBertForMaskedLM + ), + /* harmony export */ + ConvBertForQuestionAnswering: () => ( + /* binding */ + ConvBertForQuestionAnswering + ), + /* harmony export */ + ConvBertForSequenceClassification: () => ( + /* binding */ + ConvBertForSequenceClassification + ), + /* harmony export */ + ConvBertForTokenClassification: () => ( + /* binding */ + ConvBertForTokenClassification + ), + /* harmony export */ + ConvBertModel: () => ( + /* binding */ + ConvBertModel + ), + /* harmony export */ + ConvBertPreTrainedModel: () => ( + /* binding */ + ConvBertPreTrainedModel + ), + /* harmony export */ + ConvNextForImageClassification: () => ( + /* binding */ + ConvNextForImageClassification + ), + /* harmony export */ + ConvNextModel: () => ( + /* binding */ + ConvNextModel + ), + /* harmony export */ + ConvNextPreTrainedModel: () => ( + /* binding */ + ConvNextPreTrainedModel + ), + /* harmony export */ + ConvNextV2ForImageClassification: () => ( + /* binding */ + ConvNextV2ForImageClassification + ), + /* harmony export */ + ConvNextV2Model: () => ( + /* binding */ + ConvNextV2Model + ), + /* harmony export */ + ConvNextV2PreTrainedModel: () => ( + /* binding */ + ConvNextV2PreTrainedModel + ), + /* harmony export */ + DFineForObjectDetection: () => ( + /* binding */ + DFineForObjectDetection + ), + /* harmony export */ + DFineModel: () => ( + /* binding */ + DFineModel + ), + /* harmony export */ + DFinePreTrainedModel: () => ( + /* binding */ + DFinePreTrainedModel + ), + /* harmony export */ + DINOv3ConvNextModel: () => ( + /* binding */ + DINOv3ConvNextModel + ), + /* harmony export */ + DINOv3ConvNextPreTrainedModel: () => ( + /* binding */ + DINOv3ConvNextPreTrainedModel + ), + /* harmony export */ + DINOv3ViTModel: () => ( + /* binding */ + DINOv3ViTModel + ), + /* harmony export */ + DINOv3ViTPreTrainedModel: () => ( + /* binding */ + DINOv3ViTPreTrainedModel + ), + /* harmony export */ + DPTForDepthEstimation: () => ( + /* binding */ + DPTForDepthEstimation + ), + /* harmony export */ + DPTModel: () => ( + /* binding */ + DPTModel + ), + /* harmony export */ + DPTPreTrainedModel: () => ( + /* binding */ + DPTPreTrainedModel + ), + /* harmony export */ + DacDecoderModel: () => ( + /* binding */ + DacDecoderModel + ), + /* harmony export */ + DacDecoderOutput: () => ( + /* binding */ + DacDecoderOutput + ), + /* harmony export */ + DacEncoderModel: () => ( + /* binding */ + DacEncoderModel + ), + /* harmony export */ + DacEncoderOutput: () => ( + /* binding */ + DacEncoderOutput + ), + /* harmony export */ + DacModel: () => ( + /* binding */ + DacModel + ), + /* harmony export */ + DacPreTrainedModel: () => ( + /* binding */ + DacPreTrainedModel + ), + /* harmony export */ + DebertaForMaskedLM: () => ( + /* binding */ + DebertaForMaskedLM + ), + /* harmony export */ + DebertaForQuestionAnswering: () => ( + /* binding */ + DebertaForQuestionAnswering + ), + /* harmony export */ + DebertaForSequenceClassification: () => ( + /* binding */ + DebertaForSequenceClassification + ), + /* harmony export */ + DebertaForTokenClassification: () => ( + /* binding */ + DebertaForTokenClassification + ), + /* harmony export */ + DebertaModel: () => ( + /* binding */ + DebertaModel + ), + /* harmony export */ + DebertaPreTrainedModel: () => ( + /* binding */ + DebertaPreTrainedModel + ), + /* harmony export */ + DebertaV2ForMaskedLM: () => ( + /* binding */ + DebertaV2ForMaskedLM + ), + /* harmony export */ + DebertaV2ForQuestionAnswering: () => ( + /* binding */ + DebertaV2ForQuestionAnswering + ), + /* harmony export */ + DebertaV2ForSequenceClassification: () => ( + /* binding */ + DebertaV2ForSequenceClassification + ), + /* harmony export */ + DebertaV2ForTokenClassification: () => ( + /* binding */ + DebertaV2ForTokenClassification + ), + /* harmony export */ + DebertaV2Model: () => ( + /* binding */ + DebertaV2Model + ), + /* harmony export */ + DebertaV2PreTrainedModel: () => ( + /* binding */ + DebertaV2PreTrainedModel + ), + /* harmony export */ + DecisionTransformerModel: () => ( + /* binding */ + DecisionTransformerModel + ), + /* harmony export */ + DecisionTransformerPreTrainedModel: () => ( + /* binding */ + DecisionTransformerPreTrainedModel + ), + /* harmony export */ + DeiTForImageClassification: () => ( + /* binding */ + DeiTForImageClassification + ), + /* harmony export */ + DeiTModel: () => ( + /* binding */ + DeiTModel + ), + /* harmony export */ + DeiTPreTrainedModel: () => ( + /* binding */ + DeiTPreTrainedModel + ), + /* harmony export */ + DepthAnythingForDepthEstimation: () => ( + /* binding */ + DepthAnythingForDepthEstimation + ), + /* harmony export */ + DepthAnythingPreTrainedModel: () => ( + /* binding */ + DepthAnythingPreTrainedModel + ), + /* harmony export */ + DepthProForDepthEstimation: () => ( + /* binding */ + DepthProForDepthEstimation + ), + /* harmony export */ + DepthProPreTrainedModel: () => ( + /* binding */ + DepthProPreTrainedModel + ), + /* harmony export */ + DetrForObjectDetection: () => ( + /* binding */ + DetrForObjectDetection + ), + /* harmony export */ + DetrForSegmentation: () => ( + /* binding */ + DetrForSegmentation + ), + /* harmony export */ + DetrModel: () => ( + /* binding */ + DetrModel + ), + /* harmony export */ + DetrObjectDetectionOutput: () => ( + /* binding */ + DetrObjectDetectionOutput + ), + /* harmony export */ + DetrPreTrainedModel: () => ( + /* binding */ + DetrPreTrainedModel + ), + /* harmony export */ + DetrSegmentationOutput: () => ( + /* binding */ + DetrSegmentationOutput + ), + /* harmony export */ + Dinov2ForImageClassification: () => ( + /* binding */ + Dinov2ForImageClassification + ), + /* harmony export */ + Dinov2Model: () => ( + /* binding */ + Dinov2Model + ), + /* harmony export */ + Dinov2PreTrainedModel: () => ( + /* binding */ + Dinov2PreTrainedModel + ), + /* harmony export */ + Dinov2WithRegistersForImageClassification: () => ( + /* binding */ + Dinov2WithRegistersForImageClassification + ), + /* harmony export */ + Dinov2WithRegistersModel: () => ( + /* binding */ + Dinov2WithRegistersModel + ), + /* harmony export */ + Dinov2WithRegistersPreTrainedModel: () => ( + /* binding */ + Dinov2WithRegistersPreTrainedModel + ), + /* harmony export */ + DistilBertForMaskedLM: () => ( + /* binding */ + DistilBertForMaskedLM + ), + /* harmony export */ + DistilBertForQuestionAnswering: () => ( + /* binding */ + DistilBertForQuestionAnswering + ), + /* harmony export */ + DistilBertForSequenceClassification: () => ( + /* binding */ + DistilBertForSequenceClassification + ), + /* harmony export */ + DistilBertForTokenClassification: () => ( + /* binding */ + DistilBertForTokenClassification + ), + /* harmony export */ + DistilBertModel: () => ( + /* binding */ + DistilBertModel + ), + /* harmony export */ + DistilBertPreTrainedModel: () => ( + /* binding */ + DistilBertPreTrainedModel + ), + /* harmony export */ + DonutSwinModel: () => ( + /* binding */ + DonutSwinModel + ), + /* harmony export */ + DonutSwinPreTrainedModel: () => ( + /* binding */ + DonutSwinPreTrainedModel + ), + /* harmony export */ + EdgeTamModel: () => ( + /* binding */ + EdgeTamModel + ), + /* harmony export */ + EfficientNetForImageClassification: () => ( + /* binding */ + EfficientNetForImageClassification + ), + /* harmony export */ + EfficientNetModel: () => ( + /* binding */ + EfficientNetModel + ), + /* harmony export */ + EfficientNetPreTrainedModel: () => ( + /* binding */ + EfficientNetPreTrainedModel + ), + /* harmony export */ + ElectraForMaskedLM: () => ( + /* binding */ + ElectraForMaskedLM + ), + /* harmony export */ + ElectraForQuestionAnswering: () => ( + /* binding */ + ElectraForQuestionAnswering + ), + /* harmony export */ + ElectraForSequenceClassification: () => ( + /* binding */ + ElectraForSequenceClassification + ), + /* harmony export */ + ElectraForTokenClassification: () => ( + /* binding */ + ElectraForTokenClassification + ), + /* harmony export */ + ElectraModel: () => ( + /* binding */ + ElectraModel + ), + /* harmony export */ + ElectraPreTrainedModel: () => ( + /* binding */ + ElectraPreTrainedModel + ), + /* harmony export */ + Ernie4_5ForCausalLM: () => ( + /* binding */ + Ernie4_5ForCausalLM + ), + /* harmony export */ + Ernie4_5Model: () => ( + /* binding */ + Ernie4_5Model + ), + /* harmony export */ + Ernie4_5PreTrainedModel: () => ( + /* binding */ + Ernie4_5PreTrainedModel + ), + /* harmony export */ + EsmForMaskedLM: () => ( + /* binding */ + EsmForMaskedLM + ), + /* harmony export */ + EsmForSequenceClassification: () => ( + /* binding */ + EsmForSequenceClassification + ), + /* harmony export */ + EsmForTokenClassification: () => ( + /* binding */ + EsmForTokenClassification + ), + /* harmony export */ + EsmModel: () => ( + /* binding */ + EsmModel + ), + /* harmony export */ + EsmPreTrainedModel: () => ( + /* binding */ + EsmPreTrainedModel + ), + /* harmony export */ + ExaoneForCausalLM: () => ( + /* binding */ + ExaoneForCausalLM + ), + /* harmony export */ + ExaoneModel: () => ( + /* binding */ + ExaoneModel + ), + /* harmony export */ + ExaonePreTrainedModel: () => ( + /* binding */ + ExaonePreTrainedModel + ), + /* harmony export */ + FalconForCausalLM: () => ( + /* binding */ + FalconForCausalLM + ), + /* harmony export */ + FalconModel: () => ( + /* binding */ + FalconModel + ), + /* harmony export */ + FalconPreTrainedModel: () => ( + /* binding */ + FalconPreTrainedModel + ), + /* harmony export */ + FastViTForImageClassification: () => ( + /* binding */ + FastViTForImageClassification + ), + /* harmony export */ + FastViTModel: () => ( + /* binding */ + FastViTModel + ), + /* harmony export */ + FastViTPreTrainedModel: () => ( + /* binding */ + FastViTPreTrainedModel + ), + /* harmony export */ + Florence2ForConditionalGeneration: () => ( + /* binding */ + Florence2ForConditionalGeneration + ), + /* harmony export */ + Florence2PreTrainedModel: () => ( + /* binding */ + Florence2PreTrainedModel + ), + /* harmony export */ + GLPNForDepthEstimation: () => ( + /* binding */ + GLPNForDepthEstimation + ), + /* harmony export */ + GLPNModel: () => ( + /* binding */ + GLPNModel + ), + /* harmony export */ + GLPNPreTrainedModel: () => ( + /* binding */ + GLPNPreTrainedModel + ), + /* harmony export */ + GPT2LMHeadModel: () => ( + /* binding */ + GPT2LMHeadModel + ), + /* harmony export */ + GPT2Model: () => ( + /* binding */ + GPT2Model + ), + /* harmony export */ + GPT2PreTrainedModel: () => ( + /* binding */ + GPT2PreTrainedModel + ), + /* harmony export */ + GPTBigCodeForCausalLM: () => ( + /* binding */ + GPTBigCodeForCausalLM + ), + /* harmony export */ + GPTBigCodeModel: () => ( + /* binding */ + GPTBigCodeModel + ), + /* harmony export */ + GPTBigCodePreTrainedModel: () => ( + /* binding */ + GPTBigCodePreTrainedModel + ), + /* harmony export */ + GPTJForCausalLM: () => ( + /* binding */ + GPTJForCausalLM + ), + /* harmony export */ + GPTJModel: () => ( + /* binding */ + GPTJModel + ), + /* harmony export */ + GPTJPreTrainedModel: () => ( + /* binding */ + GPTJPreTrainedModel + ), + /* harmony export */ + GPTNeoForCausalLM: () => ( + /* binding */ + GPTNeoForCausalLM + ), + /* harmony export */ + GPTNeoModel: () => ( + /* binding */ + GPTNeoModel + ), + /* harmony export */ + GPTNeoPreTrainedModel: () => ( + /* binding */ + GPTNeoPreTrainedModel + ), + /* harmony export */ + GPTNeoXForCausalLM: () => ( + /* binding */ + GPTNeoXForCausalLM + ), + /* harmony export */ + GPTNeoXModel: () => ( + /* binding */ + GPTNeoXModel + ), + /* harmony export */ + GPTNeoXPreTrainedModel: () => ( + /* binding */ + GPTNeoXPreTrainedModel + ), + /* harmony export */ + Gemma2ForCausalLM: () => ( + /* binding */ + Gemma2ForCausalLM + ), + /* harmony export */ + Gemma2Model: () => ( + /* binding */ + Gemma2Model + ), + /* harmony export */ + Gemma2PreTrainedModel: () => ( + /* binding */ + Gemma2PreTrainedModel + ), + /* harmony export */ + Gemma3ForCausalLM: () => ( + /* binding */ + Gemma3ForCausalLM + ), + /* harmony export */ + Gemma3Model: () => ( + /* binding */ + Gemma3Model + ), + /* harmony export */ + Gemma3PreTrainedModel: () => ( + /* binding */ + Gemma3PreTrainedModel + ), + /* harmony export */ + Gemma3nForConditionalGeneration: () => ( + /* binding */ + Gemma3nForConditionalGeneration + ), + /* harmony export */ + Gemma3nPreTrainedModel: () => ( + /* binding */ + Gemma3nPreTrainedModel + ), + /* harmony export */ + GemmaForCausalLM: () => ( + /* binding */ + GemmaForCausalLM + ), + /* harmony export */ + GemmaModel: () => ( + /* binding */ + GemmaModel + ), + /* harmony export */ + GemmaPreTrainedModel: () => ( + /* binding */ + GemmaPreTrainedModel + ), + /* harmony export */ + GlmForCausalLM: () => ( + /* binding */ + GlmForCausalLM + ), + /* harmony export */ + GlmModel: () => ( + /* binding */ + GlmModel + ), + /* harmony export */ + GlmPreTrainedModel: () => ( + /* binding */ + GlmPreTrainedModel + ), + /* harmony export */ + GraniteForCausalLM: () => ( + /* binding */ + GraniteForCausalLM + ), + /* harmony export */ + GraniteModel: () => ( + /* binding */ + GraniteModel + ), + /* harmony export */ + GraniteMoeHybridForCausalLM: () => ( + /* binding */ + GraniteMoeHybridForCausalLM + ), + /* harmony export */ + GraniteMoeHybridModel: () => ( + /* binding */ + GraniteMoeHybridModel + ), + /* harmony export */ + GraniteMoeHybridPreTrainedModel: () => ( + /* binding */ + GraniteMoeHybridPreTrainedModel + ), + /* harmony export */ + GranitePreTrainedModel: () => ( + /* binding */ + GranitePreTrainedModel + ), + /* harmony export */ + GroundingDinoForObjectDetection: () => ( + /* binding */ + GroundingDinoForObjectDetection + ), + /* harmony export */ + GroundingDinoPreTrainedModel: () => ( + /* binding */ + GroundingDinoPreTrainedModel + ), + /* harmony export */ + GroupViTModel: () => ( + /* binding */ + GroupViTModel + ), + /* harmony export */ + GroupViTPreTrainedModel: () => ( + /* binding */ + GroupViTPreTrainedModel + ), + /* harmony export */ + HeliumForCausalLM: () => ( + /* binding */ + HeliumForCausalLM + ), + /* harmony export */ + HeliumModel: () => ( + /* binding */ + HeliumModel + ), + /* harmony export */ + HeliumPreTrainedModel: () => ( + /* binding */ + HeliumPreTrainedModel + ), + /* harmony export */ + HieraForImageClassification: () => ( + /* binding */ + HieraForImageClassification + ), + /* harmony export */ + HieraModel: () => ( + /* binding */ + HieraModel + ), + /* harmony export */ + HieraPreTrainedModel: () => ( + /* binding */ + HieraPreTrainedModel + ), + /* harmony export */ + HubertForCTC: () => ( + /* binding */ + HubertForCTC + ), + /* harmony export */ + HubertForSequenceClassification: () => ( + /* binding */ + HubertForSequenceClassification + ), + /* harmony export */ + HubertModel: () => ( + /* binding */ + HubertModel + ), + /* harmony export */ + HubertPreTrainedModel: () => ( + /* binding */ + HubertPreTrainedModel + ), + /* harmony export */ + IJepaForImageClassification: () => ( + /* binding */ + IJepaForImageClassification + ), + /* harmony export */ + IJepaModel: () => ( + /* binding */ + IJepaModel + ), + /* harmony export */ + IJepaPreTrainedModel: () => ( + /* binding */ + IJepaPreTrainedModel + ), + /* harmony export */ + Idefics3ForConditionalGeneration: () => ( + /* binding */ + Idefics3ForConditionalGeneration + ), + /* harmony export */ + Idefics3PreTrainedModel: () => ( + /* binding */ + Idefics3PreTrainedModel + ), + /* harmony export */ + ImageMattingOutput: () => ( + /* binding */ + ImageMattingOutput + ), + /* harmony export */ + JAISLMHeadModel: () => ( + /* binding */ + JAISLMHeadModel + ), + /* harmony export */ + JAISModel: () => ( + /* binding */ + JAISModel + ), + /* harmony export */ + JAISPreTrainedModel: () => ( + /* binding */ + JAISPreTrainedModel + ), + /* harmony export */ + JinaCLIPModel: () => ( + /* binding */ + JinaCLIPModel + ), + /* harmony export */ + JinaCLIPPreTrainedModel: () => ( + /* binding */ + JinaCLIPPreTrainedModel + ), + /* harmony export */ + JinaCLIPTextModel: () => ( + /* binding */ + JinaCLIPTextModel + ), + /* harmony export */ + JinaCLIPVisionModel: () => ( + /* binding */ + JinaCLIPVisionModel + ), + /* harmony export */ + Lfm2ForCausalLM: () => ( + /* binding */ + Lfm2ForCausalLM + ), + /* harmony export */ + Lfm2Model: () => ( + /* binding */ + Lfm2Model + ), + /* harmony export */ + Lfm2PreTrainedModel: () => ( + /* binding */ + Lfm2PreTrainedModel + ), + /* harmony export */ + LiteWhisperForConditionalGeneration: () => ( + /* binding */ + LiteWhisperForConditionalGeneration + ), + /* harmony export */ + Llama4ForCausalLM: () => ( + /* binding */ + Llama4ForCausalLM + ), + /* harmony export */ + Llama4PreTrainedModel: () => ( + /* binding */ + Llama4PreTrainedModel + ), + /* harmony export */ + LlamaForCausalLM: () => ( + /* binding */ + LlamaForCausalLM + ), + /* harmony export */ + LlamaModel: () => ( + /* binding */ + LlamaModel + ), + /* harmony export */ + LlamaPreTrainedModel: () => ( + /* binding */ + LlamaPreTrainedModel + ), + /* harmony export */ + LlavaForConditionalGeneration: () => ( + /* binding */ + LlavaForConditionalGeneration + ), + /* harmony export */ + LlavaOnevisionForConditionalGeneration: () => ( + /* binding */ + LlavaOnevisionForConditionalGeneration + ), + /* harmony export */ + LlavaPreTrainedModel: () => ( + /* binding */ + LlavaPreTrainedModel + ), + /* harmony export */ + LlavaQwen2ForCausalLM: () => ( + /* binding */ + LlavaQwen2ForCausalLM + ), + /* harmony export */ + LongT5ForConditionalGeneration: () => ( + /* binding */ + LongT5ForConditionalGeneration + ), + /* harmony export */ + LongT5Model: () => ( + /* binding */ + LongT5Model + ), + /* harmony export */ + LongT5PreTrainedModel: () => ( + /* binding */ + LongT5PreTrainedModel + ), + /* harmony export */ + M2M100ForConditionalGeneration: () => ( + /* binding */ + M2M100ForConditionalGeneration + ), + /* harmony export */ + M2M100Model: () => ( + /* binding */ + M2M100Model + ), + /* harmony export */ + M2M100PreTrainedModel: () => ( + /* binding */ + M2M100PreTrainedModel + ), + /* harmony export */ + MBartForCausalLM: () => ( + /* binding */ + MBartForCausalLM + ), + /* harmony export */ + MBartForConditionalGeneration: () => ( + /* binding */ + MBartForConditionalGeneration + ), + /* harmony export */ + MBartForSequenceClassification: () => ( + /* binding */ + MBartForSequenceClassification + ), + /* harmony export */ + MBartModel: () => ( + /* binding */ + MBartModel + ), + /* harmony export */ + MBartPreTrainedModel: () => ( + /* binding */ + MBartPreTrainedModel + ), + /* harmony export */ + MPNetForMaskedLM: () => ( + /* binding */ + MPNetForMaskedLM + ), + /* harmony export */ + MPNetForQuestionAnswering: () => ( + /* binding */ + MPNetForQuestionAnswering + ), + /* harmony export */ + MPNetForSequenceClassification: () => ( + /* binding */ + MPNetForSequenceClassification + ), + /* harmony export */ + MPNetForTokenClassification: () => ( + /* binding */ + MPNetForTokenClassification + ), + /* harmony export */ + MPNetModel: () => ( + /* binding */ + MPNetModel + ), + /* harmony export */ + MPNetPreTrainedModel: () => ( + /* binding */ + MPNetPreTrainedModel + ), + /* harmony export */ + MT5ForConditionalGeneration: () => ( + /* binding */ + MT5ForConditionalGeneration + ), + /* harmony export */ + MT5Model: () => ( + /* binding */ + MT5Model + ), + /* harmony export */ + MT5PreTrainedModel: () => ( + /* binding */ + MT5PreTrainedModel + ), + /* harmony export */ + MarianMTModel: () => ( + /* binding */ + MarianMTModel + ), + /* harmony export */ + MarianModel: () => ( + /* binding */ + MarianModel + ), + /* harmony export */ + MarianPreTrainedModel: () => ( + /* binding */ + MarianPreTrainedModel + ), + /* harmony export */ + MaskFormerForInstanceSegmentation: () => ( + /* binding */ + MaskFormerForInstanceSegmentation + ), + /* harmony export */ + MaskFormerModel: () => ( + /* binding */ + MaskFormerModel + ), + /* harmony export */ + MaskFormerPreTrainedModel: () => ( + /* binding */ + MaskFormerPreTrainedModel + ), + /* harmony export */ + MaskedLMOutput: () => ( + /* binding */ + MaskedLMOutput + ), + /* harmony export */ + Metric3DForDepthEstimation: () => ( + /* binding */ + Metric3DForDepthEstimation + ), + /* harmony export */ + Metric3DPreTrainedModel: () => ( + /* binding */ + Metric3DPreTrainedModel + ), + /* harmony export */ + Metric3Dv2ForDepthEstimation: () => ( + /* binding */ + Metric3Dv2ForDepthEstimation + ), + /* harmony export */ + Metric3Dv2PreTrainedModel: () => ( + /* binding */ + Metric3Dv2PreTrainedModel + ), + /* harmony export */ + MgpstrForSceneTextRecognition: () => ( + /* binding */ + MgpstrForSceneTextRecognition + ), + /* harmony export */ + MgpstrModelOutput: () => ( + /* binding */ + MgpstrModelOutput + ), + /* harmony export */ + MgpstrPreTrainedModel: () => ( + /* binding */ + MgpstrPreTrainedModel + ), + /* harmony export */ + MimiDecoderModel: () => ( + /* binding */ + MimiDecoderModel + ), + /* harmony export */ + MimiDecoderOutput: () => ( + /* binding */ + MimiDecoderOutput + ), + /* harmony export */ + MimiEncoderModel: () => ( + /* binding */ + MimiEncoderModel + ), + /* harmony export */ + MimiEncoderOutput: () => ( + /* binding */ + MimiEncoderOutput + ), + /* harmony export */ + MimiModel: () => ( + /* binding */ + MimiModel + ), + /* harmony export */ + MimiPreTrainedModel: () => ( + /* binding */ + MimiPreTrainedModel + ), + /* harmony export */ + Ministral3ForCausalLM: () => ( + /* binding */ + Ministral3ForCausalLM + ), + /* harmony export */ + Ministral3Model: () => ( + /* binding */ + Ministral3Model + ), + /* harmony export */ + Ministral3PreTrainedModel: () => ( + /* binding */ + Ministral3PreTrainedModel + ), + /* harmony export */ + MinistralForCausalLM: () => ( + /* binding */ + MinistralForCausalLM + ), + /* harmony export */ + MinistralModel: () => ( + /* binding */ + MinistralModel + ), + /* harmony export */ + MinistralPreTrainedModel: () => ( + /* binding */ + MinistralPreTrainedModel + ), + /* harmony export */ + Mistral3ForConditionalGeneration: () => ( + /* binding */ + Mistral3ForConditionalGeneration + ), + /* harmony export */ + MistralForCausalLM: () => ( + /* binding */ + MistralForCausalLM + ), + /* harmony export */ + MistralModel: () => ( + /* binding */ + MistralModel + ), + /* harmony export */ + MistralPreTrainedModel: () => ( + /* binding */ + MistralPreTrainedModel + ), + /* harmony export */ + MobileBertForMaskedLM: () => ( + /* binding */ + MobileBertForMaskedLM + ), + /* harmony export */ + MobileBertForQuestionAnswering: () => ( + /* binding */ + MobileBertForQuestionAnswering + ), + /* harmony export */ + MobileBertForSequenceClassification: () => ( + /* binding */ + MobileBertForSequenceClassification + ), + /* harmony export */ + MobileBertModel: () => ( + /* binding */ + MobileBertModel + ), + /* harmony export */ + MobileBertPreTrainedModel: () => ( + /* binding */ + MobileBertPreTrainedModel + ), + /* harmony export */ + MobileLLMForCausalLM: () => ( + /* binding */ + MobileLLMForCausalLM + ), + /* harmony export */ + MobileLLMModel: () => ( + /* binding */ + MobileLLMModel + ), + /* harmony export */ + MobileLLMPreTrainedModel: () => ( + /* binding */ + MobileLLMPreTrainedModel + ), + /* harmony export */ + MobileNetV1ForImageClassification: () => ( + /* binding */ + MobileNetV1ForImageClassification + ), + /* harmony export */ + MobileNetV1ForSemanticSegmentation: () => ( + /* binding */ + MobileNetV1ForSemanticSegmentation + ), + /* harmony export */ + MobileNetV1Model: () => ( + /* binding */ + MobileNetV1Model + ), + /* harmony export */ + MobileNetV1PreTrainedModel: () => ( + /* binding */ + MobileNetV1PreTrainedModel + ), + /* harmony export */ + MobileNetV2ForImageClassification: () => ( + /* binding */ + MobileNetV2ForImageClassification + ), + /* harmony export */ + MobileNetV2ForSemanticSegmentation: () => ( + /* binding */ + MobileNetV2ForSemanticSegmentation + ), + /* harmony export */ + MobileNetV2Model: () => ( + /* binding */ + MobileNetV2Model + ), + /* harmony export */ + MobileNetV2PreTrainedModel: () => ( + /* binding */ + MobileNetV2PreTrainedModel + ), + /* harmony export */ + MobileNetV3ForImageClassification: () => ( + /* binding */ + MobileNetV3ForImageClassification + ), + /* harmony export */ + MobileNetV3ForSemanticSegmentation: () => ( + /* binding */ + MobileNetV3ForSemanticSegmentation + ), + /* harmony export */ + MobileNetV3Model: () => ( + /* binding */ + MobileNetV3Model + ), + /* harmony export */ + MobileNetV3PreTrainedModel: () => ( + /* binding */ + MobileNetV3PreTrainedModel + ), + /* harmony export */ + MobileNetV4ForImageClassification: () => ( + /* binding */ + MobileNetV4ForImageClassification + ), + /* harmony export */ + MobileNetV4ForSemanticSegmentation: () => ( + /* binding */ + MobileNetV4ForSemanticSegmentation + ), + /* harmony export */ + MobileNetV4Model: () => ( + /* binding */ + MobileNetV4Model + ), + /* harmony export */ + MobileNetV4PreTrainedModel: () => ( + /* binding */ + MobileNetV4PreTrainedModel + ), + /* harmony export */ + MobileViTForImageClassification: () => ( + /* binding */ + MobileViTForImageClassification + ), + /* harmony export */ + MobileViTModel: () => ( + /* binding */ + MobileViTModel + ), + /* harmony export */ + MobileViTPreTrainedModel: () => ( + /* binding */ + MobileViTPreTrainedModel + ), + /* harmony export */ + MobileViTV2ForImageClassification: () => ( + /* binding */ + MobileViTV2ForImageClassification + ), + /* harmony export */ + MobileViTV2Model: () => ( + /* binding */ + MobileViTV2Model + ), + /* harmony export */ + MobileViTV2PreTrainedModel: () => ( + /* binding */ + MobileViTV2PreTrainedModel + ), + /* harmony export */ + ModelOutput: () => ( + /* binding */ + ModelOutput + ), + /* harmony export */ + ModernBertDecoderForCausalLM: () => ( + /* binding */ + ModernBertDecoderForCausalLM + ), + /* harmony export */ + ModernBertDecoderModel: () => ( + /* binding */ + ModernBertDecoderModel + ), + /* harmony export */ + ModernBertDecoderPreTrainedModel: () => ( + /* binding */ + ModernBertDecoderPreTrainedModel + ), + /* harmony export */ + ModernBertForMaskedLM: () => ( + /* binding */ + ModernBertForMaskedLM + ), + /* harmony export */ + ModernBertForSequenceClassification: () => ( + /* binding */ + ModernBertForSequenceClassification + ), + /* harmony export */ + ModernBertForTokenClassification: () => ( + /* binding */ + ModernBertForTokenClassification + ), + /* harmony export */ + ModernBertModel: () => ( + /* binding */ + ModernBertModel + ), + /* harmony export */ + ModernBertPreTrainedModel: () => ( + /* binding */ + ModernBertPreTrainedModel + ), + /* harmony export */ + Moondream1ForConditionalGeneration: () => ( + /* binding */ + Moondream1ForConditionalGeneration + ), + /* harmony export */ + MoonshineForConditionalGeneration: () => ( + /* binding */ + MoonshineForConditionalGeneration + ), + /* harmony export */ + MoonshineModel: () => ( + /* binding */ + MoonshineModel + ), + /* harmony export */ + MoonshinePreTrainedModel: () => ( + /* binding */ + MoonshinePreTrainedModel + ), + /* harmony export */ + MptForCausalLM: () => ( + /* binding */ + MptForCausalLM + ), + /* harmony export */ + MptModel: () => ( + /* binding */ + MptModel + ), + /* harmony export */ + MptPreTrainedModel: () => ( + /* binding */ + MptPreTrainedModel + ), + /* harmony export */ + MultiModalityCausalLM: () => ( + /* binding */ + MultiModalityCausalLM + ), + /* harmony export */ + MultiModalityPreTrainedModel: () => ( + /* binding */ + MultiModalityPreTrainedModel + ), + /* harmony export */ + MusicgenForCausalLM: () => ( + /* binding */ + MusicgenForCausalLM + ), + /* harmony export */ + MusicgenForConditionalGeneration: () => ( + /* binding */ + MusicgenForConditionalGeneration + ), + /* harmony export */ + MusicgenModel: () => ( + /* binding */ + MusicgenModel + ), + /* harmony export */ + MusicgenPreTrainedModel: () => ( + /* binding */ + MusicgenPreTrainedModel + ), + /* harmony export */ + NanoChatForCausalLM: () => ( + /* binding */ + NanoChatForCausalLM + ), + /* harmony export */ + NanoChatModel: () => ( + /* binding */ + NanoChatModel + ), + /* harmony export */ + NanoChatPreTrainedModel: () => ( + /* binding */ + NanoChatPreTrainedModel + ), + /* harmony export */ + NeoBertForMaskedLM: () => ( + /* binding */ + NeoBertForMaskedLM + ), + /* harmony export */ + NeoBertForQuestionAnswering: () => ( + /* binding */ + NeoBertForQuestionAnswering + ), + /* harmony export */ + NeoBertForSequenceClassification: () => ( + /* binding */ + NeoBertForSequenceClassification + ), + /* harmony export */ + NeoBertForTokenClassification: () => ( + /* binding */ + NeoBertForTokenClassification + ), + /* harmony export */ + NeoBertModel: () => ( + /* binding */ + NeoBertModel + ), + /* harmony export */ + NeoBertPreTrainedModel: () => ( + /* binding */ + NeoBertPreTrainedModel + ), + /* harmony export */ + NomicBertModel: () => ( + /* binding */ + NomicBertModel + ), + /* harmony export */ + NomicBertPreTrainedModel: () => ( + /* binding */ + NomicBertPreTrainedModel + ), + /* harmony export */ + OPTForCausalLM: () => ( + /* binding */ + OPTForCausalLM + ), + /* harmony export */ + OPTModel: () => ( + /* binding */ + OPTModel + ), + /* harmony export */ + OPTPreTrainedModel: () => ( + /* binding */ + OPTPreTrainedModel + ), + /* harmony export */ + Olmo2ForCausalLM: () => ( + /* binding */ + Olmo2ForCausalLM + ), + /* harmony export */ + Olmo2Model: () => ( + /* binding */ + Olmo2Model + ), + /* harmony export */ + Olmo2PreTrainedModel: () => ( + /* binding */ + Olmo2PreTrainedModel + ), + /* harmony export */ + OlmoForCausalLM: () => ( + /* binding */ + OlmoForCausalLM + ), + /* harmony export */ + OlmoModel: () => ( + /* binding */ + OlmoModel + ), + /* harmony export */ + OlmoPreTrainedModel: () => ( + /* binding */ + OlmoPreTrainedModel + ), + /* harmony export */ + OpenELMForCausalLM: () => ( + /* binding */ + OpenELMForCausalLM + ), + /* harmony export */ + OpenELMModel: () => ( + /* binding */ + OpenELMModel + ), + /* harmony export */ + OpenELMPreTrainedModel: () => ( + /* binding */ + OpenELMPreTrainedModel + ), + /* harmony export */ + OwlViTForObjectDetection: () => ( + /* binding */ + OwlViTForObjectDetection + ), + /* harmony export */ + OwlViTModel: () => ( + /* binding */ + OwlViTModel + ), + /* harmony export */ + OwlViTPreTrainedModel: () => ( + /* binding */ + OwlViTPreTrainedModel + ), + /* harmony export */ + Owlv2ForObjectDetection: () => ( + /* binding */ + Owlv2ForObjectDetection + ), + /* harmony export */ + Owlv2Model: () => ( + /* binding */ + Owlv2Model + ), + /* harmony export */ + Owlv2PreTrainedModel: () => ( + /* binding */ + Owlv2PreTrainedModel + ), + /* harmony export */ + PaliGemmaForConditionalGeneration: () => ( + /* binding */ + PaliGemmaForConditionalGeneration + ), + /* harmony export */ + PaliGemmaPreTrainedModel: () => ( + /* binding */ + PaliGemmaPreTrainedModel + ), + /* harmony export */ + ParakeetForCTC: () => ( + /* binding */ + ParakeetForCTC + ), + /* harmony export */ + ParakeetPreTrainedModel: () => ( + /* binding */ + ParakeetPreTrainedModel + ), + /* harmony export */ + PatchTSMixerForPrediction: () => ( + /* binding */ + PatchTSMixerForPrediction + ), + /* harmony export */ + PatchTSMixerModel: () => ( + /* binding */ + PatchTSMixerModel + ), + /* harmony export */ + PatchTSMixerPreTrainedModel: () => ( + /* binding */ + PatchTSMixerPreTrainedModel + ), + /* harmony export */ + PatchTSTForPrediction: () => ( + /* binding */ + PatchTSTForPrediction + ), + /* harmony export */ + PatchTSTModel: () => ( + /* binding */ + PatchTSTModel + ), + /* harmony export */ + PatchTSTPreTrainedModel: () => ( + /* binding */ + PatchTSTPreTrainedModel + ), + /* harmony export */ + Phi3ForCausalLM: () => ( + /* binding */ + Phi3ForCausalLM + ), + /* harmony export */ + Phi3Model: () => ( + /* binding */ + Phi3Model + ), + /* harmony export */ + Phi3PreTrainedModel: () => ( + /* binding */ + Phi3PreTrainedModel + ), + /* harmony export */ + Phi3VForCausalLM: () => ( + /* binding */ + Phi3VForCausalLM + ), + /* harmony export */ + Phi3VPreTrainedModel: () => ( + /* binding */ + Phi3VPreTrainedModel + ), + /* harmony export */ + PhiForCausalLM: () => ( + /* binding */ + PhiForCausalLM + ), + /* harmony export */ + PhiModel: () => ( + /* binding */ + PhiModel + ), + /* harmony export */ + PhiPreTrainedModel: () => ( + /* binding */ + PhiPreTrainedModel + ), + /* harmony export */ + PreTrainedModel: () => ( + /* binding */ + PreTrainedModel + ), + /* harmony export */ + PretrainedMixin: () => ( + /* binding */ + PretrainedMixin + ), + /* harmony export */ + PvtForImageClassification: () => ( + /* binding */ + PvtForImageClassification + ), + /* harmony export */ + PvtModel: () => ( + /* binding */ + PvtModel + ), + /* harmony export */ + PvtPreTrainedModel: () => ( + /* binding */ + PvtPreTrainedModel + ), + /* harmony export */ + PyAnnoteForAudioFrameClassification: () => ( + /* binding */ + PyAnnoteForAudioFrameClassification + ), + /* harmony export */ + PyAnnoteModel: () => ( + /* binding */ + PyAnnoteModel + ), + /* harmony export */ + PyAnnotePreTrainedModel: () => ( + /* binding */ + PyAnnotePreTrainedModel + ), + /* harmony export */ + QuestionAnsweringModelOutput: () => ( + /* binding */ + QuestionAnsweringModelOutput + ), + /* harmony export */ + Qwen2ForCausalLM: () => ( + /* binding */ + Qwen2ForCausalLM + ), + /* harmony export */ + Qwen2Model: () => ( + /* binding */ + Qwen2Model + ), + /* harmony export */ + Qwen2PreTrainedModel: () => ( + /* binding */ + Qwen2PreTrainedModel + ), + /* harmony export */ + Qwen2VLForConditionalGeneration: () => ( + /* binding */ + Qwen2VLForConditionalGeneration + ), + /* harmony export */ + Qwen2VLPreTrainedModel: () => ( + /* binding */ + Qwen2VLPreTrainedModel + ), + /* harmony export */ + Qwen3ForCausalLM: () => ( + /* binding */ + Qwen3ForCausalLM + ), + /* harmony export */ + Qwen3Model: () => ( + /* binding */ + Qwen3Model + ), + /* harmony export */ + Qwen3PreTrainedModel: () => ( + /* binding */ + Qwen3PreTrainedModel + ), + /* harmony export */ + RFDetrForObjectDetection: () => ( + /* binding */ + RFDetrForObjectDetection + ), + /* harmony export */ + RFDetrModel: () => ( + /* binding */ + RFDetrModel + ), + /* harmony export */ + RFDetrObjectDetectionOutput: () => ( + /* binding */ + RFDetrObjectDetectionOutput + ), + /* harmony export */ + RFDetrPreTrainedModel: () => ( + /* binding */ + RFDetrPreTrainedModel + ), + /* harmony export */ + RTDetrForObjectDetection: () => ( + /* binding */ + RTDetrForObjectDetection + ), + /* harmony export */ + RTDetrModel: () => ( + /* binding */ + RTDetrModel + ), + /* harmony export */ + RTDetrObjectDetectionOutput: () => ( + /* binding */ + RTDetrObjectDetectionOutput + ), + /* harmony export */ + RTDetrPreTrainedModel: () => ( + /* binding */ + RTDetrPreTrainedModel + ), + /* harmony export */ + RTDetrV2ForObjectDetection: () => ( + /* binding */ + RTDetrV2ForObjectDetection + ), + /* harmony export */ + RTDetrV2Model: () => ( + /* binding */ + RTDetrV2Model + ), + /* harmony export */ + RTDetrV2ObjectDetectionOutput: () => ( + /* binding */ + RTDetrV2ObjectDetectionOutput + ), + /* harmony export */ + RTDetrV2PreTrainedModel: () => ( + /* binding */ + RTDetrV2PreTrainedModel + ), + /* harmony export */ + ResNetForImageClassification: () => ( + /* binding */ + ResNetForImageClassification + ), + /* harmony export */ + ResNetModel: () => ( + /* binding */ + ResNetModel + ), + /* harmony export */ + ResNetPreTrainedModel: () => ( + /* binding */ + ResNetPreTrainedModel + ), + /* harmony export */ + RoFormerForMaskedLM: () => ( + /* binding */ + RoFormerForMaskedLM + ), + /* harmony export */ + RoFormerForQuestionAnswering: () => ( + /* binding */ + RoFormerForQuestionAnswering + ), + /* harmony export */ + RoFormerForSequenceClassification: () => ( + /* binding */ + RoFormerForSequenceClassification + ), + /* harmony export */ + RoFormerForTokenClassification: () => ( + /* binding */ + RoFormerForTokenClassification + ), + /* harmony export */ + RoFormerModel: () => ( + /* binding */ + RoFormerModel + ), + /* harmony export */ + RoFormerPreTrainedModel: () => ( + /* binding */ + RoFormerPreTrainedModel + ), + /* harmony export */ + RobertaForMaskedLM: () => ( + /* binding */ + RobertaForMaskedLM + ), + /* harmony export */ + RobertaForQuestionAnswering: () => ( + /* binding */ + RobertaForQuestionAnswering + ), + /* harmony export */ + RobertaForSequenceClassification: () => ( + /* binding */ + RobertaForSequenceClassification + ), + /* harmony export */ + RobertaForTokenClassification: () => ( + /* binding */ + RobertaForTokenClassification + ), + /* harmony export */ + RobertaModel: () => ( + /* binding */ + RobertaModel + ), + /* harmony export */ + RobertaPreTrainedModel: () => ( + /* binding */ + RobertaPreTrainedModel + ), + /* harmony export */ + Sam2ImageSegmentationOutput: () => ( + /* binding */ + Sam2ImageSegmentationOutput + ), + /* harmony export */ + Sam2Model: () => ( + /* binding */ + Sam2Model + ), + /* harmony export */ + Sam2PreTrainedModel: () => ( + /* binding */ + Sam2PreTrainedModel + ), + /* harmony export */ + Sam3TrackerModel: () => ( + /* binding */ + Sam3TrackerModel + ), + /* harmony export */ + SamImageSegmentationOutput: () => ( + /* binding */ + SamImageSegmentationOutput + ), + /* harmony export */ + SamModel: () => ( + /* binding */ + SamModel + ), + /* harmony export */ + SamPreTrainedModel: () => ( + /* binding */ + SamPreTrainedModel + ), + /* harmony export */ + SapiensForDepthEstimation: () => ( + /* binding */ + SapiensForDepthEstimation + ), + /* harmony export */ + SapiensForNormalEstimation: () => ( + /* binding */ + SapiensForNormalEstimation + ), + /* harmony export */ + SapiensForSemanticSegmentation: () => ( + /* binding */ + SapiensForSemanticSegmentation + ), + /* harmony export */ + SapiensPreTrainedModel: () => ( + /* binding */ + SapiensPreTrainedModel + ), + /* harmony export */ + SegformerForImageClassification: () => ( + /* binding */ + SegformerForImageClassification + ), + /* harmony export */ + SegformerForSemanticSegmentation: () => ( + /* binding */ + SegformerForSemanticSegmentation + ), + /* harmony export */ + SegformerModel: () => ( + /* binding */ + SegformerModel + ), + /* harmony export */ + SegformerPreTrainedModel: () => ( + /* binding */ + SegformerPreTrainedModel + ), + /* harmony export */ + Seq2SeqLMOutput: () => ( + /* binding */ + Seq2SeqLMOutput + ), + /* harmony export */ + SequenceClassifierOutput: () => ( + /* binding */ + SequenceClassifierOutput + ), + /* harmony export */ + SiglipModel: () => ( + /* binding */ + SiglipModel + ), + /* harmony export */ + SiglipPreTrainedModel: () => ( + /* binding */ + SiglipPreTrainedModel + ), + /* harmony export */ + SiglipTextModel: () => ( + /* binding */ + SiglipTextModel + ), + /* harmony export */ + SiglipVisionModel: () => ( + /* binding */ + SiglipVisionModel + ), + /* harmony export */ + SmolLM3ForCausalLM: () => ( + /* binding */ + SmolLM3ForCausalLM + ), + /* harmony export */ + SmolLM3Model: () => ( + /* binding */ + SmolLM3Model + ), + /* harmony export */ + SmolLM3PreTrainedModel: () => ( + /* binding */ + SmolLM3PreTrainedModel + ), + /* harmony export */ + SmolVLMForConditionalGeneration: () => ( + /* binding */ + SmolVLMForConditionalGeneration + ), + /* harmony export */ + SnacDecoderModel: () => ( + /* binding */ + SnacDecoderModel + ), + /* harmony export */ + SnacEncoderModel: () => ( + /* binding */ + SnacEncoderModel + ), + /* harmony export */ + SnacModel: () => ( + /* binding */ + SnacModel + ), + /* harmony export */ + SnacPreTrainedModel: () => ( + /* binding */ + SnacPreTrainedModel + ), + /* harmony export */ + SpeechT5ForSpeechToText: () => ( + /* binding */ + SpeechT5ForSpeechToText + ), + /* harmony export */ + SpeechT5ForTextToSpeech: () => ( + /* binding */ + SpeechT5ForTextToSpeech + ), + /* harmony export */ + SpeechT5HifiGan: () => ( + /* binding */ + SpeechT5HifiGan + ), + /* harmony export */ + SpeechT5Model: () => ( + /* binding */ + SpeechT5Model + ), + /* harmony export */ + SpeechT5PreTrainedModel: () => ( + /* binding */ + SpeechT5PreTrainedModel + ), + /* harmony export */ + SqueezeBertForMaskedLM: () => ( + /* binding */ + SqueezeBertForMaskedLM + ), + /* harmony export */ + SqueezeBertForQuestionAnswering: () => ( + /* binding */ + SqueezeBertForQuestionAnswering + ), + /* harmony export */ + SqueezeBertForSequenceClassification: () => ( + /* binding */ + SqueezeBertForSequenceClassification + ), + /* harmony export */ + SqueezeBertModel: () => ( + /* binding */ + SqueezeBertModel + ), + /* harmony export */ + SqueezeBertPreTrainedModel: () => ( + /* binding */ + SqueezeBertPreTrainedModel + ), + /* harmony export */ + StableLmForCausalLM: () => ( + /* binding */ + StableLmForCausalLM + ), + /* harmony export */ + StableLmModel: () => ( + /* binding */ + StableLmModel + ), + /* harmony export */ + StableLmPreTrainedModel: () => ( + /* binding */ + StableLmPreTrainedModel + ), + /* harmony export */ + Starcoder2ForCausalLM: () => ( + /* binding */ + Starcoder2ForCausalLM + ), + /* harmony export */ + Starcoder2Model: () => ( + /* binding */ + Starcoder2Model + ), + /* harmony export */ + Starcoder2PreTrainedModel: () => ( + /* binding */ + Starcoder2PreTrainedModel + ), + /* harmony export */ + StyleTextToSpeech2Model: () => ( + /* binding */ + StyleTextToSpeech2Model + ), + /* harmony export */ + StyleTextToSpeech2PreTrainedModel: () => ( + /* binding */ + StyleTextToSpeech2PreTrainedModel + ), + /* harmony export */ + SupertonicForConditionalGeneration: () => ( + /* binding */ + SupertonicForConditionalGeneration + ), + /* harmony export */ + SupertonicPreTrainedModel: () => ( + /* binding */ + SupertonicPreTrainedModel + ), + /* harmony export */ + Swin2SRForImageSuperResolution: () => ( + /* binding */ + Swin2SRForImageSuperResolution + ), + /* harmony export */ + Swin2SRModel: () => ( + /* binding */ + Swin2SRModel + ), + /* harmony export */ + Swin2SRPreTrainedModel: () => ( + /* binding */ + Swin2SRPreTrainedModel + ), + /* harmony export */ + SwinForImageClassification: () => ( + /* binding */ + SwinForImageClassification + ), + /* harmony export */ + SwinForSemanticSegmentation: () => ( + /* binding */ + SwinForSemanticSegmentation + ), + /* harmony export */ + SwinModel: () => ( + /* binding */ + SwinModel + ), + /* harmony export */ + SwinPreTrainedModel: () => ( + /* binding */ + SwinPreTrainedModel + ), + /* harmony export */ + T5ForConditionalGeneration: () => ( + /* binding */ + T5ForConditionalGeneration + ), + /* harmony export */ + T5Model: () => ( + /* binding */ + T5Model + ), + /* harmony export */ + T5PreTrainedModel: () => ( + /* binding */ + T5PreTrainedModel + ), + /* harmony export */ + TableTransformerForObjectDetection: () => ( + /* binding */ + TableTransformerForObjectDetection + ), + /* harmony export */ + TableTransformerModel: () => ( + /* binding */ + TableTransformerModel + ), + /* harmony export */ + TableTransformerObjectDetectionOutput: () => ( + /* binding */ + TableTransformerObjectDetectionOutput + ), + /* harmony export */ + TableTransformerPreTrainedModel: () => ( + /* binding */ + TableTransformerPreTrainedModel + ), + /* harmony export */ + TokenClassifierOutput: () => ( + /* binding */ + TokenClassifierOutput + ), + /* harmony export */ + TrOCRForCausalLM: () => ( + /* binding */ + TrOCRForCausalLM + ), + /* harmony export */ + TrOCRPreTrainedModel: () => ( + /* binding */ + TrOCRPreTrainedModel + ), + /* harmony export */ + UltravoxModel: () => ( + /* binding */ + UltravoxModel + ), + /* harmony export */ + UltravoxPreTrainedModel: () => ( + /* binding */ + UltravoxPreTrainedModel + ), + /* harmony export */ + UniSpeechForCTC: () => ( + /* binding */ + UniSpeechForCTC + ), + /* harmony export */ + UniSpeechForSequenceClassification: () => ( + /* binding */ + UniSpeechForSequenceClassification + ), + /* harmony export */ + UniSpeechModel: () => ( + /* binding */ + UniSpeechModel + ), + /* harmony export */ + UniSpeechPreTrainedModel: () => ( + /* binding */ + UniSpeechPreTrainedModel + ), + /* harmony export */ + UniSpeechSatForAudioFrameClassification: () => ( + /* binding */ + UniSpeechSatForAudioFrameClassification + ), + /* harmony export */ + UniSpeechSatForCTC: () => ( + /* binding */ + UniSpeechSatForCTC + ), + /* harmony export */ + UniSpeechSatForSequenceClassification: () => ( + /* binding */ + UniSpeechSatForSequenceClassification + ), + /* harmony export */ + UniSpeechSatModel: () => ( + /* binding */ + UniSpeechSatModel + ), + /* harmony export */ + UniSpeechSatPreTrainedModel: () => ( + /* binding */ + UniSpeechSatPreTrainedModel + ), + /* harmony export */ + VaultGemmaForCausalLM: () => ( + /* binding */ + VaultGemmaForCausalLM + ), + /* harmony export */ + VaultGemmaModel: () => ( + /* binding */ + VaultGemmaModel + ), + /* harmony export */ + VaultGemmaPreTrainedModel: () => ( + /* binding */ + VaultGemmaPreTrainedModel + ), + /* harmony export */ + ViTForImageClassification: () => ( + /* binding */ + ViTForImageClassification + ), + /* harmony export */ + ViTMAEModel: () => ( + /* binding */ + ViTMAEModel + ), + /* harmony export */ + ViTMAEPreTrainedModel: () => ( + /* binding */ + ViTMAEPreTrainedModel + ), + /* harmony export */ + ViTMSNForImageClassification: () => ( + /* binding */ + ViTMSNForImageClassification + ), + /* harmony export */ + ViTMSNModel: () => ( + /* binding */ + ViTMSNModel + ), + /* harmony export */ + ViTMSNPreTrainedModel: () => ( + /* binding */ + ViTMSNPreTrainedModel + ), + /* harmony export */ + ViTModel: () => ( + /* binding */ + ViTModel + ), + /* harmony export */ + ViTPreTrainedModel: () => ( + /* binding */ + ViTPreTrainedModel + ), + /* harmony export */ + VisionEncoderDecoderModel: () => ( + /* binding */ + VisionEncoderDecoderModel + ), + /* harmony export */ + VitMatteForImageMatting: () => ( + /* binding */ + VitMatteForImageMatting + ), + /* harmony export */ + VitMattePreTrainedModel: () => ( + /* binding */ + VitMattePreTrainedModel + ), + /* harmony export */ + VitPoseForPoseEstimation: () => ( + /* binding */ + VitPoseForPoseEstimation + ), + /* harmony export */ + VitPosePreTrainedModel: () => ( + /* binding */ + VitPosePreTrainedModel + ), + /* harmony export */ + VitsModel: () => ( + /* binding */ + VitsModel + ), + /* harmony export */ + VitsModelOutput: () => ( + /* binding */ + VitsModelOutput + ), + /* harmony export */ + VitsPreTrainedModel: () => ( + /* binding */ + VitsPreTrainedModel + ), + /* harmony export */ + VoxtralForConditionalGeneration: () => ( + /* binding */ + VoxtralForConditionalGeneration + ), + /* harmony export */ + Wav2Vec2BertForCTC: () => ( + /* binding */ + Wav2Vec2BertForCTC + ), + /* harmony export */ + Wav2Vec2BertForSequenceClassification: () => ( + /* binding */ + Wav2Vec2BertForSequenceClassification + ), + /* harmony export */ + Wav2Vec2BertModel: () => ( + /* binding */ + Wav2Vec2BertModel + ), + /* harmony export */ + Wav2Vec2BertPreTrainedModel: () => ( + /* binding */ + Wav2Vec2BertPreTrainedModel + ), + /* harmony export */ + Wav2Vec2ForAudioFrameClassification: () => ( + /* binding */ + Wav2Vec2ForAudioFrameClassification + ), + /* harmony export */ + Wav2Vec2ForCTC: () => ( + /* binding */ + Wav2Vec2ForCTC + ), + /* harmony export */ + Wav2Vec2ForSequenceClassification: () => ( + /* binding */ + Wav2Vec2ForSequenceClassification + ), + /* harmony export */ + Wav2Vec2Model: () => ( + /* binding */ + Wav2Vec2Model + ), + /* harmony export */ + Wav2Vec2PreTrainedModel: () => ( + /* binding */ + Wav2Vec2PreTrainedModel + ), + /* harmony export */ + WavLMForAudioFrameClassification: () => ( + /* binding */ + WavLMForAudioFrameClassification + ), + /* harmony export */ + WavLMForCTC: () => ( + /* binding */ + WavLMForCTC + ), + /* harmony export */ + WavLMForSequenceClassification: () => ( + /* binding */ + WavLMForSequenceClassification + ), + /* harmony export */ + WavLMForXVector: () => ( + /* binding */ + WavLMForXVector + ), + /* harmony export */ + WavLMModel: () => ( + /* binding */ + WavLMModel + ), + /* harmony export */ + WavLMPreTrainedModel: () => ( + /* binding */ + WavLMPreTrainedModel + ), + /* harmony export */ + WeSpeakerResNetModel: () => ( + /* binding */ + WeSpeakerResNetModel + ), + /* harmony export */ + WeSpeakerResNetPreTrainedModel: () => ( + /* binding */ + WeSpeakerResNetPreTrainedModel + ), + /* harmony export */ + WhisperForConditionalGeneration: () => ( + /* binding */ + WhisperForConditionalGeneration + ), + /* harmony export */ + WhisperModel: () => ( + /* binding */ + WhisperModel + ), + /* harmony export */ + WhisperPreTrainedModel: () => ( + /* binding */ + WhisperPreTrainedModel + ), + /* harmony export */ + XLMForQuestionAnswering: () => ( + /* binding */ + XLMForQuestionAnswering + ), + /* harmony export */ + XLMForSequenceClassification: () => ( + /* binding */ + XLMForSequenceClassification + ), + /* harmony export */ + XLMForTokenClassification: () => ( + /* binding */ + XLMForTokenClassification + ), + /* harmony export */ + XLMModel: () => ( + /* binding */ + XLMModel + ), + /* harmony export */ + XLMPreTrainedModel: () => ( + /* binding */ + XLMPreTrainedModel + ), + /* harmony export */ + XLMRobertaForMaskedLM: () => ( + /* binding */ + XLMRobertaForMaskedLM + ), + /* harmony export */ + XLMRobertaForQuestionAnswering: () => ( + /* binding */ + XLMRobertaForQuestionAnswering + ), + /* harmony export */ + XLMRobertaForSequenceClassification: () => ( + /* binding */ + XLMRobertaForSequenceClassification + ), + /* harmony export */ + XLMRobertaForTokenClassification: () => ( + /* binding */ + XLMRobertaForTokenClassification + ), + /* harmony export */ + XLMRobertaModel: () => ( + /* binding */ + XLMRobertaModel + ), + /* harmony export */ + XLMRobertaPreTrainedModel: () => ( + /* binding */ + XLMRobertaPreTrainedModel + ), + /* harmony export */ + XLMWithLMHeadModel: () => ( + /* binding */ + XLMWithLMHeadModel + ), + /* harmony export */ + XVectorOutput: () => ( + /* binding */ + XVectorOutput + ), + /* harmony export */ + YolosForObjectDetection: () => ( + /* binding */ + YolosForObjectDetection + ), + /* harmony export */ + YolosModel: () => ( + /* binding */ + YolosModel + ), + /* harmony export */ + YolosObjectDetectionOutput: () => ( + /* binding */ + YolosObjectDetectionOutput + ), + /* harmony export */ + YolosPreTrainedModel: () => ( + /* binding */ + YolosPreTrainedModel + ) + /* harmony export */ + }); + var _configs_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ./configs.js */ + "./src/configs.js" + ); + var _backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ./backends/onnx.js */ + "./src/backends/onnx.js" + ); + var _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ./utils/dtypes.js */ + "./src/utils/dtypes.js" + ); + var _utils_generic_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! ./utils/generic.js */ + "./src/utils/generic.js" + ); + var _utils_core_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__2( + /*! ./utils/core.js */ + "./src/utils/core.js" + ); + var _utils_hub_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__2( + /*! ./utils/hub.js */ + "./src/utils/hub.js" + ); + var _utils_constants_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__2( + /*! ./utils/constants.js */ + "./src/utils/constants.js" + ); + var _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__2( + /*! ./generation/logits_process.js */ + "./src/generation/logits_process.js" + ); + var _generation_configuration_utils_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__2( + /*! ./generation/configuration_utils.js */ + "./src/generation/configuration_utils.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__2( + /*! ./utils/tensor.js */ + "./src/utils/tensor.js" + ); + var _utils_image_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__2( + /*! ./utils/image.js */ + "./src/utils/image.js" + ); + var _utils_maths_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__2( + /*! ./utils/maths.js */ + "./src/utils/maths.js" + ); + var _generation_stopping_criteria_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__2( + /*! ./generation/stopping_criteria.js */ + "./src/generation/stopping_criteria.js" + ); + var _generation_logits_sampler_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__2( + /*! ./generation/logits_sampler.js */ + "./src/generation/logits_sampler.js" + ); + var _env_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__2( + /*! ./env.js */ + "./src/env.js" + ); + var _models_whisper_generation_whisper_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__2( + /*! ./models/whisper/generation_whisper.js */ + "./src/models/whisper/generation_whisper.js" + ); + var _models_whisper_common_whisper_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__2( + /*! ./models/whisper/common_whisper.js */ + "./src/models/whisper/common_whisper.js" + ); + const MODEL_TYPES = { + EncoderOnly: 0, + EncoderDecoder: 1, + Seq2Seq: 2, + Vision2Seq: 3, + DecoderOnly: 4, + MaskGeneration: 5, + ImageTextToText: 6, + Musicgen: 7, + MultiModality: 8, + Phi3V: 9, + AudioTextToText: 10, + AutoEncoder: 11, + ImageAudioTextToText: 12, + Supertonic: 13 + }; + const MODEL_TYPE_MAPPING = /* @__PURE__ */ new Map(); + const MODEL_NAME_TO_CLASS_MAPPING = /* @__PURE__ */ new Map(); + const MODEL_CLASS_TO_NAME_MAPPING = /* @__PURE__ */ new Map(); + async function getSession(pretrained_model_name_or_path, fileName, options) { + let custom_config = options.config?.["transformers.js_config"] ?? {}; + let device = options.device ?? custom_config.device; + if (device && typeof device !== "string") { + if (device.hasOwnProperty(fileName)) { + device = device[fileName]; + } else { + console.warn(`device not specified for "${fileName}". Using the default device.`); + device = null; + } + } + const selectedDevice = ( + /** @type {import("./utils/devices.js").DeviceType} */ + device ?? (_env_js__WEBPACK_IMPORTED_MODULE_14__.apis.IS_NODE_ENV ? "cpu" : "wasm") + ); + const executionProviders = (0, _backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__.deviceToExecutionProviders)(selectedDevice); + const device_config = custom_config.device_config ?? {}; + if (device_config.hasOwnProperty(selectedDevice)) { + custom_config = { + ...custom_config, + ...device_config[selectedDevice] + }; + } + let dtype = options.dtype ?? custom_config.dtype; + if (typeof dtype !== "string") { + if (dtype && dtype.hasOwnProperty(fileName)) { + dtype = dtype[fileName]; + } else { + dtype = _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DEFAULT_DEVICE_DTYPE_MAPPING[selectedDevice] ?? _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DATA_TYPES.fp32; + console.warn(`dtype not specified for "${fileName}". Using the default dtype (${dtype}) for this device (${selectedDevice}).`); + } + } + if (dtype === _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DATA_TYPES.auto) { + let config_dtype = custom_config.dtype; + if (typeof config_dtype !== "string") { + config_dtype = config_dtype?.[fileName]; + } + if (config_dtype && config_dtype !== _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DATA_TYPES.auto && _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DATA_TYPES.hasOwnProperty(config_dtype)) { + dtype = config_dtype; + } else { + dtype = _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DEFAULT_DEVICE_DTYPE_MAPPING[selectedDevice] ?? _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DATA_TYPES.fp32; + } + } + const selectedDtype = ( + /** @type {import("./utils/dtypes.js").DataType} */ + dtype + ); + if (!_utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(selectedDtype)) { + throw new Error(`Invalid dtype: ${selectedDtype}. Should be one of: ${Object.keys(_utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DATA_TYPES).join(", ")}`); + } else if (selectedDtype === _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DATA_TYPES.fp16 && selectedDevice === "webgpu" && !await (0, _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.isWebGpuFp16Supported)()) { + throw new Error(`The device (${selectedDevice}) does not support fp16.`); + } + const kv_cache_dtype_config = custom_config.kv_cache_dtype; + const kv_cache_dtype = kv_cache_dtype_config ? typeof kv_cache_dtype_config === "string" ? kv_cache_dtype_config : kv_cache_dtype_config[selectedDtype] ?? "float32" : void 0; + if (kv_cache_dtype && !["float32", "float16"].includes(kv_cache_dtype)) { + throw new Error(`Invalid kv_cache_dtype: ${kv_cache_dtype}. Should be one of: float32, float16`); + } + const session_config = { + dtype: selectedDtype, + kv_cache_dtype, + device: selectedDevice + }; + const suffix = _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DEFAULT_DTYPE_SUFFIX_MAPPING[selectedDtype]; + const baseName = `${fileName}${suffix}.onnx`; + const modelFileName = `${options.subfolder ?? ""}/${baseName}`; + const session_options = { ...options.session_options }; + session_options.executionProviders ??= executionProviders; + const free_dimension_overrides = custom_config.free_dimension_overrides; + if (free_dimension_overrides) { + session_options.freeDimensionOverrides ??= free_dimension_overrides; + } else if (selectedDevice.startsWith("webnn") && !session_options.freeDimensionOverrides) { + console.warn( + `WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${selectedDevice}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.` + ); + } + const return_path = _env_js__WEBPACK_IMPORTED_MODULE_14__.apis.IS_NODE_ENV && _env_js__WEBPACK_IMPORTED_MODULE_14__.env.useFSCache; + const bufferOrPathPromise = (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.getModelFile)(pretrained_model_name_or_path, modelFileName, true, options, return_path); + const use_external_data_format = options.use_external_data_format ?? custom_config.use_external_data_format; + let externalDataPromises = []; + if (use_external_data_format) { + let external_data_format; + if (typeof use_external_data_format === "object") { + if (use_external_data_format.hasOwnProperty(baseName)) { + external_data_format = use_external_data_format[baseName]; + } else if (use_external_data_format.hasOwnProperty(fileName)) { + external_data_format = use_external_data_format[fileName]; + } else { + external_data_format = false; + } + } else { + external_data_format = use_external_data_format; + } + const num_chunks = +external_data_format; + if (num_chunks > _utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.MAX_EXTERNAL_DATA_CHUNKS) { + throw new Error(`The number of external data chunks (${num_chunks}) exceeds the maximum allowed value (${_utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.MAX_EXTERNAL_DATA_CHUNKS}).`); + } + for (let i = 0; i < num_chunks; ++i) { + const path = `${baseName}_data${i === 0 ? "" : "_" + i}`; + const fullPath = `${options.subfolder ?? ""}/${path}`; + externalDataPromises.push(new Promise(async (resolve, reject) => { + const data = await (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.getModelFile)(pretrained_model_name_or_path, fullPath, true, options, return_path); + resolve(data instanceof Uint8Array ? { path, data } : path); + })); + } + } else if (session_options.externalData !== void 0) { + externalDataPromises = session_options.externalData.map(async (ext) => { + if (typeof ext.data === "string") { + const ext_buffer = await (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.getModelFile)(pretrained_model_name_or_path, ext.data, true, options); + return { ...ext, data: ext_buffer }; + } + return ext; + }); + } + if (externalDataPromises.length > 0) { + const externalData = await Promise.all(externalDataPromises); + if (!_env_js__WEBPACK_IMPORTED_MODULE_14__.apis.IS_NODE_ENV) { + session_options.externalData = externalData; + } + } + if (selectedDevice === "webgpu") { + const shapes = (0, _configs_js__WEBPACK_IMPORTED_MODULE_0__.getCacheShapes)(options.config, { + prefix: "present" + }); + if (Object.keys(shapes).length > 0 && !(0, _backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__.isONNXProxy)()) { + const preferredOutputLocation = {}; + for (const key in shapes) { + preferredOutputLocation[key] = "gpu-buffer"; + } + session_options.preferredOutputLocation = preferredOutputLocation; + } + } + const buffer_or_path = await bufferOrPathPromise; + return { buffer_or_path, session_options, session_config }; + } + async function constructSessions(pretrained_model_name_or_path, names, options) { + return Object.fromEntries(await Promise.all( + Object.keys(names).map(async (name) => { + const { buffer_or_path, session_options, session_config } = await getSession(pretrained_model_name_or_path, names[name], options); + const session = await (0, _backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__.createInferenceSession)(buffer_or_path, session_options, session_config); + return [name, session]; + }) + )); + } + async function getOptionalConfigs(pretrained_model_name_or_path, names, options) { + return Object.fromEntries(await Promise.all( + Object.keys(names).map(async (name) => { + const config = await (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.getModelJSON)(pretrained_model_name_or_path, names[name], false, options); + return [name, config]; + }) + )); + } + function validateInputs(session, inputs) { + const checkedInputs = /* @__PURE__ */ Object.create(null); + const missingInputs = []; + for (const inputName of session.inputNames) { + const tensor = inputs[inputName]; + if (!(tensor instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor)) { + missingInputs.push(inputName); + continue; + } + checkedInputs[inputName] = (0, _backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__.isONNXProxy)() ? tensor.clone() : tensor; + } + if (missingInputs.length > 0) { + throw new Error( + `An error occurred during model execution: "Missing the following inputs: ${missingInputs.join(", ")}.` + ); + } + const numInputsProvided = Object.keys(inputs).length; + const numInputsNeeded = session.inputNames.length; + if (numInputsProvided > numInputsNeeded) { + let ignored = Object.keys(inputs).filter((inputName) => !session.inputNames.includes(inputName)); + console.warn(`WARNING: Too many inputs were provided (${numInputsProvided} > ${numInputsNeeded}). The following inputs will be ignored: "${ignored.join(", ")}".`); + } + return checkedInputs; + } + async function sessionRun(session, inputs) { + const checkedInputs = validateInputs(session, inputs); + try { + const ortFeed = Object.fromEntries(Object.entries(checkedInputs).map(([k2, v]) => [k2, v.ort_tensor])); + const output = await (0, _backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__.runInferenceSession)(session, ortFeed); + return replaceTensors(output); + } catch (e) { + const formatted = Object.fromEntries(Object.entries(checkedInputs).map(([k2, tensor]) => { + const unpacked = { + type: tensor.type, + dims: tensor.dims, + location: tensor.location + }; + if (unpacked.location !== "gpu-buffer") { + unpacked.data = tensor.data; + } + return [k2, unpacked]; + })); + console.error(`An error occurred during model execution: "${e}".`); + console.error("Inputs given to model:", formatted); + throw e; + } + } + function replaceTensors(obj) { + for (let prop in obj) { + if ((0, _backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__.isONNXTensor)(obj[prop])) { + obj[prop] = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor(obj[prop]); + } else if (typeof obj[prop] === "object") { + replaceTensors(obj[prop]); + } + } + return obj; + } + function toI64Tensor(items) { + if (items instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor) { + return items; + } + if (items.length === 0) { + throw Error("items must be non-empty"); + } + if (Array.isArray(items[0])) { + if (items.some((x) => x.length !== items[0].length)) { + throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length."); + } + return new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor( + "int64", + BigInt64Array.from(items.flat().map((x) => BigInt(x))), + [items.length, items[0].length] + ); + } else { + return new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor( + "int64", + BigInt64Array.from(items.map((x) => BigInt(x))), + [1, items.length] + ); + } + } + function boolTensor(value) { + return new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor("bool", [value], [1]); + } + async function seq2seqForward(self2, model_inputs) { + let { encoder_outputs, input_ids, decoder_input_ids, ...other_decoder_inputs } = model_inputs; + if (!encoder_outputs) { + const encoder_inputs = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_4__.pick)(model_inputs, self2.sessions["model"].inputNames); + encoder_outputs = (await encoderForward(self2, encoder_inputs)).last_hidden_state; + } + other_decoder_inputs.input_ids = decoder_input_ids; + other_decoder_inputs.encoder_hidden_states = encoder_outputs; + if (self2.sessions["decoder_model_merged"].inputNames.includes("encoder_attention_mask")) { + other_decoder_inputs.encoder_attention_mask = model_inputs.attention_mask; + } + const decoderResults = await decoderForward(self2, other_decoder_inputs, true); + return decoderResults; + } + async function encoderForward(self2, model_inputs) { + const session = self2.sessions["model"]; + const encoderFeeds = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_4__.pick)(model_inputs, session.inputNames); + if (session.inputNames.includes("inputs_embeds") && !encoderFeeds.inputs_embeds) { + if (!model_inputs.input_ids) { + throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs."); + } + encoderFeeds.inputs_embeds = await self2.encode_text({ input_ids: model_inputs.input_ids }); + } + if (session.inputNames.includes("token_type_ids") && !encoderFeeds.token_type_ids) { + if (!encoderFeeds.input_ids) { + throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs."); + } + encoderFeeds.token_type_ids = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.zeros_like)(encoderFeeds.input_ids); + } + if (session.inputNames.includes("pixel_mask") && !encoderFeeds.pixel_mask) { + if (!encoderFeeds.pixel_values) { + throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs."); + } + const dims = encoderFeeds.pixel_values.dims; + encoderFeeds.pixel_mask = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.ones)([dims[0], dims[2], dims[3]]); + } + return await sessionRun(session, encoderFeeds); + } + async function autoEncoderForward(self2, model_inputs) { + const encoded = await self2.encode(model_inputs); + const decoded = await self2.decode(encoded); + return decoded; + } + async function decoderForward(self2, model_inputs, is_encoder_decoder = false) { + const session = self2.sessions[is_encoder_decoder ? "decoder_model_merged" : "model"]; + const { past_key_values, ...new_model_inputs } = model_inputs; + if (session.inputNames.includes("use_cache_branch")) { + new_model_inputs.use_cache_branch = boolTensor(!!past_key_values); + } + if (session.inputNames.includes("position_ids") && new_model_inputs.attention_mask && !new_model_inputs.position_ids) { + const start_index = ["paligemma", "gemma3_text", "gemma3"].includes(self2.config.model_type) ? 1 : 0; + new_model_inputs.position_ids = createPositionIds(new_model_inputs, past_key_values, start_index); + } + self2.addPastKeyValues(new_model_inputs, past_key_values); + const fixed = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_4__.pick)(new_model_inputs, session.inputNames); + return await sessionRun(session, fixed); + } + function default_merge_input_ids_with_features({ + modality_token_id, + inputs_embeds, + modality_features, + input_ids, + attention_mask + }) { + const token_positions = input_ids.tolist().map( + (ids) => ids.reduce((acc, x, idx) => { + if (x == modality_token_id) acc.push(idx); + return acc; + }, []) + ); + const n_tokens = token_positions.reduce((acc, x) => acc + x.length, 0); + const n_features = modality_features.dims[0]; + if (n_tokens !== n_features) { + throw new Error(`Number of tokens and features do not match: tokens: ${n_tokens}, features ${n_features}`); + } + let img = 0; + for (let i = 0; i < token_positions.length; ++i) { + const tokens = token_positions[i]; + const embeds = inputs_embeds[i]; + for (let j = 0; j < tokens.length; ++j) { + embeds[tokens[j]].data.set(modality_features[img++].data); + } + } + return { inputs_embeds, attention_mask }; + } + function default_merge_input_ids_with_image_features({ + image_token_id, + inputs_embeds, + image_features, + input_ids, + attention_mask + }) { + return default_merge_input_ids_with_features({ + modality_token_id: image_token_id, + inputs_embeds, + modality_features: image_features, + input_ids, + attention_mask + }); + } + function default_merge_input_ids_with_audio_features({ + audio_token_id, + inputs_embeds, + audio_features, + input_ids, + attention_mask + }) { + return default_merge_input_ids_with_features({ + modality_token_id: audio_token_id, + inputs_embeds, + modality_features: audio_features, + input_ids, + attention_mask + }); + } + async function genericTextToTextForward(self2, { + // Generic parameters: + encode_function, + merge_function, + modality_input_name, + modality_output_name, + // Produced by the tokenizer/processor: + input_ids = null, + attention_mask = null, + // Used during generation: + position_ids = null, + inputs_embeds = null, + past_key_values = null, + // Generic generation parameters + generation_config = null, + logits_processor = null, + // Additional parameters + ...kwargs + }) { + const modality_values = kwargs[modality_input_name]; + if (!inputs_embeds) { + inputs_embeds = await self2.encode_text({ input_ids, ...kwargs }); + if (modality_values && input_ids.dims[1] !== 1) { + const modality_features = await encode_function({ + // Pass the modality values under its expected key. + // The caller knows whether this is audio or image. + [modality_input_name]: modality_values, + ...kwargs + }); + ({ inputs_embeds, attention_mask } = merge_function({ + [modality_output_name]: modality_features, + inputs_embeds, + input_ids, + attention_mask + })); + } else if (past_key_values && modality_values && input_ids.dims[1] === 1) { + const target_length = input_ids.dims[1]; + const past_length = Object.values(past_key_values)[0].dims.at(-2); + attention_mask = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)([ + (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.ones)([input_ids.dims[0], past_length]), + attention_mask.slice(null, [attention_mask.dims[1] - target_length, attention_mask.dims[1]]) + ], 1); + } + } + if (!position_ids) { + if (self2.config.model_type === "qwen2_vl") { + const { image_grid_thw, video_grid_thw } = kwargs; + [position_ids] = self2.get_rope_index(input_ids, image_grid_thw, video_grid_thw, attention_mask); + } + } + const outputs = await decoderForward(self2, { + inputs_embeds, + past_key_values, + attention_mask, + position_ids, + generation_config, + logits_processor + }, true); + return outputs; + } + async function audioTextToTextForward(self2, params) { + return await genericTextToTextForward(self2, { + ...params, + modality_input_name: "audio_values", + modality_output_name: "audio_features", + encode_function: self2.encode_audio.bind(self2), + merge_function: self2._merge_input_ids_with_audio_features.bind(self2) + }); + } + async function imageTextToTextForward(self2, params) { + return await genericTextToTextForward(self2, { + ...params, + modality_input_name: "pixel_values", + modality_output_name: "image_features", + encode_function: self2.encode_image.bind(self2), + merge_function: self2._merge_input_ids_with_image_features.bind(self2) + }); + } + function cumsum_masked_fill(attention_mask, start_index = 0) { + const [bz, seq_len] = attention_mask.dims; + const attn_mask_data = attention_mask.data; + const data = new BigInt64Array(attn_mask_data.length); + for (let i = 0; i < bz; ++i) { + const start = i * seq_len; + let sum = BigInt(start_index); + for (let j = 0; j < seq_len; ++j) { + const index = start + j; + if (attn_mask_data[index] === 0n) { + data[index] = BigInt(1); + } else { + data[index] = sum; + sum += attn_mask_data[index]; + } + } + } + return { data, dims: attention_mask.dims }; + } + function createPositionIds(model_inputs, past_key_values = null, start_index = 0) { + const { input_ids, inputs_embeds, attention_mask } = model_inputs; + const { data, dims } = cumsum_masked_fill(attention_mask, start_index); + let position_ids = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor("int64", data, dims); + if (past_key_values) { + const offset = -(input_ids ?? inputs_embeds).dims.at(1); + position_ids = position_ids.slice(null, [offset, null]); + } + return position_ids; + } + function decoder_prepare_inputs_for_generation(self2, input_ids, model_inputs, generation_config) { + const past_length = model_inputs.past_key_values ? Object.values(model_inputs.past_key_values)[0].dims.at(-2) : 0; + if (!model_inputs.attention_mask) { + let dims; + for (const key of ["input_ids", "inputs_embeds", "position_ids"]) { + if (model_inputs[key]) { + dims = model_inputs[key].dims; + break; + } + } + if (!dims) { + throw new Error("attention_mask is not provided, and unable to infer its shape from model inputs."); + } + model_inputs.attention_mask = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.ones)([dims[0], past_length + dims[1]]); + } + if (model_inputs.past_key_values) { + const { input_ids: input_ids2, attention_mask } = model_inputs; + if (attention_mask && attention_mask.dims[1] > input_ids2.dims[1]) { + } else if (past_length < input_ids2.dims[1]) { + model_inputs.input_ids = input_ids2.slice(null, [past_length, null]); + } else { + } + } + return model_inputs; + } + function encoder_decoder_prepare_inputs_for_generation(self2, input_ids, model_inputs, generation_config) { + if (model_inputs.past_key_values) { + input_ids = input_ids.map((x) => [x.at(-1)]); + } + return { + ...model_inputs, + decoder_input_ids: toI64Tensor(input_ids) + }; + } + function multimodal_text_to_text_prepare_inputs_for_generation(self2, ...args) { + if (self2.config.is_encoder_decoder) { + return encoder_decoder_prepare_inputs_for_generation(self2, ...args); + } else { + return decoder_prepare_inputs_for_generation(self2, ...args); + } + } + function multimodality_prepare_inputs_for_generation(self2, input_ids, model_inputs, generation_config) { + const has_past_key_values = !!model_inputs.past_key_values; + if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) { + if (has_past_key_values) { + model_inputs.input_ids = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)([ + model_inputs.input_ids, + model_inputs.input_ids + ], 0); + } else { + model_inputs.input_ids = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)([ + model_inputs.input_ids, + (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.full_like)(model_inputs.input_ids, BigInt(generation_config.pad_token_id)) + ], 0); + model_inputs.attention_mask = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)([ + model_inputs.attention_mask, + (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.full_like)(model_inputs.attention_mask, 0n) + ], 0); + } + } + if (has_past_key_values || !model_inputs.pixel_values) { + model_inputs.pixel_values = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.full)([0, 0, 3, 384, 384], 1); + } + if (has_past_key_values) { + const num_img_tokens = 0; + const num_text_tokens = 1; + const has_image = num_img_tokens > 0 ? 1 : 0; + const batch_size = 1; + model_inputs.images_seq_mask = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor( + "bool", + new Array(num_img_tokens + num_text_tokens).fill(true).fill(false, 0, num_text_tokens), + [batch_size, num_img_tokens + num_text_tokens] + ); + model_inputs.images_emb_mask = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor( + "bool", + new Array(num_img_tokens).fill(!!has_image), + [batch_size, 1, num_img_tokens] + ); + } + return model_inputs; + } + class PreTrainedModel extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_3__.Callable { + main_input_name = "input_ids"; + forward_params = ["input_ids", "attention_mask"]; + /** + * Creates a new instance of the `PreTrainedModel` class. + * @param {import('./configs.js').PretrainedConfig} config The model configuration. + * @param {Record} sessions The inference sessions for the model. + * @param {Record} configs Additional configuration files (e.g., generation_config.json). + */ + constructor(config, sessions, configs) { + super(); + this.config = config; + this.sessions = sessions; + this.configs = configs; + const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor); + const modelType = MODEL_TYPE_MAPPING.get(modelName); + this.can_generate = false; + this._forward = null; + this._prepare_inputs_for_generation = null; + switch (modelType) { + case MODEL_TYPES.DecoderOnly: + this.can_generate = true; + this._forward = decoderForward; + this._prepare_inputs_for_generation = decoder_prepare_inputs_for_generation; + break; + case MODEL_TYPES.Seq2Seq: + case MODEL_TYPES.Vision2Seq: + case MODEL_TYPES.Musicgen: + this.can_generate = true; + this._forward = seq2seqForward; + this._prepare_inputs_for_generation = encoder_decoder_prepare_inputs_for_generation; + break; + case MODEL_TYPES.EncoderDecoder: + this._forward = seq2seqForward; + break; + case MODEL_TYPES.ImageTextToText: + this.can_generate = true; + this._forward = imageTextToTextForward; + this._prepare_inputs_for_generation = multimodal_text_to_text_prepare_inputs_for_generation; + break; + case MODEL_TYPES.AudioTextToText: + this.can_generate = true; + this._forward = audioTextToTextForward; + this._prepare_inputs_for_generation = multimodal_text_to_text_prepare_inputs_for_generation; + break; + case MODEL_TYPES.Phi3V: + case MODEL_TYPES.ImageAudioTextToText: + this.can_generate = true; + this._prepare_inputs_for_generation = multimodal_text_to_text_prepare_inputs_for_generation; + break; + case MODEL_TYPES.MultiModality: + this.can_generate = true; + this._prepare_inputs_for_generation = multimodality_prepare_inputs_for_generation; + break; + case MODEL_TYPES.AutoEncoder: + this._forward = autoEncoderForward; + break; + default: + this._forward = encoderForward; + break; + } + if (this.can_generate) { + this.forward_params.push("past_key_values"); + } + this.custom_config = this.config["transformers.js_config"] ?? {}; + } + /** + * Disposes of all the ONNX sessions that were created during inference. + * @returns {Promise} An array of promises, one for each ONNX session that is being disposed. + * @todo Use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry + */ + async dispose() { + const promises = []; + for (const session of Object.values(this.sessions)) { + if (session?.handler?.dispose) { + promises.push(session.handler.dispose()); + } + } + return await Promise.all(promises); + } + /** + * Instantiate one of the model classes of the library from a pretrained model. + * + * The model class to instantiate is selected based on the `model_type` property of the config object + * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) + * + * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: + * - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co. + * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a + * user or organization name, like `dbmdz/bert-base-german-cased`. + * - A path to a *directory* containing model weights, e.g., `./my_model_directory/`. + * @param {import('./utils/hub.js').PretrainedModelOptions} options Additional options for loading the model. + * + * @returns {Promise} A new instance of the `PreTrainedModel` class. + */ + static async from_pretrained(pretrained_model_name_or_path, { + progress_callback = null, + config = null, + cache_dir = null, + local_files_only = false, + revision = "main", + model_file_name = null, + subfolder = "onnx", + device = null, + dtype = null, + use_external_data_format = null, + session_options = {} + } = {}) { + let options = { + progress_callback, + config, + cache_dir, + local_files_only, + revision, + model_file_name, + subfolder, + device, + dtype, + use_external_data_format, + session_options + }; + const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this); + const modelType = MODEL_TYPE_MAPPING.get(modelName); + config = options.config = await _configs_js__WEBPACK_IMPORTED_MODULE_0__.AutoConfig.from_pretrained(pretrained_model_name_or_path, options); + let info; + if (modelType === MODEL_TYPES.DecoderOnly) { + info = await Promise.all([ + constructSessions(pretrained_model_name_or_path, { + model: options.model_file_name ?? "model" + }, options), + getOptionalConfigs(pretrained_model_name_or_path, { + generation_config: "generation_config.json" + }, options) + ]); + } else if (modelType === MODEL_TYPES.Seq2Seq || modelType === MODEL_TYPES.Vision2Seq) { + info = await Promise.all([ + constructSessions(pretrained_model_name_or_path, { + model: "encoder_model", + decoder_model_merged: "decoder_model_merged" + }, options), + getOptionalConfigs(pretrained_model_name_or_path, { + generation_config: "generation_config.json" + }, options) + ]); + } else if (modelType === MODEL_TYPES.MaskGeneration) { + info = await Promise.all([ + constructSessions(pretrained_model_name_or_path, { + model: "vision_encoder", + prompt_encoder_mask_decoder: "prompt_encoder_mask_decoder" + }, options) + ]); + } else if (modelType === MODEL_TYPES.EncoderDecoder) { + info = await Promise.all([ + constructSessions(pretrained_model_name_or_path, { + model: "encoder_model", + decoder_model_merged: "decoder_model_merged" + }, options) + ]); + } else if (modelType === MODEL_TYPES.ImageTextToText) { + const sessions = { + embed_tokens: "embed_tokens", + vision_encoder: "vision_encoder", + decoder_model_merged: "decoder_model_merged" + }; + if (config.is_encoder_decoder) { + sessions["model"] = "encoder_model"; + } + info = await Promise.all([ + constructSessions(pretrained_model_name_or_path, sessions, options), + getOptionalConfigs(pretrained_model_name_or_path, { + generation_config: "generation_config.json" + }, options) + ]); + } else if (modelType === MODEL_TYPES.AudioTextToText) { + const sessions = { + embed_tokens: "embed_tokens", + audio_encoder: "audio_encoder", + decoder_model_merged: "decoder_model_merged" + }; + info = await Promise.all([ + constructSessions(pretrained_model_name_or_path, sessions, options), + getOptionalConfigs(pretrained_model_name_or_path, { + generation_config: "generation_config.json" + }, options) + ]); + } else if (modelType === MODEL_TYPES.ImageAudioTextToText) { + const sessions = { + embed_tokens: "embed_tokens", + audio_encoder: "audio_encoder", + vision_encoder: "vision_encoder", + decoder_model_merged: "decoder_model_merged" + }; + info = await Promise.all([ + constructSessions(pretrained_model_name_or_path, sessions, options), + getOptionalConfigs(pretrained_model_name_or_path, { + generation_config: "generation_config.json" + }, options) + ]); + } else if (modelType === MODEL_TYPES.Musicgen) { + info = await Promise.all([ + constructSessions(pretrained_model_name_or_path, { + model: "text_encoder", + decoder_model_merged: "decoder_model_merged", + encodec_decode: "encodec_decode" + }, options), + getOptionalConfigs(pretrained_model_name_or_path, { + generation_config: "generation_config.json" + }, options) + ]); + } else if (modelType === MODEL_TYPES.MultiModality) { + info = await Promise.all([ + constructSessions(pretrained_model_name_or_path, { + prepare_inputs_embeds: "prepare_inputs_embeds", + model: "language_model", + lm_head: "lm_head", + gen_head: "gen_head", + gen_img_embeds: "gen_img_embeds", + image_decode: "image_decode" + }, options), + getOptionalConfigs(pretrained_model_name_or_path, { + generation_config: "generation_config.json" + }, options) + ]); + } else if (modelType === MODEL_TYPES.Phi3V) { + info = await Promise.all([ + constructSessions(pretrained_model_name_or_path, { + prepare_inputs_embeds: "prepare_inputs_embeds", + model: "model", + vision_encoder: "vision_encoder" + }, options), + getOptionalConfigs(pretrained_model_name_or_path, { + generation_config: "generation_config.json" + }, options) + ]); + } else if (modelType === MODEL_TYPES.AutoEncoder) { + info = await Promise.all([ + constructSessions(pretrained_model_name_or_path, { + encoder_model: "encoder_model", + decoder_model: "decoder_model" + }, options) + ]); + } else if (modelType === MODEL_TYPES.Supertonic) { + info = await Promise.all([ + constructSessions(pretrained_model_name_or_path, { + text_encoder: "text_encoder", + latent_denoiser: "latent_denoiser", + voice_decoder: "voice_decoder" + }, options) + ]); + } else { + if (modelType !== MODEL_TYPES.EncoderOnly) { + const type = modelName ?? config?.model_type; + if (type !== "custom") { + console.warn(`Model type for '${type}' not found, assuming encoder-only architecture. Please report this at ${_utils_constants_js__WEBPACK_IMPORTED_MODULE_6__.GITHUB_ISSUE_URL}.`); + } + } + info = await Promise.all([ + constructSessions(pretrained_model_name_or_path, { + model: options.model_file_name ?? "model" + }, options) + ]); + } + return new this(config, ...info); + } + /** + * Runs the model with the provided inputs + * @param {Object} model_inputs Object containing input tensors + * @returns {Promise} Object containing output tensors + */ + async _call(model_inputs) { + return await this.forward(model_inputs); + } + /** + * Forward method for a pretrained model. If not overridden by a subclass, the correct forward method + * will be chosen based on the model type. + * @param {Object} model_inputs The input data to the model in the format specified in the ONNX model. + * @returns {Promise} The output data from the model in the format specified in the ONNX model. + * @throws {Error} This method must be implemented in subclasses. + */ + async forward(model_inputs) { + return await this._forward(this, model_inputs); + } + /** + * Get the model's generation config, if it exists. + * @returns {GenerationConfig|null} The model's generation config if it exists, otherwise `null`. + */ + get generation_config() { + return this.configs?.generation_config ?? null; + } + /** + * @param {GenerationConfig} generation_config + * @param {number} input_ids_seq_length The starting sequence length for the input ids. + * @returns {LogitsProcessorList} + * @private + */ + _get_logits_processor(generation_config, input_ids_seq_length, logits_processor = null) { + const processors = new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.LogitsProcessorList(); + if (generation_config.repetition_penalty !== null && generation_config.repetition_penalty !== 1) { + processors.push(new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.RepetitionPenaltyLogitsProcessor(generation_config.repetition_penalty)); + } + if (generation_config.no_repeat_ngram_size !== null && generation_config.no_repeat_ngram_size > 0) { + processors.push(new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.NoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size)); + } + if (generation_config.bad_words_ids !== null) { + processors.push(new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.NoBadWordsLogitsProcessor(generation_config.bad_words_ids, generation_config.eos_token_id)); + } + if (generation_config.min_length !== null && generation_config.eos_token_id !== null && generation_config.min_length > 0) { + processors.push(new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.MinLengthLogitsProcessor(generation_config.min_length, generation_config.eos_token_id)); + } + if (generation_config.min_new_tokens !== null && generation_config.eos_token_id !== null && generation_config.min_new_tokens > 0) { + processors.push(new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.MinNewTokensLengthLogitsProcessor( + input_ids_seq_length, + generation_config.min_new_tokens, + generation_config.eos_token_id + )); + } + if (generation_config.forced_bos_token_id !== null) { + processors.push(new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.ForcedBOSTokenLogitsProcessor(generation_config.forced_bos_token_id)); + } + if (generation_config.forced_eos_token_id !== null) { + processors.push(new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.ForcedEOSTokenLogitsProcessor( + generation_config.max_length, + generation_config.forced_eos_token_id + )); + } + if (generation_config.begin_suppress_tokens !== null) { + const begin_index = input_ids_seq_length > 1 || generation_config.forced_bos_token_id === null ? input_ids_seq_length : input_ids_seq_length + 1; + processors.push(new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, begin_index)); + } + if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) { + processors.push(new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.ClassifierFreeGuidanceLogitsProcessor(generation_config.guidance_scale)); + } + if (generation_config.temperature === 0 && generation_config.do_sample) { + console.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."); + generation_config.do_sample = false; + } + if (generation_config.do_sample) { + if (generation_config.temperature !== null && generation_config.temperature !== 1) { + processors.push(new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.TemperatureLogitsWarper(generation_config.temperature)); + } + } + if (logits_processor !== null) { + processors.extend(logits_processor); + } + return processors; + } + /** + * This function merges multiple generation configs together to form a final generation config to be used by the model for text generation. + * It first creates an empty `GenerationConfig` object, then it applies the model's own `generation_config` property to it. Finally, if a `generation_config` object was passed in the arguments, it overwrites the corresponding properties in the final config with those of the passed config object. + * @param {GenerationConfig|null} generation_config A `GenerationConfig` object containing generation parameters. + * @param {Object} kwargs Additional generation parameters to be used in place of those in the `generation_config` object. + * @returns {GenerationConfig} The final generation config object to be used by the model for text generation. + */ + _prepare_generation_config(generation_config, kwargs, cls = _generation_configuration_utils_js__WEBPACK_IMPORTED_MODULE_8__.GenerationConfig) { + const config = { ...this.config }; + for (const key of ["decoder", "generator", "text_config"]) { + if (key in config) { + Object.assign(config, config[key]); + } + } + const gen_config = new cls(config); + Object.assign(gen_config, this.generation_config ?? {}); + if (generation_config) { + Object.assign(gen_config, generation_config); + } + if (kwargs) { + Object.assign(gen_config, (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_4__.pick)(kwargs, Object.getOwnPropertyNames(gen_config))); + } + return gen_config; + } + /** + * + * @param {GenerationConfig} generation_config + * @param {StoppingCriteriaList} [stopping_criteria=null] + */ + _get_stopping_criteria(generation_config, stopping_criteria = null) { + const criteria = new _generation_stopping_criteria_js__WEBPACK_IMPORTED_MODULE_12__.StoppingCriteriaList(); + if (generation_config.max_length !== null) { + criteria.push(new _generation_stopping_criteria_js__WEBPACK_IMPORTED_MODULE_12__.MaxLengthCriteria( + generation_config.max_length, + this.config.max_position_embeddings ?? null + )); + } + if (generation_config.eos_token_id !== null) { + criteria.push(new _generation_stopping_criteria_js__WEBPACK_IMPORTED_MODULE_12__.EosTokenCriteria(generation_config.eos_token_id)); + } + if (stopping_criteria) { + criteria.extend(stopping_criteria); + } + return criteria; + } + /** + * Confirms that the model class is compatible with generation. + * If not, raises an exception that points to the right class to use. + */ + _validate_model_class() { + if (!this.can_generate) { + const generate_compatible_mappings = [ + MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, + // MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING, // TODO + MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES, + MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, + MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES + ]; + const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor); + const generate_compatible_classes = /* @__PURE__ */ new Set(); + const modelType = this.config.model_type; + for (const model_mapping of generate_compatible_mappings) { + const supported_models = model_mapping.get(modelType); + if (supported_models) { + generate_compatible_classes.add(supported_models[0]); + } + } + let errorMessage = `The current model class (${modelName}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`; + if (generate_compatible_classes.size > 0) { + errorMessage += ` Please use the following class instead: ${[...generate_compatible_classes].join(", ")}`; + } + throw Error(errorMessage); + } + } + prepare_inputs_for_generation(...args) { + return this._prepare_inputs_for_generation(this, ...args); + } + /** + * + * @param {Object} inputs + * @param {bigint[][]} inputs.generated_input_ids + * @param {Object} inputs.outputs + * @param {Object} inputs.model_inputs + * @param {boolean} inputs.is_encoder_decoder + * @returns {Object} The updated model inputs for the next generation iteration. + */ + _update_model_kwargs_for_generation({ generated_input_ids, outputs, model_inputs, is_encoder_decoder }) { + model_inputs["past_key_values"] = this.getPastKeyValues(outputs, model_inputs.past_key_values); + model_inputs["input_ids"] = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor("int64", generated_input_ids.flat(), [generated_input_ids.length, 1]); + if (!is_encoder_decoder) { + model_inputs.attention_mask = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)( + [ + model_inputs.attention_mask, + (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.ones)([model_inputs.attention_mask.dims[0], 1]) + ], + 1 + ); + } else if ("decoder_attention_mask" in model_inputs) { + } + model_inputs["position_ids"] = null; + return model_inputs; + } + /** + * This function extracts the model-specific `inputs` for generation. + * @param {Object} params + * @param {Tensor} [params.inputs=null] + * @param {number} [params.bos_token_id=null] + * @param {Record} [params.model_kwargs] + * @returns {{inputs_tensor: Tensor, model_inputs: Record, model_input_name: string}} The model-specific inputs for generation. + */ + _prepare_model_inputs({ inputs, bos_token_id, model_kwargs }) { + const model_inputs = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_4__.pick)(model_kwargs, this.forward_params); + const input_name = this.main_input_name; + if (input_name in model_inputs) { + if (inputs) { + throw new Error( + "`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=..." + ); + } + } else { + model_inputs[input_name] = inputs; + } + const inputs_tensor = model_inputs[input_name]; + return { inputs_tensor, model_inputs, model_input_name: input_name }; + } + async _prepare_encoder_decoder_kwargs_for_generation({ inputs_tensor, model_inputs, model_input_name, generation_config }) { + if (this.sessions["model"].inputNames.includes("inputs_embeds") && !model_inputs.inputs_embeds && "_prepare_inputs_embeds" in this) { + const { input_ids, pixel_values, attention_mask, ...kwargs } = model_inputs; + const prepared_inputs = await this._prepare_inputs_embeds(model_inputs); + model_inputs = { + ...kwargs, + ...(0, _utils_core_js__WEBPACK_IMPORTED_MODULE_4__.pick)(prepared_inputs, ["inputs_embeds", "attention_mask"]) + }; + } + let { last_hidden_state } = await encoderForward(this, model_inputs); + if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) { + last_hidden_state = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)([ + last_hidden_state, + (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.full_like)(last_hidden_state, 0) + ], 0); + if ("attention_mask" in model_inputs) { + model_inputs["attention_mask"] = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)([ + model_inputs["attention_mask"], + (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.zeros_like)(model_inputs["attention_mask"]) + ], 0); + } + } else if (model_inputs.decoder_input_ids) { + const decoder_input_ids_batch_size = toI64Tensor(model_inputs.decoder_input_ids).dims[0]; + if (decoder_input_ids_batch_size !== last_hidden_state.dims[0]) { + if (last_hidden_state.dims[0] !== 1) { + throw new Error( + `The encoder outputs have a different batch size (${last_hidden_state.dims[0]}) than the decoder inputs (${decoder_input_ids_batch_size}).` + ); + } + last_hidden_state = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)(Array.from({ length: decoder_input_ids_batch_size }, () => last_hidden_state), 0); + } + } + model_inputs["encoder_outputs"] = last_hidden_state; + return model_inputs; + } + /** + * Prepares `decoder_input_ids` for generation with encoder-decoder models + * @param {*} param0 + */ + _prepare_decoder_input_ids_for_generation({ batch_size, model_input_name, model_kwargs, decoder_start_token_id, bos_token_id, generation_config }) { + let { decoder_input_ids, ...model_inputs } = model_kwargs; + if (!(decoder_input_ids instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor)) { + if (!decoder_input_ids) { + decoder_start_token_id ??= bos_token_id; + if (this.config.model_type === "musicgen") { + decoder_input_ids = Array.from({ + // @ts-expect-error TS2339 + length: batch_size * this.config.decoder.num_codebooks + }, () => [decoder_start_token_id]); + } else if (Array.isArray(decoder_start_token_id)) { + if (decoder_start_token_id.length !== batch_size) { + throw new Error( + `\`decoder_start_token_id\` expcted to have length ${batch_size} but got ${decoder_start_token_id.length}` + ); + } + decoder_input_ids = decoder_start_token_id; + } else { + decoder_input_ids = Array.from({ + length: batch_size + }, () => [decoder_start_token_id]); + } + } else if (!Array.isArray(decoder_input_ids[0])) { + decoder_input_ids = Array.from({ + length: batch_size + }, () => decoder_input_ids); + } + decoder_input_ids = toI64Tensor(decoder_input_ids); + } + model_kwargs["decoder_attention_mask"] = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.ones_like)(decoder_input_ids); + return { input_ids: decoder_input_ids, model_inputs }; + } + /** + * Generates sequences of token ids for models with a language modeling head. + * @param {import('./generation/parameters.js').GenerationFunctionParameters} options + * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores. + */ + async generate({ + inputs = null, + generation_config = null, + logits_processor = null, + stopping_criteria = null, + streamer = null, + // inputs_attention_mask = null, + ...kwargs + }) { + this._validate_model_class(); + generation_config = this._prepare_generation_config(generation_config, kwargs); + let { inputs_tensor, model_inputs, model_input_name } = this._prepare_model_inputs({ + inputs, + model_kwargs: kwargs + }); + const is_encoder_decoder = this.config.is_encoder_decoder; + if (!is_encoder_decoder) { + } else if (!("encoder_outputs" in model_inputs)) { + model_inputs = await this._prepare_encoder_decoder_kwargs_for_generation( + { inputs_tensor, model_inputs, model_input_name, generation_config } + ); + } + let input_ids; + if (is_encoder_decoder) { + ({ input_ids, model_inputs } = this._prepare_decoder_input_ids_for_generation({ + batch_size: model_inputs[model_input_name].dims.at(0), + model_input_name, + model_kwargs: model_inputs, + decoder_start_token_id: generation_config.decoder_start_token_id, + bos_token_id: generation_config.bos_token_id, + generation_config + })); + } else { + input_ids = model_inputs[model_input_name]; + } + let input_ids_length = input_ids.dims.at(-1); + if (generation_config.max_new_tokens !== null) { + generation_config.max_length = input_ids_length + generation_config.max_new_tokens; + } + const prepared_logits_processor = this._get_logits_processor( + generation_config, + input_ids_length, + logits_processor + ); + const prepared_stopping_criteria = this._get_stopping_criteria( + generation_config, + stopping_criteria + ); + const numInputs = model_inputs[model_input_name].dims.at(0); + const sampler = _generation_logits_sampler_js__WEBPACK_IMPORTED_MODULE_13__.LogitsSampler.getSampler(generation_config); + const scores = new Array(numInputs).fill(0); + const all_input_ids = input_ids.tolist(); + if (streamer) { + streamer.put(all_input_ids); + } + let outputs; + let attentions = {}; + while (true) { + model_inputs = this.prepare_inputs_for_generation(all_input_ids, model_inputs, generation_config); + outputs = await this.forward(model_inputs); + if (generation_config.output_attentions && generation_config.return_dict_in_generate) { + const token_attentions = this.getAttentions(outputs); + for (const key in token_attentions) { + if (!(key in attentions)) { + attentions[key] = []; + } + attentions[key].push(token_attentions[key]); + } + } + const logits = outputs.logits.slice(null, -1, null); + const next_tokens_scores = prepared_logits_processor(all_input_ids, logits); + const generated_input_ids = []; + for (let batch_idx = 0; batch_idx < next_tokens_scores.dims.at(0); ++batch_idx) { + const logs = next_tokens_scores[batch_idx]; + const sampledTokens = await sampler(logs); + for (const [newTokenId, logProb] of sampledTokens) { + const bigint = BigInt(newTokenId); + scores[batch_idx] += logProb; + all_input_ids[batch_idx].push(bigint); + generated_input_ids.push([bigint]); + break; + } + } + if (streamer) { + streamer.put(generated_input_ids); + } + const stop = prepared_stopping_criteria(all_input_ids); + if (stop.every((x) => x)) { + break; + } + model_inputs = this._update_model_kwargs_for_generation({ + generated_input_ids, + outputs, + model_inputs, + is_encoder_decoder + }); + } + if (streamer) { + streamer.end(); + } + const past_key_values = this.getPastKeyValues(outputs, model_inputs.past_key_values, true); + const sequences = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor("int64", all_input_ids.flat(), [all_input_ids.length, all_input_ids[0].length]); + if (generation_config.return_dict_in_generate) { + return { + sequences, + past_key_values, + ...attentions + // TODO: + // scores, + // logits, + }; + } else { + for (const tensor of Object.values(outputs)) { + if (tensor.location === "gpu-buffer") { + tensor.dispose(); + } + } + return sequences; + } + } + /** + * Returns an object containing past key values from the given decoder results object. + * + * @param {Object} decoderResults The decoder results object. + * @param {Object} pastKeyValues The previous past key values. + * @returns {Object} An object containing past key values. + */ + getPastKeyValues(decoderResults, pastKeyValues, disposeEncoderPKVs = false) { + const pkvs = /* @__PURE__ */ Object.create(null); + for (const name in decoderResults) { + if (name.startsWith("present")) { + const newName = name.replace("present_conv", "past_conv").replace("present", "past_key_values"); + const is_encoder_pkv = name.includes("encoder"); + if (is_encoder_pkv && pastKeyValues) { + pkvs[newName] = pastKeyValues[newName]; + } else { + pkvs[newName] = decoderResults[name]; + } + if (pastKeyValues && (!is_encoder_pkv || disposeEncoderPKVs)) { + const t = pastKeyValues[newName]; + if (t.location === "gpu-buffer") { + t.dispose(); + } + } + } + } + return pkvs; + } + /** + * Returns an object containing attentions from the given model output object. + * + * @param {Object} model_output The output of the model. + * @returns {{cross_attentions?: Tensor[]}} An object containing attentions. + */ + getAttentions(model_output) { + const attentions = {}; + for (const attnName of ["cross_attentions", "encoder_attentions", "decoder_attentions"]) { + for (const name in model_output) { + if (name.startsWith(attnName)) { + if (!(attnName in attentions)) { + attentions[attnName] = []; + } + attentions[attnName].push(model_output[name]); + } + } + } + return attentions; + } + /** + * Adds past key values to the decoder feeds object. If pastKeyValues is null, creates new tensors for past key values. + * + * @param {Object} decoderFeeds The decoder feeds object to add past key values to. + * @param {Object} pastKeyValues An object containing past key values. + */ + addPastKeyValues(decoderFeeds, pastKeyValues) { + if (pastKeyValues) { + Object.assign(decoderFeeds, pastKeyValues); + } else { + const session = this.sessions["decoder_model_merged"] ?? this.sessions["model"]; + const batch_size = (decoderFeeds[this.main_input_name] ?? decoderFeeds.attention_mask)?.dims?.[0] ?? 1; + const dtype = session?.config?.kv_cache_dtype ?? "float32"; + const cls = dtype === "float16" ? _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.DataTypeMap.float16 : _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.DataTypeMap.float32; + const shapes = (0, _configs_js__WEBPACK_IMPORTED_MODULE_0__.getCacheShapes)(this.config, { batch_size }); + for (const name in shapes) { + const size = shapes[name].reduce((a, b) => a * b, 1); + decoderFeeds[name] = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor(dtype, new cls(size), shapes[name]); + } + } + } + async encode_image({ pixel_values }) { + return (await sessionRun(this.sessions["vision_encoder"], { pixel_values })).image_features; + } + async encode_text({ input_ids }) { + return (await sessionRun(this.sessions["embed_tokens"], { input_ids })).inputs_embeds; + } + async encode_audio({ audio_values }) { + return (await sessionRun(this.sessions["audio_encoder"], { audio_values })).audio_features; + } + } + class ModelOutput { + } + class BaseModelOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.last_hidden_state Sequence of hidden-states at the output of the last layer of the model. + * @param {Tensor} [output.hidden_states] Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. + * @param {Tensor} [output.attentions] Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. + */ + constructor({ last_hidden_state, hidden_states = null, attentions = null }) { + super(); + this.last_hidden_state = last_hidden_state; + this.hidden_states = hidden_states; + this.attentions = attentions; + } + } + class BertPreTrainedModel extends PreTrainedModel { + } + class BertModel extends BertPreTrainedModel { + } + class BertForMaskedLM extends BertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } + } + class BertForSequenceClassification extends BertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class BertForTokenClassification extends BertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } + } + class BertForQuestionAnswering extends BertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } + } + class NeoBertPreTrainedModel extends PreTrainedModel { + } + class NeoBertModel extends NeoBertPreTrainedModel { + } + class NeoBertForMaskedLM extends NeoBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } + } + class NeoBertForSequenceClassification extends NeoBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class NeoBertForTokenClassification extends NeoBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } + } + class NeoBertForQuestionAnswering extends NeoBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } + } + class ModernBertPreTrainedModel extends PreTrainedModel { + } + class ModernBertModel extends ModernBertPreTrainedModel { + } + class ModernBertForMaskedLM extends ModernBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } + } + class ModernBertForSequenceClassification extends ModernBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class ModernBertForTokenClassification extends ModernBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } + } + class ModernBertDecoderPreTrainedModel extends PreTrainedModel { + } + class ModernBertDecoderModel extends ModernBertDecoderPreTrainedModel { + } + class ModernBertDecoderForCausalLM extends ModernBertDecoderPreTrainedModel { + } + class NomicBertPreTrainedModel extends PreTrainedModel { + } + class NomicBertModel extends NomicBertPreTrainedModel { + } + class RoFormerPreTrainedModel extends PreTrainedModel { + } + class RoFormerModel extends RoFormerPreTrainedModel { + } + class RoFormerForMaskedLM extends RoFormerPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } + } + class RoFormerForSequenceClassification extends RoFormerPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class RoFormerForTokenClassification extends RoFormerPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } + } + class RoFormerForQuestionAnswering extends RoFormerPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } + } + class ConvBertPreTrainedModel extends PreTrainedModel { + } + class ConvBertModel extends ConvBertPreTrainedModel { + } + class ConvBertForMaskedLM extends ConvBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } + } + class ConvBertForSequenceClassification extends ConvBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class ConvBertForTokenClassification extends ConvBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } + } + class ConvBertForQuestionAnswering extends ConvBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } + } + class ElectraPreTrainedModel extends PreTrainedModel { + } + class ElectraModel extends ElectraPreTrainedModel { + } + class ElectraForMaskedLM extends ElectraPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } + } + class ElectraForSequenceClassification extends ElectraPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class ElectraForTokenClassification extends ElectraPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } + } + class ElectraForQuestionAnswering extends ElectraPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } + } + class CamembertPreTrainedModel extends PreTrainedModel { + } + class CamembertModel extends CamembertPreTrainedModel { + } + class CamembertForMaskedLM extends CamembertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } + } + class CamembertForSequenceClassification extends CamembertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class CamembertForTokenClassification extends CamembertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } + } + class CamembertForQuestionAnswering extends CamembertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } + } + class DebertaPreTrainedModel extends PreTrainedModel { + } + class DebertaModel extends DebertaPreTrainedModel { + } + class DebertaForMaskedLM extends DebertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } + } + class DebertaForSequenceClassification extends DebertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class DebertaForTokenClassification extends DebertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } + } + class DebertaForQuestionAnswering extends DebertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } + } + class DebertaV2PreTrainedModel extends PreTrainedModel { + } + class DebertaV2Model extends DebertaV2PreTrainedModel { + } + class DebertaV2ForMaskedLM extends DebertaV2PreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } + } + class DebertaV2ForSequenceClassification extends DebertaV2PreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class DebertaV2ForTokenClassification extends DebertaV2PreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } + } + class DebertaV2ForQuestionAnswering extends DebertaV2PreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } + } + class DistilBertPreTrainedModel extends PreTrainedModel { + } + class DistilBertModel extends DistilBertPreTrainedModel { + } + class DistilBertForSequenceClassification extends DistilBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class DistilBertForTokenClassification extends DistilBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } + } + class DistilBertForQuestionAnswering extends DistilBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } + } + class DistilBertForMaskedLM extends DistilBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } + } + class EsmPreTrainedModel extends PreTrainedModel { + } + class EsmModel extends EsmPreTrainedModel { + } + class EsmForMaskedLM extends EsmPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } + } + class EsmForSequenceClassification extends EsmPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class EsmForTokenClassification extends EsmPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } + } + class MobileBertPreTrainedModel extends PreTrainedModel { + } + class MobileBertModel extends MobileBertPreTrainedModel { + } + class MobileBertForMaskedLM extends MobileBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } + } + class MobileBertForSequenceClassification extends MobileBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class MobileBertForQuestionAnswering extends MobileBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } + } + class MPNetPreTrainedModel extends PreTrainedModel { + } + class MPNetModel extends MPNetPreTrainedModel { + } + class MPNetForMaskedLM extends MPNetPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } + } + class MPNetForSequenceClassification extends MPNetPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class MPNetForTokenClassification extends MPNetPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } + } + class MPNetForQuestionAnswering extends MPNetPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } + } + class SqueezeBertPreTrainedModel extends PreTrainedModel { + } + class SqueezeBertModel extends SqueezeBertPreTrainedModel { + } + class SqueezeBertForMaskedLM extends SqueezeBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } + } + class SqueezeBertForSequenceClassification extends SqueezeBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class SqueezeBertForQuestionAnswering extends SqueezeBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } + } + class AlbertPreTrainedModel extends PreTrainedModel { + } + class AlbertModel extends AlbertPreTrainedModel { + } + class AlbertForSequenceClassification extends AlbertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class AlbertForQuestionAnswering extends AlbertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } + } + class AlbertForMaskedLM extends AlbertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } + } + class T5PreTrainedModel extends PreTrainedModel { + forward_params = [ + "input_ids", + "attention_mask", + "encoder_outputs", + "decoder_input_ids", + "decoder_attention_mask", + "past_key_values" + ]; + } + ; + class T5Model extends T5PreTrainedModel { + } + class T5ForConditionalGeneration extends T5PreTrainedModel { + } + class LongT5PreTrainedModel extends PreTrainedModel { + } + ; + class LongT5Model extends LongT5PreTrainedModel { + } + class LongT5ForConditionalGeneration extends LongT5PreTrainedModel { + } + class MT5PreTrainedModel extends PreTrainedModel { + } + ; + class MT5Model extends MT5PreTrainedModel { + } + class MT5ForConditionalGeneration extends MT5PreTrainedModel { + } + class BartPretrainedModel extends PreTrainedModel { + } + ; + class BartModel extends BartPretrainedModel { + } + class BartForConditionalGeneration extends BartPretrainedModel { + } + class BartForSequenceClassification extends BartPretrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class MBartPreTrainedModel extends PreTrainedModel { + } + ; + class MBartModel extends MBartPreTrainedModel { + } + class MBartForConditionalGeneration extends MBartPreTrainedModel { + } + class MBartForSequenceClassification extends MBartPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class MBartForCausalLM extends MBartPreTrainedModel { + } + class BlenderbotPreTrainedModel extends PreTrainedModel { + } + ; + class BlenderbotModel extends BlenderbotPreTrainedModel { + } + class BlenderbotForConditionalGeneration extends BlenderbotPreTrainedModel { + } + class BlenderbotSmallPreTrainedModel extends PreTrainedModel { + } + ; + class BlenderbotSmallModel extends BlenderbotSmallPreTrainedModel { + } + class BlenderbotSmallForConditionalGeneration extends BlenderbotSmallPreTrainedModel { + } + class RobertaPreTrainedModel extends PreTrainedModel { + } + class RobertaModel extends RobertaPreTrainedModel { + } + class RobertaForMaskedLM extends RobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } + } + class RobertaForSequenceClassification extends RobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class RobertaForTokenClassification extends RobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } + } + class RobertaForQuestionAnswering extends RobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } + } + class XLMPreTrainedModel extends PreTrainedModel { + } + class XLMModel extends XLMPreTrainedModel { + } + class XLMWithLMHeadModel extends XLMPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } + } + class XLMForSequenceClassification extends XLMPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class XLMForTokenClassification extends XLMPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } + } + class XLMForQuestionAnswering extends XLMPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } + } + class XLMRobertaPreTrainedModel extends PreTrainedModel { + } + class XLMRobertaModel extends XLMRobertaPreTrainedModel { + } + class XLMRobertaForMaskedLM extends XLMRobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } + } + class XLMRobertaForSequenceClassification extends XLMRobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class XLMRobertaForTokenClassification extends XLMRobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } + } + class XLMRobertaForQuestionAnswering extends XLMRobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } + } + class ASTPreTrainedModel extends PreTrainedModel { + } + ; + class ASTModel extends ASTPreTrainedModel { + } + class ASTForAudioClassification extends ASTPreTrainedModel { + } + class WhisperPreTrainedModel extends PreTrainedModel { + requires_attention_mask = false; + main_input_name = "input_features"; + forward_params = [ + "input_features", + "attention_mask", + "decoder_input_ids", + "decoder_attention_mask", + "past_key_values" + ]; + } + ; + class WhisperModel extends WhisperPreTrainedModel { + } + class WhisperForConditionalGeneration extends WhisperPreTrainedModel { + _prepare_generation_config(generation_config, kwargs) { + return ( + /** @type {WhisperGenerationConfig} */ + super._prepare_generation_config(generation_config, kwargs, _models_whisper_generation_whisper_js__WEBPACK_IMPORTED_MODULE_15__.WhisperGenerationConfig) + ); + } + /** + * + * @param {WhisperGenerationConfig} generation_config + */ + _retrieve_init_tokens(generation_config) { + const init_tokens = [generation_config.decoder_start_token_id]; + let language = generation_config.language; + const task = generation_config.task; + if (generation_config.is_multilingual) { + if (!language) { + console.warn("No language specified - defaulting to English (en)."); + language = "en"; + } + const language_code = (0, _models_whisper_common_whisper_js__WEBPACK_IMPORTED_MODULE_16__.whisper_language_to_code)(language); + const language_token = `<|${language_code}|>`; + init_tokens.push(generation_config.lang_to_id[language_token]); + init_tokens.push(generation_config.task_to_id[task ?? "transcribe"]); + } else if (language || task) { + throw new Error( + "Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config." + ); + } + if (!generation_config.return_timestamps && generation_config.no_timestamps_token_id && init_tokens.at(-1) !== generation_config.no_timestamps_token_id) { + init_tokens.push(generation_config.no_timestamps_token_id); + } else if (generation_config.return_timestamps && init_tokens.at(-1) === generation_config.no_timestamps_token_id) { + console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."); + init_tokens.pop(); + } + return init_tokens.filter((token) => token != null); + } + /** + * Transcribes or translates log-mel input features to a sequence of auto-regressively generated token ids. + * @param {import('./models/whisper/generation_whisper.js').WhisperGenerationFunctionParameters} options + * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores. + */ + async generate({ + inputs = null, + generation_config = null, + logits_processor = null, + stopping_criteria = null, + // Whisper-specific options (passed to kwargs) + // prompt_ids = null, + // language = null, + // task = null, + ...kwargs + }) { + generation_config = this._prepare_generation_config(generation_config, kwargs); + const init_tokens = kwargs.decoder_input_ids ?? this._retrieve_init_tokens(generation_config); + if (generation_config.return_timestamps) { + logits_processor ??= new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.LogitsProcessorList(); + logits_processor.push( + new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.WhisperTimeStampLogitsProcessor(generation_config, init_tokens) + ); + } + if (generation_config.begin_suppress_tokens) { + logits_processor ??= new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.LogitsProcessorList(); + logits_processor.push( + new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, init_tokens.length) + ); + } + if (generation_config.return_token_timestamps) { + if (!generation_config.alignment_heads) { + throw new Error( + "Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config." + ); + } + if (generation_config.task === "translate") { + console.warn("Token-level timestamps may not be reliable for task 'translate'."); + } + generation_config.output_attentions = true; + generation_config.return_dict_in_generate = true; + } + const outputs = await super.generate({ + inputs, + generation_config, + logits_processor, + decoder_input_ids: init_tokens, + ...kwargs + }); + if (generation_config.return_token_timestamps) { + outputs["token_timestamps"] = this._extract_token_timestamps( + // @ts-expect-error TS2345 + outputs, + generation_config.alignment_heads, + generation_config.num_frames + ); + } + return outputs; + } + /** + * Calculates token-level timestamps using the encoder-decoder cross-attentions and + * dynamic time-warping (DTW) to map each output token to a position in the input audio. + * If `num_frames` is specified, the encoder-decoder cross-attentions will be cropped before applying DTW. + * @param {Object} generate_outputs Outputs generated by the model + * @param {Tensor[][]} generate_outputs.cross_attentions The cross attentions output by the model + * @param {Tensor} generate_outputs.sequences The sequences output by the model + * @param {number[][]} alignment_heads Alignment heads of the model + * @param {number} [num_frames=null] Number of frames in the input audio. + * @param {number} [time_precision=0.02] Precision of the timestamps in seconds + * @returns {Tensor} tensor containing the timestamps in seconds for each predicted token + */ + _extract_token_timestamps(generate_outputs, alignment_heads, num_frames = null, time_precision = 0.02) { + if (!generate_outputs.cross_attentions) { + throw new Error( + "Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`." + ); + } + if (num_frames == null) { + console.warn( + "`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds)." + ); + } + let median_filter_width = this.config.median_filter_width; + if (median_filter_width === void 0) { + console.warn("Model config has no `median_filter_width`, using default value of 7."); + median_filter_width = 7; + } + const batch = generate_outputs.cross_attentions; + const cross_attentions = Array.from( + { length: this.config.decoder_layers }, + // Concatenate the cross attentions for each layer across sequence length dimension. + (_, i) => (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)(batch.map((x) => x[i]), 2) + ); + const weights = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.stack)(alignment_heads.map(([l, h]) => { + if (l >= cross_attentions.length) { + throw new Error(`Layer index ${l} is out of bounds for cross attentions (length ${cross_attentions.length}).`); + } + return num_frames ? cross_attentions[l].slice(null, h, null, [0, num_frames]) : cross_attentions[l].slice(null, h); + })).transpose(1, 0, 2, 3); + const [std, calculatedMean] = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.std_mean)(weights, -2, 0, true); + const smoothedWeights = weights.clone(); + for (let a = 0; a < smoothedWeights.dims[0]; ++a) { + const aTensor = smoothedWeights[a]; + for (let b = 0; b < aTensor.dims[0]; ++b) { + const bTensor = aTensor[b]; + const stdTensorData = std[a][b][0].data; + const meanTensorData = calculatedMean[a][b][0].data; + for (let c = 0; c < bTensor.dims[0]; ++c) { + let cTensorData = bTensor[c].data; + for (let d = 0; d < cTensorData.length; ++d) { + cTensorData[d] = (cTensorData[d] - meanTensorData[d]) / stdTensorData[d]; + } + cTensorData.set((0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_11__.medianFilter)(cTensorData, median_filter_width)); + } + } + } + const batchedMatrices = [(0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.mean)(smoothedWeights, 1)]; + const timestampsShape = generate_outputs.sequences.dims; + const timestamps = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor( + "float32", + new Float32Array(timestampsShape[0] * timestampsShape[1]), + timestampsShape + ); + for (let batch_idx = 0; batch_idx < timestampsShape[0]; ++batch_idx) { + const matrix = batchedMatrices[batch_idx].neg().squeeze_(0); + const [text_indices, time_indices] = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_11__.dynamic_time_warping)(matrix.tolist()); + const diffs = Array.from({ length: text_indices.length - 1 }, (v, i) => text_indices[i + 1] - text_indices[i]); + const jumps = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_4__.mergeArrays)([1], diffs).map((x) => !!x); + const jump_times = []; + for (let i = 0; i < jumps.length; ++i) { + if (jumps[i]) { + jump_times.push(time_indices[i] * time_precision); + } + } + timestamps[batch_idx].data.set(jump_times, 1); + } + return timestamps; + } + } + class LiteWhisperForConditionalGeneration extends WhisperForConditionalGeneration { + } + class MoonshinePreTrainedModel extends PreTrainedModel { + requires_attention_mask = false; + main_input_name = "input_values"; + forward_params = [ + "input_values", + "decoder_input_ids", + "past_key_values" + ]; + } + ; + class MoonshineModel extends MoonshinePreTrainedModel { + } + class MoonshineForConditionalGeneration extends MoonshinePreTrainedModel { + } + class VisionEncoderDecoderModel extends PreTrainedModel { + main_input_name = "pixel_values"; + forward_params = [ + // Encoder inputs + "pixel_values", + // Decoder inpputs + "decoder_input_ids", + "encoder_hidden_states", + "past_key_values" + ]; + } + class LlavaPreTrainedModel extends PreTrainedModel { + forward_params = [ + "input_ids", + "attention_mask", + "pixel_values", + "position_ids", + "past_key_values" + ]; + } + class LlavaForConditionalGeneration extends LlavaPreTrainedModel { + _merge_input_ids_with_image_features(kwargs) { + const vision_hidden_size = kwargs.image_features.dims.at(-1); + const reshaped_image_hidden_states = kwargs.image_features.view(-1, vision_hidden_size); + return default_merge_input_ids_with_image_features({ + // @ts-ignore + image_token_id: this.config.image_token_index, + ...kwargs, + image_features: reshaped_image_hidden_states + }); + } + } + class LlavaOnevisionForConditionalGeneration extends LlavaForConditionalGeneration { + } + class Moondream1ForConditionalGeneration extends LlavaForConditionalGeneration { + } + class Florence2PreTrainedModel extends PreTrainedModel { + forward_params = [ + // Encoder inputs + "input_ids", + "inputs_embeds", + "attention_mask", + "pixel_values", + // Decoder inputs + "encoder_outputs", + "decoder_input_ids", + "decoder_inputs_embeds", + "decoder_attention_mask", + "past_key_values" + ]; + main_input_name = "inputs_embeds"; + } + class Florence2ForConditionalGeneration extends Florence2PreTrainedModel { + _merge_input_ids_with_image_features({ + inputs_embeds, + image_features, + input_ids, + attention_mask + }) { + return { + inputs_embeds: (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)([ + image_features, + // image embeds + inputs_embeds + // task prefix embeds + ], 1), + attention_mask: (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)([ + (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.ones)(image_features.dims.slice(0, 2)), + // image attention mask + attention_mask + // task prefix attention mask + ], 1) + }; + } + async _prepare_inputs_embeds({ input_ids, pixel_values, inputs_embeds, attention_mask }) { + if (!input_ids && !pixel_values) { + throw new Error("Either `input_ids` or `pixel_values` should be provided."); + } + let text_features, image_features; + if (input_ids) { + text_features = await this.encode_text({ input_ids }); + } + if (pixel_values) { + image_features = await this.encode_image({ pixel_values }); + } + if (text_features && image_features) { + ({ inputs_embeds, attention_mask } = this._merge_input_ids_with_image_features({ + inputs_embeds: text_features, + image_features, + input_ids, + attention_mask + })); + } else { + inputs_embeds = text_features || image_features; + } + return { inputs_embeds, attention_mask }; + } + async forward({ + input_ids, + pixel_values, + attention_mask, + decoder_input_ids, + decoder_attention_mask, + encoder_outputs, + past_key_values, + inputs_embeds, + decoder_inputs_embeds + }) { + if (!inputs_embeds) { + ({ inputs_embeds, attention_mask } = await this._prepare_inputs_embeds({ input_ids, pixel_values, inputs_embeds, attention_mask })); + } + if (!encoder_outputs) { + let { last_hidden_state } = await encoderForward(this, { inputs_embeds, attention_mask }); + encoder_outputs = last_hidden_state; + } + if (!decoder_inputs_embeds) { + if (!decoder_input_ids) { + throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided."); + } + decoder_inputs_embeds = await this.encode_text({ input_ids: decoder_input_ids }); + } + const decoderFeeds = { + inputs_embeds: decoder_inputs_embeds, + attention_mask: decoder_attention_mask, + encoder_attention_mask: attention_mask, + encoder_hidden_states: encoder_outputs, + past_key_values + }; + const decoder_outputs = await decoderForward(this, decoderFeeds, true); + return decoder_outputs; + } + } + class PaliGemmaPreTrainedModel extends PreTrainedModel { + forward_params = [ + "input_ids", + // 'inputs_embeds', + "attention_mask", + "pixel_values", + "position_ids", + "past_key_values" + ]; + } + class PaliGemmaForConditionalGeneration extends PaliGemmaPreTrainedModel { + _merge_input_ids_with_image_features(kwargs) { + const vision_hidden_size = kwargs.image_features.dims.at(-1); + const reshaped_image_hidden_states = kwargs.image_features.view(-1, vision_hidden_size); + return default_merge_input_ids_with_image_features({ + // @ts-ignore + image_token_id: this.config.image_token_index, + ...kwargs, + image_features: reshaped_image_hidden_states + }); + } + } + class LlavaQwen2ForCausalLM extends LlavaPreTrainedModel { + _merge_input_ids_with_image_features(kwargs) { + const vision_hidden_size = kwargs.image_features.dims.at(-1); + const reshaped_image_hidden_states = kwargs.image_features.view(-1, vision_hidden_size); + return default_merge_input_ids_with_image_features({ + // @ts-ignore + image_token_id: this.config.image_token_index, + ...kwargs, + image_features: reshaped_image_hidden_states + }); + } + } + class Mistral3ForConditionalGeneration extends LlavaQwen2ForCausalLM { + } + class Gemma3nPreTrainedModel extends PreTrainedModel { + forward_params = [ + "input_ids", + "attention_mask", + "inputs_embeds", + "per_layer_inputs", + "position_ids", + "pixel_values", + "input_features", + "input_features_mask", + "past_key_values" + ]; + } + class Gemma3nForConditionalGeneration extends Gemma3nPreTrainedModel { + async forward({ + // Produced by the tokenizer/processor: + input_ids = null, + attention_mask = null, + pixel_values = null, + input_features = null, + input_features_mask = null, + // Used during generation: + position_ids = null, + inputs_embeds = null, + per_layer_inputs = null, + past_key_values = null, + // Generic generation parameters + generation_config = null, + logits_processor = null, + // TODO: needed? + ...kwargs + }) { + if (!inputs_embeds || !per_layer_inputs) { + ({ inputs_embeds, per_layer_inputs } = await sessionRun(this.sessions["embed_tokens"], { + input_ids + })); + if (input_ids.dims[1] !== 1) { + if (pixel_values) { + const { image_features } = await sessionRun(this.sessions["vision_encoder"], { + pixel_values + }); + ({ inputs_embeds, attention_mask } = this._merge_input_ids_with_image_features({ + image_features, + inputs_embeds, + input_ids, + attention_mask + })); + } + if (input_features) { + const { audio_features } = await sessionRun(this.sessions["audio_encoder"], { + input_features, + input_features_mask + }); + ({ inputs_embeds, attention_mask } = this._merge_input_ids_with_audio_features({ + audio_features, + inputs_embeds, + input_ids, + attention_mask + })); + } + } + } + const outputs = await decoderForward(this, { + inputs_embeds, + per_layer_inputs, + past_key_values, + attention_mask, + position_ids, + generation_config, + logits_processor + }, true); + return outputs; + } + _merge_input_ids_with_image_features(kwargs) { + const vision_hidden_size = kwargs.image_features.dims.at(-1); + const reshaped_image_hidden_states = kwargs.image_features.view(-1, vision_hidden_size); + return default_merge_input_ids_with_image_features({ + // @ts-ignore + image_token_id: this.config.image_token_id, + ...kwargs, + image_features: reshaped_image_hidden_states + }); + } + _merge_input_ids_with_audio_features(kwargs) { + const audio_hidden_size = kwargs.audio_features.dims.at(-1); + const reshaped_audio_features = kwargs.audio_features.view(-1, audio_hidden_size); + return default_merge_input_ids_with_audio_features({ + // @ts-ignore + audio_token_id: this.config.audio_token_id, + ...kwargs, + audio_features: reshaped_audio_features + }); + } + } + class Idefics3PreTrainedModel extends PreTrainedModel { + forward_params = [ + "input_ids", + "attention_mask", + "pixel_values", + "pixel_attention_mask", + "position_ids", + "past_key_values" + ]; + } + class Idefics3ForConditionalGeneration extends Idefics3PreTrainedModel { + async encode_image({ pixel_values, pixel_attention_mask }) { + const features = (await sessionRun(this.sessions["vision_encoder"], { pixel_values, pixel_attention_mask })).image_features; + return features; + } + _merge_input_ids_with_image_features(kwargs) { + const vision_hidden_size = kwargs.image_features.dims.at(-1); + const reshaped_image_hidden_states = kwargs.image_features.view(-1, vision_hidden_size); + return default_merge_input_ids_with_image_features({ + // @ts-ignore + image_token_id: this.config.image_token_id, + ...kwargs, + image_features: reshaped_image_hidden_states + }); + } + } + class SmolVLMForConditionalGeneration extends Idefics3ForConditionalGeneration { + } + class Phi3VPreTrainedModel extends PreTrainedModel { + forward_params = [ + "input_ids", + "inputs_embeds", + "attention_mask", + "position_ids", + "pixel_values", + "image_sizes", + "past_key_values" + ]; + } + class Phi3VForCausalLM extends Phi3VPreTrainedModel { + async forward({ + // Produced by the tokenizer/processor: + input_ids = null, + attention_mask = null, + pixel_values = null, + image_sizes = null, + // Used during generation: + position_ids = null, + inputs_embeds = null, + past_key_values = null, + // Generic generation parameters + generation_config = null, + logits_processor = null, + // TODO: needed? + ...kwargs + }) { + if (!inputs_embeds) { + let image_features; + if (pixel_values && input_ids.dims[1] !== 1) { + if (!image_sizes) { + throw new Error("`image_sizes` must be provided when `pixel_values` is provided."); + } + ({ image_features } = await sessionRun(this.sessions["vision_encoder"], { + pixel_values, + image_sizes + })); + } else { + const hidden_size = this.config.normalized_config.hidden_size; + image_features = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor( + "float32", + [], + [0, hidden_size] + ); + } + ({ inputs_embeds } = await sessionRun(this.sessions["prepare_inputs_embeds"], { + input_ids, + image_features + })); + } + const outputs = await decoderForward(this, { + inputs_embeds, + past_key_values, + attention_mask, + position_ids, + generation_config, + logits_processor + }, false); + return outputs; + } + } + class CLIPPreTrainedModel extends PreTrainedModel { + } + class CLIPModel extends CLIPPreTrainedModel { + } + class CLIPTextModel extends CLIPPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "text_model" + }); + } + } + class CLIPTextModelWithProjection extends CLIPPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "text_model" + }); + } + } + class CLIPVisionModel extends CLIPPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "vision_model" + }); + } + } + class CLIPVisionModelWithProjection extends CLIPPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "vision_model" + }); + } + } + class SiglipPreTrainedModel extends PreTrainedModel { + } + class SiglipModel extends SiglipPreTrainedModel { + } + class SiglipTextModel extends SiglipPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "text_model" + }); + } + } + class SiglipVisionModel extends CLIPPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "vision_model" + }); + } + } + class ChineseCLIPPreTrainedModel extends PreTrainedModel { + } + class ChineseCLIPModel extends ChineseCLIPPreTrainedModel { + } + class JinaCLIPPreTrainedModel extends PreTrainedModel { + } + class JinaCLIPModel extends JinaCLIPPreTrainedModel { + async forward(model_inputs) { + const missing_text_inputs = !model_inputs.input_ids; + const missing_image_inputs = !model_inputs.pixel_values; + if (missing_text_inputs && missing_image_inputs) { + throw new Error("Either `input_ids` or `pixel_values` should be provided."); + } + if (missing_text_inputs) { + model_inputs.input_ids = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.ones)([model_inputs.pixel_values.dims[0], 1]); + } + if (missing_image_inputs) { + const { image_size } = this.config.vision_config; + model_inputs.pixel_values = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.full)([0, 3, image_size, image_size], 0); + } + const { text_embeddings, image_embeddings, l2norm_text_embeddings, l2norm_image_embeddings } = await super.forward(model_inputs); + const result = {}; + if (!missing_text_inputs) { + result.text_embeddings = text_embeddings; + result.l2norm_text_embeddings = l2norm_text_embeddings; + } + if (!missing_image_inputs) { + result.image_embeddings = image_embeddings; + result.l2norm_image_embeddings = l2norm_image_embeddings; + } + return result; + } + } + class JinaCLIPTextModel extends JinaCLIPPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "text_model" + }); + } + } + class JinaCLIPVisionModel extends JinaCLIPPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "vision_model" + }); + } + } + class CLIPSegPreTrainedModel extends PreTrainedModel { + } + class CLIPSegModel extends CLIPSegPreTrainedModel { + } + class CLIPSegForImageSegmentation extends CLIPSegPreTrainedModel { + } + class GPT2PreTrainedModel extends PreTrainedModel { + } + class GPT2Model extends GPT2PreTrainedModel { + } + class GPT2LMHeadModel extends GPT2PreTrainedModel { + } + class JAISPreTrainedModel extends PreTrainedModel { + } + class JAISModel extends JAISPreTrainedModel { + } + class JAISLMHeadModel extends JAISPreTrainedModel { + } + class GPTNeoPreTrainedModel extends PreTrainedModel { + } + class GPTNeoModel extends GPTNeoPreTrainedModel { + } + class GPTNeoForCausalLM extends GPTNeoPreTrainedModel { + } + class GPTNeoXPreTrainedModel extends PreTrainedModel { + } + class GPTNeoXModel extends GPTNeoXPreTrainedModel { + } + class GPTNeoXForCausalLM extends GPTNeoXPreTrainedModel { + } + class GPTJPreTrainedModel extends PreTrainedModel { + } + class GPTJModel extends GPTJPreTrainedModel { + } + class GPTJForCausalLM extends GPTJPreTrainedModel { + } + class GPTBigCodePreTrainedModel extends PreTrainedModel { + } + class GPTBigCodeModel extends GPTBigCodePreTrainedModel { + } + class GPTBigCodeForCausalLM extends GPTBigCodePreTrainedModel { + } + class CodeGenPreTrainedModel extends PreTrainedModel { + } + class CodeGenModel extends CodeGenPreTrainedModel { + } + class CodeGenForCausalLM extends CodeGenPreTrainedModel { + } + class LlamaPreTrainedModel extends PreTrainedModel { + } + class LlamaModel extends LlamaPreTrainedModel { + } + class LlamaForCausalLM extends LlamaPreTrainedModel { + } + class Llama4PreTrainedModel extends PreTrainedModel { + } + class Llama4ForCausalLM extends Llama4PreTrainedModel { + } + class NanoChatPreTrainedModel extends PreTrainedModel { + } + class NanoChatModel extends NanoChatPreTrainedModel { + } + class NanoChatForCausalLM extends NanoChatPreTrainedModel { + } + class ArceePreTrainedModel extends PreTrainedModel { + } + class ArceeModel extends ArceePreTrainedModel { + } + class ArceeForCausalLM extends ArceePreTrainedModel { + } + class Lfm2PreTrainedModel extends PreTrainedModel { + } + class Lfm2Model extends Lfm2PreTrainedModel { + } + class Lfm2ForCausalLM extends Lfm2PreTrainedModel { + } + class SmolLM3PreTrainedModel extends PreTrainedModel { + } + class SmolLM3Model extends SmolLM3PreTrainedModel { + } + class SmolLM3ForCausalLM extends SmolLM3PreTrainedModel { + } + class HeliumPreTrainedModel extends PreTrainedModel { + } + class HeliumModel extends HeliumPreTrainedModel { + } + class HeliumForCausalLM extends HeliumPreTrainedModel { + } + class GlmPreTrainedModel extends PreTrainedModel { + } + class GlmModel extends GlmPreTrainedModel { + } + class GlmForCausalLM extends GlmPreTrainedModel { + } + class ExaonePreTrainedModel extends PreTrainedModel { + } + class ExaoneModel extends ExaonePreTrainedModel { + } + class ExaoneForCausalLM extends ExaonePreTrainedModel { + } + class MobileLLMPreTrainedModel extends PreTrainedModel { + } + class MobileLLMModel extends MobileLLMPreTrainedModel { + } + class MobileLLMForCausalLM extends MobileLLMPreTrainedModel { + } + class OlmoPreTrainedModel extends PreTrainedModel { + } + class OlmoModel extends OlmoPreTrainedModel { + } + class OlmoForCausalLM extends OlmoPreTrainedModel { + } + class Olmo2PreTrainedModel extends PreTrainedModel { + } + class Olmo2Model extends Olmo2PreTrainedModel { + } + class Olmo2ForCausalLM extends Olmo2PreTrainedModel { + } + class GranitePreTrainedModel extends PreTrainedModel { + } + class GraniteModel extends GranitePreTrainedModel { + } + class GraniteForCausalLM extends GranitePreTrainedModel { + } + class GraniteMoeHybridPreTrainedModel extends PreTrainedModel { + } + class GraniteMoeHybridModel extends GraniteMoeHybridPreTrainedModel { + } + class GraniteMoeHybridForCausalLM extends GraniteMoeHybridPreTrainedModel { + } + class CoherePreTrainedModel extends PreTrainedModel { + } + class CohereModel extends CoherePreTrainedModel { + } + class CohereForCausalLM extends CoherePreTrainedModel { + } + class GemmaPreTrainedModel extends PreTrainedModel { + } + class GemmaModel extends GemmaPreTrainedModel { + } + class GemmaForCausalLM extends GemmaPreTrainedModel { + } + class Gemma2PreTrainedModel extends PreTrainedModel { + } + class Gemma2Model extends Gemma2PreTrainedModel { + } + class Gemma2ForCausalLM extends Gemma2PreTrainedModel { + } + class VaultGemmaPreTrainedModel extends PreTrainedModel { + } + class VaultGemmaModel extends VaultGemmaPreTrainedModel { + } + class VaultGemmaForCausalLM extends VaultGemmaPreTrainedModel { + } + class Gemma3PreTrainedModel extends PreTrainedModel { + } + class Gemma3Model extends Gemma3PreTrainedModel { + } + class Gemma3ForCausalLM extends Gemma3PreTrainedModel { + } + class OpenELMPreTrainedModel extends PreTrainedModel { + } + class OpenELMModel extends OpenELMPreTrainedModel { + } + class OpenELMForCausalLM extends OpenELMPreTrainedModel { + } + class Qwen2PreTrainedModel extends PreTrainedModel { + } + class Qwen2Model extends Qwen2PreTrainedModel { + } + class Qwen2ForCausalLM extends Qwen2PreTrainedModel { + } + class Qwen3PreTrainedModel extends PreTrainedModel { + } + class Qwen3Model extends Qwen3PreTrainedModel { + } + class Qwen3ForCausalLM extends Qwen3PreTrainedModel { + } + class Qwen2VLPreTrainedModel extends PreTrainedModel { + forward_params = [ + // Text inputs + "input_ids", + "attention_mask", + "position_ids", + "past_key_values", + // Vision inputs + "pixel_values", + "image_grid_thw" + ]; + } + class Qwen2VLForConditionalGeneration extends Qwen2VLPreTrainedModel { + /** + * Calculate the 3D rope index based on image and video's temporal, height and width in LLM. + * + * Explanation: + * Each embedding sequence contains vision embedding and text embedding or just contains text embedding. + * + * For pure text embedding sequence, the rotary position embedding has no difference with mordern LLMs. + * Examples: + * input_ids: [T T T T T], here T is for text. + * temporal position_ids: [0, 1, 2, 3, 4] + * height position_ids: [0, 1, 2, 3, 4] + * width position_ids: [0, 1, 2, 3, 4] + * + * For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part + * and 1D rotary position embeddin for text part. + * Examples: + * Assume we have a video input with 3 temporal patches, 2 height patches and 2 width patches. + * input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision. + * vision temporal position_ids: [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2] + * vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1] + * vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] + * text temporal position_ids: [3, 4, 5, 6, 7] + * text height position_ids: [3, 4, 5, 6, 7] + * text width position_ids: [3, 4, 5, 6, 7] + * Here we calculate the text start position_ids as the max vision position_ids plus 1. + * + * @param {Tensor} input_ids Indices of input sequence tokens in the vocabulary. Tensor of shape `(batch_size, sequence_length)`. + * @param {Tensor} image_grid_thw (Optional) The temporal, height and width of feature shape of each image in LLM. Tensor of shape `(num_images, 3)`. + * @param {Tensor} video_grid_thw (Optional) The temporal, height and width of feature shape of each video in LLM. Tensor of shape `(num_videos, 3)`. + * @param {Tensor} attention_mask (Optional) Mask to avoid performing attention on padding token indices. Tensor of shape `(batch_size, sequence_length)`. Mask values selected in `[0, 1]`: + * - 1 for tokens that are **not masked**, + * - 0 for tokens that are **masked**. + * @returns {[Tensor, Tensor]} [position_ids, mrope_position_deltas] with: + * - position_ids: Tensor of shape `(3, batch_size, sequence_length)`. + * - mrope_position_deltas: Tensor of shape `(batch_size)`. + */ + get_rope_index(input_ids, image_grid_thw, video_grid_thw, attention_mask) { + const { vision_config, image_token_id, video_token_id, vision_start_token_id } = this.config; + const spatial_merge_size = vision_config.spatial_merge_size ?? 2; + const mrope_position_deltas = []; + if (image_grid_thw || video_grid_thw) { + let total_input_ids = input_ids.tolist(); + if (!attention_mask) { + attention_mask = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.ones_like)(input_ids); + } + const attention_mask_list = attention_mask.tolist(); + const position_ids_list = Array.from({ length: 3 }, (_) => Array.from({ length: input_ids.dims[0] }, (_2) => Array.from({ length: input_ids.dims[1] }, (_3) => 1))); + const image_grid_thw_list = image_grid_thw ? image_grid_thw.tolist() : []; + const video_grid_thw_list = video_grid_thw ? video_grid_thw.tolist() : []; + let image_index = 0; + let video_index = 0; + for (let i = 0; i < total_input_ids.length; ++i) { + const ids = total_input_ids[i].filter((_, j) => attention_mask_list[i][j] == 1); + const vision_start_indices = ids.reduce((acc, x, idx) => { + if (x == vision_start_token_id) acc.push(idx); + return acc; + }, []); + const vision_tokens = vision_start_indices.map((x) => ids[x + 1]); + const image_nums = vision_tokens.filter((x) => x == image_token_id).length; + const video_nums = vision_tokens.filter((x) => x == video_token_id).length; + let llm_pos_ids_list = []; + let st2 = 0; + let remain_images = image_nums; + let remain_videos = video_nums; + for (let j = 0; j < vision_tokens.length; ++j) { + const next_image_token = ids.findIndex((x, i2) => i2 > st2 && x == image_token_id); + const next_video_token = ids.findIndex((x, i2) => i2 > st2 && x == video_token_id); + const ed_image = remain_images > 0 && next_image_token !== -1 ? next_image_token : ids.length + 1; + const ed_video = remain_videos > 0 && next_video_token !== -1 ? next_video_token : ids.length + 1; + let ed2; + let t, h, w; + if (ed_image < ed_video) { + [t, h, w] = image_grid_thw_list[image_index]; + ++image_index; + --remain_images; + ed2 = ed_image; + } else { + [t, h, w] = video_grid_thw_list[video_index]; + ++video_index; + --remain_videos; + ed2 = ed_video; + } + const [llm_grid_t, llm_grid_h, llm_grid_w] = [ + Number(t), + Math.floor(Number(h) / spatial_merge_size), + Math.floor(Number(w) / spatial_merge_size) + ]; + const text_len = ed2 - st2; + const st_idx = llm_pos_ids_list.length > 0 ? (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_11__.max)(llm_pos_ids_list.at(-1))[0] + 1 : 0; + llm_pos_ids_list.push( + Array.from({ length: 3 * text_len }, (_, i2) => st_idx + i2 % text_len) + ); + const offset = text_len + st_idx; + const grid_size = llm_grid_t * llm_grid_h * llm_grid_w; + const t_index = Array.from({ length: grid_size }, (_, i2) => offset + Math.floor(i2 / (llm_grid_h * llm_grid_w))); + const h_index = Array.from({ length: grid_size }, (_, i2) => offset + Math.floor(i2 / llm_grid_w) % llm_grid_h); + const w_index = Array.from({ length: grid_size }, (_, i2) => offset + i2 % llm_grid_w); + llm_pos_ids_list.push([t_index, h_index, w_index].flat()); + st2 = ed2 + grid_size; + } + if (st2 < ids.length) { + const st_idx = llm_pos_ids_list.length > 0 ? (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_11__.max)(llm_pos_ids_list.at(-1))[0] + 1 : 0; + const text_len = ids.length - st2; + llm_pos_ids_list.push( + Array.from({ length: 3 * text_len }, (_, i2) => st_idx + i2 % text_len) + ); + } + const num_items = llm_pos_ids_list.reduce((acc, x) => acc + x.length, 0); + const llm_positions = new Array(num_items); + let index = 0; + for (let x = 0; x < 3; ++x) { + for (let y = 0; y < llm_pos_ids_list.length; ++y) { + const val = llm_pos_ids_list[y]; + const text_len = val.length / 3; + for (let z = x * text_len; z < (x + 1) * text_len; ++z) { + llm_positions[index++] = val[z]; + } + } + } + let count = 0; + const attn_mask = attention_mask_list[i]; + for (let y = 0; y < attn_mask.length; ++y) { + if (attn_mask[y] == 1) { + for (let x = 0; x < 3; ++x) { + position_ids_list[x][i][y] = llm_positions[x * num_items / 3 + count]; + } + ++count; + } + } + const max_llm_positions = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_11__.max)(llm_positions)[0]; + mrope_position_deltas.push(max_llm_positions + 1 - total_input_ids[i].length); + } + return [ + new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor("int64", position_ids_list.flat(Infinity), [3, input_ids.dims[0], input_ids.dims[1]]), + new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor("int64", mrope_position_deltas, [mrope_position_deltas.length, 1]) + ]; + } else { + if (attention_mask) { + const { data, dims } = cumsum_masked_fill(attention_mask); + const position_ids = BigInt64Array.from( + { length: 3 * data.length }, + (_, i) => data[i % data.length] + ); + const mrope_position_deltas2 = Array.from( + { length: dims[0] }, + (_, i) => (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_11__.max)(data.subarray(dims[1] * i, dims[1] * (i + 1)))[0] + 1n + BigInt(dims[1]) + ); + return [ + new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor("int64", position_ids, [3, ...dims]), + new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor("int64", mrope_position_deltas2, [mrope_position_deltas2.length, 1]) + ]; + } else { + const [batch_size, seq_length] = input_ids.dims; + const position_ids = BigInt64Array.from( + { length: 3 * batch_size * seq_length }, + (_, i) => BigInt(Math.floor(i % seq_length / batch_size)) + ); + return [ + new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor("int64", position_ids, [3, ...input_ids.dims]), + (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.zeros)([batch_size, 1]) + ]; + } + } + } + async encode_image({ pixel_values, image_grid_thw }) { + const features = (await sessionRun(this.sessions["vision_encoder"], { pixel_values, grid_thw: image_grid_thw })).image_features; + return features; + } + _merge_input_ids_with_image_features(kwargs) { + return default_merge_input_ids_with_image_features({ + // @ts-ignore + image_token_id: this.config.image_token_id, + ...kwargs + }); + } + prepare_inputs_for_generation(input_ids, model_inputs, generation_config) { + if (model_inputs.attention_mask && !model_inputs.position_ids) { + if (!model_inputs.past_key_values) { + [model_inputs.position_ids, model_inputs.rope_deltas] = this.get_rope_index( + model_inputs.input_ids, + model_inputs.image_grid_thw, + model_inputs.video_grid_thw, + model_inputs.attention_mask + ); + } else { + model_inputs.pixel_values = null; + const delta = BigInt(Object.values(model_inputs.past_key_values)[0].dims.at(-2)); + const rope_deltas_list = model_inputs.rope_deltas.map((x) => delta + x); + model_inputs.position_ids = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.stack)([rope_deltas_list, rope_deltas_list, rope_deltas_list], 0); + } + } + return model_inputs; + } + } + class PhiPreTrainedModel extends PreTrainedModel { + } + class PhiModel extends PhiPreTrainedModel { + } + class PhiForCausalLM extends PhiPreTrainedModel { + } + class Phi3PreTrainedModel extends PreTrainedModel { + } + class Phi3Model extends Phi3PreTrainedModel { + } + class Phi3ForCausalLM extends Phi3PreTrainedModel { + } + class BloomPreTrainedModel extends PreTrainedModel { + } + class BloomModel extends BloomPreTrainedModel { + } + class BloomForCausalLM extends BloomPreTrainedModel { + } + class MptPreTrainedModel extends PreTrainedModel { + } + class MptModel extends MptPreTrainedModel { + } + class MptForCausalLM extends MptPreTrainedModel { + } + class OPTPreTrainedModel extends PreTrainedModel { + } + class OPTModel extends OPTPreTrainedModel { + } + class OPTForCausalLM extends OPTPreTrainedModel { + } + class ViTPreTrainedModel extends PreTrainedModel { + } + class ViTModel extends ViTPreTrainedModel { + } + class ViTForImageClassification extends ViTPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class IJepaPreTrainedModel extends PreTrainedModel { + } + class IJepaModel extends IJepaPreTrainedModel { + } + class IJepaForImageClassification extends IJepaPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class VitPosePreTrainedModel extends PreTrainedModel { + } + class VitPoseForPoseEstimation extends VitPosePreTrainedModel { + } + class PvtPreTrainedModel extends PreTrainedModel { + } + class PvtModel extends PvtPreTrainedModel { + } + class PvtForImageClassification extends PvtPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class ViTMAEPreTrainedModel extends PreTrainedModel { + } + class ViTMAEModel extends ViTMAEPreTrainedModel { + } + class ViTMSNPreTrainedModel extends PreTrainedModel { + } + class ViTMSNModel extends ViTMSNPreTrainedModel { + } + class ViTMSNForImageClassification extends ViTMSNPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class GroupViTPreTrainedModel extends PreTrainedModel { + } + class GroupViTModel extends GroupViTPreTrainedModel { + } + class FastViTPreTrainedModel extends PreTrainedModel { + } + class FastViTModel extends FastViTPreTrainedModel { + } + class FastViTForImageClassification extends FastViTPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class VitMattePreTrainedModel extends PreTrainedModel { + } + class VitMatteForImageMatting extends VitMattePreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new ImageMattingOutput(await super._call(model_inputs)); + } + } + class MobileViTPreTrainedModel extends PreTrainedModel { + } + class MobileViTModel extends MobileViTPreTrainedModel { + } + class MobileViTForImageClassification extends MobileViTPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class MobileViTV2PreTrainedModel extends PreTrainedModel { + } + class MobileViTV2Model extends MobileViTV2PreTrainedModel { + } + class MobileViTV2ForImageClassification extends MobileViTV2PreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class OwlViTPreTrainedModel extends PreTrainedModel { + } + class OwlViTModel extends OwlViTPreTrainedModel { + } + class OwlViTForObjectDetection extends OwlViTPreTrainedModel { + } + class Owlv2PreTrainedModel extends PreTrainedModel { + } + class Owlv2Model extends Owlv2PreTrainedModel { + } + class Owlv2ForObjectDetection extends Owlv2PreTrainedModel { + } + class BeitPreTrainedModel extends PreTrainedModel { + } + class BeitModel extends BeitPreTrainedModel { + } + class BeitForImageClassification extends BeitPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class DetrPreTrainedModel extends PreTrainedModel { + } + class DetrModel extends DetrPreTrainedModel { + } + class DetrForObjectDetection extends DetrPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new DetrObjectDetectionOutput(await super._call(model_inputs)); + } + } + class DetrForSegmentation extends DetrPreTrainedModel { + /** + * Runs the model with the provided inputs + * @param {Object} model_inputs Model inputs + * @returns {Promise} Object containing segmentation outputs + */ + async _call(model_inputs) { + return new DetrSegmentationOutput(await super._call(model_inputs)); + } + } + class DetrObjectDetectionOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Classification logits (including no-object) for all queries. + * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). + * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding). + */ + constructor({ logits, pred_boxes }) { + super(); + this.logits = logits; + this.pred_boxes = pred_boxes; + } + } + class DetrSegmentationOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits The output logits of the model. + * @param {Tensor} output.pred_boxes Predicted boxes. + * @param {Tensor} output.pred_masks Predicted masks. + */ + constructor({ logits, pred_boxes, pred_masks }) { + super(); + this.logits = logits; + this.pred_boxes = pred_boxes; + this.pred_masks = pred_masks; + } + } + class RTDetrPreTrainedModel extends PreTrainedModel { + } + class RTDetrModel extends RTDetrPreTrainedModel { + } + class RTDetrForObjectDetection extends RTDetrPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new RTDetrObjectDetectionOutput(await super._call(model_inputs)); + } + } + class RTDetrObjectDetectionOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Classification logits (including no-object) for all queries. + * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). + * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding). + */ + constructor({ logits, pred_boxes }) { + super(); + this.logits = logits; + this.pred_boxes = pred_boxes; + } + } + class RTDetrV2PreTrainedModel extends PreTrainedModel { + } + class RTDetrV2Model extends RTDetrV2PreTrainedModel { + } + class RTDetrV2ForObjectDetection extends RTDetrV2PreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new RTDetrV2ObjectDetectionOutput(await super._call(model_inputs)); + } + } + class RTDetrV2ObjectDetectionOutput extends RTDetrObjectDetectionOutput { + } + class RFDetrPreTrainedModel extends PreTrainedModel { + } + class RFDetrModel extends RFDetrPreTrainedModel { + } + class RFDetrForObjectDetection extends RFDetrPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new RFDetrObjectDetectionOutput(await super._call(model_inputs)); + } + } + class RFDetrObjectDetectionOutput extends RTDetrObjectDetectionOutput { + } + class DFinePreTrainedModel extends PreTrainedModel { + } + class DFineModel extends DFinePreTrainedModel { + } + class DFineForObjectDetection extends DFinePreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new RTDetrObjectDetectionOutput(await super._call(model_inputs)); + } + } + class TableTransformerPreTrainedModel extends PreTrainedModel { + } + class TableTransformerModel extends TableTransformerPreTrainedModel { + } + class TableTransformerForObjectDetection extends TableTransformerPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new TableTransformerObjectDetectionOutput(await super._call(model_inputs)); + } + } + class TableTransformerObjectDetectionOutput extends DetrObjectDetectionOutput { + } + class DeiTPreTrainedModel extends PreTrainedModel { + } + class DeiTModel extends DeiTPreTrainedModel { + } + class DeiTForImageClassification extends DeiTPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class HieraPreTrainedModel extends PreTrainedModel { + } + class HieraModel extends HieraPreTrainedModel { + } + class HieraForImageClassification extends HieraPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class ResNetPreTrainedModel extends PreTrainedModel { + } + class ResNetModel extends ResNetPreTrainedModel { + } + class ResNetForImageClassification extends ResNetPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class SwinPreTrainedModel extends PreTrainedModel { + } + class SwinModel extends SwinPreTrainedModel { + } + class SwinForImageClassification extends SwinPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class SwinForSemanticSegmentation extends SwinPreTrainedModel { + } + class Swin2SRPreTrainedModel extends PreTrainedModel { + } + class Swin2SRModel extends Swin2SRPreTrainedModel { + } + class Swin2SRForImageSuperResolution extends Swin2SRPreTrainedModel { + } + class DPTPreTrainedModel extends PreTrainedModel { + } + class DPTModel extends DPTPreTrainedModel { + } + class DPTForDepthEstimation extends DPTPreTrainedModel { + } + class DepthAnythingPreTrainedModel extends PreTrainedModel { + } + class DepthAnythingForDepthEstimation extends DepthAnythingPreTrainedModel { + } + class SapiensPreTrainedModel extends PreTrainedModel { + } + class SapiensForSemanticSegmentation extends SapiensPreTrainedModel { + } + class SapiensForDepthEstimation extends SapiensPreTrainedModel { + } + class SapiensForNormalEstimation extends SapiensPreTrainedModel { + } + class DepthProPreTrainedModel extends PreTrainedModel { + } + class DepthProForDepthEstimation extends DepthProPreTrainedModel { + } + class Metric3DPreTrainedModel extends PreTrainedModel { + } + class Metric3DForDepthEstimation extends Metric3DPreTrainedModel { + } + class Metric3Dv2PreTrainedModel extends PreTrainedModel { + } + class Metric3Dv2ForDepthEstimation extends Metric3Dv2PreTrainedModel { + } + class MaskFormerPreTrainedModel extends PreTrainedModel { + } + class MaskFormerModel extends MaskFormerPreTrainedModel { + } + class MaskFormerForInstanceSegmentation extends MaskFormerPreTrainedModel { + } + class GLPNPreTrainedModel extends PreTrainedModel { + } + class GLPNModel extends GLPNPreTrainedModel { + } + class GLPNForDepthEstimation extends GLPNPreTrainedModel { + } + class DonutSwinPreTrainedModel extends PreTrainedModel { + } + class DonutSwinModel extends DonutSwinPreTrainedModel { + } + class ConvNextPreTrainedModel extends PreTrainedModel { + } + class ConvNextModel extends ConvNextPreTrainedModel { + } + class ConvNextForImageClassification extends ConvNextPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class ConvNextV2PreTrainedModel extends PreTrainedModel { + } + class ConvNextV2Model extends ConvNextV2PreTrainedModel { + } + class ConvNextV2ForImageClassification extends ConvNextV2PreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class Dinov2PreTrainedModel extends PreTrainedModel { + } + class Dinov2Model extends Dinov2PreTrainedModel { + } + class Dinov2ForImageClassification extends Dinov2PreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class Dinov2WithRegistersPreTrainedModel extends PreTrainedModel { + } + class Dinov2WithRegistersModel extends Dinov2WithRegistersPreTrainedModel { + } + class Dinov2WithRegistersForImageClassification extends Dinov2WithRegistersPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class DINOv3ViTPreTrainedModel extends PreTrainedModel { + } + class DINOv3ViTModel extends DINOv3ViTPreTrainedModel { + } + class DINOv3ConvNextPreTrainedModel extends PreTrainedModel { + } + class DINOv3ConvNextModel extends DINOv3ConvNextPreTrainedModel { + } + class GroundingDinoPreTrainedModel extends PreTrainedModel { + } + class GroundingDinoForObjectDetection extends GroundingDinoPreTrainedModel { + } + class YolosPreTrainedModel extends PreTrainedModel { + } + class YolosModel extends YolosPreTrainedModel { + } + class YolosForObjectDetection extends YolosPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new YolosObjectDetectionOutput(await super._call(model_inputs)); + } + } + class YolosObjectDetectionOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Classification logits (including no-object) for all queries. + * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). + * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding). + */ + constructor({ logits, pred_boxes }) { + super(); + this.logits = logits; + this.pred_boxes = pred_boxes; + } + } + class SamPreTrainedModel extends PreTrainedModel { + } + class SamModel extends SamPreTrainedModel { + /** + * Compute image embeddings and positional image embeddings, given the pixel values of an image. + * @param {Object} model_inputs Object containing the model inputs. + * @param {Tensor} model_inputs.pixel_values Pixel values obtained using a `SamProcessor`. + * @returns {Promise<{ image_embeddings: Tensor, image_positional_embeddings: Tensor }>} The image embeddings and positional image embeddings. + */ + async get_image_embeddings({ pixel_values }) { + return await encoderForward(this, { pixel_values }); + } + /** + * @typedef {Object} SamModelInputs Object containing the model inputs. + * @property {Tensor} pixel_values Pixel values as a Tensor with shape `(batch_size, num_channels, height, width)`. + * These can be obtained using a `SamProcessor`. + * @property {Tensor} [input_points] Input 2D spatial points with shape `(batch_size, num_points, 2)`. + * This is used by the prompt encoder to encode the prompt. + * @property {Tensor} [input_labels] Input labels for the points, as a Tensor of shape `(batch_size, point_batch_size, num_points)`. + * This is used by the prompt encoder to encode the prompt. There are 4 types of labels: + * - `1`: the point is a point that contains the object of interest + * - `0`: the point is a point that does not contain the object of interest + * - `-1`: the point corresponds to the background + * - `-10`: the point is a padding point, thus should be ignored by the prompt encoder + * @property {Tensor} [input_boxes] Input bounding boxes with shape `(batch_size, num_boxes, 4)`. + * @property {Tensor} [image_embeddings] Image embeddings used by the mask decoder. + * @property {Tensor} [image_positional_embeddings] Image positional embeddings used by the mask decoder. + */ + /** + * @param {SamModelInputs} model_inputs Object containing the model inputs. + * @returns {Promise} The output of the model. + */ + async forward(model_inputs) { + if (!model_inputs.image_embeddings || !model_inputs.image_positional_embeddings) { + model_inputs = { + ...model_inputs, + ...await this.get_image_embeddings(model_inputs) + }; + } else { + model_inputs = { ...model_inputs }; + } + model_inputs.input_labels ??= (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.ones)(model_inputs.input_points.dims.slice(0, -1)); + const decoder_inputs = { + image_embeddings: model_inputs.image_embeddings, + image_positional_embeddings: model_inputs.image_positional_embeddings + }; + if (model_inputs.input_points) { + decoder_inputs.input_points = model_inputs.input_points; + } + if (model_inputs.input_labels) { + decoder_inputs.input_labels = model_inputs.input_labels; + } + if (model_inputs.input_boxes) { + decoder_inputs.input_boxes = model_inputs.input_boxes; + } + return await sessionRun(this.sessions["prompt_encoder_mask_decoder"], decoder_inputs); + } + /** + * Runs the model with the provided inputs + * @param {Object} model_inputs Model inputs + * @returns {Promise} Object containing segmentation outputs + */ + async _call(model_inputs) { + return new SamImageSegmentationOutput(await super._call(model_inputs)); + } + } + class SamImageSegmentationOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.iou_scores The output logits of the model. + * @param {Tensor} output.pred_masks Predicted boxes. + */ + constructor({ iou_scores, pred_masks }) { + super(); + this.iou_scores = iou_scores; + this.pred_masks = pred_masks; + } + } + class Sam2ImageSegmentationOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.iou_scores The output logits of the model. + * @param {Tensor} output.pred_masks Predicted boxes. + * @param {Tensor} output.object_score_logits Logits for the object score, indicating if an object is present. + */ + constructor({ iou_scores, pred_masks, object_score_logits }) { + super(); + this.iou_scores = iou_scores; + this.pred_masks = pred_masks; + this.object_score_logits = object_score_logits; + } + } + class Sam2PreTrainedModel extends PreTrainedModel { + } + class Sam2Model extends Sam2PreTrainedModel { + /** + * Compute image embeddings and positional image embeddings, given the pixel values of an image. + * @param {Object} model_inputs Object containing the model inputs. + * @param {Tensor} model_inputs.pixel_values Pixel values obtained using a `Sam2Processor`. + * @returns {Promise>} The image embeddings. + */ + async get_image_embeddings({ pixel_values }) { + return await encoderForward(this, { pixel_values }); + } + async forward(model_inputs) { + const { num_feature_levels } = this.config.vision_config; + const image_embeddings_name = Array.from({ length: num_feature_levels }, (_, i) => `image_embeddings.${i}`); + if (image_embeddings_name.some((name) => !model_inputs[name])) { + model_inputs = { + ...model_inputs, + ...await this.get_image_embeddings(model_inputs) + }; + } else { + model_inputs = { ...model_inputs }; + } + if (model_inputs.input_points) { + if (model_inputs.input_boxes && model_inputs.input_boxes.dims[1] !== 1) { + throw new Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1."); + } + const shape = model_inputs.input_points.dims; + model_inputs.input_labels ??= (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.ones)(shape.slice(0, -1)); + model_inputs.input_boxes ??= (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.full)([shape[0], 0, 4], 0); + } else if (model_inputs.input_boxes) { + const shape = model_inputs.input_boxes.dims; + model_inputs.input_labels = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.full)([shape[0], shape[1], 0], -1n); + model_inputs.input_points = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.full)([shape[0], 1, 0, 2], 0); + } else { + throw new Error("At least one of `input_points` or `input_boxes` must be provided."); + } + const prompt_encoder_mask_decoder_session = this.sessions["prompt_encoder_mask_decoder"]; + const decoder_inputs = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_4__.pick)(model_inputs, prompt_encoder_mask_decoder_session.inputNames); + return await sessionRun(prompt_encoder_mask_decoder_session, decoder_inputs); + } + /** + * Runs the model with the provided inputs + * @param {Object} model_inputs Model inputs + * @returns {Promise} Object containing segmentation outputs + */ + async _call(model_inputs) { + return new Sam2ImageSegmentationOutput(await super._call(model_inputs)); + } + } + class EdgeTamModel extends Sam2Model { + } + class Sam3TrackerModel extends Sam2Model { + } + class MarianPreTrainedModel extends PreTrainedModel { + } + ; + class MarianModel extends MarianPreTrainedModel { + } + class MarianMTModel extends MarianPreTrainedModel { + } + class M2M100PreTrainedModel extends PreTrainedModel { + } + ; + class M2M100Model extends M2M100PreTrainedModel { + } + class M2M100ForConditionalGeneration extends M2M100PreTrainedModel { + } + class Wav2Vec2PreTrainedModel extends PreTrainedModel { + } + ; + class Wav2Vec2Model extends Wav2Vec2PreTrainedModel { + } + class Wav2Vec2ForCTC extends Wav2Vec2PreTrainedModel { + /** + * @param {Object} model_inputs + * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. + * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] + */ + async _call(model_inputs) { + return new CausalLMOutput(await super._call(model_inputs)); + } + } + class Wav2Vec2ForSequenceClassification extends Wav2Vec2PreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class Wav2Vec2ForAudioFrameClassification extends Wav2Vec2PreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } + } + class ParakeetPreTrainedModel extends PreTrainedModel { + } + ; + class ParakeetForCTC extends ParakeetPreTrainedModel { + /** + * @param {Object} model_inputs + * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. + * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] + */ + async _call(model_inputs) { + return new CausalLMOutput(await super._call(model_inputs)); + } + } + class PyAnnotePreTrainedModel extends PreTrainedModel { + } + ; + class PyAnnoteModel extends PyAnnotePreTrainedModel { + } + class PyAnnoteForAudioFrameClassification extends PyAnnotePreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } + } + class WeSpeakerResNetPreTrainedModel extends PreTrainedModel { + } + ; + class WeSpeakerResNetModel extends WeSpeakerResNetPreTrainedModel { + } + class UniSpeechPreTrainedModel extends PreTrainedModel { + } + ; + class UniSpeechModel extends UniSpeechPreTrainedModel { + } + class UniSpeechForCTC extends UniSpeechPreTrainedModel { + /** + * @param {Object} model_inputs + * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. + * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] + */ + async _call(model_inputs) { + return new CausalLMOutput(await super._call(model_inputs)); + } + } + class UniSpeechForSequenceClassification extends UniSpeechPreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class UniSpeechSatPreTrainedModel extends PreTrainedModel { + } + ; + class UniSpeechSatModel extends UniSpeechSatPreTrainedModel { + } + class UniSpeechSatForCTC extends UniSpeechSatPreTrainedModel { + /** + * @param {Object} model_inputs + * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. + * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] + */ + async _call(model_inputs) { + return new CausalLMOutput(await super._call(model_inputs)); + } + } + class UniSpeechSatForSequenceClassification extends UniSpeechSatPreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class UniSpeechSatForAudioFrameClassification extends UniSpeechSatPreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } + } + class Wav2Vec2BertPreTrainedModel extends PreTrainedModel { + } + ; + class Wav2Vec2BertModel extends Wav2Vec2BertPreTrainedModel { + } + class Wav2Vec2BertForCTC extends Wav2Vec2BertPreTrainedModel { + /** + * @param {Object} model_inputs + * @param {Tensor} model_inputs.input_features Float values of input mel-spectrogram. + * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] + */ + async _call(model_inputs) { + return new CausalLMOutput(await super._call(model_inputs)); + } + } + class Wav2Vec2BertForSequenceClassification extends Wav2Vec2BertPreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class HubertPreTrainedModel extends PreTrainedModel { + } + class HubertModel extends Wav2Vec2PreTrainedModel { + } + class HubertForCTC extends Wav2Vec2PreTrainedModel { + /** + * @param {Object} model_inputs + * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. + * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] + */ + async _call(model_inputs) { + return new CausalLMOutput(await super._call(model_inputs)); + } + } + class HubertForSequenceClassification extends Wav2Vec2PreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class WavLMPreTrainedModel extends PreTrainedModel { + } + ; + class WavLMModel extends WavLMPreTrainedModel { + } + class WavLMForCTC extends WavLMPreTrainedModel { + /** + * @param {Object} model_inputs + * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. + * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] + */ + async _call(model_inputs) { + return new CausalLMOutput(await super._call(model_inputs)); + } + } + class WavLMForSequenceClassification extends WavLMPreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class WavLMForXVector extends WavLMPreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits and speaker embeddings. + */ + async _call(model_inputs) { + return new XVectorOutput(await super._call(model_inputs)); + } + } + class WavLMForAudioFrameClassification extends WavLMPreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } + } + class StyleTextToSpeech2PreTrainedModel extends PreTrainedModel { + } + class StyleTextToSpeech2Model extends StyleTextToSpeech2PreTrainedModel { + } + class SpeechT5PreTrainedModel extends PreTrainedModel { + } + ; + class SpeechT5Model extends SpeechT5PreTrainedModel { + } + ; + class SpeechT5ForSpeechToText extends SpeechT5PreTrainedModel { + } + class SpeechT5ForTextToSpeech extends SpeechT5PreTrainedModel { + /** + * @typedef {Object} SpeechOutput + * @property {Tensor} [spectrogram] The predicted log-mel spectrogram of shape + * `(output_sequence_length, config.num_mel_bins)`. Returned when no `vocoder` is provided + * @property {Tensor} [waveform] The predicted waveform of shape `(num_frames,)`. Returned when a `vocoder` is provided. + * @property {Tensor} [cross_attentions] The outputs of the decoder's cross-attention layers of shape + * `(config.decoder_layers, config.decoder_attention_heads, output_sequence_length, input_sequence_length)`. returned when `output_cross_attentions` is `true`. + */ + /** + * Converts a sequence of input tokens into a sequence of mel spectrograms, which are subsequently turned into a speech waveform using a vocoder. + * @param {Tensor} input_values Indices of input sequence tokens in the vocabulary. + * @param {Tensor} speaker_embeddings Tensor containing the speaker embeddings. + * @param {Object} options Optional parameters for generating speech. + * @param {number} [options.threshold=0.5] The generated sequence ends when the predicted stop token probability exceeds this value. + * @param {number} [options.minlenratio=0.0] Used to calculate the minimum required length for the output sequence. + * @param {number} [options.maxlenratio=20.0] Used to calculate the maximum allowed length for the output sequence. + * @param {Object} [options.vocoder=null] The vocoder that converts the mel spectrogram into a speech waveform. If `null`, the output is the mel spectrogram. + * @param {boolean} [options.output_cross_attentions=false] Whether or not to return the attentions tensors of the decoder's cross-attention layers. + * @returns {Promise} A promise which resolves to an object containing the spectrogram, waveform, and cross-attention tensors. + */ + async generate_speech(input_values, speaker_embeddings, { + threshold = 0.5, + minlenratio = 0, + maxlenratio = 20, + vocoder = null + // output_cross_attentions = false, // TODO add + } = {}) { + const model_inputs = { + input_ids: input_values + }; + const { encoder_outputs, encoder_attention_mask } = await encoderForward(this, model_inputs); + const r = encoder_outputs.dims[1] / this.config.reduction_factor; + const maxlen = Math.floor(r * maxlenratio); + const minlen = Math.floor(r * minlenratio); + const num_mel_bins = this.config.num_mel_bins; + let spectrogramParts = []; + let past_key_values = null; + let decoder_outputs = null; + let idx = 0; + while (true) { + ++idx; + const use_cache_branch = boolTensor(!!decoder_outputs); + let output_sequence; + if (decoder_outputs) { + output_sequence = decoder_outputs.output_sequence_out; + } else { + output_sequence = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor( + "float32", + new Float32Array(num_mel_bins), + [1, 1, num_mel_bins] + ); + } + let decoderFeeds = { + use_cache_branch, + output_sequence, + encoder_attention_mask, + speaker_embeddings, + encoder_hidden_states: encoder_outputs + }; + this.addPastKeyValues(decoderFeeds, past_key_values); + decoder_outputs = await sessionRun(this.sessions["decoder_model_merged"], decoderFeeds); + past_key_values = this.getPastKeyValues(decoder_outputs, past_key_values); + const { prob, spectrum } = decoder_outputs; + spectrogramParts.push(spectrum); + if (idx >= minlen && // Finished when stop token or maximum length is reached. + (Array.from(prob.data).filter((p) => p >= threshold).length > 0 || idx >= maxlen)) { + break; + } + } + const spectrogram = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)(spectrogramParts); + const { waveform } = await sessionRun(vocoder.sessions["model"], { spectrogram }); + return { + spectrogram, + waveform + // cross_attentions: null, // TODO add + }; + } + } + class SpeechT5HifiGan extends PreTrainedModel { + main_input_name = "spectrogram"; + } + class SupertonicPreTrainedModel extends PreTrainedModel { + } + class SupertonicForConditionalGeneration extends SupertonicPreTrainedModel { + async generate_speech({ + // Required inputs + input_ids, + attention_mask, + style, + // Optional inputs + num_inference_steps = 5, + speed = 1.05 + }) { + const { sampling_rate, chunk_compress_factor, base_chunk_size, latent_dim } = this.config; + const { last_hidden_state, durations } = await sessionRun(this.sessions["text_encoder"], { + input_ids, + attention_mask, + style + }); + durations.div_(speed); + const wav_len_max = durations.max().item() * sampling_rate; + const chunk_size = base_chunk_size * chunk_compress_factor; + const latent_len = Math.floor((wav_len_max + chunk_size - 1) / chunk_size); + const batch_size = input_ids.dims[0]; + const latent_mask = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.ones)([batch_size, latent_len]); + const num_steps = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.full)([batch_size], num_inference_steps); + let noisy_latents = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.randn)([batch_size, latent_dim * chunk_compress_factor, latent_len]); + for (let step = 0; step < num_inference_steps; ++step) { + const timestep = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.full)([batch_size], step); + ({ denoised_latents: noisy_latents } = await sessionRun(this.sessions["latent_denoiser"], { + style, + noisy_latents, + latent_mask, + encoder_outputs: last_hidden_state, + attention_mask, + timestep, + num_inference_steps: num_steps + })); + } + const { waveform } = await sessionRun(this.sessions["voice_decoder"], { + latents: noisy_latents + }); + return { + waveform, + durations + }; + } + } + class TrOCRPreTrainedModel extends PreTrainedModel { + } + class TrOCRForCausalLM extends TrOCRPreTrainedModel { + } + class MistralPreTrainedModel extends PreTrainedModel { + } + class MistralModel extends MistralPreTrainedModel { + } + class MistralForCausalLM extends MistralPreTrainedModel { + } + class MinistralPreTrainedModel extends PreTrainedModel { + } + class MinistralModel extends MinistralPreTrainedModel { + } + class MinistralForCausalLM extends MinistralPreTrainedModel { + } + class Ministral3PreTrainedModel extends PreTrainedModel { + } + class Ministral3Model extends Ministral3PreTrainedModel { + } + class Ministral3ForCausalLM extends Ministral3PreTrainedModel { + } + class Ernie4_5PreTrainedModel extends PreTrainedModel { + } + class Ernie4_5Model extends Ernie4_5PreTrainedModel { + } + class Ernie4_5ForCausalLM extends Ernie4_5PreTrainedModel { + } + class Starcoder2PreTrainedModel extends PreTrainedModel { + } + class Starcoder2Model extends Starcoder2PreTrainedModel { + } + class Starcoder2ForCausalLM extends Starcoder2PreTrainedModel { + } + class FalconPreTrainedModel extends PreTrainedModel { + } + class FalconModel extends FalconPreTrainedModel { + } + class FalconForCausalLM extends FalconPreTrainedModel { + } + class ClapPreTrainedModel extends PreTrainedModel { + } + class ClapModel extends ClapPreTrainedModel { + } + class ClapTextModelWithProjection extends ClapPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "text_model" + }); + } + } + class ClapAudioModelWithProjection extends ClapPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "audio_model" + }); + } + } + class VitsPreTrainedModel extends PreTrainedModel { + } + class VitsModel extends VitsPreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} The outputs for the VITS model. + */ + async _call(model_inputs) { + return new VitsModelOutput(await super._call(model_inputs)); + } + } + class SegformerPreTrainedModel extends PreTrainedModel { + } + class SegformerModel extends SegformerPreTrainedModel { + } + class SegformerForImageClassification extends SegformerPreTrainedModel { + } + class SegformerForSemanticSegmentation extends SegformerPreTrainedModel { + } + class StableLmPreTrainedModel extends PreTrainedModel { + } + class StableLmModel extends StableLmPreTrainedModel { + } + class StableLmForCausalLM extends StableLmPreTrainedModel { + } + class EfficientNetPreTrainedModel extends PreTrainedModel { + } + class EfficientNetModel extends EfficientNetPreTrainedModel { + } + class EfficientNetForImageClassification extends EfficientNetPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class MusicgenPreTrainedModel extends PreTrainedModel { + } + class MusicgenModel extends MusicgenPreTrainedModel { + } + class MusicgenForCausalLM extends MusicgenPreTrainedModel { + } + class MusicgenForConditionalGeneration extends PreTrainedModel { + // NOTE: not MusicgenPreTrainedModel + forward_params = [ + "input_ids", + "attention_mask", + "encoder_outputs", + "decoder_input_ids", + "decoder_attention_mask", + "past_key_values" + ]; + /** + * Apply the pattern mask to the final ids, + * then revert the pattern delay mask by filtering the pad token id in a single step. + * @param {Tensor} outputs The output tensor from the model. + * @returns {Tensor} The filtered output tensor. + */ + _apply_and_filter_by_delay_pattern_mask(outputs) { + const [bs_x_codebooks, seqLength] = outputs.dims; + const num_codebooks = this.config.decoder.num_codebooks; + const upperBound = seqLength - num_codebooks; + let newDataSize = 0; + for (let i = 0; i < outputs.size; ++i) { + if (outputs.data[i] === this.config.decoder.pad_token_id) { + continue; + } + const row = i % seqLength; + const col = Math.floor(i / seqLength) % num_codebooks; + const diff = row - col; + if (diff > 0 && diff <= upperBound) { + outputs.data[newDataSize++] = outputs.data[i]; + } + } + const batch_size = Math.floor(bs_x_codebooks / num_codebooks); + const inferred = newDataSize / (batch_size * num_codebooks); + return new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor( + outputs.type, + outputs.data.slice(0, newDataSize), + [batch_size, num_codebooks, inferred] + ); + } + prepare_inputs_for_generation(input_ids, model_inputs, generation_config) { + let clonedInputIds = structuredClone(input_ids); + for (let i = 0; i < clonedInputIds.length; ++i) { + for (let j = 0; j < clonedInputIds[i].length; ++j) { + if (i % this.config.decoder.num_codebooks >= j) { + clonedInputIds[i][j] = BigInt(this.config.decoder.pad_token_id); + } + } + } + if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) { + clonedInputIds = clonedInputIds.concat(clonedInputIds); + } + const prepped = super.prepare_inputs_for_generation(clonedInputIds, model_inputs, generation_config); + return prepped; + } + /** + * Generates sequences of token ids for models with a language modeling head. + * @param {import('./generation/parameters.js').GenerationFunctionParameters} options + * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores. + */ + async generate(options) { + const output_ids = await super.generate(options); + const audio_codes = this._apply_and_filter_by_delay_pattern_mask( + /** @type {Tensor} */ + output_ids + ).unsqueeze_(0); + const { audio_values } = await sessionRun(this.sessions["encodec_decode"], { audio_codes }); + return audio_values; + } + } + class MobileNetV1PreTrainedModel extends PreTrainedModel { + } + class MobileNetV1Model extends MobileNetV1PreTrainedModel { + } + class MobileNetV1ForImageClassification extends MobileNetV1PreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class MobileNetV1ForSemanticSegmentation extends MobileNetV1PreTrainedModel { + } + class MobileNetV2PreTrainedModel extends PreTrainedModel { + } + class MobileNetV2Model extends MobileNetV2PreTrainedModel { + } + class MobileNetV2ForImageClassification extends MobileNetV2PreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class MobileNetV2ForSemanticSegmentation extends MobileNetV2PreTrainedModel { + } + class MobileNetV3PreTrainedModel extends PreTrainedModel { + } + class MobileNetV3Model extends MobileNetV3PreTrainedModel { + } + class MobileNetV3ForImageClassification extends MobileNetV3PreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class MobileNetV3ForSemanticSegmentation extends MobileNetV3PreTrainedModel { + } + class MobileNetV4PreTrainedModel extends PreTrainedModel { + } + class MobileNetV4Model extends MobileNetV4PreTrainedModel { + } + class MobileNetV4ForImageClassification extends MobileNetV4PreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } + } + class MobileNetV4ForSemanticSegmentation extends MobileNetV4PreTrainedModel { + } + class DecisionTransformerPreTrainedModel extends PreTrainedModel { + } + class DecisionTransformerModel extends DecisionTransformerPreTrainedModel { + } + class MultiModalityPreTrainedModel extends PreTrainedModel { + } + class MultiModalityCausalLM extends MultiModalityPreTrainedModel { + forward_params = [ + // prepare_inputs_embeds + "input_ids", + "pixel_values", + "images_seq_mask", + "images_emb_mask", + // language_model + "attention_mask", + "position_ids", + "past_key_values" + ]; + /** + * @param {ConstructorParameters} args + */ + constructor(...args) { + super(...args); + this._generation_mode = "text"; + } + async forward(model_inputs) { + const mode = this._generation_mode ?? "text"; + let output_1; + if (mode === "text" || !model_inputs.past_key_values) { + const session = this.sessions["prepare_inputs_embeds"]; + const prep_inputs = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_4__.pick)(model_inputs, session.inputNames); + output_1 = await sessionRun(session, prep_inputs); + } else { + const session = this.sessions["gen_img_embeds"]; + const prep_inputs = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_4__.pick)({ + image_ids: model_inputs.input_ids + }, session.inputNames); + output_1 = await sessionRun(session, prep_inputs); + } + const input_2 = { ...model_inputs, ...output_1 }; + const output_2 = await decoderForward(this, input_2); + const head = this.sessions[mode === "text" ? "lm_head" : "gen_head"]; + if (!head) { + throw new Error(`Unable to find "${head}" generation head`); + } + const output_3 = await sessionRun(head, (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_4__.pick)(output_2, head.inputNames)); + return { + ...output_1, + ...output_2, + ...output_3 + }; + } + /** + * @param {import('./generation/parameters.js').GenerationFunctionParameters} options + */ + async generate(options) { + this._generation_mode = "text"; + return super.generate(options); + } + /** + * @param {import('./generation/parameters.js').GenerationFunctionParameters} options + */ + async generate_images(options) { + this._generation_mode = "image"; + const start_num_tokens = (options.inputs ?? options[this.main_input_name]).dims[1]; + const all_tokens = await super.generate(options); + const generated_tokens = ( + /** @type {Tensor} */ + all_tokens.slice(null, [start_num_tokens, null]) + ); + const image_decode = this.sessions["image_decode"]; + const { decoded_image } = await sessionRun(image_decode, { + generated_tokens + }); + const clamped = decoded_image.add_(1).mul_(255 / 2).clamp_(0, 255).to("uint8"); + const images = []; + for (const tensor of clamped) { + const img = _utils_image_js__WEBPACK_IMPORTED_MODULE_10__.RawImage.fromTensor(tensor); + images.push(img); + } + return images; + } + } + class MgpstrModelOutput extends ModelOutput { + constructor({ char_logits, bpe_logits, wp_logits }) { + super(); + this.char_logits = char_logits; + this.bpe_logits = bpe_logits; + this.wp_logits = wp_logits; + } + get logits() { + return [this.char_logits, this.bpe_logits, this.wp_logits]; + } + } + class MgpstrPreTrainedModel extends PreTrainedModel { + } + class MgpstrForSceneTextRecognition extends MgpstrPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new MgpstrModelOutput(await super._call(model_inputs)); + } + } + class PatchTSTPreTrainedModel extends PreTrainedModel { + } + class PatchTSTModel extends PatchTSTPreTrainedModel { + } + class PatchTSTForPrediction extends PatchTSTPreTrainedModel { + } + class PatchTSMixerPreTrainedModel extends PreTrainedModel { + } + class PatchTSMixerModel extends PatchTSMixerPreTrainedModel { + } + class PatchTSMixerForPrediction extends PatchTSMixerPreTrainedModel { + } + class UltravoxPreTrainedModel extends PreTrainedModel { + forward_params = [ + "input_ids", + "attention_mask", + "position_ids", + "audio_values", + "past_key_values" + ]; + } + class UltravoxModel extends UltravoxPreTrainedModel { + _merge_input_ids_with_audio_features(kwargs) { + const audio_hidden_size = kwargs.audio_features.dims.at(-1); + const reshaped_audio_features = kwargs.audio_features.view(-1, audio_hidden_size); + return default_merge_input_ids_with_audio_features({ + // @ts-ignore + audio_token_id: this.config.ignore_index ?? this.config.audio_token_id, + ...kwargs, + audio_features: reshaped_audio_features + }); + } + } + class VoxtralForConditionalGeneration extends UltravoxModel { + } + class MimiPreTrainedModel extends PreTrainedModel { + main_input_name = "input_values"; + forward_params = ["input_values"]; + } + class MimiEncoderOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.audio_codes Discrete code embeddings, of shape `(batch_size, num_quantizers, codes_length)`. + */ + constructor({ audio_codes }) { + super(); + this.audio_codes = audio_codes; + } + } + class MimiDecoderOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.audio_values Decoded audio values, of shape `(batch_size, num_channels, sequence_length)`. + */ + constructor({ audio_values }) { + super(); + this.audio_values = audio_values; + } + } + class MimiModel extends MimiPreTrainedModel { + /** + * Encodes the input audio waveform into discrete codes. + * @param {Object} inputs Model inputs + * @param {Tensor} [inputs.input_values] Float values of the input audio waveform, of shape `(batch_size, channels, sequence_length)`). + * @returns {Promise} The output tensor of shape `(batch_size, num_codebooks, sequence_length)`. + */ + async encode(inputs) { + return new MimiEncoderOutput(await sessionRun(this.sessions["encoder_model"], inputs)); + } + /** + * Decodes the given frames into an output audio waveform. + * @param {MimiEncoderOutput} inputs The encoded audio codes. + * @returns {Promise} The output tensor of shape `(batch_size, num_channels, sequence_length)`. + */ + async decode(inputs) { + return new MimiDecoderOutput(await sessionRun(this.sessions["decoder_model"], inputs)); + } + } + class MimiEncoderModel extends MimiPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "encoder_model" + }); + } + } + class MimiDecoderModel extends MimiPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "decoder_model" + }); + } + } + class DacPreTrainedModel extends PreTrainedModel { + main_input_name = "input_values"; + forward_params = ["input_values"]; + } + class DacEncoderOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.audio_codes Discrete code embeddings, of shape `(batch_size, num_quantizers, codes_length)`. + */ + constructor({ audio_codes }) { + super(); + this.audio_codes = audio_codes; + } + } + class DacDecoderOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.audio_values Decoded audio values, of shape `(batch_size, num_channels, sequence_length)`. + */ + constructor({ audio_values }) { + super(); + this.audio_values = audio_values; + } + } + class DacModel extends DacPreTrainedModel { + /** + * Encodes the input audio waveform into discrete codes. + * @param {Object} inputs Model inputs + * @param {Tensor} [inputs.input_values] Float values of the input audio waveform, of shape `(batch_size, channels, sequence_length)`). + * @returns {Promise} The output tensor of shape `(batch_size, num_codebooks, sequence_length)`. + */ + async encode(inputs) { + return new DacEncoderOutput(await sessionRun(this.sessions["encoder_model"], inputs)); + } + /** + * Decodes the given frames into an output audio waveform. + * @param {DacEncoderOutput} inputs The encoded audio codes. + * @returns {Promise} The output tensor of shape `(batch_size, num_channels, sequence_length)`. + */ + async decode(inputs) { + return new DacDecoderOutput(await sessionRun(this.sessions["decoder_model"], inputs)); + } + } + class DacEncoderModel extends DacPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "encoder_model" + }); + } + } + class DacDecoderModel extends DacPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "decoder_model" + }); + } + } + class SnacPreTrainedModel extends PreTrainedModel { + main_input_name = "input_values"; + forward_params = ["input_values"]; + } + class SnacModel extends SnacPreTrainedModel { + /** + * Encodes the input audio waveform into discrete codes. + * @param {Object} inputs Model inputs + * @param {Tensor} [inputs.input_values] Float values of the input audio waveform, of shape `(batch_size, channels, sequence_length)`). + * @returns {Promise>} The output tensors of shape `(batch_size, num_codebooks, sequence_length)`. + */ + async encode(inputs) { + return await sessionRun(this.sessions["encoder_model"], inputs); + } + /** + * Decodes the given frames into an output audio waveform. + * @param {Record} inputs The encoded audio codes. + * @returns {Promise<{audio_values: Tensor}>} The output tensor of shape `(batch_size, num_channels, sequence_length)`. + */ + async decode(inputs) { + return await sessionRun(this.sessions["decoder_model"], inputs); + } + } + class SnacEncoderModel extends SnacPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "encoder_model" + }); + } + } + class SnacDecoderModel extends SnacPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "decoder_model" + }); + } + } + class PretrainedMixin { + /** + * Mapping from model type to model class. + * @type {Map[]} + */ + static MODEL_CLASS_MAPPINGS = null; + /** + * Whether to attempt to instantiate the base class (`PretrainedModel`) if + * the model type is not found in the mapping. + */ + static BASE_IF_FAIL = false; + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, { + progress_callback = null, + config = null, + cache_dir = null, + local_files_only = false, + revision = "main", + model_file_name = null, + subfolder = "onnx", + device = null, + dtype = null, + use_external_data_format = null, + session_options = {} + } = {}) { + const options = { + progress_callback, + config, + cache_dir, + local_files_only, + revision, + model_file_name, + subfolder, + device, + dtype, + use_external_data_format, + session_options + }; + options.config = await _configs_js__WEBPACK_IMPORTED_MODULE_0__.AutoConfig.from_pretrained(pretrained_model_name_or_path, options); + if (!this.MODEL_CLASS_MAPPINGS) { + throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: " + this.name); + } + const model_type = options.config.model_type; + for (const MODEL_CLASS_MAPPING of this.MODEL_CLASS_MAPPINGS) { + let modelInfo = MODEL_CLASS_MAPPING.get(model_type); + if (!modelInfo) { + for (const cls of MODEL_CLASS_MAPPING.values()) { + if (cls[0] === model_type) { + modelInfo = cls; + break; + } + } + if (!modelInfo) continue; + } + return await modelInfo[1].from_pretrained(pretrained_model_name_or_path, options); + } + if (this.BASE_IF_FAIL) { + if (!CUSTOM_ARCHITECTURES.has(model_type)) { + console.warn(`Unknown model class "${model_type}", attempting to construct from base class.`); + } + return await PreTrainedModel.from_pretrained(pretrained_model_name_or_path, options); + } else { + throw Error(`Unsupported model type: ${model_type}`); + } + } + } + const MODEL_MAPPING_NAMES_ENCODER_ONLY = /* @__PURE__ */ new Map([ + ["bert", ["BertModel", BertModel]], + ["neobert", ["NeoBertModel", NeoBertModel]], + ["modernbert", ["ModernBertModel", ModernBertModel]], + ["nomic_bert", ["NomicBertModel", NomicBertModel]], + ["roformer", ["RoFormerModel", RoFormerModel]], + ["electra", ["ElectraModel", ElectraModel]], + ["esm", ["EsmModel", EsmModel]], + ["convbert", ["ConvBertModel", ConvBertModel]], + ["camembert", ["CamembertModel", CamembertModel]], + ["deberta", ["DebertaModel", DebertaModel]], + ["deberta-v2", ["DebertaV2Model", DebertaV2Model]], + ["mpnet", ["MPNetModel", MPNetModel]], + ["albert", ["AlbertModel", AlbertModel]], + ["distilbert", ["DistilBertModel", DistilBertModel]], + ["roberta", ["RobertaModel", RobertaModel]], + ["xlm", ["XLMModel", XLMModel]], + ["xlm-roberta", ["XLMRobertaModel", XLMRobertaModel]], + ["clap", ["ClapModel", ClapModel]], + ["clip", ["CLIPModel", CLIPModel]], + ["clipseg", ["CLIPSegModel", CLIPSegModel]], + ["chinese_clip", ["ChineseCLIPModel", ChineseCLIPModel]], + ["siglip", ["SiglipModel", SiglipModel]], + ["jina_clip", ["JinaCLIPModel", JinaCLIPModel]], + ["mobilebert", ["MobileBertModel", MobileBertModel]], + ["squeezebert", ["SqueezeBertModel", SqueezeBertModel]], + ["wav2vec2", ["Wav2Vec2Model", Wav2Vec2Model]], + ["wav2vec2-bert", ["Wav2Vec2BertModel", Wav2Vec2BertModel]], + ["unispeech", ["UniSpeechModel", UniSpeechModel]], + ["unispeech-sat", ["UniSpeechSatModel", UniSpeechSatModel]], + ["hubert", ["HubertModel", HubertModel]], + ["wavlm", ["WavLMModel", WavLMModel]], + ["audio-spectrogram-transformer", ["ASTModel", ASTModel]], + ["vits", ["VitsModel", VitsModel]], + ["pyannote", ["PyAnnoteModel", PyAnnoteModel]], + ["wespeaker-resnet", ["WeSpeakerResNetModel", WeSpeakerResNetModel]], + ["detr", ["DetrModel", DetrModel]], + ["rt_detr", ["RTDetrModel", RTDetrModel]], + ["rt_detr_v2", ["RTDetrV2Model", RTDetrV2Model]], + ["rf_detr", ["RFDetrModel", RFDetrModel]], + ["d_fine", ["DFineModel", DFineModel]], + ["table-transformer", ["TableTransformerModel", TableTransformerModel]], + ["vit", ["ViTModel", ViTModel]], + ["ijepa", ["IJepaModel", IJepaModel]], + ["pvt", ["PvtModel", PvtModel]], + ["vit_msn", ["ViTMSNModel", ViTMSNModel]], + ["vit_mae", ["ViTMAEModel", ViTMAEModel]], + ["groupvit", ["GroupViTModel", GroupViTModel]], + ["fastvit", ["FastViTModel", FastViTModel]], + ["mobilevit", ["MobileViTModel", MobileViTModel]], + ["mobilevitv2", ["MobileViTV2Model", MobileViTV2Model]], + ["owlvit", ["OwlViTModel", OwlViTModel]], + ["owlv2", ["Owlv2Model", Owlv2Model]], + ["beit", ["BeitModel", BeitModel]], + ["deit", ["DeiTModel", DeiTModel]], + ["hiera", ["HieraModel", HieraModel]], + ["convnext", ["ConvNextModel", ConvNextModel]], + ["convnextv2", ["ConvNextV2Model", ConvNextV2Model]], + ["dinov2", ["Dinov2Model", Dinov2Model]], + ["dinov2_with_registers", ["Dinov2WithRegistersModel", Dinov2WithRegistersModel]], + ["dinov3_vit", ["DINOv3ViTModel", DINOv3ViTModel]], + ["dinov3_convnext", ["DINOv3ConvNextModel", DINOv3ConvNextModel]], + ["resnet", ["ResNetModel", ResNetModel]], + ["swin", ["SwinModel", SwinModel]], + ["swin2sr", ["Swin2SRModel", Swin2SRModel]], + ["donut-swin", ["DonutSwinModel", DonutSwinModel]], + ["yolos", ["YolosModel", YolosModel]], + ["dpt", ["DPTModel", DPTModel]], + ["glpn", ["GLPNModel", GLPNModel]], + ["hifigan", ["SpeechT5HifiGan", SpeechT5HifiGan]], + ["efficientnet", ["EfficientNetModel", EfficientNetModel]], + ["decision_transformer", ["DecisionTransformerModel", DecisionTransformerModel]], + ["patchtst", ["PatchTSTForPrediction", PatchTSTModel]], + ["patchtsmixer", ["PatchTSMixerForPrediction", PatchTSMixerModel]], + ["mobilenet_v1", ["MobileNetV1Model", MobileNetV1Model]], + ["mobilenet_v2", ["MobileNetV2Model", MobileNetV2Model]], + ["mobilenet_v3", ["MobileNetV3Model", MobileNetV3Model]], + ["mobilenet_v4", ["MobileNetV4Model", MobileNetV4Model]], + ["maskformer", ["MaskFormerModel", MaskFormerModel]], + ["mgp-str", ["MgpstrForSceneTextRecognition", MgpstrForSceneTextRecognition]], + ["style_text_to_speech_2", ["StyleTextToSpeech2Model", StyleTextToSpeech2Model]] + ]); + const MODEL_MAPPING_NAMES_ENCODER_DECODER = /* @__PURE__ */ new Map([ + ["t5", ["T5Model", T5Model]], + ["longt5", ["LongT5Model", LongT5Model]], + ["mt5", ["MT5Model", MT5Model]], + ["bart", ["BartModel", BartModel]], + ["mbart", ["MBartModel", MBartModel]], + ["marian", ["MarianModel", MarianModel]], + ["whisper", ["WhisperModel", WhisperModel]], + ["m2m_100", ["M2M100Model", M2M100Model]], + ["blenderbot", ["BlenderbotModel", BlenderbotModel]], + ["blenderbot-small", ["BlenderbotSmallModel", BlenderbotSmallModel]] + ]); + const MODEL_MAPPING_NAMES_AUTO_ENCODER = /* @__PURE__ */ new Map([ + ["mimi", ["MimiModel", MimiModel]], + ["dac", ["DacModel", DacModel]], + ["snac", ["SnacModel", SnacModel]] + ]); + const MODEL_MAPPING_NAMES_DECODER_ONLY = /* @__PURE__ */ new Map([ + ["bloom", ["BloomModel", BloomModel]], + ["jais", ["JAISModel", JAISModel]], + ["gpt2", ["GPT2Model", GPT2Model]], + ["gptj", ["GPTJModel", GPTJModel]], + ["gpt_bigcode", ["GPTBigCodeModel", GPTBigCodeModel]], + ["gpt_neo", ["GPTNeoModel", GPTNeoModel]], + ["gpt_neox", ["GPTNeoXModel", GPTNeoXModel]], + ["codegen", ["CodeGenModel", CodeGenModel]], + ["llama", ["LlamaModel", LlamaModel]], + ["nanochat", ["NanoChatModel", NanoChatModel]], + ["arcee", ["ArceeModel", ArceeModel]], + ["lfm2", ["Lfm2Model", Lfm2Model]], + ["smollm3", ["SmolLM3Model", SmolLM3Model]], + ["exaone", ["ExaoneModel", ExaoneModel]], + ["olmo", ["OlmoModel", OlmoModel]], + ["olmo2", ["Olmo2Model", Olmo2Model]], + ["mobilellm", ["MobileLLMModel", MobileLLMModel]], + ["granite", ["GraniteModel", GraniteModel]], + ["granitemoehybrid", ["GraniteMoeHybridModel", GraniteMoeHybridModel]], + ["cohere", ["CohereModel", CohereModel]], + ["gemma", ["GemmaModel", GemmaModel]], + ["gemma2", ["Gemma2Model", Gemma2Model]], + ["vaultgemma", ["VaultGemmaModel", VaultGemmaModel]], + ["gemma3_text", ["Gemma3Model", Gemma3Model]], + ["helium", ["HeliumModel", HeliumModel]], + ["glm", ["GlmModel", GlmModel]], + ["openelm", ["OpenELMModel", OpenELMModel]], + ["qwen2", ["Qwen2Model", Qwen2Model]], + ["qwen3", ["Qwen3Model", Qwen3Model]], + ["phi", ["PhiModel", PhiModel]], + ["phi3", ["Phi3Model", Phi3Model]], + ["mpt", ["MptModel", MptModel]], + ["opt", ["OPTModel", OPTModel]], + ["mistral", ["MistralModel", MistralModel]], + ["ministral", ["MinistralModel", MinistralModel]], + ["ministral3", ["Ministral3Model", Ministral3Model]], + ["ernie4_5", ["Ernie4_5Model", Ernie4_5Model]], + ["starcoder2", ["Starcoder2Model", Starcoder2Model]], + ["falcon", ["FalconModel", FalconModel]], + ["stablelm", ["StableLmModel", StableLmModel]], + ["modernbert-decoder", ["ModernBertDecoderModel", ModernBertDecoderModel]] + ]); + const MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["speecht5", ["SpeechT5ForSpeechToText", SpeechT5ForSpeechToText]], + ["whisper", ["WhisperForConditionalGeneration", WhisperForConditionalGeneration]], + ["lite-whisper", ["LiteWhisperForConditionalGeneration", LiteWhisperForConditionalGeneration]], + ["moonshine", ["MoonshineForConditionalGeneration", MoonshineForConditionalGeneration]] + ]); + const MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["speecht5", ["SpeechT5ForTextToSpeech", SpeechT5ForTextToSpeech]] + ]); + const MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["vits", ["VitsModel", VitsModel]], + ["musicgen", ["MusicgenForConditionalGeneration", MusicgenForConditionalGeneration]], + ["supertonic", ["SupertonicForConditionalGeneration", SupertonicForConditionalGeneration]] + ]); + const MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["bert", ["BertForSequenceClassification", BertForSequenceClassification]], + ["neobert", ["NeoBertForSequenceClassification", NeoBertForSequenceClassification]], + ["modernbert", ["ModernBertForSequenceClassification", ModernBertForSequenceClassification]], + ["roformer", ["RoFormerForSequenceClassification", RoFormerForSequenceClassification]], + ["electra", ["ElectraForSequenceClassification", ElectraForSequenceClassification]], + ["esm", ["EsmForSequenceClassification", EsmForSequenceClassification]], + ["convbert", ["ConvBertForSequenceClassification", ConvBertForSequenceClassification]], + ["camembert", ["CamembertForSequenceClassification", CamembertForSequenceClassification]], + ["deberta", ["DebertaForSequenceClassification", DebertaForSequenceClassification]], + ["deberta-v2", ["DebertaV2ForSequenceClassification", DebertaV2ForSequenceClassification]], + ["mpnet", ["MPNetForSequenceClassification", MPNetForSequenceClassification]], + ["albert", ["AlbertForSequenceClassification", AlbertForSequenceClassification]], + ["distilbert", ["DistilBertForSequenceClassification", DistilBertForSequenceClassification]], + ["roberta", ["RobertaForSequenceClassification", RobertaForSequenceClassification]], + ["xlm", ["XLMForSequenceClassification", XLMForSequenceClassification]], + ["xlm-roberta", ["XLMRobertaForSequenceClassification", XLMRobertaForSequenceClassification]], + ["bart", ["BartForSequenceClassification", BartForSequenceClassification]], + ["mbart", ["MBartForSequenceClassification", MBartForSequenceClassification]], + ["mobilebert", ["MobileBertForSequenceClassification", MobileBertForSequenceClassification]], + ["squeezebert", ["SqueezeBertForSequenceClassification", SqueezeBertForSequenceClassification]] + ]); + const MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["bert", ["BertForTokenClassification", BertForTokenClassification]], + ["neobert", ["NeoBertForTokenClassification", NeoBertForTokenClassification]], + ["modernbert", ["ModernBertForTokenClassification", ModernBertForTokenClassification]], + ["roformer", ["RoFormerForTokenClassification", RoFormerForTokenClassification]], + ["electra", ["ElectraForTokenClassification", ElectraForTokenClassification]], + ["esm", ["EsmForTokenClassification", EsmForTokenClassification]], + ["convbert", ["ConvBertForTokenClassification", ConvBertForTokenClassification]], + ["camembert", ["CamembertForTokenClassification", CamembertForTokenClassification]], + ["deberta", ["DebertaForTokenClassification", DebertaForTokenClassification]], + ["deberta-v2", ["DebertaV2ForTokenClassification", DebertaV2ForTokenClassification]], + ["mpnet", ["MPNetForTokenClassification", MPNetForTokenClassification]], + ["distilbert", ["DistilBertForTokenClassification", DistilBertForTokenClassification]], + ["roberta", ["RobertaForTokenClassification", RobertaForTokenClassification]], + ["xlm", ["XLMForTokenClassification", XLMForTokenClassification]], + ["xlm-roberta", ["XLMRobertaForTokenClassification", XLMRobertaForTokenClassification]] + ]); + const MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["t5", ["T5ForConditionalGeneration", T5ForConditionalGeneration]], + ["longt5", ["LongT5ForConditionalGeneration", LongT5ForConditionalGeneration]], + ["mt5", ["MT5ForConditionalGeneration", MT5ForConditionalGeneration]], + ["bart", ["BartForConditionalGeneration", BartForConditionalGeneration]], + ["mbart", ["MBartForConditionalGeneration", MBartForConditionalGeneration]], + ["marian", ["MarianMTModel", MarianMTModel]], + ["m2m_100", ["M2M100ForConditionalGeneration", M2M100ForConditionalGeneration]], + ["blenderbot", ["BlenderbotForConditionalGeneration", BlenderbotForConditionalGeneration]], + ["blenderbot-small", ["BlenderbotSmallForConditionalGeneration", BlenderbotSmallForConditionalGeneration]] + ]); + const MODEL_FOR_CAUSAL_LM_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["bloom", ["BloomForCausalLM", BloomForCausalLM]], + ["gpt2", ["GPT2LMHeadModel", GPT2LMHeadModel]], + ["jais", ["JAISLMHeadModel", JAISLMHeadModel]], + ["gptj", ["GPTJForCausalLM", GPTJForCausalLM]], + ["gpt_bigcode", ["GPTBigCodeForCausalLM", GPTBigCodeForCausalLM]], + ["gpt_neo", ["GPTNeoForCausalLM", GPTNeoForCausalLM]], + ["gpt_neox", ["GPTNeoXForCausalLM", GPTNeoXForCausalLM]], + ["codegen", ["CodeGenForCausalLM", CodeGenForCausalLM]], + ["llama", ["LlamaForCausalLM", LlamaForCausalLM]], + ["nanochat", ["NanoChatForCausalLM", NanoChatForCausalLM]], + ["llama4_text", ["Llama4ForCausalLM", Llama4ForCausalLM]], + ["arcee", ["ArceeForCausalLM", ArceeForCausalLM]], + ["lfm2", ["Lfm2ForCausalLM", Lfm2ForCausalLM]], + ["smollm3", ["SmolLM3ForCausalLM", SmolLM3ForCausalLM]], + ["exaone", ["ExaoneForCausalLM", ExaoneForCausalLM]], + ["olmo", ["OlmoForCausalLM", OlmoForCausalLM]], + ["olmo2", ["Olmo2ForCausalLM", Olmo2ForCausalLM]], + ["mobilellm", ["MobileLLMForCausalLM", MobileLLMForCausalLM]], + ["granite", ["GraniteForCausalLM", GraniteForCausalLM]], + ["granitemoehybrid", ["GraniteMoeHybridForCausalLM", GraniteMoeHybridForCausalLM]], + ["cohere", ["CohereForCausalLM", CohereForCausalLM]], + ["gemma", ["GemmaForCausalLM", GemmaForCausalLM]], + ["gemma2", ["Gemma2ForCausalLM", Gemma2ForCausalLM]], + ["vaultgemma", ["VaultGemmaForCausalLM", VaultGemmaForCausalLM]], + ["gemma3_text", ["Gemma3ForCausalLM", Gemma3ForCausalLM]], + ["helium", ["HeliumForCausalLM", HeliumForCausalLM]], + ["glm", ["GlmForCausalLM", GlmForCausalLM]], + ["openelm", ["OpenELMForCausalLM", OpenELMForCausalLM]], + ["qwen2", ["Qwen2ForCausalLM", Qwen2ForCausalLM]], + ["qwen3", ["Qwen3ForCausalLM", Qwen3ForCausalLM]], + ["phi", ["PhiForCausalLM", PhiForCausalLM]], + ["phi3", ["Phi3ForCausalLM", Phi3ForCausalLM]], + ["mpt", ["MptForCausalLM", MptForCausalLM]], + ["opt", ["OPTForCausalLM", OPTForCausalLM]], + ["mbart", ["MBartForCausalLM", MBartForCausalLM]], + ["mistral", ["MistralForCausalLM", MistralForCausalLM]], + ["ministral", ["MinistralForCausalLM", MinistralForCausalLM]], + ["ministral3", ["Ministral3ForCausalLM", Ministral3ForCausalLM]], + ["ernie4_5", ["Ernie4_5ForCausalLM", Ernie4_5ForCausalLM]], + ["starcoder2", ["Starcoder2ForCausalLM", Starcoder2ForCausalLM]], + ["falcon", ["FalconForCausalLM", FalconForCausalLM]], + ["trocr", ["TrOCRForCausalLM", TrOCRForCausalLM]], + ["stablelm", ["StableLmForCausalLM", StableLmForCausalLM]], + ["modernbert-decoder", ["ModernBertDecoderForCausalLM", ModernBertDecoderForCausalLM]], + // Also image-text-to-text + ["phi3_v", ["Phi3VForCausalLM", Phi3VForCausalLM]] + ]); + const MODEL_FOR_MULTIMODALITY_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["multi_modality", ["MultiModalityCausalLM", MultiModalityCausalLM]] + ]); + const MODEL_FOR_MASKED_LM_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["bert", ["BertForMaskedLM", BertForMaskedLM]], + ["neobert", ["NeoBertForMaskedLM", NeoBertForMaskedLM]], + ["modernbert", ["ModernBertForMaskedLM", ModernBertForMaskedLM]], + ["roformer", ["RoFormerForMaskedLM", RoFormerForMaskedLM]], + ["electra", ["ElectraForMaskedLM", ElectraForMaskedLM]], + ["esm", ["EsmForMaskedLM", EsmForMaskedLM]], + ["convbert", ["ConvBertForMaskedLM", ConvBertForMaskedLM]], + ["camembert", ["CamembertForMaskedLM", CamembertForMaskedLM]], + ["deberta", ["DebertaForMaskedLM", DebertaForMaskedLM]], + ["deberta-v2", ["DebertaV2ForMaskedLM", DebertaV2ForMaskedLM]], + ["mpnet", ["MPNetForMaskedLM", MPNetForMaskedLM]], + ["albert", ["AlbertForMaskedLM", AlbertForMaskedLM]], + ["distilbert", ["DistilBertForMaskedLM", DistilBertForMaskedLM]], + ["roberta", ["RobertaForMaskedLM", RobertaForMaskedLM]], + ["xlm", ["XLMWithLMHeadModel", XLMWithLMHeadModel]], + ["xlm-roberta", ["XLMRobertaForMaskedLM", XLMRobertaForMaskedLM]], + ["mobilebert", ["MobileBertForMaskedLM", MobileBertForMaskedLM]], + ["squeezebert", ["SqueezeBertForMaskedLM", SqueezeBertForMaskedLM]] + ]); + const MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["bert", ["BertForQuestionAnswering", BertForQuestionAnswering]], + ["neobert", ["NeoBertForQuestionAnswering", NeoBertForQuestionAnswering]], + ["roformer", ["RoFormerForQuestionAnswering", RoFormerForQuestionAnswering]], + ["electra", ["ElectraForQuestionAnswering", ElectraForQuestionAnswering]], + ["convbert", ["ConvBertForQuestionAnswering", ConvBertForQuestionAnswering]], + ["camembert", ["CamembertForQuestionAnswering", CamembertForQuestionAnswering]], + ["deberta", ["DebertaForQuestionAnswering", DebertaForQuestionAnswering]], + ["deberta-v2", ["DebertaV2ForQuestionAnswering", DebertaV2ForQuestionAnswering]], + ["mpnet", ["MPNetForQuestionAnswering", MPNetForQuestionAnswering]], + ["albert", ["AlbertForQuestionAnswering", AlbertForQuestionAnswering]], + ["distilbert", ["DistilBertForQuestionAnswering", DistilBertForQuestionAnswering]], + ["roberta", ["RobertaForQuestionAnswering", RobertaForQuestionAnswering]], + ["xlm", ["XLMForQuestionAnswering", XLMForQuestionAnswering]], + ["xlm-roberta", ["XLMRobertaForQuestionAnswering", XLMRobertaForQuestionAnswering]], + ["mobilebert", ["MobileBertForQuestionAnswering", MobileBertForQuestionAnswering]], + ["squeezebert", ["SqueezeBertForQuestionAnswering", SqueezeBertForQuestionAnswering]] + ]); + const MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["vision-encoder-decoder", ["VisionEncoderDecoderModel", VisionEncoderDecoderModel]], + ["idefics3", ["Idefics3ForConditionalGeneration", Idefics3ForConditionalGeneration]], + ["smolvlm", ["SmolVLMForConditionalGeneration", SmolVLMForConditionalGeneration]] + ]); + const MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["llava", ["LlavaForConditionalGeneration", LlavaForConditionalGeneration]], + ["llava_onevision", ["LlavaOnevisionForConditionalGeneration", LlavaOnevisionForConditionalGeneration]], + ["moondream1", ["Moondream1ForConditionalGeneration", Moondream1ForConditionalGeneration]], + ["florence2", ["Florence2ForConditionalGeneration", Florence2ForConditionalGeneration]], + ["qwen2-vl", ["Qwen2VLForConditionalGeneration", Qwen2VLForConditionalGeneration]], + ["idefics3", ["Idefics3ForConditionalGeneration", Idefics3ForConditionalGeneration]], + ["smolvlm", ["SmolVLMForConditionalGeneration", SmolVLMForConditionalGeneration]], + ["paligemma", ["PaliGemmaForConditionalGeneration", PaliGemmaForConditionalGeneration]], + ["llava_qwen2", ["LlavaQwen2ForCausalLM", LlavaQwen2ForCausalLM]], + ["gemma3n", ["Gemma3nForConditionalGeneration", Gemma3nForConditionalGeneration]], + ["mistral3", ["Mistral3ForConditionalGeneration", Mistral3ForConditionalGeneration]] + ]); + const MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["ultravox", ["UltravoxModel", UltravoxModel]], + ["voxtral", ["VoxtralForConditionalGeneration", VoxtralForConditionalGeneration]] + ]); + const MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["vision-encoder-decoder", ["VisionEncoderDecoderModel", VisionEncoderDecoderModel]] + ]); + const MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["vit", ["ViTForImageClassification", ViTForImageClassification]], + ["ijepa", ["IJepaForImageClassification", IJepaForImageClassification]], + ["pvt", ["PvtForImageClassification", PvtForImageClassification]], + ["vit_msn", ["ViTMSNForImageClassification", ViTMSNForImageClassification]], + ["fastvit", ["FastViTForImageClassification", FastViTForImageClassification]], + ["mobilevit", ["MobileViTForImageClassification", MobileViTForImageClassification]], + ["mobilevitv2", ["MobileViTV2ForImageClassification", MobileViTV2ForImageClassification]], + ["beit", ["BeitForImageClassification", BeitForImageClassification]], + ["deit", ["DeiTForImageClassification", DeiTForImageClassification]], + ["hiera", ["HieraForImageClassification", HieraForImageClassification]], + ["convnext", ["ConvNextForImageClassification", ConvNextForImageClassification]], + ["convnextv2", ["ConvNextV2ForImageClassification", ConvNextV2ForImageClassification]], + ["dinov2", ["Dinov2ForImageClassification", Dinov2ForImageClassification]], + ["dinov2_with_registers", ["Dinov2WithRegistersForImageClassification", Dinov2WithRegistersForImageClassification]], + ["resnet", ["ResNetForImageClassification", ResNetForImageClassification]], + ["swin", ["SwinForImageClassification", SwinForImageClassification]], + ["segformer", ["SegformerForImageClassification", SegformerForImageClassification]], + ["efficientnet", ["EfficientNetForImageClassification", EfficientNetForImageClassification]], + ["mobilenet_v1", ["MobileNetV1ForImageClassification", MobileNetV1ForImageClassification]], + ["mobilenet_v2", ["MobileNetV2ForImageClassification", MobileNetV2ForImageClassification]], + ["mobilenet_v3", ["MobileNetV3ForImageClassification", MobileNetV3ForImageClassification]], + ["mobilenet_v4", ["MobileNetV4ForImageClassification", MobileNetV4ForImageClassification]] + ]); + const MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["detr", ["DetrForObjectDetection", DetrForObjectDetection]], + ["rt_detr", ["RTDetrForObjectDetection", RTDetrForObjectDetection]], + ["rt_detr_v2", ["RTDetrV2ForObjectDetection", RTDetrV2ForObjectDetection]], + ["rf_detr", ["RFDetrForObjectDetection", RFDetrForObjectDetection]], + ["d_fine", ["DFineForObjectDetection", DFineForObjectDetection]], + ["table-transformer", ["TableTransformerForObjectDetection", TableTransformerForObjectDetection]], + ["yolos", ["YolosForObjectDetection", YolosForObjectDetection]] + ]); + const MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["owlvit", ["OwlViTForObjectDetection", OwlViTForObjectDetection]], + ["owlv2", ["Owlv2ForObjectDetection", Owlv2ForObjectDetection]], + ["grounding-dino", ["GroundingDinoForObjectDetection", GroundingDinoForObjectDetection]] + ]); + const MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + // TODO: Do not add new models here + ["detr", ["DetrForSegmentation", DetrForSegmentation]], + ["clipseg", ["CLIPSegForImageSegmentation", CLIPSegForImageSegmentation]] + ]); + const MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["segformer", ["SegformerForSemanticSegmentation", SegformerForSemanticSegmentation]], + ["sapiens", ["SapiensForSemanticSegmentation", SapiensForSemanticSegmentation]], + ["swin", ["SwinForSemanticSegmentation", SwinForSemanticSegmentation]], + ["mobilenet_v1", ["MobileNetV1ForSemanticSegmentation", MobileNetV1ForSemanticSegmentation]], + ["mobilenet_v2", ["MobileNetV2ForSemanticSegmentation", MobileNetV2ForSemanticSegmentation]], + ["mobilenet_v3", ["MobileNetV3ForSemanticSegmentation", MobileNetV3ForSemanticSegmentation]], + ["mobilenet_v4", ["MobileNetV4ForSemanticSegmentation", MobileNetV4ForSemanticSegmentation]] + ]); + const MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["detr", ["DetrForSegmentation", DetrForSegmentation]], + ["maskformer", ["MaskFormerForInstanceSegmentation", MaskFormerForInstanceSegmentation]] + ]); + const MODEL_FOR_MASK_GENERATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["sam", ["SamModel", SamModel]], + ["sam2", ["Sam2Model", Sam2Model]], + ["edgetam", ["EdgeTamModel", EdgeTamModel]], + ["sam3_tracker", ["Sam3TrackerModel", Sam3TrackerModel]] + ]); + const MODEL_FOR_CTC_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["wav2vec2", ["Wav2Vec2ForCTC", Wav2Vec2ForCTC]], + ["wav2vec2-bert", ["Wav2Vec2BertForCTC", Wav2Vec2BertForCTC]], + ["unispeech", ["UniSpeechForCTC", UniSpeechForCTC]], + ["unispeech-sat", ["UniSpeechSatForCTC", UniSpeechSatForCTC]], + ["wavlm", ["WavLMForCTC", WavLMForCTC]], + ["hubert", ["HubertForCTC", HubertForCTC]], + ["parakeet_ctc", ["ParakeetForCTC", ParakeetForCTC]] + ]); + const MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["wav2vec2", ["Wav2Vec2ForSequenceClassification", Wav2Vec2ForSequenceClassification]], + ["wav2vec2-bert", ["Wav2Vec2BertForSequenceClassification", Wav2Vec2BertForSequenceClassification]], + ["unispeech", ["UniSpeechForSequenceClassification", UniSpeechForSequenceClassification]], + ["unispeech-sat", ["UniSpeechSatForSequenceClassification", UniSpeechSatForSequenceClassification]], + ["wavlm", ["WavLMForSequenceClassification", WavLMForSequenceClassification]], + ["hubert", ["HubertForSequenceClassification", HubertForSequenceClassification]], + ["audio-spectrogram-transformer", ["ASTForAudioClassification", ASTForAudioClassification]] + ]); + const MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["wavlm", ["WavLMForXVector", WavLMForXVector]] + ]); + const MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["unispeech-sat", ["UniSpeechSatForAudioFrameClassification", UniSpeechSatForAudioFrameClassification]], + ["wavlm", ["WavLMForAudioFrameClassification", WavLMForAudioFrameClassification]], + ["wav2vec2", ["Wav2Vec2ForAudioFrameClassification", Wav2Vec2ForAudioFrameClassification]], + ["pyannote", ["PyAnnoteForAudioFrameClassification", PyAnnoteForAudioFrameClassification]] + ]); + const MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["vitmatte", ["VitMatteForImageMatting", VitMatteForImageMatting]] + ]); + const MODEL_FOR_TIME_SERIES_PREDICTION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["patchtst", ["PatchTSTForPrediction", PatchTSTForPrediction]], + ["patchtsmixer", ["PatchTSMixerForPrediction", PatchTSMixerForPrediction]] + ]); + const MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["swin2sr", ["Swin2SRForImageSuperResolution", Swin2SRForImageSuperResolution]] + ]); + const MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["dpt", ["DPTForDepthEstimation", DPTForDepthEstimation]], + ["depth_anything", ["DepthAnythingForDepthEstimation", DepthAnythingForDepthEstimation]], + ["glpn", ["GLPNForDepthEstimation", GLPNForDepthEstimation]], + ["sapiens", ["SapiensForDepthEstimation", SapiensForDepthEstimation]], + ["depth_pro", ["DepthProForDepthEstimation", DepthProForDepthEstimation]], + ["metric3d", ["Metric3DForDepthEstimation", Metric3DForDepthEstimation]], + ["metric3dv2", ["Metric3Dv2ForDepthEstimation", Metric3Dv2ForDepthEstimation]] + ]); + const MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["sapiens", ["SapiensForNormalEstimation", SapiensForNormalEstimation]] + ]); + const MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["vitpose", ["VitPoseForPoseEstimation", VitPoseForPoseEstimation]] + ]); + const MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["clip", ["CLIPVisionModelWithProjection", CLIPVisionModelWithProjection]], + ["siglip", ["SiglipVisionModel", SiglipVisionModel]], + ["jina_clip", ["JinaCLIPVisionModel", JinaCLIPVisionModel]] + ]); + const MODEL_CLASS_TYPE_MAPPING = [ + // MODEL_MAPPING_NAMES: + [MODEL_MAPPING_NAMES_ENCODER_ONLY, MODEL_TYPES.EncoderOnly], + [MODEL_MAPPING_NAMES_ENCODER_DECODER, MODEL_TYPES.EncoderDecoder], + [MODEL_MAPPING_NAMES_DECODER_ONLY, MODEL_TYPES.DecoderOnly], + [MODEL_MAPPING_NAMES_AUTO_ENCODER, MODEL_TYPES.AutoEncoder], + [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq], + [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Seq2Seq], + [MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, MODEL_TYPES.DecoderOnly], + [MODEL_FOR_MULTIMODALITY_MAPPING_NAMES, MODEL_TYPES.MultiModality], + [MODEL_FOR_MASKED_LM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Vision2Seq], + [MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES, MODEL_TYPES.ImageTextToText], + [MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES, MODEL_TYPES.AudioTextToText], + [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_TIME_SERIES_PREDICTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_MASK_GENERATION_MAPPING_NAMES, MODEL_TYPES.MaskGeneration], + [MODEL_FOR_CTC_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq], + [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + // Custom: + [MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly] + ]; + for (const [mappings, type] of MODEL_CLASS_TYPE_MAPPING) { + for (const [name, model] of mappings.values()) { + MODEL_TYPE_MAPPING.set(name, type); + MODEL_CLASS_TO_NAME_MAPPING.set(model, name); + MODEL_NAME_TO_CLASS_MAPPING.set(name, model); + } + } + const CUSTOM_MAPPING = [ + // OVERRIDE: + // TODO: Refactor to allow class to specify model + ["MusicgenForConditionalGeneration", MusicgenForConditionalGeneration, MODEL_TYPES.Musicgen], + ["Phi3VForCausalLM", Phi3VForCausalLM, MODEL_TYPES.Phi3V], + ["CLIPTextModelWithProjection", CLIPTextModelWithProjection, MODEL_TYPES.EncoderOnly], + ["SiglipTextModel", SiglipTextModel, MODEL_TYPES.EncoderOnly], + ["JinaCLIPTextModel", JinaCLIPTextModel, MODEL_TYPES.EncoderOnly], + ["ClapTextModelWithProjection", ClapTextModelWithProjection, MODEL_TYPES.EncoderOnly], + ["ClapAudioModelWithProjection", ClapAudioModelWithProjection, MODEL_TYPES.EncoderOnly], + ["DacEncoderModel", DacEncoderModel, MODEL_TYPES.EncoderOnly], + ["DacDecoderModel", DacDecoderModel, MODEL_TYPES.EncoderOnly], + ["MimiEncoderModel", MimiEncoderModel, MODEL_TYPES.EncoderOnly], + ["MimiDecoderModel", MimiDecoderModel, MODEL_TYPES.EncoderOnly], + ["SnacEncoderModel", SnacEncoderModel, MODEL_TYPES.EncoderOnly], + ["SnacDecoderModel", SnacDecoderModel, MODEL_TYPES.EncoderOnly], + ["Gemma3nForConditionalGeneration", Gemma3nForConditionalGeneration, MODEL_TYPES.ImageAudioTextToText], + ["SupertonicForConditionalGeneration", SupertonicForConditionalGeneration, MODEL_TYPES.Supertonic] + ]; + for (const [name, model, type] of CUSTOM_MAPPING) { + MODEL_TYPE_MAPPING.set(name, type); + MODEL_CLASS_TO_NAME_MAPPING.set(model, name); + MODEL_NAME_TO_CLASS_MAPPING.set(name, model); + } + const CUSTOM_ARCHITECTURES = /* @__PURE__ */ new Map([ + ["modnet", MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES], + ["birefnet", MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES], + ["isnet", MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES], + ["ben", MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES] + ]); + for (const [name, mapping] of CUSTOM_ARCHITECTURES.entries()) { + mapping.set(name, ["PreTrainedModel", PreTrainedModel]); + MODEL_TYPE_MAPPING.set(name, MODEL_TYPES.EncoderOnly); + MODEL_CLASS_TO_NAME_MAPPING.set(PreTrainedModel, name); + MODEL_NAME_TO_CLASS_MAPPING.set(name, PreTrainedModel); + } + class AutoModel extends PretrainedMixin { + /** @type {Map[]} */ + // @ts-ignore + static MODEL_CLASS_MAPPINGS = MODEL_CLASS_TYPE_MAPPING.map((x) => x[0]); + static BASE_IF_FAIL = true; + } + class AutoModelForSequenceClassification extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]; + } + class AutoModelForTokenClassification extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]; + } + class AutoModelForSeq2SeqLM extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]; + } + class AutoModelForSpeechSeq2Seq extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]; + } + class AutoModelForTextToSpectrogram extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]; + } + class AutoModelForTextToWaveform extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]; + } + class AutoModelForCausalLM extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]; + } + class AutoModelForMaskedLM extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_MASKED_LM_MAPPING_NAMES]; + } + class AutoModelForQuestionAnswering extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]; + } + class AutoModelForVision2Seq extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]; + } + class AutoModelForImageClassification extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]; + } + class AutoModelForImageSegmentation extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]; + } + class AutoModelForSemanticSegmentation extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]; + } + class AutoModelForUniversalSegmentation extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]; + } + class AutoModelForObjectDetection extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]; + } + class AutoModelForZeroShotObjectDetection extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]; + } + class AutoModelForMaskGeneration extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]; + } + class AutoModelForCTC extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_CTC_MAPPING_NAMES]; + } + class AutoModelForAudioClassification extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]; + } + class AutoModelForXVector extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]; + } + class AutoModelForAudioFrameClassification extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]; + } + class AutoModelForDocumentQuestionAnswering extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]; + } + class AutoModelForImageMatting extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]; + } + class AutoModelForImageToImage extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]; + } + class AutoModelForDepthEstimation extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]; + } + class AutoModelForNormalEstimation extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]; + } + class AutoModelForPoseEstimation extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]; + } + class AutoModelForImageFeatureExtraction extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]; + } + class AutoModelForImageTextToText extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]; + } + class AutoModelForAudioTextToText extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]; + } + class Seq2SeqLMOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits The output logits of the model. + * @param {Tensor} output.past_key_values An tensor of key/value pairs that represent the previous state of the model. + * @param {Tensor} output.encoder_outputs The output of the encoder in a sequence-to-sequence model. + * @param {Tensor} [output.decoder_attentions] Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads. + * @param {Tensor} [output.cross_attentions] Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads. + */ + constructor({ logits, past_key_values, encoder_outputs, decoder_attentions = null, cross_attentions = null }) { + super(); + this.logits = logits; + this.past_key_values = past_key_values; + this.encoder_outputs = encoder_outputs; + this.decoder_attentions = decoder_attentions; + this.cross_attentions = cross_attentions; + } + } + class SequenceClassifierOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits classification (or regression if config.num_labels==1) scores (before SoftMax). + * @param {Record} [output.attentions] Object of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. + * Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. + */ + constructor({ logits, ...attentions }) { + super(); + this.logits = logits; + const attentions_list = Object.values(attentions); + if (attentions_list.length > 0) { + this.attentions = attentions_list; + } + } + } + class XVectorOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Classification hidden states before AMSoftmax, of shape `(batch_size, config.xvector_output_dim)`. + * @param {Tensor} output.embeddings Utterance embeddings used for vector similarity-based retrieval, of shape `(batch_size, config.xvector_output_dim)`. + */ + constructor({ logits, embeddings }) { + super(); + this.logits = logits; + this.embeddings = embeddings; + } + } + class TokenClassifierOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Classification scores (before SoftMax). + */ + constructor({ logits }) { + super(); + this.logits = logits; + } + } + class MaskedLMOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). + */ + constructor({ logits }) { + super(); + this.logits = logits; + } + } + class QuestionAnsweringModelOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.start_logits Span-start scores (before SoftMax). + * @param {Tensor} output.end_logits Span-end scores (before SoftMax). + */ + constructor({ start_logits, end_logits }) { + super(); + this.start_logits = start_logits; + this.end_logits = end_logits; + } + } + class CausalLMOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax). + */ + constructor({ logits }) { + super(); + this.logits = logits; + } + } + class CausalLMOutputWithPast extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax). + * @param {Tensor} output.past_key_values Contains pre-computed hidden-states (key and values in the self-attention blocks) + * that can be used (see `past_key_values` input) to speed up sequential decoding. + */ + constructor({ logits, past_key_values }) { + super(); + this.logits = logits; + this.past_key_values = past_key_values; + } + } + class ImageMattingOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.alphas Estimated alpha values, of shape `(batch_size, num_channels, height, width)`. + */ + constructor({ alphas }) { + super(); + this.alphas = alphas; + } + } + class VitsModelOutput extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.waveform The final audio waveform predicted by the model, of shape `(batch_size, sequence_length)`. + * @param {Tensor} output.spectrogram The log-mel spectrogram predicted at the output of the flow model. + * This spectrogram is passed to the Hi-Fi GAN decoder model to obtain the final audio waveform. + */ + constructor({ waveform, spectrogram }) { + super(); + this.waveform = waveform; + this.spectrogram = spectrogram; + } + } + }) + ), + /***/ + "./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js": ( + /*!******************************************************************************************************!*\ + !*** ./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js ***! + \******************************************************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + ASTFeatureExtractor: () => ( + /* binding */ + ASTFeatureExtractor + ) + /* harmony export */ + }); + var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/feature_extraction_utils.js */ + "./src/base/feature_extraction_utils.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../utils/tensor.js */ + "./src/utils/tensor.js" + ); + var _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../utils/audio.js */ + "./src/utils/audio.js" + ); + class ASTFeatureExtractor extends _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractor { + constructor(config) { + super(config); + const sampling_rate = this.config.sampling_rate; + const mel_filters = (0, _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.mel_filter_bank)( + 257, + // num_frequency_bins + this.config.num_mel_bins, + // num_mel_filters + 20, + // min_frequency + Math.floor(sampling_rate / 2), + // max_frequency + sampling_rate, + // sampling_rate + null, + // norm + "kaldi", + // mel_scale + true + // triangularize_in_mel_space + ); + this.mel_filters = mel_filters; + this.window = (0, _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.window_function)(400, "hann", { + periodic: false + }); + this.mean = this.config.mean; + this.std = this.config.std; + } + /** + * Computes the log-Mel spectrogram of the provided audio waveform. + * @param {Float32Array|Float64Array} waveform The audio waveform to process. + * @param {number} max_length The maximum number of frames to return. + * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. + */ + async _extract_fbank_features(waveform, max_length) { + return (0, _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.spectrogram)( + waveform, + this.window, + // window + 400, + // frame_length + 160, + // hop_length + { + fft_length: 512, + power: 2, + center: false, + preemphasis: 0.97, + mel_filters: this.mel_filters, + log_mel: "log", + mel_floor: 1192092955078125e-22, + remove_dc_offset: true, + // Custom + max_num_frames: max_length, + transpose: true + } + ); + } + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_values: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. + */ + async _call(audio) { + (0, _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.validate_audio_inputs)(audio, "ASTFeatureExtractor"); + const features = await this._extract_fbank_features(audio, this.config.max_length); + if (this.config.do_normalize) { + const denom = this.std * 2; + const features_data = features.data; + for (let i = 0; i < features_data.length; ++i) { + features_data[i] = (features_data[i] - this.mean) / denom; + } + } + return { + input_values: features.unsqueeze_(0) + }; + } + } + }) + ), + /***/ + "./src/models/auto/feature_extraction_auto.js": ( + /*!****************************************************!*\ + !*** ./src/models/auto/feature_extraction_auto.js ***! + \****************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + AutoFeatureExtractor: () => ( + /* binding */ + AutoFeatureExtractor + ) + /* harmony export */ + }); + var _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../utils/constants.js */ + "./src/utils/constants.js" + ); + var _utils_hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../utils/hub.js */ + "./src/utils/hub.js" + ); + var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../base/feature_extraction_utils.js */ + "./src/base/feature_extraction_utils.js" + ); + var _feature_extractors_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! ../feature_extractors.js */ + "./src/models/feature_extractors.js" + ); + class AutoFeatureExtractor { + /** @type {typeof FeatureExtractor.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + const preprocessorConfig = await (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_1__.getModelJSON)(pretrained_model_name_or_path, _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__.FEATURE_EXTRACTOR_NAME, true, options); + const key = preprocessorConfig.feature_extractor_type; + const feature_extractor_class = _feature_extractors_js__WEBPACK_IMPORTED_MODULE_3__[key]; + if (!feature_extractor_class) { + throw new Error(`Unknown feature_extractor_type: '${key}'. Please report this at ${_utils_constants_js__WEBPACK_IMPORTED_MODULE_0__.GITHUB_ISSUE_URL}.`); + } + return new feature_extractor_class(preprocessorConfig); + } + } + }) + ), + /***/ + "./src/models/auto/image_processing_auto.js": ( + /*!**************************************************!*\ + !*** ./src/models/auto/image_processing_auto.js ***! + \**************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + AutoImageProcessor: () => ( + /* binding */ + AutoImageProcessor + ) + /* harmony export */ + }); + var _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../utils/constants.js */ + "./src/utils/constants.js" + ); + var _utils_hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../utils/hub.js */ + "./src/utils/hub.js" + ); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + var _image_processors_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! ../image_processors.js */ + "./src/models/image_processors.js" + ); + class AutoImageProcessor { + /** @type {typeof ImageProcessor.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + const preprocessorConfig = await (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_1__.getModelJSON)(pretrained_model_name_or_path, _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__.IMAGE_PROCESSOR_NAME, true, options); + const key = preprocessorConfig.image_processor_type ?? preprocessorConfig.feature_extractor_type; + let image_processor_class = _image_processors_js__WEBPACK_IMPORTED_MODULE_3__[key?.replace(/Fast$/, "")]; + if (!image_processor_class) { + if (key !== void 0) { + console.warn(`Image processor type '${key}' not found, assuming base ImageProcessor. Please report this at ${_utils_constants_js__WEBPACK_IMPORTED_MODULE_0__.GITHUB_ISSUE_URL}.`); + } + image_processor_class = _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_2__.ImageProcessor; + } + return new image_processor_class(preprocessorConfig); + } + } + }) + ), + /***/ + "./src/models/auto/processing_auto.js": ( + /*!********************************************!*\ + !*** ./src/models/auto/processing_auto.js ***! + \********************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + AutoProcessor: () => ( + /* binding */ + AutoProcessor + ) + /* harmony export */ + }); + var _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../utils/constants.js */ + "./src/utils/constants.js" + ); + var _utils_hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../utils/hub.js */ + "./src/utils/hub.js" + ); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + var _processors_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! ../processors.js */ + "./src/models/processors.js" + ); + var _image_processors_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__2( + /*! ../image_processors.js */ + "./src/models/image_processors.js" + ); + var _feature_extractors_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__2( + /*! ../feature_extractors.js */ + "./src/models/feature_extractors.js" + ); + class AutoProcessor { + /** @type {typeof Processor.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + const preprocessorConfig = await (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_1__.getModelJSON)(pretrained_model_name_or_path, _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__.IMAGE_PROCESSOR_NAME, true, options); + const { image_processor_type, feature_extractor_type, processor_class } = preprocessorConfig; + if (processor_class && _processors_js__WEBPACK_IMPORTED_MODULE_3__[processor_class]) { + return _processors_js__WEBPACK_IMPORTED_MODULE_3__[processor_class].from_pretrained(pretrained_model_name_or_path, options); + } + if (!image_processor_type && !feature_extractor_type) { + throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config."); + } + const components = {}; + if (image_processor_type) { + const image_processor_class = _image_processors_js__WEBPACK_IMPORTED_MODULE_4__[image_processor_type.replace(/Fast$/, "")]; + if (!image_processor_class) { + throw new Error(`Unknown image_processor_type: '${image_processor_type}'.`); + } + components.image_processor = new image_processor_class(preprocessorConfig); + } + if (feature_extractor_type) { + const image_processor_class = _image_processors_js__WEBPACK_IMPORTED_MODULE_4__[feature_extractor_type]; + if (image_processor_class) { + components.image_processor = new image_processor_class(preprocessorConfig); + } else { + const feature_extractor_class = _feature_extractors_js__WEBPACK_IMPORTED_MODULE_5__[feature_extractor_type]; + if (!feature_extractor_class) { + throw new Error(`Unknown feature_extractor_type: '${feature_extractor_type}'.`); + } + components.feature_extractor = new feature_extractor_class(preprocessorConfig); + } + } + const config = {}; + return new _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__.Processor(config, components, null); + } + } + }) + ), + /***/ + "./src/models/beit/image_processing_beit.js": ( + /*!**************************************************!*\ + !*** ./src/models/beit/image_processing_beit.js ***! + \**************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + BeitFeatureExtractor: () => ( + /* binding */ + BeitFeatureExtractor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class BeitFeatureExtractor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + } + }) + ), + /***/ + "./src/models/bit/image_processing_bit.js": ( + /*!************************************************!*\ + !*** ./src/models/bit/image_processing_bit.js ***! + \************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + BitImageProcessor: () => ( + /* binding */ + BitImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class BitImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + } + }) + ), + /***/ + "./src/models/chinese_clip/image_processing_chinese_clip.js": ( + /*!******************************************************************!*\ + !*** ./src/models/chinese_clip/image_processing_chinese_clip.js ***! + \******************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + ChineseCLIPFeatureExtractor: () => ( + /* binding */ + ChineseCLIPFeatureExtractor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class ChineseCLIPFeatureExtractor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + } + }) + ), + /***/ + "./src/models/clap/feature_extraction_clap.js": ( + /*!****************************************************!*\ + !*** ./src/models/clap/feature_extraction_clap.js ***! + \****************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + ClapFeatureExtractor: () => ( + /* binding */ + ClapFeatureExtractor + ) + /* harmony export */ + }); + var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/feature_extraction_utils.js */ + "./src/base/feature_extraction_utils.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../utils/tensor.js */ + "./src/utils/tensor.js" + ); + var _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../utils/audio.js */ + "./src/utils/audio.js" + ); + class ClapFeatureExtractor extends _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractor { + constructor(config) { + super(config); + this.mel_filters = (0, _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.mel_filter_bank)( + this.config.nb_frequency_bins, + // num_frequency_bins + this.config.feature_size, + // num_mel_filters + this.config.frequency_min, + // min_frequency + this.config.frequency_max, + // max_frequency + this.config.sampling_rate, + // sampling_rate + null, + // norm + "htk" + // mel_scale + ); + this.mel_filters_slaney = (0, _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.mel_filter_bank)( + this.config.nb_frequency_bins, + // num_frequency_bins + this.config.feature_size, + // num_mel_filters + this.config.frequency_min, + // min_frequency + this.config.frequency_max, + // max_frequency + this.config.sampling_rate, + // sampling_rate + "slaney", + // norm + "slaney" + // mel_scale + ); + this.window = (0, _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.window_function)(this.config.fft_window_size, "hann"); + } + /** + * Extracts the mel spectrogram and prepares it for the mode based on the `truncation` and `padding` arguments. + * + * Four different path are possible: + * - `truncation="fusion"` and the length of the waveform is greater than the max length: the mel spectrogram + * will be computed on the entire audio. 3 random crops and a dowsampled version of the full mel spectrogram + * are then stacked together. They will later be used for `feature_fusion`. + * - `truncation="rand_trunc"` and the length of the waveform is smaller than the max length: the audio is + * padded based on `padding`. + * - `truncation="fusion"` and the length of the waveform is smaller than the max length: the audio is padded + * based on `padding`, and is repeated `4` times. + * - `truncation="rand_trunc"` and the length of the waveform is greater than the max length: the mel + * spectrogram will be computed on a random crop of the waveform. + * + * @param {Float32Array|Float64Array} waveform The input waveform. + * @param {number} max_length The maximum length of the waveform. + * @param {string} truncation The truncation strategy to use. + * @param {string} padding The padding strategy to use. + * @returns {Promise} An object containing the mel spectrogram data as a Float32Array, its dimensions as an array of numbers, and a boolean indicating whether the waveform was longer than the max length. + * @private + */ + async _get_input_mel(waveform, max_length, truncation, padding) { + let input_mel; + let longer = false; + const diff = waveform.length - max_length; + if (diff > 0) { + if (truncation === "rand_trunc") { + longer = true; + const idx = Math.floor(Math.random() * (diff + 1)); + waveform = waveform.subarray(idx, idx + max_length); + input_mel = await this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples); + } else { + throw new Error(`Truncation strategy "${truncation}" not implemented`); + } + } else { + if (diff < 0) { + let padded = new Float64Array(max_length); + padded.set(waveform); + if (padding === "repeat") { + for (let i = waveform.length; i < max_length; i += waveform.length) { + padded.set(waveform.subarray(0, Math.min(waveform.length, max_length - i)), i); + } + } else if (padding === "repeatpad") { + for (let i = waveform.length; i < -diff; i += waveform.length) { + padded.set(waveform, i); + } + } + waveform = padded; + } + if (truncation === "fusion") { + throw new Error(`Truncation strategy "${truncation}" not implemented`); + } + input_mel = await this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples); + } + return input_mel.unsqueeze_(0); + } + /** + * Compute the log-mel spectrogram of the provided `waveform` using the Hann window. + * In CLAP, two different filter banks are used depending on the truncation pattern: + * - `self.mel_filters`: they correspond to the default parameters of `torchaudio` which can be obtained from + * calling `torchaudio.transforms.MelSpectrogram().mel_scale.fb`. These filters are used when `truncation` + * is set to `"fusion"`. + * - `self.mel_filteres_slaney` : they correspond to the default parameters of `librosa` which used + * `librosa.filters.mel` when computing the mel spectrogram. These filters were only used in the original + * implementation when the truncation mode is not `"fusion"`. + * + * @param {Float32Array|Float64Array} waveform The audio waveform to process. + * @param {number[][]} mel_filters The mel filters to use. + * @param {number} [max_length=null] The maximum number of frames to return. + * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. + */ + async _extract_fbank_features(waveform, mel_filters, max_length = null) { + return (0, _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.spectrogram)( + waveform, + this.window, + // window + this.config.fft_window_size, + // frame_length + this.config.hop_length, + // hop_length + { + power: 2, + mel_filters, + log_mel: "dB", + // Custom + max_num_frames: max_length, + do_pad: false, + transpose: true + } + ); + } + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. + */ + async _call(audio, { + max_length = null + } = {}) { + (0, _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.validate_audio_inputs)(audio, "ClapFeatureExtractor"); + const padded_inputs = await this._get_input_mel( + audio, + max_length ?? this.config.nb_max_samples, + this.config.truncation, + this.config.padding + ); + return { + input_features: padded_inputs.unsqueeze_(0) + }; + } + } + }) + ), + /***/ + "./src/models/clip/image_processing_clip.js": ( + /*!**************************************************!*\ + !*** ./src/models/clip/image_processing_clip.js ***! + \**************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + CLIPFeatureExtractor: () => ( + /* binding */ + CLIPFeatureExtractor + ), + /* harmony export */ + CLIPImageProcessor: () => ( + /* binding */ + CLIPImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class CLIPImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + } + class CLIPFeatureExtractor extends CLIPImageProcessor { + } + }) + ), + /***/ + "./src/models/convnext/image_processing_convnext.js": ( + /*!**********************************************************!*\ + !*** ./src/models/convnext/image_processing_convnext.js ***! + \**********************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + ConvNextFeatureExtractor: () => ( + /* binding */ + ConvNextFeatureExtractor + ), + /* harmony export */ + ConvNextImageProcessor: () => ( + /* binding */ + ConvNextImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class ConvNextImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + constructor(config) { + super(config); + this.crop_pct = this.config.crop_pct ?? 224 / 256; + } + async resize(image) { + const shortest_edge = this.size?.shortest_edge; + if (shortest_edge === void 0) { + throw new Error(`Size dictionary must contain 'shortest_edge' key.`); + } + if (shortest_edge < 384) { + const resize_shortest_edge = Math.floor(shortest_edge / this.crop_pct); + const [newWidth, newHeight] = this.get_resize_output_image_size(image, { + shortest_edge: resize_shortest_edge + }); + image = await image.resize(newWidth, newHeight, { + resample: this.resample + }); + image = await image.center_crop(shortest_edge, shortest_edge); + } else { + image = await image.resize(shortest_edge, shortest_edge, { + resample: this.resample + }); + } + return image; + } + } + class ConvNextFeatureExtractor extends ConvNextImageProcessor { + } + }) + ), + /***/ + "./src/models/dac/feature_extraction_dac.js": ( + /*!**************************************************!*\ + !*** ./src/models/dac/feature_extraction_dac.js ***! + \**************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + DacFeatureExtractor: () => ( + /* binding */ + DacFeatureExtractor + ) + /* harmony export */ + }); + var _encodec_feature_extraction_encodec_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../encodec/feature_extraction_encodec.js */ + "./src/models/encodec/feature_extraction_encodec.js" + ); + class DacFeatureExtractor extends _encodec_feature_extraction_encodec_js__WEBPACK_IMPORTED_MODULE_0__.EncodecFeatureExtractor { + } + }) + ), + /***/ + "./src/models/deit/image_processing_deit.js": ( + /*!**************************************************!*\ + !*** ./src/models/deit/image_processing_deit.js ***! + \**************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + DeiTFeatureExtractor: () => ( + /* binding */ + DeiTFeatureExtractor + ), + /* harmony export */ + DeiTImageProcessor: () => ( + /* binding */ + DeiTImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class DeiTImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + } + class DeiTFeatureExtractor extends DeiTImageProcessor { + } + }) + ), + /***/ + "./src/models/detr/image_processing_detr.js": ( + /*!**************************************************!*\ + !*** ./src/models/detr/image_processing_detr.js ***! + \**************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + DetrFeatureExtractor: () => ( + /* binding */ + DetrFeatureExtractor + ), + /* harmony export */ + DetrImageProcessor: () => ( + /* binding */ + DetrImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../utils/tensor.js */ + "./src/utils/tensor.js" + ); + class DetrImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + /** + * Calls the feature extraction process on an array of images, preprocesses + * each image, and concatenates the resulting features into a single Tensor. + * @param {import('../../utils/image.js').RawImage[]} images The image(s) to extract features from. + * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images. + */ + async _call(images) { + const result = await super._call(images); + const maskSize = [result.pixel_values.dims[0], 64, 64]; + const pixel_mask = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.full)(maskSize, 1n); + return { ...result, pixel_mask }; + } + /** @type {typeof post_process_object_detection} */ + post_process_object_detection(...args) { + return (0, _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.post_process_object_detection)(...args); + } + /** @type {typeof post_process_panoptic_segmentation} */ + post_process_panoptic_segmentation(...args) { + return (0, _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.post_process_panoptic_segmentation)(...args); + } + /** @type {typeof post_process_instance_segmentation} */ + post_process_instance_segmentation(...args) { + return (0, _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.post_process_instance_segmentation)(...args); + } + } + class DetrFeatureExtractor extends DetrImageProcessor { + } + }) + ), + /***/ + "./src/models/dinov3_vit/image_processing_dinov3_vit.js": ( + /*!**************************************************************!*\ + !*** ./src/models/dinov3_vit/image_processing_dinov3_vit.js ***! + \**************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + DINOv3ViTImageProcessor: () => ( + /* binding */ + DINOv3ViTImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class DINOv3ViTImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + } + }) + ), + /***/ + "./src/models/donut/image_processing_donut.js": ( + /*!****************************************************!*\ + !*** ./src/models/donut/image_processing_donut.js ***! + \****************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + DonutFeatureExtractor: () => ( + /* binding */ + DonutFeatureExtractor + ), + /* harmony export */ + DonutImageProcessor: () => ( + /* binding */ + DonutImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class DonutImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + pad_image(pixelData, imgDims, padSize, options = {}) { + const [imageHeight, imageWidth, imageChannels] = imgDims; + let image_mean = this.image_mean; + if (!Array.isArray(this.image_mean)) { + image_mean = new Array(imageChannels).fill(image_mean); + } + let image_std = this.image_std; + if (!Array.isArray(image_std)) { + image_std = new Array(imageChannels).fill(image_mean); + } + const constant_values = image_mean.map((x, i) => -x / image_std[i]); + return super.pad_image(pixelData, imgDims, padSize, { + center: true, + // Since normalization is done after padding, we need to use certain constant values to ensure the same behaviour is observed. + // For more information, see https://github.com/huggingface/transformers/blob/main/src/transformers/models/donut/image_processing_donut.py#L433-L451 + constant_values, + ...options + }); + } + } + class DonutFeatureExtractor extends DonutImageProcessor { + } + }) + ), + /***/ + "./src/models/dpt/image_processing_dpt.js": ( + /*!************************************************!*\ + !*** ./src/models/dpt/image_processing_dpt.js ***! + \************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + DPTFeatureExtractor: () => ( + /* binding */ + DPTFeatureExtractor + ), + /* harmony export */ + DPTImageProcessor: () => ( + /* binding */ + DPTImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class DPTImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + } + class DPTFeatureExtractor extends DPTImageProcessor { + } + }) + ), + /***/ + "./src/models/efficientnet/image_processing_efficientnet.js": ( + /*!******************************************************************!*\ + !*** ./src/models/efficientnet/image_processing_efficientnet.js ***! + \******************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + EfficientNetImageProcessor: () => ( + /* binding */ + EfficientNetImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class EfficientNetImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + constructor(config) { + super(config); + this.include_top = this.config.include_top ?? true; + if (this.include_top) { + this.image_std = this.image_std.map((x) => x * x); + } + } + } + }) + ), + /***/ + "./src/models/encodec/feature_extraction_encodec.js": ( + /*!**********************************************************!*\ + !*** ./src/models/encodec/feature_extraction_encodec.js ***! + \**********************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + EncodecFeatureExtractor: () => ( + /* binding */ + EncodecFeatureExtractor + ) + /* harmony export */ + }); + var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/feature_extraction_utils.js */ + "./src/base/feature_extraction_utils.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../utils/tensor.js */ + "./src/utils/tensor.js" + ); + class EncodecFeatureExtractor extends _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractor { + /** + * Asynchronously extracts input values from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_values: Tensor; }>} The extracted input values. + */ + async _call(audio) { + (0, _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.validate_audio_inputs)(audio, "EncodecFeatureExtractor"); + if (audio instanceof Float64Array) { + audio = new Float32Array(audio); + } + const num_channels = this.config.feature_size; + if (audio.length % num_channels !== 0) { + throw new Error(`The length of the audio data must be a multiple of the number of channels (${num_channels}).`); + } + const shape = [ + 1, + /* batch_size */ + num_channels, + /* num_channels */ + audio.length / num_channels + /* num_samples */ + ]; + return { + input_values: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor("float32", audio, shape) + }; + } + } + }) + ), + /***/ + "./src/models/feature_extractors.js": ( + /*!******************************************!*\ + !*** ./src/models/feature_extractors.js ***! + \******************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + ASTFeatureExtractor: () => ( + /* reexport safe */ + _audio_spectrogram_transformer_feature_extraction_audio_spectrogram_transformer_js__WEBPACK_IMPORTED_MODULE_0__.ASTFeatureExtractor + ), + /* harmony export */ + ClapFeatureExtractor: () => ( + /* reexport safe */ + _clap_feature_extraction_clap_js__WEBPACK_IMPORTED_MODULE_2__.ClapFeatureExtractor + ), + /* harmony export */ + DacFeatureExtractor: () => ( + /* reexport safe */ + _dac_feature_extraction_dac_js__WEBPACK_IMPORTED_MODULE_3__.DacFeatureExtractor + ), + /* harmony export */ + EncodecFeatureExtractor: () => ( + /* reexport safe */ + _encodec_feature_extraction_encodec_js__WEBPACK_IMPORTED_MODULE_1__.EncodecFeatureExtractor + ), + /* harmony export */ + Gemma3nAudioFeatureExtractor: () => ( + /* reexport safe */ + _gemma3n_feature_extraction_gemma3n_js__WEBPACK_IMPORTED_MODULE_4__.Gemma3nAudioFeatureExtractor + ), + /* harmony export */ + ImageFeatureExtractor: () => ( + /* reexport safe */ + _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_14__.ImageProcessor + ), + /* harmony export */ + MoonshineFeatureExtractor: () => ( + /* reexport safe */ + _moonshine_feature_extraction_moonshine_js__WEBPACK_IMPORTED_MODULE_5__.MoonshineFeatureExtractor + ), + /* harmony export */ + ParakeetFeatureExtractor: () => ( + /* reexport safe */ + _parakeet_feature_extraction_parakeet_js__WEBPACK_IMPORTED_MODULE_6__.ParakeetFeatureExtractor + ), + /* harmony export */ + PyAnnoteFeatureExtractor: () => ( + /* reexport safe */ + _pyannote_feature_extraction_pyannote_js__WEBPACK_IMPORTED_MODULE_7__.PyAnnoteFeatureExtractor + ), + /* harmony export */ + SeamlessM4TFeatureExtractor: () => ( + /* reexport safe */ + _seamless_m4t_feature_extraction_seamless_m4t_js__WEBPACK_IMPORTED_MODULE_8__.SeamlessM4TFeatureExtractor + ), + /* harmony export */ + SnacFeatureExtractor: () => ( + /* reexport safe */ + _snac_feature_extraction_snac_js__WEBPACK_IMPORTED_MODULE_9__.SnacFeatureExtractor + ), + /* harmony export */ + SpeechT5FeatureExtractor: () => ( + /* reexport safe */ + _speecht5_feature_extraction_speecht5_js__WEBPACK_IMPORTED_MODULE_10__.SpeechT5FeatureExtractor + ), + /* harmony export */ + Wav2Vec2FeatureExtractor: () => ( + /* reexport safe */ + _wav2vec2_feature_extraction_wav2vec2_js__WEBPACK_IMPORTED_MODULE_11__.Wav2Vec2FeatureExtractor + ), + /* harmony export */ + WeSpeakerFeatureExtractor: () => ( + /* reexport safe */ + _wespeaker_feature_extraction_wespeaker_js__WEBPACK_IMPORTED_MODULE_12__.WeSpeakerFeatureExtractor + ), + /* harmony export */ + WhisperFeatureExtractor: () => ( + /* reexport safe */ + _whisper_feature_extraction_whisper_js__WEBPACK_IMPORTED_MODULE_13__.WhisperFeatureExtractor + ) + /* harmony export */ + }); + var _audio_spectrogram_transformer_feature_extraction_audio_spectrogram_transformer_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ./audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js */ + "./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js" + ); + var _encodec_feature_extraction_encodec_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ./encodec/feature_extraction_encodec.js */ + "./src/models/encodec/feature_extraction_encodec.js" + ); + var _clap_feature_extraction_clap_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ./clap/feature_extraction_clap.js */ + "./src/models/clap/feature_extraction_clap.js" + ); + var _dac_feature_extraction_dac_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! ./dac/feature_extraction_dac.js */ + "./src/models/dac/feature_extraction_dac.js" + ); + var _gemma3n_feature_extraction_gemma3n_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__2( + /*! ./gemma3n/feature_extraction_gemma3n.js */ + "./src/models/gemma3n/feature_extraction_gemma3n.js" + ); + var _moonshine_feature_extraction_moonshine_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__2( + /*! ./moonshine/feature_extraction_moonshine.js */ + "./src/models/moonshine/feature_extraction_moonshine.js" + ); + var _parakeet_feature_extraction_parakeet_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__2( + /*! ./parakeet/feature_extraction_parakeet.js */ + "./src/models/parakeet/feature_extraction_parakeet.js" + ); + var _pyannote_feature_extraction_pyannote_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__2( + /*! ./pyannote/feature_extraction_pyannote.js */ + "./src/models/pyannote/feature_extraction_pyannote.js" + ); + var _seamless_m4t_feature_extraction_seamless_m4t_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__2( + /*! ./seamless_m4t/feature_extraction_seamless_m4t.js */ + "./src/models/seamless_m4t/feature_extraction_seamless_m4t.js" + ); + var _snac_feature_extraction_snac_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__2( + /*! ./snac/feature_extraction_snac.js */ + "./src/models/snac/feature_extraction_snac.js" + ); + var _speecht5_feature_extraction_speecht5_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__2( + /*! ./speecht5/feature_extraction_speecht5.js */ + "./src/models/speecht5/feature_extraction_speecht5.js" + ); + var _wav2vec2_feature_extraction_wav2vec2_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__2( + /*! ./wav2vec2/feature_extraction_wav2vec2.js */ + "./src/models/wav2vec2/feature_extraction_wav2vec2.js" + ); + var _wespeaker_feature_extraction_wespeaker_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__2( + /*! ./wespeaker/feature_extraction_wespeaker.js */ + "./src/models/wespeaker/feature_extraction_wespeaker.js" + ); + var _whisper_feature_extraction_whisper_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__2( + /*! ./whisper/feature_extraction_whisper.js */ + "./src/models/whisper/feature_extraction_whisper.js" + ); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__2( + /*! ../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + }) + ), + /***/ + "./src/models/florence2/processing_florence2.js": ( + /*!******************************************************!*\ + !*** ./src/models/florence2/processing_florence2.js ***! + \******************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + Florence2Processor: () => ( + /* binding */ + Florence2Processor + ) + /* harmony export */ + }); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../auto/image_processing_auto.js */ + "./src/models/auto/image_processing_auto.js" + ); + var _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../tokenizers.js */ + "./src/tokenizers.js" + ); + class Florence2Processor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { + static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer; + static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor; + constructor(config, components, chat_template) { + super(config, components, chat_template); + const { + // @ts-expect-error TS2339 + tasks_answer_post_processing_type, + // @ts-expect-error TS2339 + task_prompts_without_inputs, + // @ts-expect-error TS2339 + task_prompts_with_input + } = this.image_processor.config; + this.tasks_answer_post_processing_type = new Map(Object.entries(tasks_answer_post_processing_type ?? {})); + this.task_prompts_without_inputs = new Map(Object.entries(task_prompts_without_inputs ?? {})); + this.task_prompts_with_input = new Map(Object.entries(task_prompts_with_input ?? {})); + this.regexes = { + quad_boxes: /(.+?)/gm, + bboxes: /([^<]+)?/gm + }; + this.size_per_bin = 1e3; + } + /** + * Helper function to construct prompts from input texts + * @param {string|string[]} text + * @returns {string[]} + */ + construct_prompts(text) { + if (typeof text === "string") { + text = [text]; + } + const prompts = []; + for (const t of text) { + if (this.task_prompts_without_inputs.has(t)) { + prompts.push(this.task_prompts_without_inputs.get(t)); + } else { + for (const [task, prompt] of this.task_prompts_with_input) { + if (t.includes(task)) { + prompts.push(prompt.replaceAll("{input}", t).replaceAll(task, "")); + break; + } + } + if (prompts.length !== text.length) { + prompts.push(t); + } + } + } + return prompts; + } + /** + * Post-process the output of the model to each of the task outputs. + * @param {string} text The text to post-process. + * @param {string} task The task to post-process the text for. + * @param {[number, number]} image_size The size of the image. height x width. + */ + post_process_generation(text, task, image_size) { + const task_answer_post_processing_type = this.tasks_answer_post_processing_type.get(task) ?? "pure_text"; + text = text.replaceAll("", "").replaceAll("", ""); + let final_answer; + switch (task_answer_post_processing_type) { + case "pure_text": + final_answer = text; + break; + case "description_with_bboxes": + case "bboxes": + case "phrase_grounding": + case "ocr": + const key = task_answer_post_processing_type === "ocr" ? "quad_boxes" : "bboxes"; + const matches = text.matchAll(this.regexes[key]); + const labels = []; + const items = []; + for (const [_, label, ...locations] of matches) { + labels.push(label ? label.trim() : labels.at(-1) ?? ""); + items.push( + locations.map((x, i) => ( + // NOTE: Add 0.5 to use the center position of the bin as the coordinate. + (Number(x) + 0.5) / this.size_per_bin * image_size[i % 2] + )) + ); + } + final_answer = { labels, [key]: items }; + break; + default: + throw new Error(`Task "${task}" (of type "${task_answer_post_processing_type}") not yet implemented.`); + } + return { [task]: final_answer }; + } + // NOTE: images and text are switched from the python version + // `images` is required, `text` is optional + async _call(images, text = null, kwargs = {}) { + if (!images && !text) { + throw new Error("Either text or images must be provided"); + } + const image_inputs = await this.image_processor(images, kwargs); + const text_inputs = text ? this.tokenizer(this.construct_prompts(text), kwargs) : {}; + return { + ...image_inputs, + ...text_inputs + }; + } + } + }) + ), + /***/ + "./src/models/gemma3n/feature_extraction_gemma3n.js": ( + /*!**********************************************************!*\ + !*** ./src/models/gemma3n/feature_extraction_gemma3n.js ***! + \**********************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + Gemma3nAudioFeatureExtractor: () => ( + /* binding */ + Gemma3nAudioFeatureExtractor + ) + /* harmony export */ + }); + var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/feature_extraction_utils.js */ + "./src/base/feature_extraction_utils.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../utils/tensor.js */ + "./src/utils/tensor.js" + ); + var _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../utils/audio.js */ + "./src/utils/audio.js" + ); + class Gemma3nAudioFeatureExtractor extends _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractor { + constructor(config) { + super(config); + const { + fft_length, + feature_size, + min_frequency, + max_frequency, + sampling_rate, + frame_length + } = this.config; + const mel_filters = (0, _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.mel_filter_bank)( + Math.floor(1 + fft_length / 2), + // num_frequency_bins + feature_size, + // num_mel_filters + min_frequency, + // min_frequency + max_frequency, + // max_frequency + sampling_rate, + // sampling_rate + null, + // norm + "htk", + // mel_scale + false + // triangularize_in_mel_space + ); + this.mel_filters = mel_filters; + this.window = (0, _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.window_function)(frame_length, "hann"); + } + /** + * Computes the log-Mel spectrogram of the provided audio waveform. + * @param {Float32Array|Float64Array} waveform The audio waveform to process. + * @param {number} max_length The maximum number of frames to return. + * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. + */ + async _extract_fbank_features(waveform, max_length) { + return (0, _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.spectrogram)( + waveform, + this.window, + // window + this.config.frame_length, + // frame_length + this.config.hop_length, + // hop_length + { + fft_length: this.config.fft_length, + center: false, + onesided: true, + preemphasis: this.config.preemphasis, + preemphasis_htk_flavor: this.config.preemphasis_htk_flavor, + mel_filters: this.mel_filters, + log_mel: "log", + mel_floor: this.config.mel_floor, + remove_dc_offset: false, + // Custom + transpose: true + } + ); + } + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @param {Object} options Optional parameters for feature extraction. + * @param {number} [options.max_length=480_000] If provided, defines the maximum length of the audio to allow. + * Audio longer than this will be truncated if `truncation=True`. + * @param {boolean} [options.truncation=true] Whether or not to truncate audio above `max_length`. + * @param {boolean} [options.padding=true] Whether to pad the sequence to a multiple of `pad_to_multiple_of`. + * @param {number} [options.pad_to_multiple_of=128] The number to pad the sequence to a multiple of. + * @returns {Promise<{ input_features: Tensor, input_features_mask: Tensor }>} A Promise resolving to an object containing the extracted input features and attention masks as Tensors. + */ + async _call(audio, { + max_length = 48e4, + truncation = true, + padding = true, + pad_to_multiple_of = 128 + } = {}) { + (0, _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.validate_audio_inputs)(audio, "Gemma3nAudioFeatureExtractor"); + if (truncation && audio.length > max_length) { + audio = audio.slice(0, max_length); + } + if (padding && audio.length % pad_to_multiple_of !== 0) { + const padding_length = pad_to_multiple_of - audio.length % pad_to_multiple_of; + const padded_audio = new Float64Array(audio.length + padding_length); + padded_audio.set(audio); + if (this.config.padding_value !== 0) { + padded_audio.fill(this.config.padding_value, audio.length); + } + audio = padded_audio; + } + const features = await this._extract_fbank_features(audio, this.config.max_length); + const padded_attention_mask = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.full)([1, features.dims[0]], true); + return { + input_features: features.unsqueeze_(0), + input_features_mask: padded_attention_mask + }; + } + } + }) + ), + /***/ + "./src/models/gemma3n/processing_gemma3n.js": ( + /*!**************************************************!*\ + !*** ./src/models/gemma3n/processing_gemma3n.js ***! + \**************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + Gemma3nProcessor: () => ( + /* binding */ + Gemma3nProcessor + ) + /* harmony export */ + }); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../auto/image_processing_auto.js */ + "./src/models/auto/image_processing_auto.js" + ); + var _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../auto/feature_extraction_auto.js */ + "./src/models/auto/feature_extraction_auto.js" + ); + var _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! ../../tokenizers.js */ + "./src/tokenizers.js" + ); + var _utils_image_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__2( + /*! ../../utils/image.js */ + "./src/utils/image.js" + ); + var _utils_audio_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__2( + /*! ../../utils/audio.js */ + "./src/utils/audio.js" + ); + class Gemma3nProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { + static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor; + static feature_extractor_class = _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoFeatureExtractor; + static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.AutoTokenizer; + static uses_processor_config = true; + static uses_chat_template_file = true; + constructor(config, components, chat_template) { + super(config, components, chat_template); + this.audio_seq_length = this.config.audio_seq_length; + this.image_seq_length = this.config.image_seq_length; + const { + // Audio tokens + audio_token_id, + boa_token, + audio_token, + eoa_token, + // Image tokens + image_token_id, + boi_token, + image_token, + eoi_token + } = this.tokenizer.config; + this.audio_token_id = audio_token_id; + this.boa_token = boa_token; + this.audio_token = audio_token; + const audio_tokens_expanded = audio_token.repeat(this.audio_seq_length); + this.full_audio_sequence = ` + +${boa_token}${audio_tokens_expanded}${eoa_token} + +`; + this.image_token_id = image_token_id; + this.boi_token = boi_token; + this.image_token = image_token; + const image_tokens_expanded = image_token.repeat(this.image_seq_length); + this.full_image_sequence = ` + +${boi_token}${image_tokens_expanded}${eoi_token} + +`; + } + /** + * + * @param {string|string[]} text + * @param {RawImage|RawImage[]|RawImage[][]} images + * @param {RawAudio|RawAudio[]|RawAudio[][]} audio + * @returns {Promise} + */ + async _call(text, images = null, audio = null, options = {}) { + if (typeof text === "string") { + text = [text]; + } + let audio_inputs; + if (audio) { + audio_inputs = await this.feature_extractor(audio, options); + text = text.map((prompt) => prompt.replaceAll(this.audio_token, this.full_audio_sequence)); + } + let image_inputs; + if (images) { + image_inputs = await this.image_processor(images, options); + text = text.map((prompt) => prompt.replaceAll(this.image_token, this.full_image_sequence)); + } + let text_inputs = this.tokenizer(text, options); + return { + ...text_inputs, + ...image_inputs, + ...audio_inputs + }; + } + } + }) + ), + /***/ + "./src/models/glpn/image_processing_glpn.js": ( + /*!**************************************************!*\ + !*** ./src/models/glpn/image_processing_glpn.js ***! + \**************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + GLPNFeatureExtractor: () => ( + /* binding */ + GLPNFeatureExtractor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class GLPNFeatureExtractor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + } + }) + ), + /***/ + "./src/models/grounding_dino/image_processing_grounding_dino.js": ( + /*!**********************************************************************!*\ + !*** ./src/models/grounding_dino/image_processing_grounding_dino.js ***! + \**********************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + GroundingDinoImageProcessor: () => ( + /* binding */ + GroundingDinoImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../utils/tensor.js */ + "./src/utils/tensor.js" + ); + class GroundingDinoImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + /** + * Calls the feature extraction process on an array of images, preprocesses + * each image, and concatenates the resulting features into a single Tensor. + * @param {import('../../utils/image.js').RawImage[]} images The image(s) to extract features from. + * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images. + */ + async _call(images) { + const result = await super._call(images); + const dims = result.pixel_values.dims; + const pixel_mask = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.ones)([dims[0], dims[2], dims[3]]); + return { ...result, pixel_mask }; + } + } + }) + ), + /***/ + "./src/models/grounding_dino/processing_grounding_dino.js": ( + /*!****************************************************************!*\ + !*** ./src/models/grounding_dino/processing_grounding_dino.js ***! + \****************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + GroundingDinoProcessor: () => ( + /* binding */ + GroundingDinoProcessor + ) + /* harmony export */ + }); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../auto/image_processing_auto.js */ + "./src/models/auto/image_processing_auto.js" + ); + var _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../tokenizers.js */ + "./src/tokenizers.js" + ); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + function get_phrases_from_posmap(posmaps, input_ids) { + const left_idx = 0; + const right_idx = posmaps.dims.at(-1) - 1; + const posmaps_list = posmaps.tolist(); + posmaps_list.fill(false, 0, left_idx + 1); + posmaps_list.fill(false, right_idx); + const input_ids_list = input_ids.tolist(); + return posmaps_list.map((val, idx) => val ? idx : null).filter((idx) => idx !== null).map((i) => input_ids_list[i]); + } + class GroundingDinoProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { + static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer; + static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor; + /** + * @typedef {import('../../utils/image.js').RawImage} RawImage + */ + /** + * + * @param {RawImage|RawImage[]|RawImage[][]} images + * @param {string|string[]} text + * @returns {Promise} + */ + async _call(images, text, options = {}) { + const image_inputs = images ? await this.image_processor(images, options) : {}; + const text_inputs = text ? this.tokenizer(text, options) : {}; + return { + ...text_inputs, + ...image_inputs + }; + } + post_process_grounded_object_detection(outputs, input_ids, { + box_threshold = 0.25, + text_threshold = 0.25, + target_sizes = null + } = {}) { + const { logits, pred_boxes } = outputs; + const batch_size = logits.dims[0]; + if (target_sizes !== null && target_sizes.length !== batch_size) { + throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits"); + } + const num_queries = logits.dims.at(1); + const probs = logits.sigmoid(); + const scores = probs.max(-1).tolist(); + const boxes = pred_boxes.tolist().map((batch) => batch.map((box) => (0, _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_3__.center_to_corners_format)(box))); + const results = []; + for (let i = 0; i < batch_size; ++i) { + const target_size = target_sizes !== null ? target_sizes[i] : null; + if (target_size !== null) { + boxes[i] = boxes[i].map((box) => box.map((x, j) => x * target_size[(j + 1) % 2])); + } + const batch_scores = scores[i]; + const final_scores = []; + const final_phrases = []; + const final_boxes = []; + for (let j = 0; j < num_queries; ++j) { + const score = batch_scores[j]; + if (score <= box_threshold) { + continue; + } + const box = boxes[i][j]; + const prob = probs[i][j]; + final_scores.push(score); + final_boxes.push(box); + const phrases = get_phrases_from_posmap(prob.gt(text_threshold), input_ids[i]); + final_phrases.push(phrases); + } + results.push({ scores: final_scores, boxes: final_boxes, labels: this.batch_decode(final_phrases) }); + } + return results; + } + } + }) + ), + /***/ + "./src/models/idefics3/image_processing_idefics3.js": ( + /*!**********************************************************!*\ + !*** ./src/models/idefics3/image_processing_idefics3.js ***! + \**********************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + Idefics3ImageProcessor: () => ( + /* binding */ + Idefics3ImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../utils/tensor.js */ + "./src/utils/tensor.js" + ); + class Idefics3ImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + constructor(config) { + super(config); + this.do_image_splitting = config.do_image_splitting ?? true; + this.max_image_size = config.max_image_size; + } + /** + * @typedef {import('../../utils/image.js').RawImage} RawImage + * @typedef {import('../../utils/tensor.js').Tensor} Tensor + */ + /** + * Calculate size to resize images to, to be multiples of `vision_encoder_max_size` while preserving the aspect ratio. + * @param {Tensor} pixel_values Tensor of the image to resize. + * @param {number} vision_encoder_max_size Maximum size of the output image. If the image is larger than this size, + * it will be split into patches of this size, and the original image will be concatenated with the patches, resized to max_size. + */ + get_resize_for_vision_encoder(pixel_values, vision_encoder_max_size) { + let [height, width] = pixel_values.dims.slice(-2); + const aspect_ratio = width / height; + if (width >= height) { + width = Math.ceil(width / vision_encoder_max_size) * vision_encoder_max_size; + height = Math.floor(width / aspect_ratio); + height = Math.ceil(height / vision_encoder_max_size) * vision_encoder_max_size; + } else { + height = Math.ceil(height / vision_encoder_max_size) * vision_encoder_max_size; + width = Math.floor(height * aspect_ratio); + width = Math.ceil(width / vision_encoder_max_size) * vision_encoder_max_size; + } + return { height, width }; + } + /** @param {RawImage|RawImage[]|RawImage[][]} images */ + async _call(images, { + do_image_splitting = null, + return_row_col_info = false + } = {}) { + let batched_2d_images; + if (!Array.isArray(images)) { + batched_2d_images = [[images]]; + } else { + if (images.length === 0 || !images[0]) { + throw new Error("No images provided."); + } + if (!Array.isArray(images[0])) { + batched_2d_images = [ + /** @type {RawImage[]} */ + images + ]; + } else { + batched_2d_images = /** @type {RawImage[][]} */ + images; + } + } + let all_pixel_values = []; + let images_list_rows = []; + let images_list_cols = []; + const original_sizes = []; + const reshaped_input_sizes = []; + for (const image_batch of batched_2d_images) { + let images_list = await Promise.all(image_batch.map((x) => this.preprocess(x))); + original_sizes.push(...images_list.map((x) => x.original_size)); + reshaped_input_sizes.push(...images_list.map((x) => x.reshaped_input_size)); + images_list.forEach((x) => x.pixel_values.unsqueeze_(0)); + const { longest_edge } = this.max_image_size; + let images_tensor; + if (do_image_splitting ?? this.do_image_splitting) { + let image_rows = new Array(images_list.length); + let image_cols = new Array(images_list.length); + images_tensor = await Promise.all(images_list.map(async (x, i) => { + const new_size = this.get_resize_for_vision_encoder(x.pixel_values, longest_edge); + const resized = await (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.interpolate_4d)(x.pixel_values, { + size: [new_size.height, new_size.width] + }); + const { frames, num_splits_h, num_splits_w } = await this.split_image(resized, this.max_image_size); + image_rows[i] = num_splits_h; + image_cols[i] = num_splits_w; + return (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.cat)(frames, 0); + })); + images_list_rows.push(image_rows); + images_list_cols.push(image_cols); + } else { + const size = [longest_edge, longest_edge]; + images_tensor = await Promise.all( + images_list.map((x) => (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.interpolate_4d)(x.pixel_values, { size })) + ); + images_list_rows.push(new Array(images_list.length).fill(0)); + images_list_cols.push(new Array(images_list.length).fill(0)); + } + all_pixel_values.push((0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.cat)(images_tensor, 0)); + } + const batch_size = all_pixel_values.length; + const [n, c, h, w] = all_pixel_values[0].dims; + let pixel_values; + let pixel_attention_mask; + if (batch_size === 1) { + pixel_values = all_pixel_values[0].unsqueeze_(0); + pixel_attention_mask = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.full)([batch_size, n, h, w], true); + } else { + const max_num_patches = Math.max(...all_pixel_values.map((x) => x.dims.at(0))); + pixel_attention_mask = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.full)([batch_size, max_num_patches, h, w], true); + const pixel_attention_mask_data = pixel_attention_mask.data; + const pixel_attention_mask_stride = max_num_patches * h * w; + for (let i = 0; i < batch_size; ++i) { + const num_patches = all_pixel_values[i].dims[0]; + if (num_patches < max_num_patches) { + all_pixel_values[i] = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.cat)([ + all_pixel_values[i], + (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.full)([max_num_patches - num_patches, c, h, w], 0) + ], 0); + const start_offset = i * pixel_attention_mask_stride + num_patches * h * w; + const end_offset = (i + 1) * pixel_attention_mask_stride; + pixel_attention_mask_data.fill(false, start_offset, end_offset); + } + } + pixel_values = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.stack)(all_pixel_values, 0); + } + return { + pixel_values, + pixel_attention_mask, + original_sizes, + reshaped_input_sizes, + ...return_row_col_info ? { rows: images_list_rows, cols: images_list_cols } : {} + }; + } + async split_image(pixel_values, { longest_edge }) { + const max_height = longest_edge; + const max_width = longest_edge; + const frames = []; + const [height, width] = pixel_values.dims.slice(-2); + let num_splits_h = 0, num_splits_w = 0; + if (height > max_height || width > max_width) { + num_splits_h = Math.ceil(height / max_height); + num_splits_w = Math.ceil(width / max_width); + const optimal_height = Math.ceil(height / num_splits_h); + const optimal_width = Math.ceil(width / num_splits_w); + for (let r = 0; r < num_splits_h; ++r) { + for (let c = 0; c < num_splits_w; ++c) { + let start_x, start_y, end_x, end_y; + if (r === num_splits_h - 1) { + start_y = height - optimal_height; + end_y = height; + } else { + start_y = r * optimal_height; + end_y = (r + 1) * optimal_height; + } + if (c === num_splits_w - 1) { + start_x = width - optimal_width; + end_x = width; + } else { + start_x = c * optimal_width; + end_x = (c + 1) * optimal_width; + } + const starts = [start_y, start_x]; + const ends = [end_y, end_x]; + const patch = await (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.slice)(pixel_values, starts, ends, [2, 3]); + frames.push(patch); + } + } + const global_image_height = max_height; + const global_image_width = max_width; + if (height !== global_image_height || width !== global_image_width) { + pixel_values = await (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.interpolate_4d)(pixel_values, { + size: [global_image_height, global_image_width] + }); + } + } + frames.push(pixel_values); + return { frames, num_splits_h, num_splits_w }; + } + } + }) + ), + /***/ + "./src/models/idefics3/processing_idefics3.js": ( + /*!****************************************************!*\ + !*** ./src/models/idefics3/processing_idefics3.js ***! + \****************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + Idefics3Processor: () => ( + /* binding */ + Idefics3Processor + ) + /* harmony export */ + }); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../auto/image_processing_auto.js */ + "./src/models/auto/image_processing_auto.js" + ); + var _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../tokenizers.js */ + "./src/tokenizers.js" + ); + var _utils_image_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! ../../utils/image.js */ + "./src/utils/image.js" + ); + var _utils_core_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__2( + /*! ../../utils/core.js */ + "./src/utils/core.js" + ); + function _prompt_split_image(image_seq_len, image_rows, image_cols, fake_token_around_image, image_token, global_img_token) { + let text_split_images = ""; + for (let n_h = 0; n_h < image_rows; ++n_h) { + for (let n_w = 0; n_w < image_cols; ++n_w) { + text_split_images += fake_token_around_image + `` + image_token.repeat(image_seq_len); + } + text_split_images += "\n"; + } + text_split_images += ` +${fake_token_around_image}${global_img_token}` + image_token.repeat(image_seq_len) + `${fake_token_around_image}`; + return text_split_images; + } + function _prompt_single_image(image_seq_len, fake_token_around_image, image_token, global_img_token) { + return `${fake_token_around_image}${global_img_token}` + image_token.repeat(image_seq_len) + `${fake_token_around_image}`; + } + function get_image_prompt_string(image_rows, image_cols, image_seq_len, fake_token_around_image, image_token, global_img_token) { + if (image_rows === 0 && image_cols === 0) { + return _prompt_single_image( + image_seq_len, + fake_token_around_image, + image_token, + global_img_token + ); + } + return _prompt_split_image( + image_seq_len, + image_rows, + image_cols, + fake_token_around_image, + image_token, + global_img_token + ); + } + class Idefics3Processor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { + static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor; + static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer; + static uses_processor_config = true; + fake_image_token = ""; + image_token = ""; + global_img_token = ""; + /** + * + * @param {string|string[]} text + * @param {RawImage|RawImage[]|RawImage[][]} images + * @returns {Promise} + */ + async _call(text, images = null, options = {}) { + options.return_row_col_info ??= true; + let image_inputs; + if (images) { + image_inputs = await this.image_processor(images, options); + } + if (!Array.isArray(text)) { + text = [text]; + } + const image_rows = image_inputs.rows ?? [new Array(text.length).fill(0)]; + const image_cols = image_inputs.cols ?? [new Array(text.length).fill(0)]; + const image_seq_len = this.config.image_seq_len; + const n_images_in_text = []; + const prompt_strings = []; + for (let i = 0; i < text.length; ++i) { + const sample = text[i]; + const sample_rows = image_rows[i]; + const sample_cols = image_cols[i]; + n_images_in_text.push((0, _utils_core_js__WEBPACK_IMPORTED_MODULE_4__.count)(sample, this.image_token)); + const image_prompt_strings = sample_rows.map( + (n_rows, j) => get_image_prompt_string( + n_rows, + sample_cols[j], + image_seq_len, + this.fake_image_token, + this.image_token, + this.global_img_token + ) + ); + const split_sample = sample.split(this.image_token); + if (split_sample.length === 0) { + throw new Error("The image token should be present in the text."); + } + let new_sample = split_sample[0]; + for (let j = 0; j < image_prompt_strings.length; ++j) { + new_sample += image_prompt_strings[j] + split_sample[j + 1]; + } + prompt_strings.push(new_sample); + } + const text_inputs = this.tokenizer(prompt_strings); + return { + ...text_inputs, + ...image_inputs + }; + } + } + }) + ), + /***/ + "./src/models/image_processors.js": ( + /*!****************************************!*\ + !*** ./src/models/image_processors.js ***! + \****************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + BeitFeatureExtractor: () => ( + /* reexport safe */ + _beit_image_processing_beit_js__WEBPACK_IMPORTED_MODULE_0__.BeitFeatureExtractor + ), + /* harmony export */ + BitImageProcessor: () => ( + /* reexport safe */ + _bit_image_processing_bit_js__WEBPACK_IMPORTED_MODULE_1__.BitImageProcessor + ), + /* harmony export */ + CLIPFeatureExtractor: () => ( + /* reexport safe */ + _clip_image_processing_clip_js__WEBPACK_IMPORTED_MODULE_3__.CLIPFeatureExtractor + ), + /* harmony export */ + CLIPImageProcessor: () => ( + /* reexport safe */ + _clip_image_processing_clip_js__WEBPACK_IMPORTED_MODULE_3__.CLIPImageProcessor + ), + /* harmony export */ + ChineseCLIPFeatureExtractor: () => ( + /* reexport safe */ + _chinese_clip_image_processing_chinese_clip_js__WEBPACK_IMPORTED_MODULE_2__.ChineseCLIPFeatureExtractor + ), + /* harmony export */ + ConvNextFeatureExtractor: () => ( + /* reexport safe */ + _convnext_image_processing_convnext_js__WEBPACK_IMPORTED_MODULE_4__.ConvNextFeatureExtractor + ), + /* harmony export */ + ConvNextImageProcessor: () => ( + /* reexport safe */ + _convnext_image_processing_convnext_js__WEBPACK_IMPORTED_MODULE_4__.ConvNextImageProcessor + ), + /* harmony export */ + DINOv3ViTImageProcessor: () => ( + /* reexport safe */ + _dinov3_vit_image_processing_dinov3_vit_js__WEBPACK_IMPORTED_MODULE_7__.DINOv3ViTImageProcessor + ), + /* harmony export */ + DPTFeatureExtractor: () => ( + /* reexport safe */ + _dpt_image_processing_dpt_js__WEBPACK_IMPORTED_MODULE_9__.DPTFeatureExtractor + ), + /* harmony export */ + DPTImageProcessor: () => ( + /* reexport safe */ + _dpt_image_processing_dpt_js__WEBPACK_IMPORTED_MODULE_9__.DPTImageProcessor + ), + /* harmony export */ + DeiTFeatureExtractor: () => ( + /* reexport safe */ + _deit_image_processing_deit_js__WEBPACK_IMPORTED_MODULE_5__.DeiTFeatureExtractor + ), + /* harmony export */ + DeiTImageProcessor: () => ( + /* reexport safe */ + _deit_image_processing_deit_js__WEBPACK_IMPORTED_MODULE_5__.DeiTImageProcessor + ), + /* harmony export */ + DetrFeatureExtractor: () => ( + /* reexport safe */ + _detr_image_processing_detr_js__WEBPACK_IMPORTED_MODULE_6__.DetrFeatureExtractor + ), + /* harmony export */ + DetrImageProcessor: () => ( + /* reexport safe */ + _detr_image_processing_detr_js__WEBPACK_IMPORTED_MODULE_6__.DetrImageProcessor + ), + /* harmony export */ + DonutFeatureExtractor: () => ( + /* reexport safe */ + _donut_image_processing_donut_js__WEBPACK_IMPORTED_MODULE_8__.DonutFeatureExtractor + ), + /* harmony export */ + DonutImageProcessor: () => ( + /* reexport safe */ + _donut_image_processing_donut_js__WEBPACK_IMPORTED_MODULE_8__.DonutImageProcessor + ), + /* harmony export */ + EfficientNetImageProcessor: () => ( + /* reexport safe */ + _efficientnet_image_processing_efficientnet_js__WEBPACK_IMPORTED_MODULE_10__.EfficientNetImageProcessor + ), + /* harmony export */ + GLPNFeatureExtractor: () => ( + /* reexport safe */ + _glpn_image_processing_glpn_js__WEBPACK_IMPORTED_MODULE_11__.GLPNFeatureExtractor + ), + /* harmony export */ + GroundingDinoImageProcessor: () => ( + /* reexport safe */ + _grounding_dino_image_processing_grounding_dino_js__WEBPACK_IMPORTED_MODULE_12__.GroundingDinoImageProcessor + ), + /* harmony export */ + Idefics3ImageProcessor: () => ( + /* reexport safe */ + _idefics3_image_processing_idefics3_js__WEBPACK_IMPORTED_MODULE_13__.Idefics3ImageProcessor + ), + /* harmony export */ + JinaCLIPImageProcessor: () => ( + /* reexport safe */ + _jina_clip_image_processing_jina_clip_js__WEBPACK_IMPORTED_MODULE_15__.JinaCLIPImageProcessor + ), + /* harmony export */ + LlavaOnevisionImageProcessor: () => ( + /* reexport safe */ + _llava_onevision_image_processing_llava_onevision_js__WEBPACK_IMPORTED_MODULE_16__.LlavaOnevisionImageProcessor + ), + /* harmony export */ + Mask2FormerImageProcessor: () => ( + /* reexport safe */ + _mask2former_image_processing_mask2former_js__WEBPACK_IMPORTED_MODULE_17__.Mask2FormerImageProcessor + ), + /* harmony export */ + MaskFormerFeatureExtractor: () => ( + /* reexport safe */ + _maskformer_image_processing_maskformer_js__WEBPACK_IMPORTED_MODULE_18__.MaskFormerFeatureExtractor + ), + /* harmony export */ + MaskFormerImageProcessor: () => ( + /* reexport safe */ + _maskformer_image_processing_maskformer_js__WEBPACK_IMPORTED_MODULE_18__.MaskFormerImageProcessor + ), + /* harmony export */ + MobileNetV1FeatureExtractor: () => ( + /* reexport safe */ + _mobilenet_v1_image_processing_mobilenet_v1_js__WEBPACK_IMPORTED_MODULE_19__.MobileNetV1FeatureExtractor + ), + /* harmony export */ + MobileNetV1ImageProcessor: () => ( + /* reexport safe */ + _mobilenet_v1_image_processing_mobilenet_v1_js__WEBPACK_IMPORTED_MODULE_19__.MobileNetV1ImageProcessor + ), + /* harmony export */ + MobileNetV2FeatureExtractor: () => ( + /* reexport safe */ + _mobilenet_v2_image_processing_mobilenet_v2_js__WEBPACK_IMPORTED_MODULE_20__.MobileNetV2FeatureExtractor + ), + /* harmony export */ + MobileNetV2ImageProcessor: () => ( + /* reexport safe */ + _mobilenet_v2_image_processing_mobilenet_v2_js__WEBPACK_IMPORTED_MODULE_20__.MobileNetV2ImageProcessor + ), + /* harmony export */ + MobileNetV3FeatureExtractor: () => ( + /* reexport safe */ + _mobilenet_v3_image_processing_mobilenet_v3_js__WEBPACK_IMPORTED_MODULE_21__.MobileNetV3FeatureExtractor + ), + /* harmony export */ + MobileNetV3ImageProcessor: () => ( + /* reexport safe */ + _mobilenet_v3_image_processing_mobilenet_v3_js__WEBPACK_IMPORTED_MODULE_21__.MobileNetV3ImageProcessor + ), + /* harmony export */ + MobileNetV4FeatureExtractor: () => ( + /* reexport safe */ + _mobilenet_v4_image_processing_mobilenet_v4_js__WEBPACK_IMPORTED_MODULE_22__.MobileNetV4FeatureExtractor + ), + /* harmony export */ + MobileNetV4ImageProcessor: () => ( + /* reexport safe */ + _mobilenet_v4_image_processing_mobilenet_v4_js__WEBPACK_IMPORTED_MODULE_22__.MobileNetV4ImageProcessor + ), + /* harmony export */ + MobileViTFeatureExtractor: () => ( + /* reexport safe */ + _mobilevit_image_processing_mobilevit_js__WEBPACK_IMPORTED_MODULE_23__.MobileViTFeatureExtractor + ), + /* harmony export */ + MobileViTImageProcessor: () => ( + /* reexport safe */ + _mobilevit_image_processing_mobilevit_js__WEBPACK_IMPORTED_MODULE_23__.MobileViTImageProcessor + ), + /* harmony export */ + NougatImageProcessor: () => ( + /* reexport safe */ + _nougat_image_processing_nougat_js__WEBPACK_IMPORTED_MODULE_24__.NougatImageProcessor + ), + /* harmony export */ + OwlViTFeatureExtractor: () => ( + /* reexport safe */ + _owlvit_image_processing_owlvit_js__WEBPACK_IMPORTED_MODULE_26__.OwlViTFeatureExtractor + ), + /* harmony export */ + OwlViTImageProcessor: () => ( + /* reexport safe */ + _owlvit_image_processing_owlvit_js__WEBPACK_IMPORTED_MODULE_26__.OwlViTImageProcessor + ), + /* harmony export */ + Owlv2ImageProcessor: () => ( + /* reexport safe */ + _owlv2_image_processing_owlv2_js__WEBPACK_IMPORTED_MODULE_25__.Owlv2ImageProcessor + ), + /* harmony export */ + Phi3VImageProcessor: () => ( + /* reexport safe */ + _phi3_v_image_processing_phi3_v_js__WEBPACK_IMPORTED_MODULE_27__.Phi3VImageProcessor + ), + /* harmony export */ + PixtralImageProcessor: () => ( + /* reexport safe */ + _pixtral_image_processing_pixtral_js__WEBPACK_IMPORTED_MODULE_28__.PixtralImageProcessor + ), + /* harmony export */ + PvtImageProcessor: () => ( + /* reexport safe */ + _pvt_image_processing_pvt_js__WEBPACK_IMPORTED_MODULE_29__.PvtImageProcessor + ), + /* harmony export */ + Qwen2VLImageProcessor: () => ( + /* reexport safe */ + _qwen2_vl_image_processing_qwen2_vl_js__WEBPACK_IMPORTED_MODULE_30__.Qwen2VLImageProcessor + ), + /* harmony export */ + RTDetrImageProcessor: () => ( + /* reexport safe */ + _rt_detr_image_processing_rt_detr_js__WEBPACK_IMPORTED_MODULE_31__.RTDetrImageProcessor + ), + /* harmony export */ + Sam2ImageProcessor: () => ( + /* reexport safe */ + _sam2_image_processing_sam2_js__WEBPACK_IMPORTED_MODULE_33__.Sam2ImageProcessor + ), + /* harmony export */ + Sam3ImageProcessor: () => ( + /* reexport safe */ + _sam3_image_processing_sam3_js__WEBPACK_IMPORTED_MODULE_34__.Sam3ImageProcessor + ), + /* harmony export */ + SamImageProcessor: () => ( + /* reexport safe */ + _sam_image_processing_sam_js__WEBPACK_IMPORTED_MODULE_32__.SamImageProcessor + ), + /* harmony export */ + SegformerFeatureExtractor: () => ( + /* reexport safe */ + _segformer_image_processing_segformer_js__WEBPACK_IMPORTED_MODULE_35__.SegformerFeatureExtractor + ), + /* harmony export */ + SegformerImageProcessor: () => ( + /* reexport safe */ + _segformer_image_processing_segformer_js__WEBPACK_IMPORTED_MODULE_35__.SegformerImageProcessor + ), + /* harmony export */ + SiglipImageProcessor: () => ( + /* reexport safe */ + _siglip_image_processing_siglip_js__WEBPACK_IMPORTED_MODULE_36__.SiglipImageProcessor + ), + /* harmony export */ + SmolVLMImageProcessor: () => ( + /* reexport safe */ + _smolvlm_image_processing_smolvlm_js__WEBPACK_IMPORTED_MODULE_37__.SmolVLMImageProcessor + ), + /* harmony export */ + Swin2SRImageProcessor: () => ( + /* reexport safe */ + _swin2sr_image_processing_swin2sr_js__WEBPACK_IMPORTED_MODULE_38__.Swin2SRImageProcessor + ), + /* harmony export */ + VLMImageProcessor: () => ( + /* reexport safe */ + _janus_image_processing_janus_js__WEBPACK_IMPORTED_MODULE_14__.VLMImageProcessor + ), + /* harmony export */ + ViTFeatureExtractor: () => ( + /* reexport safe */ + _vit_image_processing_vit_js__WEBPACK_IMPORTED_MODULE_39__.ViTFeatureExtractor + ), + /* harmony export */ + ViTImageProcessor: () => ( + /* reexport safe */ + _vit_image_processing_vit_js__WEBPACK_IMPORTED_MODULE_39__.ViTImageProcessor + ), + /* harmony export */ + VitMatteImageProcessor: () => ( + /* reexport safe */ + _vitmatte_image_processing_vitmatte_js__WEBPACK_IMPORTED_MODULE_40__.VitMatteImageProcessor + ), + /* harmony export */ + VitPoseImageProcessor: () => ( + /* reexport safe */ + _vitpose_image_processing_vitpose_js__WEBPACK_IMPORTED_MODULE_41__.VitPoseImageProcessor + ), + /* harmony export */ + YolosFeatureExtractor: () => ( + /* reexport safe */ + _yolos_image_processing_yolos_js__WEBPACK_IMPORTED_MODULE_42__.YolosFeatureExtractor + ), + /* harmony export */ + YolosImageProcessor: () => ( + /* reexport safe */ + _yolos_image_processing_yolos_js__WEBPACK_IMPORTED_MODULE_42__.YolosImageProcessor + ) + /* harmony export */ + }); + var _beit_image_processing_beit_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ./beit/image_processing_beit.js */ + "./src/models/beit/image_processing_beit.js" + ); + var _bit_image_processing_bit_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ./bit/image_processing_bit.js */ + "./src/models/bit/image_processing_bit.js" + ); + var _chinese_clip_image_processing_chinese_clip_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ./chinese_clip/image_processing_chinese_clip.js */ + "./src/models/chinese_clip/image_processing_chinese_clip.js" + ); + var _clip_image_processing_clip_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! ./clip/image_processing_clip.js */ + "./src/models/clip/image_processing_clip.js" + ); + var _convnext_image_processing_convnext_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__2( + /*! ./convnext/image_processing_convnext.js */ + "./src/models/convnext/image_processing_convnext.js" + ); + var _deit_image_processing_deit_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__2( + /*! ./deit/image_processing_deit.js */ + "./src/models/deit/image_processing_deit.js" + ); + var _detr_image_processing_detr_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__2( + /*! ./detr/image_processing_detr.js */ + "./src/models/detr/image_processing_detr.js" + ); + var _dinov3_vit_image_processing_dinov3_vit_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__2( + /*! ./dinov3_vit/image_processing_dinov3_vit.js */ + "./src/models/dinov3_vit/image_processing_dinov3_vit.js" + ); + var _donut_image_processing_donut_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__2( + /*! ./donut/image_processing_donut.js */ + "./src/models/donut/image_processing_donut.js" + ); + var _dpt_image_processing_dpt_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__2( + /*! ./dpt/image_processing_dpt.js */ + "./src/models/dpt/image_processing_dpt.js" + ); + var _efficientnet_image_processing_efficientnet_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__2( + /*! ./efficientnet/image_processing_efficientnet.js */ + "./src/models/efficientnet/image_processing_efficientnet.js" + ); + var _glpn_image_processing_glpn_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__2( + /*! ./glpn/image_processing_glpn.js */ + "./src/models/glpn/image_processing_glpn.js" + ); + var _grounding_dino_image_processing_grounding_dino_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__2( + /*! ./grounding_dino/image_processing_grounding_dino.js */ + "./src/models/grounding_dino/image_processing_grounding_dino.js" + ); + var _idefics3_image_processing_idefics3_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__2( + /*! ./idefics3/image_processing_idefics3.js */ + "./src/models/idefics3/image_processing_idefics3.js" + ); + var _janus_image_processing_janus_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__2( + /*! ./janus/image_processing_janus.js */ + "./src/models/janus/image_processing_janus.js" + ); + var _jina_clip_image_processing_jina_clip_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__2( + /*! ./jina_clip/image_processing_jina_clip.js */ + "./src/models/jina_clip/image_processing_jina_clip.js" + ); + var _llava_onevision_image_processing_llava_onevision_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__2( + /*! ./llava_onevision/image_processing_llava_onevision.js */ + "./src/models/llava_onevision/image_processing_llava_onevision.js" + ); + var _mask2former_image_processing_mask2former_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__2( + /*! ./mask2former/image_processing_mask2former.js */ + "./src/models/mask2former/image_processing_mask2former.js" + ); + var _maskformer_image_processing_maskformer_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__2( + /*! ./maskformer/image_processing_maskformer.js */ + "./src/models/maskformer/image_processing_maskformer.js" + ); + var _mobilenet_v1_image_processing_mobilenet_v1_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__2( + /*! ./mobilenet_v1/image_processing_mobilenet_v1.js */ + "./src/models/mobilenet_v1/image_processing_mobilenet_v1.js" + ); + var _mobilenet_v2_image_processing_mobilenet_v2_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__2( + /*! ./mobilenet_v2/image_processing_mobilenet_v2.js */ + "./src/models/mobilenet_v2/image_processing_mobilenet_v2.js" + ); + var _mobilenet_v3_image_processing_mobilenet_v3_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__2( + /*! ./mobilenet_v3/image_processing_mobilenet_v3.js */ + "./src/models/mobilenet_v3/image_processing_mobilenet_v3.js" + ); + var _mobilenet_v4_image_processing_mobilenet_v4_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__2( + /*! ./mobilenet_v4/image_processing_mobilenet_v4.js */ + "./src/models/mobilenet_v4/image_processing_mobilenet_v4.js" + ); + var _mobilevit_image_processing_mobilevit_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__2( + /*! ./mobilevit/image_processing_mobilevit.js */ + "./src/models/mobilevit/image_processing_mobilevit.js" + ); + var _nougat_image_processing_nougat_js__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__2( + /*! ./nougat/image_processing_nougat.js */ + "./src/models/nougat/image_processing_nougat.js" + ); + var _owlv2_image_processing_owlv2_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__2( + /*! ./owlv2/image_processing_owlv2.js */ + "./src/models/owlv2/image_processing_owlv2.js" + ); + var _owlvit_image_processing_owlvit_js__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__2( + /*! ./owlvit/image_processing_owlvit.js */ + "./src/models/owlvit/image_processing_owlvit.js" + ); + var _phi3_v_image_processing_phi3_v_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__2( + /*! ./phi3_v/image_processing_phi3_v.js */ + "./src/models/phi3_v/image_processing_phi3_v.js" + ); + var _pixtral_image_processing_pixtral_js__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__2( + /*! ./pixtral/image_processing_pixtral.js */ + "./src/models/pixtral/image_processing_pixtral.js" + ); + var _pvt_image_processing_pvt_js__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__2( + /*! ./pvt/image_processing_pvt.js */ + "./src/models/pvt/image_processing_pvt.js" + ); + var _qwen2_vl_image_processing_qwen2_vl_js__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__2( + /*! ./qwen2_vl/image_processing_qwen2_vl.js */ + "./src/models/qwen2_vl/image_processing_qwen2_vl.js" + ); + var _rt_detr_image_processing_rt_detr_js__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__2( + /*! ./rt_detr/image_processing_rt_detr.js */ + "./src/models/rt_detr/image_processing_rt_detr.js" + ); + var _sam_image_processing_sam_js__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__2( + /*! ./sam/image_processing_sam.js */ + "./src/models/sam/image_processing_sam.js" + ); + var _sam2_image_processing_sam2_js__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__2( + /*! ./sam2/image_processing_sam2.js */ + "./src/models/sam2/image_processing_sam2.js" + ); + var _sam3_image_processing_sam3_js__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__2( + /*! ./sam3/image_processing_sam3.js */ + "./src/models/sam3/image_processing_sam3.js" + ); + var _segformer_image_processing_segformer_js__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__2( + /*! ./segformer/image_processing_segformer.js */ + "./src/models/segformer/image_processing_segformer.js" + ); + var _siglip_image_processing_siglip_js__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__2( + /*! ./siglip/image_processing_siglip.js */ + "./src/models/siglip/image_processing_siglip.js" + ); + var _smolvlm_image_processing_smolvlm_js__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__2( + /*! ./smolvlm/image_processing_smolvlm.js */ + "./src/models/smolvlm/image_processing_smolvlm.js" + ); + var _swin2sr_image_processing_swin2sr_js__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__2( + /*! ./swin2sr/image_processing_swin2sr.js */ + "./src/models/swin2sr/image_processing_swin2sr.js" + ); + var _vit_image_processing_vit_js__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__2( + /*! ./vit/image_processing_vit.js */ + "./src/models/vit/image_processing_vit.js" + ); + var _vitmatte_image_processing_vitmatte_js__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__2( + /*! ./vitmatte/image_processing_vitmatte.js */ + "./src/models/vitmatte/image_processing_vitmatte.js" + ); + var _vitpose_image_processing_vitpose_js__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__2( + /*! ./vitpose/image_processing_vitpose.js */ + "./src/models/vitpose/image_processing_vitpose.js" + ); + var _yolos_image_processing_yolos_js__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__2( + /*! ./yolos/image_processing_yolos.js */ + "./src/models/yolos/image_processing_yolos.js" + ); + }) + ), + /***/ + "./src/models/janus/image_processing_janus.js": ( + /*!****************************************************!*\ + !*** ./src/models/janus/image_processing_janus.js ***! + \****************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + VLMImageProcessor: () => ( + /* binding */ + VLMImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class VLMImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + constructor(config) { + super({ + do_pad: true, + pad_size: { + width: config.image_size, + height: config.image_size + }, + ...config + }); + this.constant_values = this.config.background_color.map((x) => x * this.rescale_factor); + } + pad_image(pixelData, imgDims, padSize, options) { + return super.pad_image(pixelData, imgDims, padSize, { + constant_values: this.constant_values, + center: true, + ...options + }); + } + } + }) + ), + /***/ + "./src/models/janus/processing_janus.js": ( + /*!**********************************************!*\ + !*** ./src/models/janus/processing_janus.js ***! + \**********************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + VLChatProcessor: () => ( + /* binding */ + VLChatProcessor + ) + /* harmony export */ + }); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../auto/image_processing_auto.js */ + "./src/models/auto/image_processing_auto.js" + ); + var _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../tokenizers.js */ + "./src/tokenizers.js" + ); + var _utils_core_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! ../../utils/core.js */ + "./src/utils/core.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__2( + /*! ../../utils/tensor.js */ + "./src/utils/tensor.js" + ); + var _utils_image_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__2( + /*! ../../utils/image.js */ + "./src/utils/image.js" + ); + class VLChatProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { + static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor; + static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer; + static uses_processor_config = true; + constructor(config, components, chat_template) { + super(config, components, chat_template); + this.image_tag = this.config.image_tag; + this.image_start_tag = this.config.image_start_tag; + this.image_end_tag = this.config.image_end_tag; + this.num_image_tokens = this.config.num_image_tokens; + } + /** + * @typedef {Object} MultimodalMessageProperties Additional properties for multimodal messages. + * @property {(RawImage | string | URL)[]} [images] The images in the message. + * @typedef {(import('../../tokenizers.js').Message & MultimodalMessageProperties)[]} MultimodalConversation The conversation possibly containing multimodal inputs. + */ + /** + * @typedef {Object} VLCChatProcessorResult The processed input. + * @property {Tensor} input_ids The input IDs. + * @property {Tensor} attention_mask The attention mask. + * @property {Tensor} images_seq_mask The image sequence mask. + * @property {Tensor} images_emb_mask The image embedding mask. + */ + /** + * @param {MultimodalConversation} conversation The chat messages to process. + * @param {Object} options Additional options for processing. + * @param {RawImage|RawImage[]} [options.images] The images to process, if not set in the conversation. + * @param {string} [options.chat_template="default"] The chat template to use. + * @returns {Promise} The processed input. + */ + async _call(conversation, { + images = null, + chat_template = "default" + } = {}) { + if (!images) { + images = await Promise.all( + conversation.filter((msg) => msg.images).flatMap((msg) => msg.images).map((img) => _utils_image_js__WEBPACK_IMPORTED_MODULE_5__.RawImage.read(img)) + ); + } else if (!Array.isArray(images)) { + images = [images]; + } + const tokenizer = this.tokenizer; + const result = tokenizer.apply_chat_template(conversation, { + tokenize: false, + add_generation_prompt: true, + chat_template + }); + const encode = (text) => tokenizer.encode(text, { add_special_tokens: false }); + const parts = ( + /** @type {string} */ + result.split(this.image_tag) + ); + const num_images = parts.length - 1; + if (images.length !== num_images) { + throw new Error(`Number of images provided (${images.length}) does not match number of "${this.image_tag}" image tags (${num_images})`); + } + const [ + image_placeholder_tag_id, + image_start_tag_id, + image_end_tag_id + ] = tokenizer.model.convert_tokens_to_ids([ + this.image_tag, + this.image_start_tag, + this.image_end_tag + ]); + let input_ids = encode(parts[0]); + let images_seq_mask = new Array(input_ids.length).fill(false); + for (let i = 1; i < parts.length; ++i) { + const placeholder_image_tokens = new Array(this.num_image_tokens).fill(image_placeholder_tag_id); + const tokens = encode(parts[i]); + input_ids = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_3__.mergeArrays)( + input_ids, + [image_start_tag_id], + placeholder_image_tokens, + [image_end_tag_id], + tokens + ); + const image_mask = new Array(this.num_image_tokens).fill(true); + images_seq_mask = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_3__.mergeArrays)( + images_seq_mask, + [false], + image_mask, + [false], + new Array(tokens.length).fill(false) + ); + } + const dims = [1, input_ids.length]; + const final = { + input_ids: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor("int64", input_ids, dims), + attention_mask: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor("int64", new Array(input_ids.length).fill(1), dims), + images_seq_mask: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor("bool", images_seq_mask, dims), + images_emb_mask: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor( + "bool", + new Array(num_images * this.num_image_tokens).fill(true), + [1, num_images, this.num_image_tokens] + ) + }; + if (images && images.length > 0) { + const image_inputs = await this.image_processor(images); + image_inputs.pixel_values.unsqueeze_(0); + return { ...final, ...image_inputs }; + } + return final; + } + } + }) + ), + /***/ + "./src/models/jina_clip/image_processing_jina_clip.js": ( + /*!************************************************************!*\ + !*** ./src/models/jina_clip/image_processing_jina_clip.js ***! + \************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + JinaCLIPImageProcessor: () => ( + /* binding */ + JinaCLIPImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class JinaCLIPImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + constructor(config) { + const { resize_mode, fill_color, interpolation, size, ...other } = config; + const new_size = resize_mode === "squash" ? { width: size, height: size } : resize_mode === "shortest" ? { shortest_edge: size } : { longest_edge: size }; + const resample = interpolation === "bicubic" ? 3 : 2; + super({ + ...other, + size: new_size, + resample, + do_center_crop: true, + crop_size: size, + do_normalize: true + }); + } + } + }) + ), + /***/ + "./src/models/jina_clip/processing_jina_clip.js": ( + /*!******************************************************!*\ + !*** ./src/models/jina_clip/processing_jina_clip.js ***! + \******************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + JinaCLIPProcessor: () => ( + /* binding */ + JinaCLIPProcessor + ) + /* harmony export */ + }); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../auto/image_processing_auto.js */ + "./src/models/auto/image_processing_auto.js" + ); + var _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../tokenizers.js */ + "./src/tokenizers.js" + ); + class JinaCLIPProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { + static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer; + static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor; + async _call(text = null, images = null, kwargs = {}) { + if (!text && !images) { + throw new Error("Either text or images must be provided"); + } + const text_inputs = text ? this.tokenizer(text, kwargs) : {}; + const image_inputs = images ? await this.image_processor(images, kwargs) : {}; + return { + ...text_inputs, + ...image_inputs + }; + } + } + }) + ), + /***/ + "./src/models/llava/processing_llava.js": ( + /*!**********************************************!*\ + !*** ./src/models/llava/processing_llava.js ***! + \**********************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + LlavaProcessor: () => ( + /* binding */ + LlavaProcessor + ) + /* harmony export */ + }); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../auto/image_processing_auto.js */ + "./src/models/auto/image_processing_auto.js" + ); + var _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../tokenizers.js */ + "./src/tokenizers.js" + ); + class LlavaProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { + static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer; + static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor; + static uses_processor_config = true; + /** + * @typedef {import('../../utils/image.js').RawImage} RawImage + */ + // `images` is required, `text` is optional + async _call(images, text = null, kwargs = {}) { + const image_inputs = await this.image_processor(images, kwargs); + if (text) { + const [height, width] = image_inputs.pixel_values.dims.slice(-2); + const { image_token, patch_size, num_additional_image_tokens } = this.config; + const num_image_tokens = Math.floor( + height / patch_size + ) * Math.floor(width / patch_size) + num_additional_image_tokens; + text = structuredClone(text); + if (!Array.isArray(text)) { + text = [text]; + } + for (let i = 0; i < text.length; ++i) { + text[i] = text[i].replace(image_token, image_token.repeat(num_image_tokens)); + } + } + const text_inputs = text ? this.tokenizer(text, kwargs) : {}; + return { + ...image_inputs, + ...text_inputs + }; + } + } + }) + ), + /***/ + "./src/models/llava_onevision/image_processing_llava_onevision.js": ( + /*!************************************************************************!*\ + !*** ./src/models/llava_onevision/image_processing_llava_onevision.js ***! + \************************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + LlavaOnevisionImageProcessor: () => ( + /* binding */ + LlavaOnevisionImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class LlavaOnevisionImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + } + }) + ), + /***/ + "./src/models/mask2former/image_processing_mask2former.js": ( + /*!****************************************************************!*\ + !*** ./src/models/mask2former/image_processing_mask2former.js ***! + \****************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + Mask2FormerImageProcessor: () => ( + /* binding */ + Mask2FormerImageProcessor + ) + /* harmony export */ + }); + var _maskformer_image_processing_maskformer_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../maskformer/image_processing_maskformer.js */ + "./src/models/maskformer/image_processing_maskformer.js" + ); + class Mask2FormerImageProcessor extends _maskformer_image_processing_maskformer_js__WEBPACK_IMPORTED_MODULE_0__.MaskFormerImageProcessor { + } + }) + ), + /***/ + "./src/models/maskformer/image_processing_maskformer.js": ( + /*!**************************************************************!*\ + !*** ./src/models/maskformer/image_processing_maskformer.js ***! + \**************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + MaskFormerFeatureExtractor: () => ( + /* binding */ + MaskFormerFeatureExtractor + ), + /* harmony export */ + MaskFormerImageProcessor: () => ( + /* binding */ + MaskFormerImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class MaskFormerImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + /** @type {typeof post_process_panoptic_segmentation} */ + post_process_panoptic_segmentation(...args) { + return (0, _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.post_process_panoptic_segmentation)(...args); + } + /** @type {typeof post_process_instance_segmentation} */ + post_process_instance_segmentation(...args) { + return (0, _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.post_process_instance_segmentation)(...args); + } + } + class MaskFormerFeatureExtractor extends MaskFormerImageProcessor { + } + }) + ), + /***/ + "./src/models/mgp_str/processing_mgp_str.js": ( + /*!**************************************************!*\ + !*** ./src/models/mgp_str/processing_mgp_str.js ***! + \**************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + MgpstrProcessor: () => ( + /* binding */ + MgpstrProcessor + ) + /* harmony export */ + }); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../auto/image_processing_auto.js */ + "./src/models/auto/image_processing_auto.js" + ); + var _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../tokenizers.js */ + "./src/tokenizers.js" + ); + var _utils_maths_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! ../../utils/maths.js */ + "./src/utils/maths.js" + ); + const DECODE_TYPE_MAPPING = { + "char": ["char_decode", 1], + "bpe": ["bpe_decode", 2], + "wp": ["wp_decode", 102] + }; + class MgpstrProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { + static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer; + static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor; + /** + * @returns {import('../../tokenizers.js').MgpstrTokenizer} The character tokenizer. + */ + get char_tokenizer() { + return this.components.char_tokenizer; + } + /** + * @returns {import('../../tokenizers.js').GPT2Tokenizer} The BPE tokenizer. + */ + get bpe_tokenizer() { + return this.components.bpe_tokenizer; + } + /** + * @returns {import('../../tokenizers.js').BertTokenizer} The WordPiece tokenizer. + */ + get wp_tokenizer() { + return this.components.wp_tokenizer; + } + /** + * Helper function to decode the model prediction logits. + * @param {import('../../utils/tensor.js').Tensor} pred_logits Model prediction logits. + * @param {string} format Type of model prediction. Must be one of ['char', 'bpe', 'wp']. + * @returns {[string[], number[]]} The decoded sentences and their confidence scores. + */ + _decode_helper(pred_logits, format) { + if (!DECODE_TYPE_MAPPING.hasOwnProperty(format)) { + throw new Error(`Format ${format} is not supported.`); + } + const [decoder_name, eos_token] = DECODE_TYPE_MAPPING[format]; + const decoder = this[decoder_name].bind(this); + const [batch_size, batch_max_length] = pred_logits.dims; + const conf_scores = []; + const all_ids = []; + const pred_logits_list = pred_logits.tolist(); + for (let i = 0; i < batch_size; ++i) { + const logits = pred_logits_list[i]; + const ids = []; + const scores = []; + for (let j = 1; j < batch_max_length; ++j) { + const [max_prob, max_prob_index] = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_3__.max)((0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_3__.softmax)(logits[j])); + scores.push(max_prob); + if (max_prob_index == eos_token) { + break; + } + ids.push(max_prob_index); + } + const confidence_score = scores.length > 0 ? scores.reduce((a, b) => a * b, 1) : 0; + all_ids.push(ids); + conf_scores.push(confidence_score); + } + const decoded = decoder(all_ids); + return [decoded, conf_scores]; + } + /** + * Convert a list of lists of char token ids into a list of strings by calling char tokenizer. + * @param {number[][]} sequences List of tokenized input ids. + * @returns {string[]} The list of char decoded sentences. + */ + char_decode(sequences) { + return this.char_tokenizer.batch_decode(sequences).map((str) => str.replaceAll(" ", "")); + } + /** + * Convert a list of lists of BPE token ids into a list of strings by calling BPE tokenizer. + * @param {number[][]} sequences List of tokenized input ids. + * @returns {string[]} The list of BPE decoded sentences. + */ + bpe_decode(sequences) { + return this.bpe_tokenizer.batch_decode(sequences); + } + /** + * Convert a list of lists of word piece token ids into a list of strings by calling word piece tokenizer. + * @param {number[][]} sequences List of tokenized input ids. + * @returns {string[]} The list of wp decoded sentences. + */ + wp_decode(sequences) { + return this.wp_tokenizer.batch_decode(sequences).map((str) => str.replaceAll(" ", "")); + } + /** + * Convert a list of lists of token ids into a list of strings by calling decode. + * @param {[import('../../utils/tensor.js').Tensor, import('../../utils/tensor.js').Tensor, import('../../utils/tensor.js').Tensor]} sequences List of tokenized input ids. + * @returns {{generated_text: string[], scores: number[], char_preds: string[], bpe_preds: string[], wp_preds: string[]}} + * Dictionary of all the outputs of the decoded results. + * - generated_text: The final results after fusion of char, bpe, and wp. + * - scores: The final scores after fusion of char, bpe, and wp. + * - char_preds: The list of character decoded sentences. + * - bpe_preds: The list of BPE decoded sentences. + * - wp_preds: The list of wp decoded sentences. + */ + // @ts-expect-error The type of this method is not compatible with the one in the base class. + batch_decode([char_logits, bpe_logits, wp_logits]) { + const [char_preds, char_scores] = this._decode_helper(char_logits, "char"); + const [bpe_preds, bpe_scores] = this._decode_helper(bpe_logits, "bpe"); + const [wp_preds, wp_scores] = this._decode_helper(wp_logits, "wp"); + const generated_text = []; + const scores = []; + for (let i = 0; i < char_preds.length; ++i) { + const [max_score, max_score_index] = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_3__.max)([char_scores[i], bpe_scores[i], wp_scores[i]]); + generated_text.push([char_preds[i], bpe_preds[i], wp_preds[i]][max_score_index]); + scores.push(max_score); + } + return { + generated_text, + scores, + char_preds, + bpe_preds, + wp_preds + }; + } + /** @type {typeof Processor.from_pretrained} */ + static async from_pretrained(...args) { + const base = await super.from_pretrained(...args); + const bpe_tokenizer = await _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer.from_pretrained("Xenova/gpt2"); + const wp_tokenizer = await _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer.from_pretrained("Xenova/bert-base-uncased"); + base.components = { + image_processor: base.image_processor, + char_tokenizer: base.tokenizer, + bpe_tokenizer, + wp_tokenizer + }; + return base; + } + async _call(images, text = null) { + const result = await this.image_processor(images); + if (text) { + result.labels = this.tokenizer(text).input_ids; + } + return result; + } + } + }) + ), + /***/ + "./src/models/mobilenet_v1/image_processing_mobilenet_v1.js": ( + /*!******************************************************************!*\ + !*** ./src/models/mobilenet_v1/image_processing_mobilenet_v1.js ***! + \******************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + MobileNetV1FeatureExtractor: () => ( + /* binding */ + MobileNetV1FeatureExtractor + ), + /* harmony export */ + MobileNetV1ImageProcessor: () => ( + /* binding */ + MobileNetV1ImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class MobileNetV1ImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + } + class MobileNetV1FeatureExtractor extends MobileNetV1ImageProcessor { + } + }) + ), + /***/ + "./src/models/mobilenet_v2/image_processing_mobilenet_v2.js": ( + /*!******************************************************************!*\ + !*** ./src/models/mobilenet_v2/image_processing_mobilenet_v2.js ***! + \******************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + MobileNetV2FeatureExtractor: () => ( + /* binding */ + MobileNetV2FeatureExtractor + ), + /* harmony export */ + MobileNetV2ImageProcessor: () => ( + /* binding */ + MobileNetV2ImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class MobileNetV2ImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + } + class MobileNetV2FeatureExtractor extends MobileNetV2ImageProcessor { + } + }) + ), + /***/ + "./src/models/mobilenet_v3/image_processing_mobilenet_v3.js": ( + /*!******************************************************************!*\ + !*** ./src/models/mobilenet_v3/image_processing_mobilenet_v3.js ***! + \******************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + MobileNetV3FeatureExtractor: () => ( + /* binding */ + MobileNetV3FeatureExtractor + ), + /* harmony export */ + MobileNetV3ImageProcessor: () => ( + /* binding */ + MobileNetV3ImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class MobileNetV3ImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + } + class MobileNetV3FeatureExtractor extends MobileNetV3ImageProcessor { + } + }) + ), + /***/ + "./src/models/mobilenet_v4/image_processing_mobilenet_v4.js": ( + /*!******************************************************************!*\ + !*** ./src/models/mobilenet_v4/image_processing_mobilenet_v4.js ***! + \******************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + MobileNetV4FeatureExtractor: () => ( + /* binding */ + MobileNetV4FeatureExtractor + ), + /* harmony export */ + MobileNetV4ImageProcessor: () => ( + /* binding */ + MobileNetV4ImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class MobileNetV4ImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + } + class MobileNetV4FeatureExtractor extends MobileNetV4ImageProcessor { + } + }) + ), + /***/ + "./src/models/mobilevit/image_processing_mobilevit.js": ( + /*!************************************************************!*\ + !*** ./src/models/mobilevit/image_processing_mobilevit.js ***! + \************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + MobileViTFeatureExtractor: () => ( + /* binding */ + MobileViTFeatureExtractor + ), + /* harmony export */ + MobileViTImageProcessor: () => ( + /* binding */ + MobileViTImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class MobileViTImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + } + class MobileViTFeatureExtractor extends MobileViTImageProcessor { + } + }) + ), + /***/ + "./src/models/moonshine/feature_extraction_moonshine.js": ( + /*!**************************************************************!*\ + !*** ./src/models/moonshine/feature_extraction_moonshine.js ***! + \**************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + MoonshineFeatureExtractor: () => ( + /* binding */ + MoonshineFeatureExtractor + ) + /* harmony export */ + }); + var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/feature_extraction_utils.js */ + "./src/base/feature_extraction_utils.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../utils/tensor.js */ + "./src/utils/tensor.js" + ); + class MoonshineFeatureExtractor extends _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractor { + /** + * Asynchronously extracts input values from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_values: Tensor; }>} The extracted input values. + */ + async _call(audio) { + (0, _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.validate_audio_inputs)(audio, "MoonshineFeatureExtractor"); + if (audio instanceof Float64Array) { + audio = new Float32Array(audio); + } + const shape = [ + 1, + /* batch_size */ + audio.length + /* num_samples */ + ]; + return { + input_values: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor("float32", audio, shape) + }; + } + } + }) + ), + /***/ + "./src/models/moonshine/processing_moonshine.js": ( + /*!******************************************************!*\ + !*** ./src/models/moonshine/processing_moonshine.js ***! + \******************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + MoonshineProcessor: () => ( + /* binding */ + MoonshineProcessor + ) + /* harmony export */ + }); + var _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../auto/feature_extraction_auto.js */ + "./src/models/auto/feature_extraction_auto.js" + ); + var _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../tokenizers.js */ + "./src/tokenizers.js" + ); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + class MoonshineProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__.Processor { + static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__.AutoTokenizer; + static feature_extractor_class = _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_0__.AutoFeatureExtractor; + /** + * Calls the feature_extractor function with the given audio input. + * @param {any} audio The audio input to extract features from. + * @returns {Promise} A Promise that resolves with the extracted features. + */ + async _call(audio) { + return await this.feature_extractor(audio); + } + } + }) + ), + /***/ + "./src/models/nougat/image_processing_nougat.js": ( + /*!******************************************************!*\ + !*** ./src/models/nougat/image_processing_nougat.js ***! + \******************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + NougatImageProcessor: () => ( + /* binding */ + NougatImageProcessor + ) + /* harmony export */ + }); + var _donut_image_processing_donut_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../donut/image_processing_donut.js */ + "./src/models/donut/image_processing_donut.js" + ); + class NougatImageProcessor extends _donut_image_processing_donut_js__WEBPACK_IMPORTED_MODULE_0__.DonutImageProcessor { + } + }) + ), + /***/ + "./src/models/owlv2/image_processing_owlv2.js": ( + /*!****************************************************!*\ + !*** ./src/models/owlv2/image_processing_owlv2.js ***! + \****************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + Owlv2ImageProcessor: () => ( + /* binding */ + Owlv2ImageProcessor + ) + /* harmony export */ + }); + var _owlvit_image_processing_owlvit_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../owlvit/image_processing_owlvit.js */ + "./src/models/owlvit/image_processing_owlvit.js" + ); + class Owlv2ImageProcessor extends _owlvit_image_processing_owlvit_js__WEBPACK_IMPORTED_MODULE_0__.OwlViTImageProcessor { + } + }) + ), + /***/ + "./src/models/owlvit/image_processing_owlvit.js": ( + /*!******************************************************!*\ + !*** ./src/models/owlvit/image_processing_owlvit.js ***! + \******************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + OwlViTFeatureExtractor: () => ( + /* binding */ + OwlViTFeatureExtractor + ), + /* harmony export */ + OwlViTImageProcessor: () => ( + /* binding */ + OwlViTImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class OwlViTImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + /** @type {typeof post_process_object_detection} */ + post_process_object_detection(...args) { + return (0, _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.post_process_object_detection)(...args); + } + } + class OwlViTFeatureExtractor extends OwlViTImageProcessor { + } + }) + ), + /***/ + "./src/models/owlvit/processing_owlvit.js": ( + /*!************************************************!*\ + !*** ./src/models/owlvit/processing_owlvit.js ***! + \************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + OwlViTProcessor: () => ( + /* binding */ + OwlViTProcessor + ) + /* harmony export */ + }); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../auto/image_processing_auto.js */ + "./src/models/auto/image_processing_auto.js" + ); + var _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../tokenizers.js */ + "./src/tokenizers.js" + ); + class OwlViTProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { + static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer; + static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor; + } + }) + ), + /***/ + "./src/models/paligemma/processing_paligemma.js": ( + /*!******************************************************!*\ + !*** ./src/models/paligemma/processing_paligemma.js ***! + \******************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + PaliGemmaProcessor: () => ( + /* binding */ + PaliGemmaProcessor + ) + /* harmony export */ + }); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../auto/image_processing_auto.js */ + "./src/models/auto/image_processing_auto.js" + ); + var _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../tokenizers.js */ + "./src/tokenizers.js" + ); + const IMAGE_TOKEN = ""; + function build_string_from_input(prompt, bos_token, image_seq_len, image_token, num_images) { + return `${image_token.repeat(image_seq_len * num_images)}${bos_token}${prompt} +`; + } + class PaliGemmaProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { + static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer; + static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor; + static uses_processor_config = false; + /** + * @typedef {import('../../utils/image.js').RawImage} RawImage + */ + // `images` is required, `text` is optional + async _call(images, text = null, kwargs = {}) { + if (!text) { + console.warn( + "You are using PaliGemma without a text prefix. It will perform as a picture-captioning model." + ); + text = ""; + } + if (!Array.isArray(images)) { + images = [images]; + } + if (!Array.isArray(text)) { + text = [text]; + } + const bos_token = this.tokenizer.bos_token; + const image_seq_length = this.image_processor.config.image_seq_length; + let input_strings; + if (text.some((t) => t.includes(IMAGE_TOKEN))) { + input_strings = text.map( + (sample) => { + const expanded_sample = sample.replaceAll(IMAGE_TOKEN, IMAGE_TOKEN.repeat(image_seq_length)); + const bos_rfind_index = expanded_sample.lastIndexOf(IMAGE_TOKEN); + const bos_index = bos_rfind_index === -1 ? 0 : bos_rfind_index + IMAGE_TOKEN.length; + return expanded_sample.slice(0, bos_index) + bos_token + expanded_sample.slice(bos_index) + "\n"; + } + ); + } else { + console.warn( + "You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens." + ); + input_strings = text.map( + (sample) => build_string_from_input( + sample, + bos_token, + image_seq_length, + IMAGE_TOKEN, + images.length + ) + ); + } + const text_inputs = this.tokenizer(input_strings, kwargs); + const image_inputs = await this.image_processor(images, kwargs); + return { + ...image_inputs, + ...text_inputs + }; + } + } + }) + ), + /***/ + "./src/models/parakeet/feature_extraction_parakeet.js": ( + /*!************************************************************!*\ + !*** ./src/models/parakeet/feature_extraction_parakeet.js ***! + \************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + ParakeetFeatureExtractor: () => ( + /* binding */ + ParakeetFeatureExtractor + ) + /* harmony export */ + }); + var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/feature_extraction_utils.js */ + "./src/base/feature_extraction_utils.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../utils/tensor.js */ + "./src/utils/tensor.js" + ); + var _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../utils/audio.js */ + "./src/utils/audio.js" + ); + const EPSILON = 1e-5; + class ParakeetFeatureExtractor extends _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractor { + constructor(config) { + super(config); + this.config.mel_filters ??= (0, _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.mel_filter_bank)( + Math.floor(1 + this.config.n_fft / 2), + // num_frequency_bins + this.config.feature_size, + // num_mel_filters + 0, + // min_frequency + this.config.sampling_rate / 2, + // max_frequency + this.config.sampling_rate, + // sampling_rate + "slaney", + // norm + "slaney" + // mel_scale + ); + const window2 = (0, _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.window_function)(this.config.win_length, "hann", { + periodic: false + }); + this.window = new Float64Array(this.config.n_fft); + const offset = Math.floor((this.config.n_fft - this.config.win_length) / 2); + this.window.set(window2, offset); + } + /** + * Computes the log-Mel spectrogram of the provided audio waveform. + * @param {Float32Array|Float64Array} waveform The audio waveform to process. + * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. + */ + async _extract_fbank_features(waveform) { + const preemphasis = this.config.preemphasis; + waveform = new Float64Array(waveform); + for (let j = waveform.length - 1; j >= 1; --j) { + waveform[j] -= preemphasis * waveform[j - 1]; + } + const features = await (0, _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.spectrogram)( + waveform, + this.window, + // window + this.window.length, + // frame_length + this.config.hop_length, + // hop_length + { + fft_length: this.config.n_fft, + power: 2, + mel_filters: this.config.mel_filters, + log_mel: "log", + mel_floor: -Infinity, + pad_mode: "constant", + center: true, + // Custom + transpose: true, + mel_offset: 2 ** -24 + } + ); + return features; + } + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_features: Tensor; attention_mask: Tensor; }>} A Promise resolving to an object containing the extracted input features as a Tensor. + */ + async _call(audio) { + (0, _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.validate_audio_inputs)(audio, "ParakeetFeatureExtractor"); + const features = await this._extract_fbank_features(audio); + const features_length = Math.floor( + (audio.length + Math.floor(this.config.n_fft / 2) * 2 - this.config.n_fft) / this.config.hop_length + ); + const features_data = ( + /** @type {Float32Array} */ + features.data + ); + features_data.fill(0, features_length * features.dims[1]); + const [num_frames, num_features] = features.dims; + const sum = new Float64Array(num_features); + const sum_sq = new Float64Array(num_features); + for (let i = 0; i < features_length; ++i) { + const offset = i * num_features; + for (let j = 0; j < num_features; ++j) { + const val = features_data[offset + j]; + sum[j] += val; + sum_sq[j] += val * val; + } + } + const divisor = features_length > 1 ? features_length - 1 : 1; + for (let j = 0; j < num_features; ++j) { + const mean = sum[j] / features_length; + const variance = (sum_sq[j] - features_length * mean * mean) / divisor; + const std = Math.sqrt(variance) + EPSILON; + const inv_std = 1 / std; + for (let i = 0; i < features_length; ++i) { + const index = i * num_features + j; + features_data[index] = (features_data[index] - mean) * inv_std; + } + } + const mask_data = new BigInt64Array(num_frames); + mask_data.fill(1n, 0, features_length); + return { + input_features: features.unsqueeze_(0), + attention_mask: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor("int64", mask_data, [1, num_frames]) + }; + } + } + }) + ), + /***/ + "./src/models/phi3_v/image_processing_phi3_v.js": ( + /*!******************************************************!*\ + !*** ./src/models/phi3_v/image_processing_phi3_v.js ***! + \******************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + Phi3VImageProcessor: () => ( + /* binding */ + Phi3VImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../utils/tensor.js */ + "./src/utils/tensor.js" + ); + const IMAGE_SIZE = 336; + const SLICE_AXES = [2, 3]; + const { ceil, floor, sqrt } = Math; + class Phi3VImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + constructor(config) { + super({ + ...config, + do_normalize: true, + do_pad: true, + pad_size: "custom", + do_convert_rgb: true, + do_resize: true + // Smart resizing "hd_transform" + }); + this._num_crops = config.num_crops; + } + calc_num_image_tokens_from_image_size(width, height) { + const { num_img_tokens } = this.config; + return floor((floor(height / IMAGE_SIZE) * floor(width / IMAGE_SIZE) + 1) * num_img_tokens + 1 + (floor(height / IMAGE_SIZE) + 1) * sqrt(num_img_tokens)); + } + /** @type {ImageProcessor['get_resize_output_image_size']} */ + get_resize_output_image_size(image, size) { + const hd_num = this._num_crops; + const [width, height] = image.size; + let ratio = width / height; + let scale = 1; + while (scale * Math.ceil(scale / ratio) <= hd_num) { + scale += 1; + } + scale -= 1; + const new_w = Math.floor(scale * 336); + const new_h = Math.floor(new_w / ratio); + return [new_w, new_h]; + } + /** @type {ImageProcessor['pad_image']} */ + pad_image(pixelData, imgDims, padSize, options = {}) { + const [imageHeight, imageWidth] = imgDims; + const height = IMAGE_SIZE * ceil(imageHeight / IMAGE_SIZE); + const width = IMAGE_SIZE * ceil(imageWidth / IMAGE_SIZE); + const constant_values = [1, 1, 1].map((x, i) => (x - this.image_mean[i]) / this.image_std[i]); + return super.pad_image(pixelData, imgDims, { width, height }, { + center: true, + constant_values, + ...options + }); + } + async _call(images, { + num_crops = null + } = {}) { + this._num_crops = num_crops ??= this.config.num_crops; + if (num_crops < 4 || sqrt(num_crops) % 1 !== 0) { + throw new Error("num_crops must be a square number >= 4"); + } + if (!Array.isArray(images)) { + images = [images]; + } + const num_images = images.length; + const imageData = await Promise.all(images.map((x) => this.preprocess(x))); + const original_sizes = imageData.map((x) => x.original_size); + const reshaped_input_sizes = imageData.map((x) => x.reshaped_input_size); + const all_pixel_values = []; + for (const { pixel_values: pixel_values2 } of imageData) { + pixel_values2.unsqueeze_(0); + const [height, width] = pixel_values2.dims.slice(-2); + const batch_pixel_values = await (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.interpolate_4d)(pixel_values2, { + size: [IMAGE_SIZE, IMAGE_SIZE], + mode: "bicubic" + }); + if (num_crops > 0) { + const patches = []; + const sqrt_patches = sqrt(num_crops); + const patch_width = floor(width / sqrt_patches); + const patch_height = floor(height / sqrt_patches); + for (let y = 0; y < sqrt_patches; ++y) { + for (let x = 0; x < sqrt_patches; ++x) { + let start_x, start_y, end_x, end_y; + if (y === sqrt_patches - 1) { + start_y = height - patch_height; + end_y = height; + } else { + start_y = y * patch_height; + end_y = (y + 1) * patch_height; + } + if (x === sqrt_patches - 1) { + start_x = width - patch_width; + end_x = width; + } else { + start_x = x * patch_width; + end_x = (x + 1) * patch_width; + } + const starts = [start_y, start_x]; + const ends = [end_y, end_x]; + const patch = await (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.slice)(pixel_values2, starts, ends, SLICE_AXES); + patches.push(patch); + } + } + const resized_tensors = await (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.interpolate_4d)((0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.cat)(patches, 0), { + size: [IMAGE_SIZE, IMAGE_SIZE], + mode: "bicubic" + }); + all_pixel_values.push((0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.cat)([batch_pixel_values, resized_tensors], 0)); + } else { + all_pixel_values.push(batch_pixel_values); + } + } + const pixel_values = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.stack)(all_pixel_values, 0); + const sizes = reshaped_input_sizes.map((x) => x.map((y) => IMAGE_SIZE * ceil(y / IMAGE_SIZE))); + const image_sizes = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor( + "int64", + sizes.flat(), + [num_images, 2] + ); + const num_img_tokens = sizes.map( + ([height, width]) => this.calc_num_image_tokens_from_image_size(width, height) + ); + return { pixel_values, original_sizes, reshaped_input_sizes, image_sizes, num_img_tokens }; + } + } + }) + ), + /***/ + "./src/models/phi3_v/processing_phi3_v.js": ( + /*!************************************************!*\ + !*** ./src/models/phi3_v/processing_phi3_v.js ***! + \************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + Phi3VProcessor: () => ( + /* binding */ + Phi3VProcessor + ) + /* harmony export */ + }); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../auto/image_processing_auto.js */ + "./src/models/auto/image_processing_auto.js" + ); + var _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../tokenizers.js */ + "./src/tokenizers.js" + ); + var _utils_image_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! ../../utils/image.js */ + "./src/utils/image.js" + ); + const IMAGE_TOKEN = "<|image|>"; + const IMAGE_TOKEN_PATTERN = /<\|image_\d+\|>/g; + class Phi3VProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { + static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor; + static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer; + /** + * + * @param {string|string[]} text + * @param {RawImage|RawImage[]} images + * @param { { padding?: boolean, truncation?: boolean, num_crops?: number } | undefined } options + * @returns {Promise} + */ + async _call(text, images = null, { + padding = true, + truncation = true, + num_crops = null + } = {}) { + if (!Array.isArray(text)) { + text = [text]; + } + let text_inputs, image_inputs; + if (images) { + image_inputs = await this.image_processor(images, { num_crops }); + const { num_img_tokens } = image_inputs; + const prompt_chunks = text.map((t, i) => t.split(IMAGE_TOKEN_PATTERN).join(IMAGE_TOKEN.repeat(num_img_tokens[i]))); + text_inputs = this.tokenizer(prompt_chunks, { padding, truncation }); + const image_token_id = this.tokenizer.model.convert_tokens_to_ids([IMAGE_TOKEN])[0]; + text_inputs.input_ids.map_((id2) => id2 == image_token_id ? -id2 : id2); + } else { + text_inputs = this.tokenizer(text); + } + return { + ...text_inputs, + ...image_inputs + }; + } + } + }) + ), + /***/ + "./src/models/pixtral/image_processing_pixtral.js": ( + /*!********************************************************!*\ + !*** ./src/models/pixtral/image_processing_pixtral.js ***! + \********************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + PixtralImageProcessor: () => ( + /* binding */ + PixtralImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class PixtralImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + /** @type {ImageProcessor['get_resize_output_image_size']} */ + get_resize_output_image_size(image, size) { + const { longest_edge } = size; + if (longest_edge === void 0) { + throw new Error("size must contain 'longest_edge'"); + } + const [srcWidth, srcHeight] = image.size; + const ratio = Math.max(srcWidth, srcHeight) / longest_edge; + let newWidth = srcWidth; + let newHeight = srcHeight; + if (ratio > 1) { + newWidth = Math.floor(srcWidth / ratio); + newHeight = Math.floor(srcHeight / ratio); + } + const { patch_size, spatial_merge_size } = this.config; + if (!spatial_merge_size) { + throw new Error("config must contain 'spatial_merge_size'"); + } + const real_patch_size = patch_size * spatial_merge_size; + const num_width_tokens = Math.floor((newWidth - 1) / real_patch_size) + 1; + const num_height_tokens = Math.floor((newHeight - 1) / real_patch_size) + 1; + return [num_width_tokens * real_patch_size, num_height_tokens * real_patch_size]; + } + } + }) + ), + /***/ + "./src/models/pixtral/processing_pixtral.js": ( + /*!**************************************************!*\ + !*** ./src/models/pixtral/processing_pixtral.js ***! + \**************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + PixtralProcessor: () => ( + /* binding */ + PixtralProcessor + ) + /* harmony export */ + }); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../auto/image_processing_auto.js */ + "./src/models/auto/image_processing_auto.js" + ); + var _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../tokenizers.js */ + "./src/tokenizers.js" + ); + class PixtralProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { + static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer; + static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor; + static uses_processor_config = true; + /** + * @typedef {import('../../utils/image.js').RawImage} RawImage + */ + // `images` is required, `text` is optional + async _call(images, text = null, kwargs = {}) { + const image_inputs = await this.image_processor(images, kwargs); + if (text) { + const [height, width] = image_inputs.pixel_values.dims.slice(-2); + const { image_token, image_break_token, image_end_token, patch_size, spatial_merge_size } = this.config; + const real_patch_size = patch_size * spatial_merge_size; + const num_height_tokens = Math.floor(height / real_patch_size); + const num_width_tokens = Math.floor(width / real_patch_size); + text = structuredClone(text); + if (!Array.isArray(text)) { + text = [text]; + } + for (let i = 0; i < text.length; ++i) { + const width_tokens = image_token.repeat(num_width_tokens); + const row = width_tokens + image_break_token; + const finalRow = width_tokens + image_end_token; + const full = row.repeat(num_height_tokens - 1) + finalRow; + text[i] = text[i].replace(image_token, full); + } + } + const text_inputs = text ? this.tokenizer(text, kwargs) : {}; + return { + ...image_inputs, + ...text_inputs + }; + } + } + }) + ), + /***/ + "./src/models/processors.js": ( + /*!**********************************!*\ + !*** ./src/models/processors.js ***! + \**********************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + Florence2Processor: () => ( + /* reexport safe */ + _florence2_processing_florence2_js__WEBPACK_IMPORTED_MODULE_0__.Florence2Processor + ), + /* harmony export */ + Gemma3nProcessor: () => ( + /* reexport safe */ + _gemma3n_processing_gemma3n_js__WEBPACK_IMPORTED_MODULE_1__.Gemma3nProcessor + ), + /* harmony export */ + GroundingDinoProcessor: () => ( + /* reexport safe */ + _grounding_dino_processing_grounding_dino_js__WEBPACK_IMPORTED_MODULE_2__.GroundingDinoProcessor + ), + /* harmony export */ + Idefics3Processor: () => ( + /* reexport safe */ + _idefics3_processing_idefics3_js__WEBPACK_IMPORTED_MODULE_3__.Idefics3Processor + ), + /* harmony export */ + JinaCLIPProcessor: () => ( + /* reexport safe */ + _jina_clip_processing_jina_clip_js__WEBPACK_IMPORTED_MODULE_5__.JinaCLIPProcessor + ), + /* harmony export */ + LlavaProcessor: () => ( + /* reexport safe */ + _llava_processing_llava_js__WEBPACK_IMPORTED_MODULE_6__.LlavaProcessor + ), + /* harmony export */ + MgpstrProcessor: () => ( + /* reexport safe */ + _mgp_str_processing_mgp_str_js__WEBPACK_IMPORTED_MODULE_7__.MgpstrProcessor + ), + /* harmony export */ + MoonshineProcessor: () => ( + /* reexport safe */ + _moonshine_processing_moonshine_js__WEBPACK_IMPORTED_MODULE_8__.MoonshineProcessor + ), + /* harmony export */ + OwlViTProcessor: () => ( + /* reexport safe */ + _owlvit_processing_owlvit_js__WEBPACK_IMPORTED_MODULE_9__.OwlViTProcessor + ), + /* harmony export */ + PaliGemmaProcessor: () => ( + /* reexport safe */ + _paligemma_processing_paligemma_js__WEBPACK_IMPORTED_MODULE_10__.PaliGemmaProcessor + ), + /* harmony export */ + Phi3VProcessor: () => ( + /* reexport safe */ + _phi3_v_processing_phi3_v_js__WEBPACK_IMPORTED_MODULE_11__.Phi3VProcessor + ), + /* harmony export */ + PixtralProcessor: () => ( + /* reexport safe */ + _pixtral_processing_pixtral_js__WEBPACK_IMPORTED_MODULE_12__.PixtralProcessor + ), + /* harmony export */ + PyAnnoteProcessor: () => ( + /* reexport safe */ + _pyannote_processing_pyannote_js__WEBPACK_IMPORTED_MODULE_13__.PyAnnoteProcessor + ), + /* harmony export */ + Qwen2VLProcessor: () => ( + /* reexport safe */ + _qwen2_vl_processing_qwen2_vl_js__WEBPACK_IMPORTED_MODULE_14__.Qwen2VLProcessor + ), + /* harmony export */ + Sam2Processor: () => ( + /* reexport safe */ + _sam2_processing_sam2_js__WEBPACK_IMPORTED_MODULE_16__.Sam2Processor + ), + /* harmony export */ + Sam2VideoProcessor: () => ( + /* reexport safe */ + _sam2_processing_sam2_js__WEBPACK_IMPORTED_MODULE_16__.Sam2VideoProcessor + ), + /* harmony export */ + SamProcessor: () => ( + /* reexport safe */ + _sam_processing_sam_js__WEBPACK_IMPORTED_MODULE_15__.SamProcessor + ), + /* harmony export */ + SmolVLMProcessor: () => ( + /* reexport safe */ + _smolvlm_processing_smolvlm_js__WEBPACK_IMPORTED_MODULE_17__.SmolVLMProcessor + ), + /* harmony export */ + SpeechT5Processor: () => ( + /* reexport safe */ + _speecht5_processing_speecht5_js__WEBPACK_IMPORTED_MODULE_18__.SpeechT5Processor + ), + /* harmony export */ + UltravoxProcessor: () => ( + /* reexport safe */ + _ultravox_processing_ultravox_js__WEBPACK_IMPORTED_MODULE_19__.UltravoxProcessor + ), + /* harmony export */ + VLChatProcessor: () => ( + /* reexport safe */ + _janus_processing_janus_js__WEBPACK_IMPORTED_MODULE_4__.VLChatProcessor + ), + /* harmony export */ + VoxtralProcessor: () => ( + /* reexport safe */ + _voxtral_processing_voxtral_js__WEBPACK_IMPORTED_MODULE_20__.VoxtralProcessor + ), + /* harmony export */ + Wav2Vec2Processor: () => ( + /* reexport safe */ + _wav2vec2_processing_wav2vec2_js__WEBPACK_IMPORTED_MODULE_21__.Wav2Vec2Processor + ), + /* harmony export */ + Wav2Vec2ProcessorWithLM: () => ( + /* reexport safe */ + _wav2vec2_with_lm_processing_wav2vec2_with_lm_js__WEBPACK_IMPORTED_MODULE_22__.Wav2Vec2ProcessorWithLM + ), + /* harmony export */ + WhisperProcessor: () => ( + /* reexport safe */ + _whisper_processing_whisper_js__WEBPACK_IMPORTED_MODULE_23__.WhisperProcessor + ) + /* harmony export */ + }); + var _florence2_processing_florence2_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ./florence2/processing_florence2.js */ + "./src/models/florence2/processing_florence2.js" + ); + var _gemma3n_processing_gemma3n_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ./gemma3n/processing_gemma3n.js */ + "./src/models/gemma3n/processing_gemma3n.js" + ); + var _grounding_dino_processing_grounding_dino_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ./grounding_dino/processing_grounding_dino.js */ + "./src/models/grounding_dino/processing_grounding_dino.js" + ); + var _idefics3_processing_idefics3_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! ./idefics3/processing_idefics3.js */ + "./src/models/idefics3/processing_idefics3.js" + ); + var _janus_processing_janus_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__2( + /*! ./janus/processing_janus.js */ + "./src/models/janus/processing_janus.js" + ); + var _jina_clip_processing_jina_clip_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__2( + /*! ./jina_clip/processing_jina_clip.js */ + "./src/models/jina_clip/processing_jina_clip.js" + ); + var _llava_processing_llava_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__2( + /*! ./llava/processing_llava.js */ + "./src/models/llava/processing_llava.js" + ); + var _mgp_str_processing_mgp_str_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__2( + /*! ./mgp_str/processing_mgp_str.js */ + "./src/models/mgp_str/processing_mgp_str.js" + ); + var _moonshine_processing_moonshine_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__2( + /*! ./moonshine/processing_moonshine.js */ + "./src/models/moonshine/processing_moonshine.js" + ); + var _owlvit_processing_owlvit_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__2( + /*! ./owlvit/processing_owlvit.js */ + "./src/models/owlvit/processing_owlvit.js" + ); + var _paligemma_processing_paligemma_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__2( + /*! ./paligemma/processing_paligemma.js */ + "./src/models/paligemma/processing_paligemma.js" + ); + var _phi3_v_processing_phi3_v_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__2( + /*! ./phi3_v/processing_phi3_v.js */ + "./src/models/phi3_v/processing_phi3_v.js" + ); + var _pixtral_processing_pixtral_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__2( + /*! ./pixtral/processing_pixtral.js */ + "./src/models/pixtral/processing_pixtral.js" + ); + var _pyannote_processing_pyannote_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__2( + /*! ./pyannote/processing_pyannote.js */ + "./src/models/pyannote/processing_pyannote.js" + ); + var _qwen2_vl_processing_qwen2_vl_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__2( + /*! ./qwen2_vl/processing_qwen2_vl.js */ + "./src/models/qwen2_vl/processing_qwen2_vl.js" + ); + var _sam_processing_sam_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__2( + /*! ./sam/processing_sam.js */ + "./src/models/sam/processing_sam.js" + ); + var _sam2_processing_sam2_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__2( + /*! ./sam2/processing_sam2.js */ + "./src/models/sam2/processing_sam2.js" + ); + var _smolvlm_processing_smolvlm_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__2( + /*! ./smolvlm/processing_smolvlm.js */ + "./src/models/smolvlm/processing_smolvlm.js" + ); + var _speecht5_processing_speecht5_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__2( + /*! ./speecht5/processing_speecht5.js */ + "./src/models/speecht5/processing_speecht5.js" + ); + var _ultravox_processing_ultravox_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__2( + /*! ./ultravox/processing_ultravox.js */ + "./src/models/ultravox/processing_ultravox.js" + ); + var _voxtral_processing_voxtral_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__2( + /*! ./voxtral/processing_voxtral.js */ + "./src/models/voxtral/processing_voxtral.js" + ); + var _wav2vec2_processing_wav2vec2_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__2( + /*! ./wav2vec2/processing_wav2vec2.js */ + "./src/models/wav2vec2/processing_wav2vec2.js" + ); + var _wav2vec2_with_lm_processing_wav2vec2_with_lm_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__2( + /*! ./wav2vec2_with_lm/processing_wav2vec2_with_lm.js */ + "./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js" + ); + var _whisper_processing_whisper_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__2( + /*! ./whisper/processing_whisper.js */ + "./src/models/whisper/processing_whisper.js" + ); + }) + ), + /***/ + "./src/models/pvt/image_processing_pvt.js": ( + /*!************************************************!*\ + !*** ./src/models/pvt/image_processing_pvt.js ***! + \************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + PvtImageProcessor: () => ( + /* binding */ + PvtImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class PvtImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + } + }) + ), + /***/ + "./src/models/pyannote/feature_extraction_pyannote.js": ( + /*!************************************************************!*\ + !*** ./src/models/pyannote/feature_extraction_pyannote.js ***! + \************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + PyAnnoteFeatureExtractor: () => ( + /* binding */ + PyAnnoteFeatureExtractor + ) + /* harmony export */ + }); + var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/feature_extraction_utils.js */ + "./src/base/feature_extraction_utils.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../utils/tensor.js */ + "./src/utils/tensor.js" + ); + var _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../utils/maths.js */ + "./src/utils/maths.js" + ); + class PyAnnoteFeatureExtractor extends _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractor { + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_values: Tensor; }>} The extracted input features. + */ + async _call(audio) { + (0, _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.validate_audio_inputs)(audio, "PyAnnoteFeatureExtractor"); + if (audio instanceof Float64Array) { + audio = new Float32Array(audio); + } + const shape = [ + 1, + /* batch_size */ + 1, + /* num_channels */ + audio.length + /* num_samples */ + ]; + return { + input_values: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor("float32", audio, shape) + }; + } + /** + * NOTE: Can return fractional values. `Math.ceil` will ensure correct value. + * @param {number} samples The number of frames in the audio. + * @returns {number} The number of frames in the audio. + */ + samples_to_frames(samples) { + return (samples - this.config.offset) / this.config.step; + } + /** + * Post-processes the speaker diarization logits output by the model. + * @param {import('../../utils/tensor.js').Tensor} logits The speaker diarization logits output by the model. + * @param {number} num_samples Number of samples in the input audio. + * @returns {Array>} The post-processed speaker diarization results. + */ + post_process_speaker_diarization(logits, num_samples) { + const ratio = num_samples / this.samples_to_frames(num_samples) / this.config.sampling_rate; + const results = []; + for (const scores of logits.tolist()) { + const accumulated_segments = []; + let current_speaker = -1; + for (let i = 0; i < scores.length; ++i) { + const probabilities = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.softmax)(scores[i]); + const [score, id2] = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(probabilities); + const [start, end] = [i, i + 1]; + if (id2 !== current_speaker) { + current_speaker = id2; + accumulated_segments.push({ id: id2, start, end, score }); + } else { + accumulated_segments.at(-1).end = end; + accumulated_segments.at(-1).score += score; + } + } + results.push(accumulated_segments.map( + // Convert frame-space to time-space + // and compute the confidence + ({ id: id2, start, end, score }) => ({ + id: id2, + start: start * ratio, + end: end * ratio, + confidence: score / (end - start) + }) + )); + } + return results; + } + } + }) + ), + /***/ + "./src/models/pyannote/processing_pyannote.js": ( + /*!****************************************************!*\ + !*** ./src/models/pyannote/processing_pyannote.js ***! + \****************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + PyAnnoteProcessor: () => ( + /* binding */ + PyAnnoteProcessor + ) + /* harmony export */ + }); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + var _feature_extraction_pyannote_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ./feature_extraction_pyannote.js */ + "./src/models/pyannote/feature_extraction_pyannote.js" + ); + class PyAnnoteProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { + static feature_extractor_class = _feature_extraction_pyannote_js__WEBPACK_IMPORTED_MODULE_1__.PyAnnoteFeatureExtractor; + /** + * Calls the feature_extractor function with the given audio input. + * @param {any} audio The audio input to extract features from. + * @returns {Promise} A Promise that resolves with the extracted features. + */ + async _call(audio) { + return await this.feature_extractor(audio); + } + /** @type {PyAnnoteFeatureExtractor['post_process_speaker_diarization']} */ + post_process_speaker_diarization(...args) { + return ( + /** @type {PyAnnoteFeatureExtractor} */ + this.feature_extractor.post_process_speaker_diarization(...args) + ); + } + get sampling_rate() { + return this.feature_extractor.config.sampling_rate; + } + } + }) + ), + /***/ + "./src/models/qwen2_vl/image_processing_qwen2_vl.js": ( + /*!**********************************************************!*\ + !*** ./src/models/qwen2_vl/image_processing_qwen2_vl.js ***! + \**********************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + Qwen2VLImageProcessor: () => ( + /* binding */ + Qwen2VLImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../utils/tensor.js */ + "./src/utils/tensor.js" + ); + class Qwen2VLImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + async _call(images, ...args) { + const { pixel_values, original_sizes, reshaped_input_sizes } = await super._call(images, ...args); + let patches = pixel_values; + const { temporal_patch_size, merge_size, patch_size } = this.config; + if (patches.dims[0] === 1) { + patches = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.cat)(Array.from({ length: temporal_patch_size }, () => patches), 0); + } + const grid_t = patches.dims[0] / temporal_patch_size; + const channel = patches.dims[1]; + const grid_h = Math.floor(patches.dims[2] / patch_size); + const grid_w = Math.floor(patches.dims[3] / patch_size); + const flatten_patches = patches.view( + grid_t, + temporal_patch_size, + channel, + Math.floor(grid_h / merge_size), + merge_size, + patch_size, + Math.floor(grid_w / merge_size), + merge_size, + patch_size + ).permute(0, 3, 6, 4, 7, 2, 1, 5, 8).view( + grid_t * grid_h * grid_w, + channel * temporal_patch_size * patch_size * patch_size + ); + const image_grid_thw = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor("int64", [grid_t, grid_h, grid_w], [1, 3]); + return { + pixel_values: flatten_patches, + image_grid_thw, + original_sizes, + reshaped_input_sizes + }; + } + } + }) + ), + /***/ + "./src/models/qwen2_vl/processing_qwen2_vl.js": ( + /*!****************************************************!*\ + !*** ./src/models/qwen2_vl/processing_qwen2_vl.js ***! + \****************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + Qwen2VLProcessor: () => ( + /* binding */ + Qwen2VLProcessor + ) + /* harmony export */ + }); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../auto/image_processing_auto.js */ + "./src/models/auto/image_processing_auto.js" + ); + var _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../tokenizers.js */ + "./src/tokenizers.js" + ); + var _utils_image_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! ../../utils/image.js */ + "./src/utils/image.js" + ); + class Qwen2VLProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { + static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor; + static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer; + /** + * + * @param {string|string[]} text + * @param {RawImage|RawImage[]} images + * @param {...any} args + * @returns {Promise} + */ + async _call(text, images = null, ...args) { + if (!Array.isArray(text)) { + text = [text]; + } + let image_inputs, image_grid_thw; + if (images) { + image_inputs = await this.image_processor(images); + image_grid_thw = image_inputs.image_grid_thw; + } + if (image_grid_thw) { + let merge_length = this.image_processor.config.merge_size ** 2; + let index = 0; + const image_grid_thw_list = image_grid_thw.tolist(); + text = text.map((t) => { + while (t.includes("<|image_pad|>")) { + const prod = Number(image_grid_thw_list[index++].reduce((a, b) => a * b, 1n)); + t = t.replace("<|image_pad|>", "<|placeholder|>".repeat(Math.floor(prod / merge_length))); + } + return t.replaceAll("<|placeholder|>", "<|image_pad|>"); + }); + } + const text_inputs = this.tokenizer(text); + return { + ...text_inputs, + ...image_inputs + // TODO: ...videos_inputs, + }; + } + } + }) + ), + /***/ + "./src/models/rt_detr/image_processing_rt_detr.js": ( + /*!********************************************************!*\ + !*** ./src/models/rt_detr/image_processing_rt_detr.js ***! + \********************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + RTDetrImageProcessor: () => ( + /* binding */ + RTDetrImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class RTDetrImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + /** @type {typeof post_process_object_detection} */ + post_process_object_detection(...args) { + return (0, _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.post_process_object_detection)(...args); + } + } + }) + ), + /***/ + "./src/models/sam/image_processing_sam.js": ( + /*!************************************************!*\ + !*** ./src/models/sam/image_processing_sam.js ***! + \************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + SamImageProcessor: () => ( + /* binding */ + SamImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + var _utils_core_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../utils/core.js */ + "./src/utils/core.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../utils/tensor.js */ + "./src/utils/tensor.js" + ); + class SamImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + /** + * + * @param {any} input_points + * @param {import("../../base/image_processors_utils.js").HeightWidth[]} original_sizes + * @param {import("../../base/image_processors_utils.js").HeightWidth[]} reshaped_input_sizes + * @returns {Tensor} + */ + reshape_input_points(input_points, original_sizes, reshaped_input_sizes, is_bounding_box = false) { + input_points = structuredClone(input_points); + let shape = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_1__.calculateDimensions)(input_points); + if (shape.length === 3) { + if (!is_bounding_box) { + shape = [1, ...shape]; + } + input_points = [input_points]; + } else if (shape.length !== 4) { + throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`."); + } + for (let i = 0; i < input_points.length; ++i) { + const [originalHeight, originalWidth] = original_sizes[i]; + const [reshapedHeight, reshapedWidth] = reshaped_input_sizes[i]; + const resizeFactors = [ + reshapedWidth / originalWidth, + reshapedHeight / originalHeight + ]; + for (let j = 0; j < input_points[i].length; ++j) { + for (let k2 = 0; k2 < input_points[i][j].length; ++k2) { + for (let w = 0; w < input_points[i][j][k2].length; ++w) { + input_points[i][j][k2][w] *= resizeFactors[w % 2]; + } + } + } + } + return new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_2__.Tensor( + "float32", + Float32Array.from(input_points.flat(Infinity)), + shape + ); + } + /** + * + * @param {any} input_labels + * @param {Tensor} input_points + * @returns {Tensor} + */ + add_input_labels(input_labels, input_points) { + let shape = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_1__.calculateDimensions)(input_labels); + if (shape.length === 2) { + shape = [1, ...shape]; + input_labels = [input_labels]; + } else if (shape.length !== 3) { + throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`."); + } + if (shape.some((x, i) => x !== input_points.dims[i])) { + throw Error(`The first ${shape.length} dimensions of 'input_points' and 'input_labels' must be the same.`); + } + return new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_2__.Tensor( + "int64", + input_labels.flat(Infinity).map(BigInt), + shape + ); + } + /** + * @param {any[]} images The URL(s) of the image(s) to extract features from. + * @param {Object} [options] Additional options for the processor. + * @param {any} [options.input_points=null] A 3D or 4D array, representing the input points provided by the user. + * - 3D: `[point_batch_size, nb_points_per_image, 2]`. In this case, `batch_size` is assumed to be 1. + * - 4D: `[batch_size, point_batch_size, nb_points_per_image, 2]`. + * @param {any} [options.input_labels=null] A 2D or 3D array, representing the input labels for the points, used by the prompt encoder to encode the prompt. + * - 2D: `[point_batch_size, nb_points_per_image]`. In this case, `batch_size` is assumed to be 1. + * - 3D: `[batch_size, point_batch_size, nb_points_per_image]`. + * @param {number[][][]} [options.input_boxes=null] A 3D array of shape `(batch_size, num_boxes, 4)`, representing the input boxes provided by the user. + * This is used by the prompt encoder to encode the prompt. Generally yields to much better generated masks. + * The processor will generate a tensor, with each dimension corresponding respectively to the image batch size, + * the number of boxes per image and the coordinates of the top left and botton right point of the box. + * In the order (`x1`, `y1`, `x2`, `y2`): + * - `x1`: the x coordinate of the top left point of the input box + * - `y1`: the y coordinate of the top left point of the input box + * - `x2`: the x coordinate of the bottom right point of the input box + * - `y2`: the y coordinate of the bottom right point of the input box + * @returns {Promise} + */ + async _call(images, { + input_points = null, + input_labels = null, + input_boxes = null + } = {}) { + const processed = await super._call(images); + if (input_points) { + processed.input_points = this.reshape_input_points( + input_points, + processed.original_sizes, + processed.reshaped_input_sizes + ); + } + if (input_labels) { + if (!processed.input_points) { + throw Error("`input_points` must be provided if `input_labels` are provided."); + } + processed.input_labels = this.add_input_labels(input_labels, processed.input_points); + } + if (input_boxes) { + processed.input_boxes = this.reshape_input_points( + input_boxes, + processed.original_sizes, + processed.reshaped_input_sizes, + true + ); + } + return processed; + } + /** + * Remove padding and upscale masks to the original image size. + * @param {Tensor} masks Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format. + * @param {[number, number][]} original_sizes The original sizes of each image before it was resized to the model's expected input shape, in (height, width) format. + * @param {[number, number][]} reshaped_input_sizes The size of each image as it is fed to the model, in (height, width) format. Used to remove padding. + * @param {Object} options Optional parameters for post-processing. + * @param {number} [options.mask_threshold] The threshold to use for binarizing the masks. + * @param {boolean} [options.binarize] Whether to binarize the masks. + * @param {Object} [options.pad_size] The target size the images were padded to before being passed to the model. If `null`, the target size is assumed to be the processor's `pad_size`. + * @param {number} [options.pad_size.height] The height the images were padded to. + * @param {number} [options.pad_size.width] The width the images were padded to. + * @returns {Promise} Batched masks in batch_size, num_channels, height, width) format, where (height, width) is given by original_size. + */ + async post_process_masks(masks, original_sizes, reshaped_input_sizes, { + mask_threshold = 0, + binarize = true, + pad_size = null + } = {}) { + const output_masks = []; + pad_size = pad_size ?? this.pad_size ?? this.size; + const target_image_size = [pad_size.height, pad_size.width]; + for (let i = 0; i < original_sizes.length; ++i) { + const original_size = original_sizes[i]; + const reshaped_input_size = reshaped_input_sizes[i]; + let interpolated_mask = await (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_2__.interpolate_4d)( + masks[i], + { mode: "bilinear", size: target_image_size } + ); + interpolated_mask = interpolated_mask.slice(null, null, [0, reshaped_input_size[0]], [0, reshaped_input_size[1]]); + interpolated_mask = await (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_2__.interpolate_4d)( + interpolated_mask, + { mode: "bilinear", size: original_size } + ); + if (binarize) { + const data = interpolated_mask.data; + const binarizedMaskData = new Uint8Array(data.length); + for (let i2 = 0; i2 < data.length; ++i2) { + if (data[i2] > mask_threshold) { + binarizedMaskData[i2] = 1; + } + } + interpolated_mask = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_2__.Tensor( + "bool", + binarizedMaskData, + interpolated_mask.dims + ); + } + output_masks.push(interpolated_mask); + } + return output_masks; + } + /** + * Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer. + * @param {import("../../utils/image.js").RawImage} image Input original image + * @param {number} target_size Target size of the resized image + * @param {Object} options Options for generating crop boxes + * @param {number} [options.crop_n_layers] If >0, mask prediction will be run again on crops of the image. + * Sets the number of layers to run, where each layer has 2**i_layer number of image crops. + * @param {number} [options.overlap_ratio] Sets the degree to which crops overlap. In the first crop layer, + * crops will overlap by this fraction of the image length. Later layers with more crops scale down this overlap. + * @param {number} [options.points_per_crop] Number of points to sample from each crop. + * @param {number} [options.crop_n_points_downscale_factor] The number of points-per-side sampled in layer n is + * scaled down by crop_n_points_downscale_factor**n. + * @returns {Object} An object containing the crop boxes, number of points per crop, cropped images, and input labels. + */ + generate_crop_boxes(image, target_size, { + crop_n_layers = 0, + overlap_ratio = 512 / 1500, + points_per_crop = 32, + crop_n_points_downscale_factor = 1 + } = {}) { + } + } + }) + ), + /***/ + "./src/models/sam/processing_sam.js": ( + /*!******************************************!*\ + !*** ./src/models/sam/processing_sam.js ***! + \******************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + SamProcessor: () => ( + /* binding */ + SamProcessor + ) + /* harmony export */ + }); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../auto/image_processing_auto.js */ + "./src/models/auto/image_processing_auto.js" + ); + class SamProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { + static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor; + async _call(...args) { + return await this.image_processor(...args); + } + post_process_masks(...args) { + return this.image_processor.post_process_masks(...args); + } + reshape_input_points(...args) { + return this.image_processor.reshape_input_points(...args); + } + } + }) + ), + /***/ + "./src/models/sam2/image_processing_sam2.js": ( + /*!**************************************************!*\ + !*** ./src/models/sam2/image_processing_sam2.js ***! + \**************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + Sam2ImageProcessor: () => ( + /* reexport safe */ + _sam_image_processing_sam_js__WEBPACK_IMPORTED_MODULE_0__.SamImageProcessor + ) + /* harmony export */ + }); + var _sam_image_processing_sam_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../sam/image_processing_sam.js */ + "./src/models/sam/image_processing_sam.js" + ); + }) + ), + /***/ + "./src/models/sam2/processing_sam2.js": ( + /*!********************************************!*\ + !*** ./src/models/sam2/processing_sam2.js ***! + \********************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + Sam2Processor: () => ( + /* binding */ + Sam2Processor + ), + /* harmony export */ + Sam2VideoProcessor: () => ( + /* binding */ + Sam2VideoProcessor + ) + /* harmony export */ + }); + var _sam_processing_sam_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../sam/processing_sam.js */ + "./src/models/sam/processing_sam.js" + ); + class Sam2Processor extends _sam_processing_sam_js__WEBPACK_IMPORTED_MODULE_0__.SamProcessor { + } + class Sam2VideoProcessor extends Sam2Processor { + } + }) + ), + /***/ + "./src/models/sam3/image_processing_sam3.js": ( + /*!**************************************************!*\ + !*** ./src/models/sam3/image_processing_sam3.js ***! + \**************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + Sam3ImageProcessor: () => ( + /* reexport safe */ + _sam2_image_processing_sam2_js__WEBPACK_IMPORTED_MODULE_0__.Sam2ImageProcessor + ) + /* harmony export */ + }); + var _sam2_image_processing_sam2_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../sam2/image_processing_sam2.js */ + "./src/models/sam2/image_processing_sam2.js" + ); + }) + ), + /***/ + "./src/models/seamless_m4t/feature_extraction_seamless_m4t.js": ( + /*!********************************************************************!*\ + !*** ./src/models/seamless_m4t/feature_extraction_seamless_m4t.js ***! + \********************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + SeamlessM4TFeatureExtractor: () => ( + /* binding */ + SeamlessM4TFeatureExtractor + ) + /* harmony export */ + }); + var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/feature_extraction_utils.js */ + "./src/base/feature_extraction_utils.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../utils/tensor.js */ + "./src/utils/tensor.js" + ); + var _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../utils/audio.js */ + "./src/utils/audio.js" + ); + class SeamlessM4TFeatureExtractor extends _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractor { + constructor(config) { + super(config); + const sampling_rate = this.config.sampling_rate; + const mel_filters = (0, _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.mel_filter_bank)( + 257, + // num_frequency_bins + this.config.num_mel_bins, + // num_mel_filters + 20, + // min_frequency + Math.floor(sampling_rate / 2), + // max_frequency + sampling_rate, + // sampling_rate + null, + // norm + "kaldi", + // mel_scale + true + // triangularize_in_mel_space + ); + this.mel_filters = mel_filters; + this.window = (0, _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.window_function)(400, "povey", { + periodic: false + }); + } + /** + * Computes the log-Mel spectrogram of the provided audio waveform. + * @param {Float32Array|Float64Array} waveform The audio waveform to process. + * @param {number} max_length The maximum number of frames to return. + * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. + */ + async _extract_fbank_features(waveform, max_length) { + waveform = waveform.map((x) => x * 32768); + return (0, _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.spectrogram)( + waveform, + this.window, + // window + 400, + // frame_length + 160, + // hop_length + { + fft_length: 512, + power: 2, + center: false, + preemphasis: 0.97, + mel_filters: this.mel_filters, + log_mel: "log", + mel_floor: 1192092955078125e-22, + remove_dc_offset: true, + // Custom + max_num_frames: max_length, + transpose: true + } + ); + } + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @param {Object} options Optional parameters for feature extraction. + * @param {boolean} [options.padding=true] Whether to pad the sequence to a multiple of `pad_to_multiple_of`. + * @param {number} [options.pad_to_multiple_of=2] The number to pad the sequence to a multiple of. + * @param {boolean} [options.do_normalize_per_mel_bins=true] Whether or not to zero-mean unit-variance normalize the input per mel-channel. + * @param {boolean} [options.return_attention_mask=true] Whether to return the attention mask. + * @returns {Promise<{ input_features: Tensor, attention_mask?: Tensor }>} A Promise resolving to an object containing the extracted input features and attention masks as Tensors. + */ + async _call(audio, { + padding = true, + pad_to_multiple_of = 2, + do_normalize_per_mel_bins = true, + return_attention_mask = true + } = {}) { + (0, _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.validate_audio_inputs)(audio, "SeamlessM4TFeatureExtractor"); + let features = await this._extract_fbank_features(audio, this.config.max_length); + if (do_normalize_per_mel_bins) { + const [num_features, feature_size] = features.dims; + const data = features.data; + for (let i = 0; i < feature_size; ++i) { + let sum = 0; + for (let j = 0; j < num_features; ++j) { + sum += data[j * feature_size + i]; + } + const mean = sum / num_features; + let variance = 0; + for (let j = 0; j < num_features; ++j) { + variance += (data[j * feature_size + i] - mean) ** 2; + } + variance /= num_features - 1; + const std = Math.sqrt(variance + 1e-7); + for (let j = 0; j < num_features; ++j) { + const index = j * feature_size + i; + data[index] = (data[index] - mean) / std; + } + } + } + let padded_attention_mask; + if (padding) { + const [num_frames2, num_channels2] = features.dims; + const data = ( + /** @type {Float32Array} */ + features.data + ); + const pad_size = num_frames2 % pad_to_multiple_of; + if (pad_size > 0) { + const padded_data = new Float32Array(num_channels2 * (num_frames2 + pad_size)); + padded_data.set(data); + padded_data.fill(this.config.padding_value, data.length); + const numPaddedFrames = num_frames2 + pad_size; + features = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor( + features.type, + padded_data, + [numPaddedFrames, num_channels2] + ); + if (return_attention_mask) { + padded_attention_mask = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor( + "int64", + new BigInt64Array(numPaddedFrames), + [1, numPaddedFrames] + ); + padded_attention_mask.data.fill(1n, 0, num_frames2); + } + } + } + const [num_frames, num_channels] = features.dims; + const stride = this.config.stride; + const remainder = num_frames % stride; + if (remainder !== 0) { + throw new Error(`The number of frames (${num_frames}) must be a multiple of the stride (${stride}).`); + } + const input_features = features.view( + 1, + Math.floor(num_frames / stride), + num_channels * stride + ); + const result = { input_features }; + if (return_attention_mask) { + const reshapedNumFrames = input_features.dims[1]; + const attention_mask_data = new BigInt64Array(reshapedNumFrames); + if (padded_attention_mask) { + const padded_attention_mask_data = padded_attention_mask.data; + for (let i = 1, j = 0; i < num_frames; i += stride, ++j) { + attention_mask_data[j] = padded_attention_mask_data[i]; + } + } else { + attention_mask_data.fill(1n); + } + result.attention_mask = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor( + "int64", + attention_mask_data, + [1, reshapedNumFrames] + ); + } + return result; + } + } + }) + ), + /***/ + "./src/models/segformer/image_processing_segformer.js": ( + /*!************************************************************!*\ + !*** ./src/models/segformer/image_processing_segformer.js ***! + \************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + SegformerFeatureExtractor: () => ( + /* binding */ + SegformerFeatureExtractor + ), + /* harmony export */ + SegformerImageProcessor: () => ( + /* binding */ + SegformerImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class SegformerImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + /** @type {typeof post_process_semantic_segmentation} */ + post_process_semantic_segmentation(...args) { + return (0, _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.post_process_semantic_segmentation)(...args); + } + } + class SegformerFeatureExtractor extends SegformerImageProcessor { + } + }) + ), + /***/ + "./src/models/siglip/image_processing_siglip.js": ( + /*!******************************************************!*\ + !*** ./src/models/siglip/image_processing_siglip.js ***! + \******************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + SiglipImageProcessor: () => ( + /* binding */ + SiglipImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class SiglipImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + } + }) + ), + /***/ + "./src/models/smolvlm/image_processing_smolvlm.js": ( + /*!********************************************************!*\ + !*** ./src/models/smolvlm/image_processing_smolvlm.js ***! + \********************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + SmolVLMImageProcessor: () => ( + /* reexport safe */ + _idefics3_image_processing_idefics3_js__WEBPACK_IMPORTED_MODULE_0__.Idefics3ImageProcessor + ) + /* harmony export */ + }); + var _idefics3_image_processing_idefics3_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../idefics3/image_processing_idefics3.js */ + "./src/models/idefics3/image_processing_idefics3.js" + ); + }) + ), + /***/ + "./src/models/smolvlm/processing_smolvlm.js": ( + /*!**************************************************!*\ + !*** ./src/models/smolvlm/processing_smolvlm.js ***! + \**************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + SmolVLMProcessor: () => ( + /* reexport safe */ + _idefics3_processing_idefics3_js__WEBPACK_IMPORTED_MODULE_0__.Idefics3Processor + ) + /* harmony export */ + }); + var _idefics3_processing_idefics3_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../idefics3/processing_idefics3.js */ + "./src/models/idefics3/processing_idefics3.js" + ); + }) + ), + /***/ + "./src/models/snac/feature_extraction_snac.js": ( + /*!****************************************************!*\ + !*** ./src/models/snac/feature_extraction_snac.js ***! + \****************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + SnacFeatureExtractor: () => ( + /* binding */ + SnacFeatureExtractor + ) + /* harmony export */ + }); + var _dac_feature_extraction_dac_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../dac/feature_extraction_dac.js */ + "./src/models/dac/feature_extraction_dac.js" + ); + class SnacFeatureExtractor extends _dac_feature_extraction_dac_js__WEBPACK_IMPORTED_MODULE_0__.DacFeatureExtractor { + } + }) + ), + /***/ + "./src/models/speecht5/feature_extraction_speecht5.js": ( + /*!************************************************************!*\ + !*** ./src/models/speecht5/feature_extraction_speecht5.js ***! + \************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + SpeechT5FeatureExtractor: () => ( + /* binding */ + SpeechT5FeatureExtractor + ) + /* harmony export */ + }); + var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/feature_extraction_utils.js */ + "./src/base/feature_extraction_utils.js" + ); + class SpeechT5FeatureExtractor extends _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractor { + } + }) + ), + /***/ + "./src/models/speecht5/processing_speecht5.js": ( + /*!****************************************************!*\ + !*** ./src/models/speecht5/processing_speecht5.js ***! + \****************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + SpeechT5Processor: () => ( + /* binding */ + SpeechT5Processor + ) + /* harmony export */ + }); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + var _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../tokenizers.js */ + "./src/tokenizers.js" + ); + var _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../auto/feature_extraction_auto.js */ + "./src/models/auto/feature_extraction_auto.js" + ); + class SpeechT5Processor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { + static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__.AutoTokenizer; + static feature_extractor_class = _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoFeatureExtractor; + /** + * Calls the feature_extractor function with the given input. + * @param {any} input The input to extract features from. + * @returns {Promise} A Promise that resolves with the extracted features. + */ + async _call(input) { + return await this.feature_extractor(input); + } + } + }) + ), + /***/ + "./src/models/swin2sr/image_processing_swin2sr.js": ( + /*!********************************************************!*\ + !*** ./src/models/swin2sr/image_processing_swin2sr.js ***! + \********************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + Swin2SRImageProcessor: () => ( + /* binding */ + Swin2SRImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class Swin2SRImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + pad_image(pixelData, imgDims, padSize, options = {}) { + const [imageHeight, imageWidth, imageChannels] = imgDims; + return super.pad_image(pixelData, imgDims, { + // NOTE: For Swin2SR models, the original python implementation adds padding even when the image's width/height is already + // a multiple of `pad_size`. However, this is most likely a bug (PR: https://github.com/mv-lab/swin2sr/pull/19). + // For this reason, we only add padding when the image's width/height is not a multiple of `pad_size`. + width: imageWidth + (padSize - imageWidth % padSize) % padSize, + height: imageHeight + (padSize - imageHeight % padSize) % padSize + }, { + mode: "symmetric", + center: false, + constant_values: -1, + ...options + }); + } + } + }) + ), + /***/ + "./src/models/ultravox/processing_ultravox.js": ( + /*!****************************************************!*\ + !*** ./src/models/ultravox/processing_ultravox.js ***! + \****************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + UltravoxProcessor: () => ( + /* binding */ + UltravoxProcessor + ) + /* harmony export */ + }); + var _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../auto/feature_extraction_auto.js */ + "./src/models/auto/feature_extraction_auto.js" + ); + var _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../tokenizers.js */ + "./src/tokenizers.js" + ); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + class UltravoxProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__.Processor { + static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__.AutoTokenizer; + static feature_extractor_class = _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_0__.AutoFeatureExtractor; + static uses_processor_config = true; + /** + * @param {string} text The text input to process. + * @param {Float32Array} audio The audio input to process. + */ + async _call(text, audio = null, kwargs = {}) { + if (Array.isArray(text)) { + throw new Error("Batched inputs are not supported yet."); + } + let audio_inputs = {}; + if (audio) { + const audio_len = audio.length; + const { input_features } = await this.feature_extractor(audio, { + ...kwargs, + max_length: audio_len + }); + const nb_encoder_frames = Math.round(audio_len / this.config.encoder_ds_factor + 1e-4); + const audio_embed_frames = 1 + Math.ceil(nb_encoder_frames / this.config.stack_factor); + audio_inputs["audio_token_len"] = [audio_embed_frames]; + audio_inputs["audio_values"] = input_features; + const image_token = this.config.audio_placeholder; + if (!text.includes(image_token)) { + throw new Error(`The input text does not contain the image token ${image_token}.`); + } + text = text.replaceAll(image_token, image_token.repeat(audio_embed_frames)); + } + const text_inputs = this.tokenizer(text, { + add_special_tokens: false, + ...kwargs + }); + return { + ...text_inputs, + ...audio_inputs + }; + } + } + }) + ), + /***/ + "./src/models/vit/image_processing_vit.js": ( + /*!************************************************!*\ + !*** ./src/models/vit/image_processing_vit.js ***! + \************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + ViTFeatureExtractor: () => ( + /* binding */ + ViTFeatureExtractor + ), + /* harmony export */ + ViTImageProcessor: () => ( + /* binding */ + ViTImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class ViTImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + } + class ViTFeatureExtractor extends ViTImageProcessor { + } + }) + ), + /***/ + "./src/models/vitmatte/image_processing_vitmatte.js": ( + /*!**********************************************************!*\ + !*** ./src/models/vitmatte/image_processing_vitmatte.js ***! + \**********************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + VitMatteImageProcessor: () => ( + /* binding */ + VitMatteImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../utils/tensor.js */ + "./src/utils/tensor.js" + ); + class VitMatteImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + /** + * Calls the feature extraction process on an array of images, preprocesses + * each image, and concatenates the resulting features into a single Tensor. + * @param {import("../../utils/image.js").RawImage[]} images The image(s) to extract features from. + * @param {import("../../utils/image.js").RawImage[]} trimaps The trimaps(s) to extract features from. + * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images. + */ + async _call(images, trimaps) { + if (!Array.isArray(images)) { + images = [images]; + } + if (!Array.isArray(trimaps)) { + trimaps = [trimaps]; + } + const imageData = await Promise.all(images.map((x) => this.preprocess(x))); + const trimapData = await Promise.all(trimaps.map((x) => this.preprocess(x, { + do_normalize: false, + do_convert_rgb: false, + do_convert_grayscale: true + }))); + const pixel_values = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.stack)(imageData.map( + // Concatenate images and trimaps + (x, i) => (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.cat)([x.pixel_values, trimapData[i].pixel_values], 0) + ), 0); + return { + pixel_values, + // Original sizes of images + original_sizes: imageData.map((x) => x.original_size), + // Reshaped sizes of images, before padding or cropping + reshaped_input_sizes: imageData.map((x) => x.reshaped_input_size) + }; + } + } + }) + ), + /***/ + "./src/models/vitpose/image_processing_vitpose.js": ( + /*!********************************************************!*\ + !*** ./src/models/vitpose/image_processing_vitpose.js ***! + \********************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + VitPoseImageProcessor: () => ( + /* binding */ + VitPoseImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class VitPoseImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + /** + * Transform the heatmaps into keypoint predictions and transform them back to the image. + * NOTE: This is a naive implementation and does not include advanced post-processing techniques, + * so the results may not be as accurate as the original implementation. + * @param {import('../../utils/tensor.js').Tensor} outputs The model outputs. + * @param {[number, number, number, number][][]} boxes List or array of bounding boxes for each image. + * Each box should be a list of 4 floats representing the bounding box coordinates in COCO format (top_left_x, top_left_y, width, height). + * @returns {{ + * bbox: [number, number, number, number], + * scores: number[], + * labels: number[], + * keypoints: [number, number][] + * }[][]} List of keypoints predictions for each image. + */ + post_process_pose_estimation(outputs, boxes, { + threshold = null + // TODO: + // kernel_size = 11, + // target_sizes = null, + } = {}) { + const heatmaps = outputs.tolist(); + const [batch_size, num_classes, height, width] = outputs.dims; + const results = []; + for (let b = 0; b < batch_size; ++b) { + const heatmap = heatmaps[b]; + const bboxes = boxes[b]; + const batch_results = []; + for (let n = 0; n < bboxes.length; ++n) { + const bbox = bboxes[n]; + const keypoints = []; + const scores = []; + const labels = []; + const xScale = bbox.at(-2) / width; + const yScale = bbox.at(-1) / height; + for (let c = 0; c < heatmap.length; ++c) { + let [xWeightedSum, yWeightedSum] = [0, 0]; + let sum = 0; + let score = -Infinity; + const row = heatmap[c]; + for (let y = 0; y < row.length; ++y) { + const col = row[y]; + for (let x = 0; x < col.length; ++x) { + const value = col[x]; + sum += value; + score = Math.max(score, value); + xWeightedSum += (x + 0.5) * value; + yWeightedSum += y * value; + } + } + if (threshold != null && score < threshold) continue; + const keypoint = [ + xScale * xWeightedSum / sum, + yScale * yWeightedSum / sum + ]; + keypoints.push(keypoint); + labels.push(c); + scores.push(score); + } + batch_results.push({ + bbox, + scores, + labels, + keypoints + }); + } + results.push(batch_results); + } + return results; + } + } + }) + ), + /***/ + "./src/models/voxtral/processing_voxtral.js": ( + /*!**************************************************!*\ + !*** ./src/models/voxtral/processing_voxtral.js ***! + \**************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + VoxtralProcessor: () => ( + /* binding */ + VoxtralProcessor + ) + /* harmony export */ + }); + var _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../auto/feature_extraction_auto.js */ + "./src/models/auto/feature_extraction_auto.js" + ); + var _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../tokenizers.js */ + "./src/tokenizers.js" + ); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! ../../utils/tensor.js */ + "./src/utils/tensor.js" + ); + const AUDIO_TOKEN = "[AUDIO]"; + const BEGIN_AUDIO_TOKEN = "[BEGIN_AUDIO]"; + const NUM_AUDIO_TOKENS = 375; + function chunk(audio, n_samples) { + const chunks = []; + for (let i = 0; i < audio.length; i += n_samples) { + chunks.push(audio.subarray(i, Math.min(i + n_samples, audio.length))); + } + return chunks; + } + class VoxtralProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__.Processor { + static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__.AutoTokenizer; + static feature_extractor_class = _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_0__.AutoFeatureExtractor; + static uses_processor_config = false; + /** + * @param {string} text The text input to process. + * @param {Float32Array|Float32Array[]} audio The audio input(s) to process. + */ + async _call(text, audio = null, kwargs = {}) { + if (Array.isArray(text)) { + throw new Error("Batched inputs are not supported yet."); + } + const audio_inputs = {}; + if (audio) { + if (!text.includes(AUDIO_TOKEN)) { + throw new Error(`The input text does not contain the audio token ${AUDIO_TOKEN}.`); + } + if (!Array.isArray(audio)) { + audio = [audio]; + } + const text_parts = text.split(AUDIO_TOKEN); + const num_audio_tokens = text_parts.length - 1; + if (num_audio_tokens !== audio.length) { + throw new Error(`The number of audio inputs (${audio.length}) does not match the number of audio tokens in the text (${num_audio_tokens}).`); + } + const n_samples = this.feature_extractor.config.n_samples; + const audio_chunks = audio.map((a) => chunk(a, n_samples)); + const chunk_counts = audio_chunks.map((chunks) => chunks.length); + const all_chunks = audio_chunks.flat(); + const features = (await Promise.all( + all_chunks.map((audio_input) => this.feature_extractor(audio_input, kwargs)) + )).map((x) => x.input_features); + audio_inputs["audio_values"] = features.length > 1 ? (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.cat)(features, 0) : features[0]; + let new_text = text_parts[0]; + for (let i = 0; i < chunk_counts.length; ++i) { + new_text += BEGIN_AUDIO_TOKEN; + for (let j = 0; j < chunk_counts[i]; ++j) { + new_text += AUDIO_TOKEN.repeat(NUM_AUDIO_TOKENS); + } + new_text += text_parts[i + 1]; + } + text = new_text; + } + const text_inputs = this.tokenizer(text, { + add_special_tokens: false, + ...kwargs + }); + return { + ...text_inputs, + ...audio_inputs + }; + } + } + }) + ), + /***/ + "./src/models/wav2vec2/feature_extraction_wav2vec2.js": ( + /*!************************************************************!*\ + !*** ./src/models/wav2vec2/feature_extraction_wav2vec2.js ***! + \************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + Wav2Vec2FeatureExtractor: () => ( + /* binding */ + Wav2Vec2FeatureExtractor + ) + /* harmony export */ + }); + var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/feature_extraction_utils.js */ + "./src/base/feature_extraction_utils.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../utils/tensor.js */ + "./src/utils/tensor.js" + ); + class Wav2Vec2FeatureExtractor extends _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractor { + /** + * @param {Float32Array} input_values + * @returns {Float32Array} + */ + _zero_mean_unit_var_norm(input_values) { + const sum = input_values.reduce((a, b) => a + b, 0); + const mean = sum / input_values.length; + const variance = input_values.reduce((a, b) => a + (b - mean) ** 2, 0) / input_values.length; + return input_values.map((x) => (x - mean) / Math.sqrt(variance + 1e-7)); + } + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_values: Tensor; attention_mask: Tensor }>} A Promise resolving to an object containing the extracted input features and attention mask as Tensors. + */ + async _call(audio) { + (0, _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.validate_audio_inputs)(audio, "Wav2Vec2FeatureExtractor"); + if (audio instanceof Float64Array) { + audio = new Float32Array(audio); + } + let input_values = audio; + if (this.config.do_normalize) { + input_values = this._zero_mean_unit_var_norm(input_values); + } + const shape = [1, input_values.length]; + return { + input_values: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor("float32", input_values, shape), + attention_mask: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor("int64", new BigInt64Array(input_values.length).fill(1n), shape) + }; + } + } + }) + ), + /***/ + "./src/models/wav2vec2/processing_wav2vec2.js": ( + /*!****************************************************!*\ + !*** ./src/models/wav2vec2/processing_wav2vec2.js ***! + \****************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + Wav2Vec2Processor: () => ( + /* binding */ + Wav2Vec2Processor + ) + /* harmony export */ + }); + var _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../tokenizers.js */ + "./src/tokenizers.js" + ); + var _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../auto/feature_extraction_auto.js */ + "./src/models/auto/feature_extraction_auto.js" + ); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + class Wav2Vec2Processor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__.Processor { + static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer; + static feature_extractor_class = _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoFeatureExtractor; + /** + * Calls the feature_extractor function with the given audio input. + * @param {any} audio The audio input to extract features from. + * @returns {Promise} A Promise that resolves with the extracted features. + */ + async _call(audio) { + return await this.feature_extractor(audio); + } + } + }) + ), + /***/ + "./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js": ( + /*!********************************************************************!*\ + !*** ./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js ***! + \********************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + Wav2Vec2ProcessorWithLM: () => ( + /* binding */ + Wav2Vec2ProcessorWithLM + ) + /* harmony export */ + }); + var _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../tokenizers.js */ + "./src/tokenizers.js" + ); + var _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../auto/feature_extraction_auto.js */ + "./src/models/auto/feature_extraction_auto.js" + ); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + class Wav2Vec2ProcessorWithLM extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__.Processor { + static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer; + static feature_extractor_class = _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoFeatureExtractor; + /** + * Calls the feature_extractor function with the given audio input. + * @param {any} audio The audio input to extract features from. + * @returns {Promise} A Promise that resolves with the extracted features. + */ + async _call(audio) { + return await this.feature_extractor(audio); + } + } + }) + ), + /***/ + "./src/models/wespeaker/feature_extraction_wespeaker.js": ( + /*!**************************************************************!*\ + !*** ./src/models/wespeaker/feature_extraction_wespeaker.js ***! + \**************************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + WeSpeakerFeatureExtractor: () => ( + /* binding */ + WeSpeakerFeatureExtractor + ) + /* harmony export */ + }); + var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/feature_extraction_utils.js */ + "./src/base/feature_extraction_utils.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../utils/tensor.js */ + "./src/utils/tensor.js" + ); + var _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../utils/audio.js */ + "./src/utils/audio.js" + ); + class WeSpeakerFeatureExtractor extends _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractor { + constructor(config) { + super(config); + const sampling_rate = this.config.sampling_rate; + const mel_filters = (0, _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.mel_filter_bank)( + 257, + // num_frequency_bins + this.config.num_mel_bins, + // num_mel_filters + 20, + // min_frequency + Math.floor(sampling_rate / 2), + // max_frequency + sampling_rate, + // sampling_rate + null, + // norm + "kaldi", + // mel_scale + true + // triangularize_in_mel_space + ); + this.mel_filters = mel_filters; + this.window = (0, _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.window_function)(400, "hamming", { + periodic: false + }); + this.min_num_frames = this.config.min_num_frames; + } + /** + * Computes the log-Mel spectrogram of the provided audio waveform. + * @param {Float32Array|Float64Array} waveform The audio waveform to process. + * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. + */ + async _extract_fbank_features(waveform) { + waveform = waveform.map((x) => x * 32768); + return (0, _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.spectrogram)( + waveform, + this.window, + // window + 400, + // frame_length + 160, + // hop_length + { + fft_length: 512, + power: 2, + center: false, + preemphasis: 0.97, + mel_filters: this.mel_filters, + log_mel: "log", + mel_floor: 1192092955078125e-22, + remove_dc_offset: true, + // Custom + transpose: true, + min_num_frames: this.min_num_frames + } + ); + } + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. + */ + async _call(audio) { + (0, _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.validate_audio_inputs)(audio, "WeSpeakerFeatureExtractor"); + const features = (await this._extract_fbank_features(audio)).unsqueeze_(0); + if (this.config.fbank_centering_span === null) { + const meanData = ( + /** @type {Float32Array} */ + features.mean(1).data + ); + const featuresData = ( + /** @type {Float32Array} */ + features.data + ); + const [batch_size, num_frames, feature_size] = features.dims; + for (let i = 0; i < batch_size; ++i) { + const offset1 = i * num_frames * feature_size; + const offset2 = i * feature_size; + for (let j = 0; j < num_frames; ++j) { + const offset3 = offset1 + j * feature_size; + for (let k2 = 0; k2 < feature_size; ++k2) { + featuresData[offset3 + k2] -= meanData[offset2 + k2]; + } + } + } + } + return { + input_features: features + }; + } + } + }) + ), + /***/ + "./src/models/whisper/common_whisper.js": ( + /*!**********************************************!*\ + !*** ./src/models/whisper/common_whisper.js ***! + \**********************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + WHISPER_LANGUAGE_MAPPING: () => ( + /* binding */ + WHISPER_LANGUAGE_MAPPING + ), + /* harmony export */ + WHISPER_TO_LANGUAGE_CODE_MAPPING: () => ( + /* binding */ + WHISPER_TO_LANGUAGE_CODE_MAPPING + ), + /* harmony export */ + whisper_language_to_code: () => ( + /* binding */ + whisper_language_to_code + ) + /* harmony export */ + }); + const WHISPER_LANGUAGES = [ + ["en", "english"], + ["zh", "chinese"], + ["de", "german"], + ["es", "spanish"], + ["ru", "russian"], + ["ko", "korean"], + ["fr", "french"], + ["ja", "japanese"], + ["pt", "portuguese"], + ["tr", "turkish"], + ["pl", "polish"], + ["ca", "catalan"], + ["nl", "dutch"], + ["ar", "arabic"], + ["sv", "swedish"], + ["it", "italian"], + ["id", "indonesian"], + ["hi", "hindi"], + ["fi", "finnish"], + ["vi", "vietnamese"], + ["he", "hebrew"], + ["uk", "ukrainian"], + ["el", "greek"], + ["ms", "malay"], + ["cs", "czech"], + ["ro", "romanian"], + ["da", "danish"], + ["hu", "hungarian"], + ["ta", "tamil"], + ["no", "norwegian"], + ["th", "thai"], + ["ur", "urdu"], + ["hr", "croatian"], + ["bg", "bulgarian"], + ["lt", "lithuanian"], + ["la", "latin"], + ["mi", "maori"], + ["ml", "malayalam"], + ["cy", "welsh"], + ["sk", "slovak"], + ["te", "telugu"], + ["fa", "persian"], + ["lv", "latvian"], + ["bn", "bengali"], + ["sr", "serbian"], + ["az", "azerbaijani"], + ["sl", "slovenian"], + ["kn", "kannada"], + ["et", "estonian"], + ["mk", "macedonian"], + ["br", "breton"], + ["eu", "basque"], + ["is", "icelandic"], + ["hy", "armenian"], + ["ne", "nepali"], + ["mn", "mongolian"], + ["bs", "bosnian"], + ["kk", "kazakh"], + ["sq", "albanian"], + ["sw", "swahili"], + ["gl", "galician"], + ["mr", "marathi"], + ["pa", "punjabi"], + ["si", "sinhala"], + ["km", "khmer"], + ["sn", "shona"], + ["yo", "yoruba"], + ["so", "somali"], + ["af", "afrikaans"], + ["oc", "occitan"], + ["ka", "georgian"], + ["be", "belarusian"], + ["tg", "tajik"], + ["sd", "sindhi"], + ["gu", "gujarati"], + ["am", "amharic"], + ["yi", "yiddish"], + ["lo", "lao"], + ["uz", "uzbek"], + ["fo", "faroese"], + ["ht", "haitian creole"], + ["ps", "pashto"], + ["tk", "turkmen"], + ["nn", "nynorsk"], + ["mt", "maltese"], + ["sa", "sanskrit"], + ["lb", "luxembourgish"], + ["my", "myanmar"], + ["bo", "tibetan"], + ["tl", "tagalog"], + ["mg", "malagasy"], + ["as", "assamese"], + ["tt", "tatar"], + ["haw", "hawaiian"], + ["ln", "lingala"], + ["ha", "hausa"], + ["ba", "bashkir"], + ["jw", "javanese"], + ["su", "sundanese"] + ]; + const WHISPER_LANGUAGE_MAPPING = new Map(WHISPER_LANGUAGES); + const WHISPER_TO_LANGUAGE_CODE_MAPPING = new Map([ + ...WHISPER_LANGUAGES.map(([k2, v]) => [v, k2]), + ...[ + ["burmese", "my"], + ["valencian", "ca"], + ["flemish", "nl"], + ["haitian", "ht"], + ["letzeburgesch", "lb"], + ["pushto", "ps"], + ["panjabi", "pa"], + ["moldavian", "ro"], + ["moldovan", "ro"], + ["sinhalese", "si"], + ["castilian", "es"] + ] + ]); + function whisper_language_to_code(language) { + language = language.toLowerCase(); + let language_code = WHISPER_TO_LANGUAGE_CODE_MAPPING.get(language); + if (language_code === void 0) { + const language_special_token = language.match(/^<\|([a-z]{2})\|>$/); + if (language_special_token) { + language = language_special_token[1]; + } + if (WHISPER_LANGUAGE_MAPPING.has(language)) { + language_code = language; + } else { + const is_language_code = language.length === 2; + const langs = is_language_code ? WHISPER_LANGUAGE_MAPPING.keys() : WHISPER_LANGUAGE_MAPPING.values(); + throw new Error(`Language "${language}" is not supported. Must be one of: ${JSON.stringify(Array.from(langs))}`); + } + } + return language_code; + } + }) + ), + /***/ + "./src/models/whisper/feature_extraction_whisper.js": ( + /*!**********************************************************!*\ + !*** ./src/models/whisper/feature_extraction_whisper.js ***! + \**********************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + WhisperFeatureExtractor: () => ( + /* binding */ + WhisperFeatureExtractor + ) + /* harmony export */ + }); + var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/feature_extraction_utils.js */ + "./src/base/feature_extraction_utils.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../utils/tensor.js */ + "./src/utils/tensor.js" + ); + var _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../utils/audio.js */ + "./src/utils/audio.js" + ); + var _utils_maths_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! ../../utils/maths.js */ + "./src/utils/maths.js" + ); + class WhisperFeatureExtractor extends _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractor { + constructor(config) { + super(config); + this.config.mel_filters ??= (0, _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.mel_filter_bank)( + Math.floor(1 + this.config.n_fft / 2), + // num_frequency_bins + this.config.feature_size, + // num_mel_filters + 0, + // min_frequency + 8e3, + // max_frequency + this.config.sampling_rate, + // sampling_rate + "slaney", + // norm + "slaney" + // mel_scale + ); + this.window = (0, _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.window_function)(this.config.n_fft, "hann"); + } + /** + * Computes the log-Mel spectrogram of the provided audio waveform. + * @param {Float32Array|Float64Array} waveform The audio waveform to process. + * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. + */ + async _extract_fbank_features(waveform) { + const features = await (0, _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.spectrogram)( + waveform, + this.window, + // window + this.config.n_fft, + // frame_length + this.config.hop_length, + // hop_length + { + power: 2, + mel_filters: this.config.mel_filters, + log_mel: "log10", + // Custom + max_num_frames: Math.min( + Math.floor(waveform.length / this.config.hop_length), + this.config.nb_max_frames + // 3000 + ) + } + ); + const data = features.data; + const maxValue = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_3__.max)( + /** @type {Float32Array} */ + data + )[0]; + for (let i = 0; i < data.length; ++i) { + data[i] = (Math.max(data[i], maxValue - 8) + 4) / 4; + } + return features; + } + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. + */ + async _call(audio, { + max_length = null + } = {}) { + (0, _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.validate_audio_inputs)(audio, "WhisperFeatureExtractor"); + let waveform; + const length = max_length ?? this.config.n_samples; + if (audio.length > length) { + if (audio.length > this.config.n_samples) { + console.warn( + "Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`." + ); + } + waveform = audio.slice(0, length); + } else { + waveform = new Float32Array(length); + waveform.set(audio); + } + const features = await this._extract_fbank_features(waveform); + return { + input_features: features.unsqueeze_(0) + }; + } + } + }) + ), + /***/ + "./src/models/whisper/generation_whisper.js": ( + /*!**************************************************!*\ + !*** ./src/models/whisper/generation_whisper.js ***! + \**************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + WhisperGenerationConfig: () => ( + /* binding */ + WhisperGenerationConfig + ) + /* harmony export */ + }); + var _generation_configuration_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../generation/configuration_utils.js */ + "./src/generation/configuration_utils.js" + ); + class WhisperGenerationConfig extends _generation_configuration_utils_js__WEBPACK_IMPORTED_MODULE_0__.GenerationConfig { + /** + * Whether to return the timestamps with the text. This enables the `WhisperTimestampsLogitsProcessor`. + * @type {boolean} + */ + return_timestamps = null; + /** + * Whether to return token-level timestamps + * with the text. This can be used with or without the `return_timestamps` option. To get word-level + * timestamps, use the tokenizer to group the tokens into words. + * @type {boolean} + */ + return_token_timestamps = null; + /** + * The number of audio frames available in this chunk. This is only used generating word-level timestamps. + * @type {number} + */ + num_frames = null; + /** + * Alignment heads to predict word-level timestamps. This is a list of [layer, head] pairs that + * select the cross-attention heads that are highly correlated to word-level timing. + * @type {[number, number][]} + */ + alignment_heads = null; + /** + * Task to use for generation, either "translate" or "transcribe". + * @type {string} + */ + task = null; + /** + * Language token to use for generation, can be either in the form of `<|en|>`, `en` or `english`. + * You can find all the possible language tokens in the `model.generation_config.lang_to_id` dictionary. + * @type {string} + */ + language = null; + /** + * The id of the `"<|notimestamps|>"` token. + * @type {number} + */ + no_timestamps_token_id = null; + /** + * Rank-1 list of token IDs created by passing text to [`~WhisperProcessor.get_prompt_ids`] that is + * provided as a prompt to each chunk. This can be used to provide or "prompt-engineer" a context for + * transcription, e.g. custom vocabularies or proper nouns to make it more likely to predict those words + * correctly. It cannot be used in conjunction with `decoder_start_token_id` as it overwrites this value. + * @type {number[]} + */ + prompt_ids = null; + /** + * Whether the model is multilingual or not. + * @type {boolean} + */ + is_multilingual = null; + /** + * (Optional) A mapping from language tokens to their corresponding IDs. + * Only required if the model is multilingual. + * @type {Record|null} + */ + lang_to_id = null; + /** + * (Optional) A mapping from task tokens to their corresponding IDs. + * @type {Record|null} + */ + task_to_id = null; + /** + * Used to set the maximum value of the initial timestamp. This is used to prevent the model from + * predicting timestamps that are too far in the future. + * @type {number} + */ + max_initial_timestamp_index = 1; + } + }) + ), + /***/ + "./src/models/whisper/processing_whisper.js": ( + /*!**************************************************!*\ + !*** ./src/models/whisper/processing_whisper.js ***! + \**************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + WhisperProcessor: () => ( + /* binding */ + WhisperProcessor + ) + /* harmony export */ + }); + var _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../auto/feature_extraction_auto.js */ + "./src/models/auto/feature_extraction_auto.js" + ); + var _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../../tokenizers.js */ + "./src/tokenizers.js" + ); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../../base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + class WhisperProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__.Processor { + static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__.AutoTokenizer; + static feature_extractor_class = _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_0__.AutoFeatureExtractor; + /** + * Calls the feature_extractor function with the given audio input. + * @param {any} audio The audio input to extract features from. + * @returns {Promise} A Promise that resolves with the extracted features. + */ + async _call(audio) { + return await this.feature_extractor(audio); + } + } + }) + ), + /***/ + "./src/models/yolos/image_processing_yolos.js": ( + /*!****************************************************!*\ + !*** ./src/models/yolos/image_processing_yolos.js ***! + \****************************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + YolosFeatureExtractor: () => ( + /* binding */ + YolosFeatureExtractor + ), + /* harmony export */ + YolosImageProcessor: () => ( + /* binding */ + YolosImageProcessor + ) + /* harmony export */ + }); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../../base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + class YolosImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { + /** @type {typeof post_process_object_detection} */ + post_process_object_detection(...args) { + return (0, _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.post_process_object_detection)(...args); + } + } + class YolosFeatureExtractor extends YolosImageProcessor { + } + }) + ), + /***/ + "./src/ops/registry.js": ( + /*!*****************************!*\ + !*** ./src/ops/registry.js ***! + \*****************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + TensorOpRegistry: () => ( + /* binding */ + TensorOpRegistry + ) + /* harmony export */ + }); + var _backends_onnx_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../backends/onnx.js */ + "./src/backends/onnx.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../utils/tensor.js */ + "./src/utils/tensor.js" + ); + const wrap = async (session_bytes, session_options, names) => { + const session = await (0, _backends_onnx_js__WEBPACK_IMPORTED_MODULE_0__.createInferenceSession)( + new Uint8Array(session_bytes), + session_options + ); + return ( + /** @type {any} */ + (async (inputs) => { + const proxied = (0, _backends_onnx_js__WEBPACK_IMPORTED_MODULE_0__.isONNXProxy)(); + const ortFeed = Object.fromEntries(Object.entries(inputs).map(([k2, v]) => [k2, (proxied ? v.clone() : v).ort_tensor])); + const outputs = await (0, _backends_onnx_js__WEBPACK_IMPORTED_MODULE_0__.runInferenceSession)(session, ortFeed); + if (Array.isArray(names)) { + return names.map((n) => new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor(outputs[n])); + } else { + return new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor(outputs[ + /** @type {string} */ + names + ]); + } + }) + ); + }; + class TensorOpRegistry { + static session_options = { + // TODO: Allow for multiple execution providers + // executionProviders: ['webgpu'], + }; + static get nearest_interpolate_4d() { + if (!this._nearest_interpolate_4d) { + this._nearest_interpolate_4d = wrap( + [8, 10, 18, 0, 58, 129, 1, 10, 41, 10, 1, 120, 10, 0, 10, 0, 10, 1, 115, 18, 1, 121, 34, 6, 82, 101, 115, 105, 122, 101, 42, 18, 10, 4, 109, 111, 100, 101, 34, 7, 110, 101, 97, 114, 101, 115, 116, 160, 1, 3, 18, 1, 114, 90, 31, 10, 1, 120, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 90, 15, 10, 1, 115, 18, 10, 10, 8, 8, 7, 18, 4, 10, 2, 8, 4, 98, 31, 10, 1, 121, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 66, 2, 16, 21], + this.session_options, + "y" + ); + } + return this._nearest_interpolate_4d; + } + static get bilinear_interpolate_4d() { + if (!this._bilinear_interpolate_4d) { + this._bilinear_interpolate_4d = wrap( + [8, 9, 18, 0, 58, 128, 1, 10, 40, 10, 1, 120, 10, 0, 10, 0, 10, 1, 115, 18, 1, 121, 34, 6, 82, 101, 115, 105, 122, 101, 42, 17, 10, 4, 109, 111, 100, 101, 34, 6, 108, 105, 110, 101, 97, 114, 160, 1, 3, 18, 1, 114, 90, 31, 10, 1, 120, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 90, 15, 10, 1, 115, 18, 10, 10, 8, 8, 7, 18, 4, 10, 2, 8, 4, 98, 31, 10, 1, 121, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 66, 2, 16, 20], + this.session_options, + "y" + ); + } + return this._bilinear_interpolate_4d; + } + static get bicubic_interpolate_4d() { + if (!this._bicubic_interpolate_4d) { + this._bicubic_interpolate_4d = wrap( + [8, 9, 18, 0, 58, 127, 10, 39, 10, 1, 120, 10, 0, 10, 0, 10, 1, 115, 18, 1, 121, 34, 6, 82, 101, 115, 105, 122, 101, 42, 16, 10, 4, 109, 111, 100, 101, 34, 5, 99, 117, 98, 105, 99, 160, 1, 3, 18, 1, 114, 90, 31, 10, 1, 120, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 90, 15, 10, 1, 115, 18, 10, 10, 8, 8, 7, 18, 4, 10, 2, 8, 4, 98, 31, 10, 1, 121, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 99, 10, 3, 18, 1, 104, 10, 3, 18, 1, 119, 66, 2, 16, 20], + this.session_options, + "y" + ); + } + return this._bicubic_interpolate_4d; + } + static get matmul() { + if (!this._matmul) { + this._matmul = wrap( + [8, 9, 18, 0, 58, 55, 10, 17, 10, 1, 97, 10, 1, 98, 18, 1, 99, 34, 6, 77, 97, 116, 77, 117, 108, 18, 1, 114, 90, 9, 10, 1, 97, 18, 4, 10, 2, 8, 1, 90, 9, 10, 1, 98, 18, 4, 10, 2, 8, 1, 98, 9, 10, 1, 99, 18, 4, 10, 2, 8, 1, 66, 2, 16, 20], + this.session_options, + "c" + ); + } + return this._matmul; + } + static get stft() { + if (!this._stft) { + this._stft = wrap( + [8, 7, 18, 0, 58, 148, 1, 10, 38, 10, 1, 115, 10, 1, 106, 10, 1, 119, 10, 1, 108, 18, 1, 111, 34, 4, 83, 84, 70, 84, 42, 15, 10, 8, 111, 110, 101, 115, 105, 100, 101, 100, 24, 1, 160, 1, 2, 18, 1, 115, 90, 26, 10, 1, 115, 18, 21, 10, 19, 8, 1, 18, 15, 10, 3, 18, 1, 98, 10, 3, 18, 1, 115, 10, 3, 18, 1, 99, 90, 11, 10, 1, 106, 18, 6, 10, 4, 8, 7, 18, 0, 90, 16, 10, 1, 119, 18, 11, 10, 9, 8, 1, 18, 5, 10, 3, 18, 1, 119, 90, 11, 10, 1, 108, 18, 6, 10, 4, 8, 7, 18, 0, 98, 31, 10, 1, 111, 18, 26, 10, 24, 8, 1, 18, 20, 10, 3, 18, 1, 98, 10, 3, 18, 1, 102, 10, 3, 18, 1, 100, 10, 3, 18, 1, 99, 66, 2, 16, 17], + this.session_options, + "o" + ); + } + return this._stft; + } + static get rfft() { + if (!this._rfft) { + this._rfft = wrap( + [8, 9, 18, 0, 58, 97, 10, 33, 10, 1, 120, 10, 0, 10, 1, 97, 18, 1, 121, 34, 3, 68, 70, 84, 42, 15, 10, 8, 111, 110, 101, 115, 105, 100, 101, 100, 24, 1, 160, 1, 2, 18, 1, 100, 90, 21, 10, 1, 120, 18, 16, 10, 14, 8, 1, 18, 10, 10, 3, 18, 1, 115, 10, 3, 18, 1, 99, 90, 11, 10, 1, 97, 18, 6, 10, 4, 8, 7, 18, 0, 98, 21, 10, 1, 121, 18, 16, 10, 14, 8, 1, 18, 10, 10, 3, 18, 1, 115, 10, 3, 18, 1, 99, 66, 2, 16, 20], + this.session_options, + "y" + ); + } + return this._rfft; + } + static get top_k() { + if (!this._top_k) { + this._top_k = wrap( + [8, 10, 18, 0, 58, 73, 10, 18, 10, 1, 120, 10, 1, 107, 18, 1, 118, 18, 1, 105, 34, 4, 84, 111, 112, 75, 18, 1, 116, 90, 9, 10, 1, 120, 18, 4, 10, 2, 8, 1, 90, 15, 10, 1, 107, 18, 10, 10, 8, 8, 7, 18, 4, 10, 2, 8, 1, 98, 9, 10, 1, 118, 18, 4, 10, 2, 8, 1, 98, 9, 10, 1, 105, 18, 4, 10, 2, 8, 7, 66, 2, 16, 21], + this.session_options, + [ + /* Values */ + "v", + /* Indices */ + "i" + ] + ); + } + return this._top_k; + } + static get slice() { + if (!this._slice) { + this._slice = wrap( + [8, 7, 18, 0, 58, 96, 10, 25, 10, 1, 120, 10, 1, 115, 10, 1, 101, 10, 1, 97, 10, 1, 116, 18, 1, 121, 34, 5, 83, 108, 105, 99, 101, 18, 1, 114, 90, 9, 10, 1, 120, 18, 4, 10, 2, 8, 1, 90, 9, 10, 1, 115, 18, 4, 10, 2, 8, 7, 90, 9, 10, 1, 101, 18, 4, 10, 2, 8, 7, 90, 9, 10, 1, 97, 18, 4, 10, 2, 8, 7, 90, 9, 10, 1, 116, 18, 4, 10, 2, 8, 7, 98, 9, 10, 1, 121, 18, 4, 10, 2, 8, 1, 66, 2, 16, 13], + this.session_options, + "y" + ); + } + return this._slice; + } + } + }) + ), + /***/ + "./src/pipelines.js": ( + /*!**************************!*\ + !*** ./src/pipelines.js ***! + \**************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + AudioClassificationPipeline: () => ( + /* binding */ + AudioClassificationPipeline + ), + /* harmony export */ + AutomaticSpeechRecognitionPipeline: () => ( + /* binding */ + AutomaticSpeechRecognitionPipeline + ), + /* harmony export */ + BackgroundRemovalPipeline: () => ( + /* binding */ + BackgroundRemovalPipeline + ), + /* harmony export */ + DepthEstimationPipeline: () => ( + /* binding */ + DepthEstimationPipeline + ), + /* harmony export */ + DocumentQuestionAnsweringPipeline: () => ( + /* binding */ + DocumentQuestionAnsweringPipeline + ), + /* harmony export */ + FeatureExtractionPipeline: () => ( + /* binding */ + FeatureExtractionPipeline + ), + /* harmony export */ + FillMaskPipeline: () => ( + /* binding */ + FillMaskPipeline + ), + /* harmony export */ + ImageClassificationPipeline: () => ( + /* binding */ + ImageClassificationPipeline + ), + /* harmony export */ + ImageFeatureExtractionPipeline: () => ( + /* binding */ + ImageFeatureExtractionPipeline + ), + /* harmony export */ + ImageSegmentationPipeline: () => ( + /* binding */ + ImageSegmentationPipeline + ), + /* harmony export */ + ImageToImagePipeline: () => ( + /* binding */ + ImageToImagePipeline + ), + /* harmony export */ + ImageToTextPipeline: () => ( + /* binding */ + ImageToTextPipeline + ), + /* harmony export */ + ObjectDetectionPipeline: () => ( + /* binding */ + ObjectDetectionPipeline + ), + /* harmony export */ + Pipeline: () => ( + /* binding */ + Pipeline + ), + /* harmony export */ + QuestionAnsweringPipeline: () => ( + /* binding */ + QuestionAnsweringPipeline + ), + /* harmony export */ + SummarizationPipeline: () => ( + /* binding */ + SummarizationPipeline + ), + /* harmony export */ + Text2TextGenerationPipeline: () => ( + /* binding */ + Text2TextGenerationPipeline + ), + /* harmony export */ + TextClassificationPipeline: () => ( + /* binding */ + TextClassificationPipeline + ), + /* harmony export */ + TextGenerationPipeline: () => ( + /* binding */ + TextGenerationPipeline + ), + /* harmony export */ + TextToAudioPipeline: () => ( + /* binding */ + TextToAudioPipeline + ), + /* harmony export */ + TokenClassificationPipeline: () => ( + /* binding */ + TokenClassificationPipeline + ), + /* harmony export */ + TranslationPipeline: () => ( + /* binding */ + TranslationPipeline + ), + /* harmony export */ + ZeroShotAudioClassificationPipeline: () => ( + /* binding */ + ZeroShotAudioClassificationPipeline + ), + /* harmony export */ + ZeroShotClassificationPipeline: () => ( + /* binding */ + ZeroShotClassificationPipeline + ), + /* harmony export */ + ZeroShotImageClassificationPipeline: () => ( + /* binding */ + ZeroShotImageClassificationPipeline + ), + /* harmony export */ + ZeroShotObjectDetectionPipeline: () => ( + /* binding */ + ZeroShotObjectDetectionPipeline + ), + /* harmony export */ + pipeline: () => ( + /* binding */ + pipeline + ) + /* harmony export */ + }); + var _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ./tokenizers.js */ + "./src/tokenizers.js" + ); + var _models_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ./models.js */ + "./src/models.js" + ); + var _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ./models/auto/processing_auto.js */ + "./src/models/auto/processing_auto.js" + ); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! ./base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + var _utils_generic_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__2( + /*! ./utils/generic.js */ + "./src/utils/generic.js" + ); + var _utils_core_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__2( + /*! ./utils/core.js */ + "./src/utils/core.js" + ); + var _utils_maths_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__2( + /*! ./utils/maths.js */ + "./src/utils/maths.js" + ); + var _utils_audio_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__2( + /*! ./utils/audio.js */ + "./src/utils/audio.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__2( + /*! ./utils/tensor.js */ + "./src/utils/tensor.js" + ); + var _utils_image_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__2( + /*! ./utils/image.js */ + "./src/utils/image.js" + ); + async function prepareImages(images) { + if (!Array.isArray(images)) { + images = [images]; + } + return await Promise.all(images.map((x) => _utils_image_js__WEBPACK_IMPORTED_MODULE_9__.RawImage.read(x))); + } + async function prepareAudios(audios, sampling_rate) { + if (!Array.isArray(audios)) { + audios = [audios]; + } + return await Promise.all(audios.map((x) => { + if (typeof x === "string" || x instanceof URL) { + return (0, _utils_audio_js__WEBPACK_IMPORTED_MODULE_7__.read_audio)(x, sampling_rate); + } else if (x instanceof Float64Array) { + return new Float32Array(x); + } + return x; + })); + } + function get_bounding_box(box, asInteger) { + if (asInteger) { + box = box.map((x) => x | 0); + } + const [xmin, ymin, xmax, ymax] = box; + return { xmin, ymin, xmax, ymax }; + } + class Pipeline extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_4__.Callable { + /** + * Create a new Pipeline. + * @param {Object} options An object containing the following properties: + * @param {string} [options.task] The task of the pipeline. Useful for specifying subtasks. + * @param {PreTrainedModel} [options.model] The model used by the pipeline. + * @param {PreTrainedTokenizer} [options.tokenizer=null] The tokenizer used by the pipeline (if any). + * @param {Processor} [options.processor=null] The processor used by the pipeline (if any). + */ + constructor({ task, model, tokenizer = null, processor = null }) { + super(); + this.task = task; + this.model = model; + this.tokenizer = tokenizer; + this.processor = processor; + } + /** @type {DisposeType} */ + async dispose() { + await this.model.dispose(); + } + } + class TextClassificationPipeline extends /** @type {new (options: TextPipelineConstructorArgs) => TextClassificationPipelineType} */ + Pipeline { + /** + * Create a new TextClassificationPipeline. + * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + /** @type {TextClassificationPipelineCallback} */ + async _call(texts, { + top_k = 1 + } = {}) { + const model_inputs = this.tokenizer(texts, { + padding: true, + truncation: true + }); + const outputs = await this.model(model_inputs); + const function_to_apply = ( + // @ts-expect-error TS2339 + this.model.config.problem_type === "multi_label_classification" ? (batch) => batch.sigmoid() : (batch) => new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.Tensor( + "float32", + (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.softmax)(batch.data), + batch.dims + ) + ); + const id2label = this.model.config.id2label; + const toReturn = []; + for (const batch of outputs.logits) { + const output = function_to_apply(batch); + const scores = await (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.topk)(output, top_k); + const values = scores[0].tolist(); + const indices = scores[1].tolist(); + const vals = indices.map((x, i) => ({ + label: id2label ? id2label[x] : `LABEL_${x}`, + score: values[i] + })); + if (top_k === 1) { + toReturn.push(...vals); + } else { + toReturn.push(vals); + } + } + return Array.isArray(texts) || top_k === 1 ? ( + /** @type {TextClassificationOutput} */ + toReturn + ) : ( + /** @type {TextClassificationOutput[]} */ + toReturn[0] + ); + } + } + class TokenClassificationPipeline extends /** @type {new (options: TextPipelineConstructorArgs) => TokenClassificationPipelineType} */ + Pipeline { + /** + * Create a new TokenClassificationPipeline. + * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + /** @type {TokenClassificationPipelineCallback} */ + async _call(texts, { + ignore_labels = ["O"] + } = {}) { + const isBatched = Array.isArray(texts); + const model_inputs = this.tokenizer(isBatched ? texts : [texts], { + padding: true, + truncation: true + }); + const outputs = await this.model(model_inputs); + const logits = outputs.logits; + const id2label = this.model.config.id2label; + const toReturn = []; + for (let i = 0; i < logits.dims[0]; ++i) { + const ids = model_inputs.input_ids[i]; + const batch = logits[i]; + const tokens = []; + for (let j = 0; j < batch.dims[0]; ++j) { + const tokenData = batch[j]; + const topScoreIndex = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.max)(tokenData.data)[1]; + const entity = id2label ? id2label[topScoreIndex] : `LABEL_${topScoreIndex}`; + if (ignore_labels.includes(entity)) { + continue; + } + const word = this.tokenizer.decode([ids[j].item()], { skip_special_tokens: true }); + if (word === "") { + continue; + } + const scores = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.softmax)(tokenData.data); + tokens.push({ + entity, + score: scores[topScoreIndex], + index: j, + word + // TODO: Add support for start and end + // start: null, + // end: null, + }); + } + toReturn.push(tokens); + } + return isBatched ? toReturn : toReturn[0]; + } + } + class QuestionAnsweringPipeline extends /** @type {new (options: TextPipelineConstructorArgs) => QuestionAnsweringPipelineType} */ + Pipeline { + /** + * Create a new QuestionAnsweringPipeline. + * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + /** @type {QuestionAnsweringPipelineCallback} */ + async _call(question, context, { + top_k = 1 + } = {}) { + const inputs = this.tokenizer(question, { + text_pair: context, + padding: true, + truncation: true + }); + const { start_logits, end_logits } = await this.model(inputs); + const input_ids = inputs.input_ids.tolist(); + const attention_mask = inputs.attention_mask.tolist(); + const special_tokens = this.tokenizer.all_special_ids; + const toReturn = []; + for (let j = 0; j < start_logits.dims[0]; ++j) { + const ids = input_ids[j]; + const sepIndex = ids.findIndex( + (x) => ( + // We use == to match bigint with number + // @ts-ignore + x == this.tokenizer.sep_token_id + ) + ); + const valid_mask = attention_mask[j].map((y, ix) => y == 1 && (ix === 0 || ix > sepIndex && special_tokens.findIndex((x) => x == ids[ix]) === -1)); + const start = start_logits[j].tolist(); + const end = end_logits[j].tolist(); + for (let i = 1; i < start.length; ++i) { + if (attention_mask[j] == 0 || i <= sepIndex || special_tokens.findIndex((x) => x == ids[i]) !== -1) { + start[i] = -Infinity; + end[i] = -Infinity; + } + } + const start_scores = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.softmax)(start).map((x, i) => [x, i]); + const end_scores = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.softmax)(end).map((x, i) => [x, i]); + start_scores[0][0] = 0; + end_scores[0][0] = 0; + const options = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_5__.product)(start_scores, end_scores).filter((x) => x[0][1] <= x[1][1]).map((x) => [x[0][1], x[1][1], x[0][0] * x[1][0]]).sort((a, b) => b[2] - a[2]); + for (let k2 = 0; k2 < Math.min(options.length, top_k); ++k2) { + const [start2, end2, score] = options[k2]; + const answer_tokens = ids.slice(start2, end2 + 1); + const answer = this.tokenizer.decode(answer_tokens, { + skip_special_tokens: true + }); + toReturn.push({ + answer, + score + }); + } + } + return top_k === 1 ? toReturn[0] : toReturn; + } + } + class FillMaskPipeline extends /** @type {new (options: TextPipelineConstructorArgs) => FillMaskPipelineType} */ + Pipeline { + /** + * Create a new FillMaskPipeline. + * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + /** @type {FillMaskPipelineCallback} */ + async _call(texts, { + top_k = 5 + } = {}) { + const model_inputs = this.tokenizer(texts, { + padding: true, + truncation: true + }); + const { logits } = await this.model(model_inputs); + const toReturn = []; + const input_ids = model_inputs.input_ids.tolist(); + for (let i = 0; i < input_ids.length; ++i) { + const ids = input_ids[i]; + const mask_token_index = ids.findIndex( + (x) => ( + // We use == to match bigint with number + // @ts-ignore + x == this.tokenizer.mask_token_id + ) + ); + if (mask_token_index === -1) { + throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`); + } + const itemLogits = logits[i][mask_token_index]; + const scores = await (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.topk)(new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.Tensor( + "float32", + (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.softmax)(itemLogits.data), + itemLogits.dims + ), top_k); + const values = scores[0].tolist(); + const indices = scores[1].tolist(); + toReturn.push(indices.map((x, i2) => { + const sequence = ids.slice(); + sequence[mask_token_index] = x; + return { + score: values[i2], + token: Number(x), + token_str: this.tokenizer.decode([x]), + sequence: this.tokenizer.decode(sequence, { skip_special_tokens: true }) + }; + })); + } + return Array.isArray(texts) ? toReturn : toReturn[0]; + } + } + class Text2TextGenerationPipeline extends /** @type {new (options: TextPipelineConstructorArgs) => Text2TextGenerationPipelineType} */ + Pipeline { + /** @type {'generated_text'} */ + _key = "generated_text"; + /** + * Create a new Text2TextGenerationPipeline. + * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + /** @type {Text2TextGenerationPipelineCallback} */ + async _call(texts, generate_kwargs = {}) { + if (!Array.isArray(texts)) { + texts = [texts]; + } + if (this.model.config.prefix) { + texts = texts.map((x) => this.model.config.prefix + x); + } + const task_specific_params = this.model.config.task_specific_params; + if (task_specific_params && task_specific_params[this.task]) { + if (task_specific_params[this.task].prefix) { + texts = texts.map((x) => task_specific_params[this.task].prefix + x); + } + } + const tokenizer = this.tokenizer; + const tokenizer_options = { + padding: true, + truncation: true + }; + let inputs; + if (this instanceof TranslationPipeline && "_build_translation_inputs" in tokenizer) { + inputs = tokenizer._build_translation_inputs(texts, tokenizer_options, generate_kwargs); + } else { + inputs = tokenizer(texts, tokenizer_options); + } + const outputTokenIds = await this.model.generate({ ...inputs, ...generate_kwargs }); + return tokenizer.batch_decode( + /** @type {Tensor} */ + outputTokenIds, + { + skip_special_tokens: true + } + ).map((text) => ({ [this._key]: text })); + } + } + class SummarizationPipeline extends /** @type {new (options: TextPipelineConstructorArgs) => SummarizationPipelineType} */ + /** @type {any} */ + Text2TextGenerationPipeline { + /** @type {'summary_text'} */ + _key = "summary_text"; + /** + * Create a new SummarizationPipeline. + * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + } + class TranslationPipeline extends /** @type {new (options: TextPipelineConstructorArgs) => TranslationPipelineType} */ + /** @type {any} */ + Text2TextGenerationPipeline { + /** @type {'translation_text'} */ + _key = "translation_text"; + /** + * Create a new TranslationPipeline. + * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + } + function isChat(x) { + return Array.isArray(x) && x.every((x2) => "role" in x2 && "content" in x2); + } + class TextGenerationPipeline extends /** @type {new (options: TextPipelineConstructorArgs) => TextGenerationPipelineType} */ + Pipeline { + /** + * Create a new TextGenerationPipeline. + * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + /** @type {TextGenerationPipelineCallback} */ + async _call(texts, generate_kwargs = {}) { + let isBatched = false; + let isChatInput = false; + let add_special_tokens = generate_kwargs.add_special_tokens ?? (this.tokenizer.add_bos_token || this.tokenizer.add_eos_token) ?? false; + let inputs; + if (typeof texts === "string") { + inputs = texts = [texts]; + } else if (Array.isArray(texts) && texts.every((x) => typeof x === "string")) { + isBatched = true; + inputs = /** @type {string[]} */ + texts; + } else { + if (isChat(texts)) { + texts = [ + /** @type {Chat} */ + texts + ]; + } else if (Array.isArray(texts) && texts.every(isChat)) { + isBatched = true; + } else { + throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats"); + } + isChatInput = true; + inputs = /** @type {string[]} */ + /** @type {Chat[]} */ + texts.map( + (x) => this.tokenizer.apply_chat_template(x, { + tokenize: false, + add_generation_prompt: true + }) + ); + add_special_tokens = false; + } + const return_full_text = isChatInput ? false : generate_kwargs.return_full_text ?? true; + this.tokenizer.padding_side = "left"; + const text_inputs = this.tokenizer(inputs, { + add_special_tokens, + padding: true, + truncation: true + }); + const outputTokenIds = ( + /** @type {Tensor} */ + await this.model.generate({ + ...text_inputs, + ...generate_kwargs + }) + ); + const decoded = this.tokenizer.batch_decode(outputTokenIds, { + skip_special_tokens: true + }); + let promptLengths; + if (!return_full_text && text_inputs.input_ids.dims.at(-1) > 0) { + promptLengths = this.tokenizer.batch_decode(text_inputs.input_ids, { + skip_special_tokens: true + }).map((x) => x.length); + } + const toReturn = Array.from({ length: texts.length }, (_) => []); + for (let i = 0; i < decoded.length; ++i) { + const textIndex = Math.floor(i / outputTokenIds.dims[0] * texts.length); + if (promptLengths) { + decoded[i] = decoded[i].slice(promptLengths[textIndex]); + } + toReturn[textIndex].push({ + generated_text: isChatInput ? [ + .../** @type {Chat[]} */ + texts[textIndex], + { role: "assistant", content: decoded[i] } + ] : decoded[i] + }); + } + return !isBatched && toReturn.length === 1 ? toReturn[0] : toReturn; + } + } + class ZeroShotClassificationPipeline extends /** @type {new (options: TextPipelineConstructorArgs) => ZeroShotClassificationPipelineType} */ + Pipeline { + /** + * Create a new ZeroShotClassificationPipeline. + * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + this.label2id = Object.fromEntries( + Object.entries( + /** @type {any} */ + this.model.config.label2id + ).map( + ([k2, v]) => [k2.toLowerCase(), v] + ) + ); + this.entailment_id = this.label2id["entailment"]; + if (this.entailment_id === void 0) { + console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."); + this.entailment_id = 2; + } + this.contradiction_id = this.label2id["contradiction"] ?? this.label2id["not_entailment"]; + if (this.contradiction_id === void 0) { + console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."); + this.contradiction_id = 0; + } + } + /** @type {ZeroShotClassificationPipelineCallback} */ + async _call(texts, candidate_labels, { + hypothesis_template = "This example is {}.", + multi_label = false + } = {}) { + const isBatched = Array.isArray(texts); + if (!isBatched) { + texts = [ + /** @type {string} */ + texts + ]; + } + if (!Array.isArray(candidate_labels)) { + candidate_labels = [candidate_labels]; + } + const hypotheses = candidate_labels.map( + (x) => hypothesis_template.replace("{}", x) + ); + const softmaxEach = multi_label || candidate_labels.length === 1; + const toReturn = []; + for (const premise of texts) { + const entails_logits = []; + for (const hypothesis of hypotheses) { + const inputs = this.tokenizer(premise, { + text_pair: hypothesis, + padding: true, + truncation: true + }); + const outputs = await this.model(inputs); + if (softmaxEach) { + entails_logits.push([ + outputs.logits.data[this.contradiction_id], + outputs.logits.data[this.entailment_id] + ]); + } else { + entails_logits.push(outputs.logits.data[this.entailment_id]); + } + } + const scores = softmaxEach ? entails_logits.map((x) => (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.softmax)(x)[1]) : (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.softmax)(entails_logits); + const scores_sorted = scores.map((x, i) => [x, i]).sort((a, b) => b[0] - a[0]); + toReturn.push({ + sequence: premise, + labels: scores_sorted.map((x) => candidate_labels[x[1]]), + scores: scores_sorted.map((x) => x[0]) + }); + } + return isBatched ? toReturn : toReturn[0]; + } + } + class FeatureExtractionPipeline extends /** @type {new (options: TextPipelineConstructorArgs) => FeatureExtractionPipelineType} */ + Pipeline { + /** + * Create a new FeatureExtractionPipeline. + * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + /** @type {FeatureExtractionPipelineCallback} */ + async _call(texts, { + pooling = ( + /** @type {'none'} */ + "none" + ), + normalize = false, + quantize = false, + precision = ( + /** @type {'binary'} */ + "binary" + ) + } = {}) { + const model_inputs = this.tokenizer(texts, { + padding: true, + truncation: true + }); + const outputs = await this.model(model_inputs); + let result = outputs.last_hidden_state ?? outputs.logits ?? outputs.token_embeddings; + switch (pooling) { + case "none": + break; + case "mean": + result = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.mean_pooling)(result, model_inputs.attention_mask); + break; + case "first_token": + case "cls": + result = result.slice(null, 0); + break; + case "last_token": + case "eos": + result = result.slice(null, -1); + break; + default: + throw Error(`Pooling method '${pooling}' not supported.`); + } + if (normalize) { + result = result.normalize(2, -1); + } + if (quantize) { + result = (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.quantize_embeddings)(result, precision); + } + return result; + } + } + class ImageFeatureExtractionPipeline extends /** @type {new (options: ImagePipelineConstructorArgs) => ImageFeatureExtractionPipelineType} */ + Pipeline { + /** + * Create a new ImageFeatureExtractionPipeline. + * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + /** @type {ImageFeatureExtractionPipelineCallback} */ + async _call(images, { + pool = null + } = {}) { + const preparedImages = await prepareImages(images); + const { pixel_values } = await this.processor(preparedImages); + const outputs = await this.model({ pixel_values }); + let result; + if (pool) { + if (!("pooler_output" in outputs)) { + throw Error(`No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.`); + } + result = outputs.pooler_output; + } else { + result = outputs.last_hidden_state ?? outputs.logits ?? outputs.image_embeds; + } + return result; + } + } + class AudioClassificationPipeline extends /** @type {new (options: AudioPipelineConstructorArgs) => AudioClassificationPipelineType} */ + Pipeline { + /** + * Create a new AudioClassificationPipeline. + * @param {AudioPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + /** @type {AudioClassificationPipelineCallback} */ + async _call(audio, { + top_k = 5 + } = {}) { + const sampling_rate = this.processor.feature_extractor.config.sampling_rate; + const preparedAudios = await prepareAudios(audio, sampling_rate); + const id2label = this.model.config.id2label; + const toReturn = []; + for (const aud of preparedAudios) { + const inputs = await this.processor(aud); + const output = await this.model(inputs); + const logits = output.logits[0]; + const scores = await (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.topk)(new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.Tensor( + "float32", + (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.softmax)(logits.data), + logits.dims + ), top_k); + const values = scores[0].tolist(); + const indices = scores[1].tolist(); + const vals = indices.map((x, i) => ({ + label: ( + /** @type {string} */ + id2label ? id2label[x] : `LABEL_${x}` + ), + score: ( + /** @type {number} */ + values[i] + ) + })); + toReturn.push(vals); + } + ; + return Array.isArray(audio) ? toReturn : toReturn[0]; + } + } + class ZeroShotAudioClassificationPipeline extends /** @type {new (options: TextAudioPipelineConstructorArgs) => ZeroShotAudioClassificationPipelineType} */ + Pipeline { + /** + * Create a new ZeroShotAudioClassificationPipeline. + * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + /** @type {ZeroShotAudioClassificationPipelineCallback} */ + async _call(audio, candidate_labels, { + hypothesis_template = "This is a sound of {}." + } = {}) { + const single = !Array.isArray(audio); + if (single) { + audio = [ + /** @type {AudioInput} */ + audio + ]; + } + const texts = candidate_labels.map( + (x) => hypothesis_template.replace("{}", x) + ); + const text_inputs = this.tokenizer(texts, { + padding: true, + truncation: true + }); + const sampling_rate = this.processor.feature_extractor.config.sampling_rate; + const preparedAudios = await prepareAudios(audio, sampling_rate); + const toReturn = []; + for (const aud of preparedAudios) { + const audio_inputs = await this.processor(aud); + const output = await this.model({ ...text_inputs, ...audio_inputs }); + const probs = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.softmax)(output.logits_per_audio.data); + toReturn.push([...probs].map((x, i) => ({ + score: x, + label: candidate_labels[i] + }))); + } + return single ? toReturn[0] : toReturn; + } + } + class AutomaticSpeechRecognitionPipeline extends /** @type {new (options: TextAudioPipelineConstructorArgs) => AutomaticSpeechRecognitionPipelineType} */ + Pipeline { + /** + * Create a new AutomaticSpeechRecognitionPipeline. + * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + /** @type {AutomaticSpeechRecognitionPipelineCallback} */ + async _call(audio, kwargs = {}) { + switch (this.model.config.model_type) { + case "whisper": + case "lite-whisper": + return this._call_whisper(audio, kwargs); + case "wav2vec2": + case "wav2vec2-bert": + case "unispeech": + case "unispeech-sat": + case "hubert": + case "parakeet_ctc": + return this._call_wav2vec2(audio, kwargs); + case "moonshine": + return this._call_moonshine(audio, kwargs); + default: + throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`); + } + } + /** + * @type {AutomaticSpeechRecognitionPipelineCallback} + * @private + */ + async _call_wav2vec2(audio, kwargs) { + if (kwargs.language) { + console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'); + } + if (kwargs.task) { + console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".'); + } + const single = !Array.isArray(audio); + if (single) { + audio = [ + /** @type {AudioInput} */ + audio + ]; + } + const sampling_rate = this.processor.feature_extractor.config.sampling_rate; + const preparedAudios = await prepareAudios(audio, sampling_rate); + const toReturn = []; + for (const aud of preparedAudios) { + const inputs = await this.processor(aud); + const output = await this.model(inputs); + const logits = output.logits[0]; + const predicted_ids = []; + for (const item of logits) { + predicted_ids.push((0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.max)(item.data)[1]); + } + const predicted_sentences = this.tokenizer.decode(predicted_ids, { skip_special_tokens: true }).trim(); + toReturn.push({ text: predicted_sentences }); + } + return single ? toReturn[0] : toReturn; + } + /** + * @type {AutomaticSpeechRecognitionPipelineCallback} + * @private + */ + async _call_whisper(audio, kwargs) { + const return_timestamps = kwargs.return_timestamps ?? false; + const chunk_length_s = kwargs.chunk_length_s ?? 0; + const force_full_sequences = kwargs.force_full_sequences ?? false; + let stride_length_s = kwargs.stride_length_s ?? null; + const generation_config = { ...kwargs }; + if (return_timestamps === "word") { + generation_config["return_token_timestamps"] = true; + generation_config["return_timestamps"] = false; + } + const single = !Array.isArray(audio); + if (single) { + audio = [ + /** @type {AudioInput} */ + audio + ]; + } + const time_precision = this.processor.feature_extractor.config.chunk_length / this.model.config.max_source_positions; + const hop_length = this.processor.feature_extractor.config.hop_length; + const sampling_rate = this.processor.feature_extractor.config.sampling_rate; + const preparedAudios = await prepareAudios(audio, sampling_rate); + const toReturn = []; + for (const aud of preparedAudios) { + let chunks = []; + if (chunk_length_s > 0) { + if (stride_length_s === null) { + stride_length_s = chunk_length_s / 6; + } else if (chunk_length_s <= stride_length_s) { + throw Error("`chunk_length_s` must be larger than `stride_length_s`."); + } + const window2 = sampling_rate * chunk_length_s; + const stride = sampling_rate * stride_length_s; + const jump = window2 - 2 * stride; + let offset = 0; + while (true) { + const offset_end = offset + window2; + const subarr = aud.subarray(offset, offset_end); + const feature = await this.processor(subarr); + const is_first = offset === 0; + const is_last = offset_end >= aud.length; + chunks.push({ + stride: [ + subarr.length, + is_first ? 0 : stride, + is_last ? 0 : stride + ], + input_features: feature.input_features, + is_last + }); + if (is_last) break; + offset += jump; + } + } else { + chunks = [{ + stride: [aud.length, 0, 0], + input_features: (await this.processor(aud)).input_features, + is_last: true + }]; + } + for (const chunk of chunks) { + generation_config.num_frames = Math.floor(chunk.stride[0] / hop_length); + const data = await this.model.generate({ + inputs: chunk.input_features, + ...generation_config + }); + if (return_timestamps === "word") { + chunk.tokens = data.sequences.tolist()[0]; + chunk.token_timestamps = data.token_timestamps.tolist()[0].map( + (x) => (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.round)(x, 2) + ); + } else { + chunk.tokens = /** @type {Tensor} */ + data[0].tolist(); + } + chunk.stride = chunk.stride.map((x) => x / sampling_rate); + } + const [full_text, optional] = this.tokenizer._decode_asr(chunks, { + time_precision, + return_timestamps, + force_full_sequences + }); + toReturn.push({ text: full_text, ...optional }); + } + return single ? toReturn[0] : toReturn; + } + /** + * @type {AutomaticSpeechRecognitionPipelineCallback} + * @private + */ + async _call_moonshine(audio, kwargs) { + const single = !Array.isArray(audio); + if (single) { + audio = [ + /** @type {AudioInput} */ + audio + ]; + } + const sampling_rate = this.processor.feature_extractor.config.sampling_rate; + const preparedAudios = await prepareAudios(audio, sampling_rate); + const toReturn = []; + for (const aud of preparedAudios) { + const inputs = await this.processor(aud); + const max_new_tokens = Math.floor(aud.length / sampling_rate) * 6; + const outputs = await this.model.generate({ max_new_tokens, ...kwargs, ...inputs }); + const text = this.processor.batch_decode( + /** @type {Tensor} */ + outputs, + { skip_special_tokens: true } + )[0]; + toReturn.push({ text }); + } + return single ? toReturn[0] : toReturn; + } + } + class ImageToTextPipeline extends /** @type {new (options: TextImagePipelineConstructorArgs) => ImageToTextPipelineType} */ + Pipeline { + /** + * Create a new ImageToTextPipeline. + * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + /** @type {ImageToTextPipelineCallback} */ + async _call(images, generate_kwargs = {}) { + const isBatched = Array.isArray(images); + const preparedImages = await prepareImages(images); + const { pixel_values } = await this.processor(preparedImages); + const toReturn = []; + for (const batch of pixel_values) { + batch.dims = [1, ...batch.dims]; + const output = await this.model.generate({ inputs: batch, ...generate_kwargs }); + const decoded = this.tokenizer.batch_decode( + /** @type {Tensor} */ + output, + { + skip_special_tokens: true + } + ).map((x) => ({ generated_text: x.trim() })); + toReturn.push(decoded); + } + return isBatched ? toReturn : toReturn[0]; + } + } + class ImageClassificationPipeline extends /** @type {new (options: ImagePipelineConstructorArgs) => ImageClassificationPipelineType} */ + Pipeline { + /** + * Create a new ImageClassificationPipeline. + * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + /** @type {ImageClassificationPipelineCallback} */ + async _call(images, { + top_k = 5 + } = {}) { + const preparedImages = await prepareImages(images); + const { pixel_values } = await this.processor(preparedImages); + const output = await this.model({ pixel_values }); + const id2label = this.model.config.id2label; + const toReturn = []; + for (const batch of output.logits) { + const scores = await (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.topk)(new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.Tensor( + "float32", + (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.softmax)(batch.data), + batch.dims + ), top_k); + const values = scores[0].tolist(); + const indices = scores[1].tolist(); + const vals = indices.map((x, i) => ({ + label: ( + /** @type {string} */ + id2label ? id2label[x] : `LABEL_${x}` + ), + score: ( + /** @type {number} */ + values[i] + ) + })); + toReturn.push(vals); + } + return Array.isArray(images) ? toReturn : toReturn[0]; + } + } + class ImageSegmentationPipeline extends /** @type {new (options: ImagePipelineConstructorArgs) => ImageSegmentationPipelineType} */ + Pipeline { + /** + * Create a new ImageSegmentationPipeline. + * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + this.subtasks_mapping = { + // Mapping of subtasks to their corresponding post-processing function names. + panoptic: "post_process_panoptic_segmentation", + instance: "post_process_instance_segmentation", + semantic: "post_process_semantic_segmentation" + }; + } + /** @type {ImageSegmentationPipelineCallback} */ + async _call(images, { + threshold = 0.5, + mask_threshold = 0.5, + overlap_mask_area_threshold = 0.8, + label_ids_to_fuse = null, + target_sizes = null, + subtask = null + } = {}) { + const isBatched = Array.isArray(images); + if (isBatched && images.length !== 1) { + throw Error("Image segmentation pipeline currently only supports a batch size of 1."); + } + const preparedImages = await prepareImages(images); + const imageSizes = preparedImages.map((x) => [x.height, x.width]); + const inputs = await this.processor(preparedImages); + const { inputNames, outputNames } = this.model.sessions["model"]; + if (!inputNames.includes("pixel_values")) { + if (inputNames.length !== 1) { + throw Error(`Expected a single input name, but got ${inputNames.length} inputs: ${inputNames}.`); + } + const newName = inputNames[0]; + if (newName in inputs) { + throw Error(`Input name ${newName} already exists in the inputs.`); + } + inputs[newName] = inputs.pixel_values; + } + const output = await this.model(inputs); + let fn = null; + if (subtask !== null) { + fn = this.subtasks_mapping[subtask]; + } else if (this.processor.image_processor) { + for (const [task, func] of Object.entries(this.subtasks_mapping)) { + if (func in this.processor.image_processor) { + fn = this.processor.image_processor[func].bind(this.processor.image_processor); + subtask = task; + break; + } + } + } + const id2label = this.model.config.id2label; + const annotation = []; + if (!subtask) { + const epsilon = 1e-5; + const result = output[outputNames[0]]; + for (let i = 0; i < imageSizes.length; ++i) { + const size = imageSizes[i]; + const item = result[i]; + if (item.data.some((x) => x < -epsilon || x > 1 + epsilon)) { + item.sigmoid_(); + } + const mask = await _utils_image_js__WEBPACK_IMPORTED_MODULE_9__.RawImage.fromTensor(item.mul_(255).to("uint8")).resize(size[1], size[0]); + annotation.push({ + label: null, + score: null, + mask + }); + } + } else if (subtask === "panoptic" || subtask === "instance") { + const processed = fn( + output, + threshold, + mask_threshold, + overlap_mask_area_threshold, + label_ids_to_fuse, + target_sizes ?? imageSizes + // TODO FIX? + )[0]; + const segmentation = processed.segmentation; + for (const segment of processed.segments_info) { + const maskData = new Uint8ClampedArray(segmentation.data.length); + for (let i = 0; i < segmentation.data.length; ++i) { + if (segmentation.data[i] === segment.id) { + maskData[i] = 255; + } + } + const mask = new _utils_image_js__WEBPACK_IMPORTED_MODULE_9__.RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1); + annotation.push({ + score: segment.score, + label: id2label[segment.label_id], + mask + }); + } + } else if (subtask === "semantic") { + const { segmentation, labels } = fn(output, target_sizes ?? imageSizes)[0]; + for (const label of labels) { + const maskData = new Uint8ClampedArray(segmentation.data.length); + for (let i = 0; i < segmentation.data.length; ++i) { + if (segmentation.data[i] === label) { + maskData[i] = 255; + } + } + const mask = new _utils_image_js__WEBPACK_IMPORTED_MODULE_9__.RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1); + annotation.push({ + score: null, + label: id2label[label], + mask + }); + } + } else { + throw Error(`Subtask ${subtask} not supported.`); + } + return annotation; + } + } + class BackgroundRemovalPipeline extends /** @type {new (options: ImagePipelineConstructorArgs) => BackgroundRemovalPipelineType} */ + /** @type {any} */ + ImageSegmentationPipeline { + /** + * Create a new BackgroundRemovalPipeline. + * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + /** @type {BackgroundRemovalPipelineCallback} */ + async _call(images, options = {}) { + const isBatched = Array.isArray(images); + if (isBatched && images.length !== 1) { + throw Error("Background removal pipeline currently only supports a batch size of 1."); + } + const preparedImages = await prepareImages(images); + const masks = await super._call(images, options); + const result = preparedImages.map((img, i) => { + const cloned = img.clone(); + cloned.putAlpha(masks[i].mask); + return cloned; + }); + return result; + } + } + class ZeroShotImageClassificationPipeline extends /** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotImageClassificationPipelineType} */ + Pipeline { + /** + * Create a new ZeroShotImageClassificationPipeline. + * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + /** @type {ZeroShotImageClassificationPipelineCallback} */ + async _call(images, candidate_labels, { + hypothesis_template = "This is a photo of {}" + } = {}) { + const isBatched = Array.isArray(images); + const preparedImages = await prepareImages(images); + const texts = candidate_labels.map( + (x) => hypothesis_template.replace("{}", x) + ); + const text_inputs = this.tokenizer(texts, { + padding: this.model.config.model_type === "siglip" ? "max_length" : true, + truncation: true + }); + const { pixel_values } = await this.processor(preparedImages); + const output = await this.model({ ...text_inputs, pixel_values }); + const function_to_apply = this.model.config.model_type === "siglip" ? (batch) => batch.sigmoid().data : (batch) => (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.softmax)(batch.data); + const toReturn = []; + for (const batch of output.logits_per_image) { + const probs = function_to_apply(batch); + const result = [...probs].map((x, i) => ({ + score: x, + label: candidate_labels[i] + })); + result.sort((a, b) => b.score - a.score); + toReturn.push(result); + } + return isBatched ? toReturn : toReturn[0]; + } + } + class ObjectDetectionPipeline extends /** @type {new (options: ImagePipelineConstructorArgs) => ObjectDetectionPipelineType} */ + Pipeline { + /** + * Create a new ObjectDetectionPipeline. + * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + /** @type {ObjectDetectionPipelineCallback} */ + async _call(images, { + threshold = 0.9, + percentage = false + } = {}) { + const isBatched = Array.isArray(images); + if (isBatched && images.length !== 1) { + throw Error("Object detection pipeline currently only supports a batch size of 1."); + } + const preparedImages = await prepareImages(images); + const imageSizes = percentage ? null : preparedImages.map((x) => [x.height, x.width]); + const { pixel_values, pixel_mask } = await this.processor(preparedImages); + const output = await this.model({ pixel_values, pixel_mask }); + const processed = this.processor.image_processor.post_process_object_detection(output, threshold, imageSizes); + const id2label = this.model.config.id2label; + const result = processed.map((batch) => batch.boxes.map((box, i) => ({ + score: batch.scores[i], + label: id2label[batch.classes[i]], + box: get_bounding_box(box, !percentage) + }))); + return isBatched ? result : result[0]; + } + } + class ZeroShotObjectDetectionPipeline extends /** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotObjectDetectionPipelineType} */ + Pipeline { + /** + * Create a new ZeroShotObjectDetectionPipeline. + * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + /** @type {ZeroShotObjectDetectionPipelineCallback} */ + async _call(images, candidate_labels, { + threshold = 0.1, + top_k = null, + percentage = false + } = {}) { + const isBatched = Array.isArray(images); + const preparedImages = await prepareImages(images); + const text_inputs = this.tokenizer(candidate_labels, { + padding: true, + truncation: true + }); + const model_inputs = await this.processor(preparedImages); + const toReturn = []; + for (let i = 0; i < preparedImages.length; ++i) { + const image = preparedImages[i]; + const imageSize = percentage ? null : [[image.height, image.width]]; + const pixel_values = model_inputs.pixel_values[i].unsqueeze_(0); + const output = await this.model({ ...text_inputs, pixel_values }); + let result; + if ("post_process_grounded_object_detection" in this.processor) { + const processed = this.processor.post_process_grounded_object_detection( + output, + text_inputs.input_ids, + { + // TODO: support separate threshold values + box_threshold: threshold, + text_threshold: threshold, + target_sizes: imageSize + } + )[0]; + result = processed.boxes.map((box, i2) => ({ + score: processed.scores[i2], + label: processed.labels[i2], + box: get_bounding_box(box, !percentage) + })); + } else { + const processed = this.processor.image_processor.post_process_object_detection(output, threshold, imageSize, true)[0]; + result = processed.boxes.map((box, i2) => ({ + score: processed.scores[i2], + label: candidate_labels[processed.classes[i2]], + box: get_bounding_box(box, !percentage) + })); + } + result.sort((a, b) => b.score - a.score); + if (top_k !== null) { + result = result.slice(0, top_k); + } + toReturn.push(result); + } + return isBatched ? toReturn : toReturn[0]; + } + } + class DocumentQuestionAnsweringPipeline extends /** @type {new (options: TextImagePipelineConstructorArgs) => DocumentQuestionAnsweringPipelineType} */ + Pipeline { + /** + * Create a new DocumentQuestionAnsweringPipeline. + * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + /** @type {DocumentQuestionAnsweringPipelineCallback} */ + async _call(image, question, generate_kwargs = {}) { + const preparedImage = (await prepareImages(image))[0]; + const { pixel_values } = await this.processor(preparedImage); + const task_prompt = `${question}`; + const decoder_input_ids = this.tokenizer(task_prompt, { + add_special_tokens: false, + padding: true, + truncation: true + }).input_ids; + const output = await this.model.generate({ + inputs: pixel_values, + // @ts-expect-error TS2339 + max_length: this.model.config.decoder.max_position_embeddings, + decoder_input_ids, + ...generate_kwargs + }); + const decoded = this.tokenizer.batch_decode( + /** @type {Tensor} */ + output + )[0]; + const match = decoded.match(/(.*?)<\/s_answer>/); + let answer = null; + if (match && match.length >= 2) { + answer = match[1].trim(); + } + return [{ answer }]; + } + } + class TextToAudioPipeline extends /** @type {new (options: TextToAudioPipelineConstructorArgs) => TextToAudioPipelineType} */ + Pipeline { + DEFAULT_VOCODER_ID = "Xenova/speecht5_hifigan"; + /** + * Create a new TextToAudioPipeline. + * @param {TextToAudioPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + this.vocoder = options.vocoder ?? null; + } + async _prepare_speaker_embeddings(speaker_embeddings) { + if (typeof speaker_embeddings === "string" || speaker_embeddings instanceof URL) { + speaker_embeddings = new Float32Array( + await (await fetch(speaker_embeddings)).arrayBuffer() + ); + } + if (speaker_embeddings instanceof Float32Array) { + speaker_embeddings = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.Tensor( + "float32", + speaker_embeddings, + [speaker_embeddings.length] + ); + } else if (!(speaker_embeddings instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.Tensor)) { + throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`."); + } + return speaker_embeddings; + } + /** @type {TextToAudioPipelineCallback} */ + async _call(text_inputs, { + speaker_embeddings = null, + num_inference_steps, + speed + } = {}) { + if (this.processor) { + return this._call_text_to_spectrogram(text_inputs, { speaker_embeddings }); + } else if (this.model.config.model_type === "supertonic") { + return this._call_supertonic(text_inputs, { speaker_embeddings, num_inference_steps, speed }); + } else { + return this._call_text_to_waveform(text_inputs); + } + } + async _call_supertonic(text_inputs, { speaker_embeddings, num_inference_steps, speed }) { + if (!speaker_embeddings) { + throw new Error("Speaker embeddings must be provided for Supertonic models."); + } + speaker_embeddings = await this._prepare_speaker_embeddings(speaker_embeddings); + const { sampling_rate, style_dim } = this.model.config; + speaker_embeddings = /** @type {Tensor} */ + speaker_embeddings.view(1, -1, style_dim); + const inputs = this.tokenizer(text_inputs, { + padding: true, + truncation: true + }); + const { waveform } = await this.model.generate_speech({ + ...inputs, + style: speaker_embeddings, + num_inference_steps, + speed + }); + return new _utils_audio_js__WEBPACK_IMPORTED_MODULE_7__.RawAudio( + waveform.data, + sampling_rate + ); + } + async _call_text_to_waveform(text_inputs) { + const inputs = this.tokenizer(text_inputs, { + padding: true, + truncation: true + }); + const { waveform } = await this.model(inputs); + const sampling_rate = this.model.config.sampling_rate; + return new _utils_audio_js__WEBPACK_IMPORTED_MODULE_7__.RawAudio( + waveform.data, + sampling_rate + ); + } + async _call_text_to_spectrogram(text_inputs, { speaker_embeddings }) { + if (!this.vocoder) { + console.log("No vocoder specified, using default HifiGan vocoder."); + this.vocoder = await _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID, { dtype: "fp32" }); + } + const { input_ids } = this.tokenizer(text_inputs, { + padding: true, + truncation: true + }); + speaker_embeddings = await this._prepare_speaker_embeddings(speaker_embeddings); + speaker_embeddings = speaker_embeddings.view(1, -1); + const { waveform } = await this.model.generate_speech(input_ids, speaker_embeddings, { vocoder: this.vocoder }); + const sampling_rate = this.processor.feature_extractor.config.sampling_rate; + return new _utils_audio_js__WEBPACK_IMPORTED_MODULE_7__.RawAudio( + waveform.data, + sampling_rate + ); + } + } + class ImageToImagePipeline extends /** @type {new (options: ImagePipelineConstructorArgs) => ImageToImagePipelineType} */ + Pipeline { + /** + * Create a new ImageToImagePipeline. + * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + /** @type {ImageToImagePipelineCallback} */ + async _call(images) { + const preparedImages = await prepareImages(images); + const inputs = await this.processor(preparedImages); + const outputs = await this.model(inputs); + const toReturn = []; + for (const batch of outputs.reconstruction) { + const output = batch.squeeze().clamp_(0, 1).mul_(255).round_().to("uint8"); + toReturn.push(_utils_image_js__WEBPACK_IMPORTED_MODULE_9__.RawImage.fromTensor(output)); + } + return toReturn.length > 1 ? toReturn : toReturn[0]; + } + } + class DepthEstimationPipeline extends /** @type {new (options: ImagePipelineConstructorArgs) => DepthEstimationPipelineType} */ + Pipeline { + /** + * Create a new DepthEstimationPipeline. + * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + } + /** @type {DepthEstimationPipelineCallback} */ + async _call(images) { + const preparedImages = await prepareImages(images); + const inputs = await this.processor(preparedImages); + const { predicted_depth } = await this.model(inputs); + const toReturn = []; + for (let i = 0; i < preparedImages.length; ++i) { + const batch = predicted_depth[i]; + const [height, width] = batch.dims.slice(-2); + const [new_width, new_height] = preparedImages[i].size; + const prediction = (await (0, _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.interpolate_4d)(batch.view(1, 1, height, width), { + size: [new_height, new_width], + mode: "bilinear" + })).view(new_height, new_width); + const minval = ( + /** @type {number} */ + prediction.min().item() + ); + const maxval = ( + /** @type {number} */ + prediction.max().item() + ); + const formatted = prediction.sub(minval).div_(maxval - minval).mul_(255).to("uint8").unsqueeze(0); + const depth = _utils_image_js__WEBPACK_IMPORTED_MODULE_9__.RawImage.fromTensor(formatted); + toReturn.push({ + predicted_depth: prediction, + depth + }); + } + return toReturn.length > 1 ? toReturn : toReturn[0]; + } + } + const SUPPORTED_TASKS = Object.freeze({ + "text-classification": { + "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, + "pipeline": TextClassificationPipeline, + "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForSequenceClassification, + "default": { + // TODO: replace with original + // "model": "distilbert-base-uncased-finetuned-sst-2-english", + "model": "Xenova/distilbert-base-uncased-finetuned-sst-2-english" + }, + "type": "text" + }, + "token-classification": { + "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, + "pipeline": TokenClassificationPipeline, + "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForTokenClassification, + "default": { + // TODO: replace with original + // "model": "Davlan/bert-base-multilingual-cased-ner-hrl", + "model": "Xenova/bert-base-multilingual-cased-ner-hrl" + }, + "type": "text" + }, + "question-answering": { + "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, + "pipeline": QuestionAnsweringPipeline, + "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForQuestionAnswering, + "default": { + // TODO: replace with original + // "model": "distilbert-base-cased-distilled-squad", + "model": "Xenova/distilbert-base-cased-distilled-squad" + }, + "type": "text" + }, + "fill-mask": { + "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, + "pipeline": FillMaskPipeline, + "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForMaskedLM, + "default": { + // TODO: replace with original + // "model": "bert-base-uncased", + "model": "Xenova/bert-base-uncased" + }, + "type": "text" + }, + "summarization": { + "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, + "pipeline": SummarizationPipeline, + "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForSeq2SeqLM, + "default": { + // TODO: replace with original + // "model": "sshleifer/distilbart-cnn-6-6", + "model": "Xenova/distilbart-cnn-6-6" + }, + "type": "text" + }, + "translation": { + "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, + "pipeline": TranslationPipeline, + "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForSeq2SeqLM, + "default": { + // TODO: replace with original + // "model": "t5-small", + "model": "Xenova/t5-small" + }, + "type": "text" + }, + "text2text-generation": { + "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, + "pipeline": Text2TextGenerationPipeline, + "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForSeq2SeqLM, + "default": { + // TODO: replace with original + // "model": "google/flan-t5-small", + "model": "Xenova/flan-t5-small" + }, + "type": "text" + }, + "text-generation": { + "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, + "pipeline": TextGenerationPipeline, + "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForCausalLM, + "default": { + // TODO: replace with original + // "model": "gpt2", + "model": "Xenova/gpt2" + }, + "type": "text" + }, + "zero-shot-classification": { + "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, + "pipeline": ZeroShotClassificationPipeline, + "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForSequenceClassification, + "default": { + // TODO: replace with original + // "model": "typeform/distilbert-base-uncased-mnli", + "model": "Xenova/distilbert-base-uncased-mnli" + }, + "type": "text" + }, + "audio-classification": { + "pipeline": AudioClassificationPipeline, + "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForAudioClassification, + "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, + "default": { + // TODO: replace with original + // "model": "superb/wav2vec2-base-superb-ks", + "model": "Xenova/wav2vec2-base-superb-ks" + }, + "type": "audio" + }, + "zero-shot-audio-classification": { + "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, + "pipeline": ZeroShotAudioClassificationPipeline, + "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModel, + "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, + "default": { + // TODO: replace with original + // "model": "laion/clap-htsat-fused", + "model": "Xenova/clap-htsat-unfused" + }, + "type": "multimodal" + }, + "automatic-speech-recognition": { + "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, + "pipeline": AutomaticSpeechRecognitionPipeline, + "model": [_models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForSpeechSeq2Seq, _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForCTC], + "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, + "default": { + // TODO: replace with original + // "model": "openai/whisper-tiny.en", + "model": "Xenova/whisper-tiny.en" + }, + "type": "multimodal" + }, + "text-to-audio": { + "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, + "pipeline": TextToAudioPipeline, + "model": [_models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForTextToWaveform, _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForTextToSpectrogram], + "processor": [ + _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, + /* Some don't use a processor */ + null + ], + "default": { + // TODO: replace with original + // "model": "microsoft/speecht5_tts", + "model": "Xenova/speecht5_tts" + }, + "type": "text" + }, + "image-to-text": { + "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, + "pipeline": ImageToTextPipeline, + "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForVision2Seq, + "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, + "default": { + // TODO: replace with original + // "model": "nlpconnect/vit-gpt2-image-captioning", + "model": "Xenova/vit-gpt2-image-captioning" + }, + "type": "multimodal" + }, + "image-classification": { + // no tokenizer + "pipeline": ImageClassificationPipeline, + "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForImageClassification, + "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, + "default": { + // TODO: replace with original + // "model": "google/vit-base-patch16-224", + "model": "Xenova/vit-base-patch16-224" + }, + "type": "multimodal" + }, + "image-segmentation": { + // no tokenizer + "pipeline": ImageSegmentationPipeline, + "model": [_models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForImageSegmentation, _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForSemanticSegmentation, _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForUniversalSegmentation], + "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, + "default": { + // TODO: replace with original + // "model": "facebook/detr-resnet-50-panoptic", + "model": "Xenova/detr-resnet-50-panoptic" + }, + "type": "multimodal" + }, + "background-removal": { + // no tokenizer + "pipeline": BackgroundRemovalPipeline, + "model": [_models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForImageSegmentation, _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForSemanticSegmentation, _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForUniversalSegmentation], + "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, + "default": { + "model": "Xenova/modnet" + }, + "type": "image" + }, + "zero-shot-image-classification": { + "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, + "pipeline": ZeroShotImageClassificationPipeline, + "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModel, + "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, + "default": { + // TODO: replace with original + // "model": "openai/clip-vit-base-patch32", + "model": "Xenova/clip-vit-base-patch32" + }, + "type": "multimodal" + }, + "object-detection": { + // no tokenizer + "pipeline": ObjectDetectionPipeline, + "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForObjectDetection, + "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, + "default": { + // TODO: replace with original + // "model": "facebook/detr-resnet-50", + "model": "Xenova/detr-resnet-50" + }, + "type": "multimodal" + }, + "zero-shot-object-detection": { + "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, + "pipeline": ZeroShotObjectDetectionPipeline, + "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForZeroShotObjectDetection, + "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, + "default": { + // TODO: replace with original + // "model": "google/owlvit-base-patch32", + "model": "Xenova/owlvit-base-patch32" + }, + "type": "multimodal" + }, + "document-question-answering": { + "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, + "pipeline": DocumentQuestionAnsweringPipeline, + "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForDocumentQuestionAnswering, + "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, + "default": { + // TODO: replace with original + // "model": "naver-clova-ix/donut-base-finetuned-docvqa", + "model": "Xenova/donut-base-finetuned-docvqa" + }, + "type": "multimodal" + }, + "image-to-image": { + // no tokenizer + "pipeline": ImageToImagePipeline, + "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForImageToImage, + "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, + "default": { + // TODO: replace with original + // "model": "caidas/swin2SR-classical-sr-x2-64", + "model": "Xenova/swin2SR-classical-sr-x2-64" + }, + "type": "image" + }, + "depth-estimation": { + // no tokenizer + "pipeline": DepthEstimationPipeline, + "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForDepthEstimation, + "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, + "default": { + // TODO: replace with original + // "model": "Intel/dpt-large", + "model": "Xenova/dpt-large" + }, + "type": "image" + }, + // This task serves as a useful interface for dealing with sentence-transformers (https://huggingface.co/sentence-transformers). + "feature-extraction": { + "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, + "pipeline": FeatureExtractionPipeline, + "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModel, + "default": { + // TODO: replace with original + // "model": "sentence-transformers/all-MiniLM-L6-v2", + "model": "Xenova/all-MiniLM-L6-v2" + }, + "type": "text" + }, + "image-feature-extraction": { + "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, + "pipeline": ImageFeatureExtractionPipeline, + "model": [_models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForImageFeatureExtraction, _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModel], + "default": { + // TODO: replace with original + // "model": "google/vit-base-patch16-224", + "model": "Xenova/vit-base-patch16-224-in21k" + }, + "type": "image" + } + }); + const TASK_ALIASES = Object.freeze({ + "sentiment-analysis": "text-classification", + "ner": "token-classification", + // "vqa": "visual-question-answering", // TODO: Add + "asr": "automatic-speech-recognition", + "text-to-speech": "text-to-audio", + // Add for backwards compatibility + "embeddings": "feature-extraction" + }); + async function pipeline(task, model = null, { + progress_callback = null, + config = null, + cache_dir = null, + local_files_only = false, + revision = "main", + device = null, + dtype = null, + subfolder = "onnx", + use_external_data_format = null, + model_file_name = null, + session_options = {} + } = {}) { + task = TASK_ALIASES[task] ?? task; + const pipelineInfo = SUPPORTED_TASKS[task.split("_", 1)[0]]; + if (!pipelineInfo) { + throw Error(`Unsupported pipeline: ${task}. Must be one of [${Object.keys(SUPPORTED_TASKS)}]`); + } + if (!model) { + model = pipelineInfo.default.model; + console.log(`No model specified. Using default model: "${model}".`); + } + const pretrainedOptions = { + progress_callback, + config, + cache_dir, + local_files_only, + revision, + device, + dtype, + subfolder, + use_external_data_format, + model_file_name, + session_options + }; + const classes = /* @__PURE__ */ new Map([ + ["tokenizer", pipelineInfo.tokenizer], + ["model", pipelineInfo.model], + ["processor", pipelineInfo.processor] + ]); + const results = await loadItems(classes, model, pretrainedOptions); + results.task = task; + (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_5__.dispatchCallback)(progress_callback, { + "status": "ready", + "task": task, + "model": model + }); + const pipelineClass = pipelineInfo.pipeline; + return new pipelineClass(results); + } + async function loadItems(mapping, model, pretrainedOptions) { + const result = /* @__PURE__ */ Object.create(null); + const promises = []; + for (const [name, cls] of mapping.entries()) { + if (!cls) continue; + let promise; + if (Array.isArray(cls)) { + promise = new Promise(async (resolve, reject) => { + let e; + for (const c of cls) { + if (c === null) { + resolve(null); + return; + } + try { + resolve(await c.from_pretrained(model, pretrainedOptions)); + return; + } catch (err) { + if (err.message?.includes("Unsupported model type")) { + e = err; + } else if (err.message?.includes("Could not locate file")) { + e = err; + } else { + reject(err); + return; + } + } + } + reject(e); + }); + } else { + promise = cls.from_pretrained(model, pretrainedOptions); + } + result[name] = promise; + promises.push(promise); + } + await Promise.all(promises); + for (const [name, promise] of Object.entries(result)) { + result[name] = await promise; + } + return result; + } + }) + ), + /***/ + "./src/tokenizers.js": ( + /*!***************************!*\ + !*** ./src/tokenizers.js ***! + \***************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + AlbertTokenizer: () => ( + /* binding */ + AlbertTokenizer + ), + /* harmony export */ + AutoTokenizer: () => ( + /* binding */ + AutoTokenizer + ), + /* harmony export */ + BartTokenizer: () => ( + /* binding */ + BartTokenizer + ), + /* harmony export */ + BertTokenizer: () => ( + /* binding */ + BertTokenizer + ), + /* harmony export */ + BlenderbotSmallTokenizer: () => ( + /* binding */ + BlenderbotSmallTokenizer + ), + /* harmony export */ + BlenderbotTokenizer: () => ( + /* binding */ + BlenderbotTokenizer + ), + /* harmony export */ + BloomTokenizer: () => ( + /* binding */ + BloomTokenizer + ), + /* harmony export */ + CLIPTokenizer: () => ( + /* binding */ + CLIPTokenizer + ), + /* harmony export */ + CamembertTokenizer: () => ( + /* binding */ + CamembertTokenizer + ), + /* harmony export */ + CodeGenTokenizer: () => ( + /* binding */ + CodeGenTokenizer + ), + /* harmony export */ + CodeLlamaTokenizer: () => ( + /* binding */ + CodeLlamaTokenizer + ), + /* harmony export */ + CohereTokenizer: () => ( + /* binding */ + CohereTokenizer + ), + /* harmony export */ + ConvBertTokenizer: () => ( + /* binding */ + ConvBertTokenizer + ), + /* harmony export */ + DebertaTokenizer: () => ( + /* binding */ + DebertaTokenizer + ), + /* harmony export */ + DebertaV2Tokenizer: () => ( + /* binding */ + DebertaV2Tokenizer + ), + /* harmony export */ + DistilBertTokenizer: () => ( + /* binding */ + DistilBertTokenizer + ), + /* harmony export */ + ElectraTokenizer: () => ( + /* binding */ + ElectraTokenizer + ), + /* harmony export */ + EsmTokenizer: () => ( + /* binding */ + EsmTokenizer + ), + /* harmony export */ + FalconTokenizer: () => ( + /* binding */ + FalconTokenizer + ), + /* harmony export */ + GPT2Tokenizer: () => ( + /* binding */ + GPT2Tokenizer + ), + /* harmony export */ + GPTNeoXTokenizer: () => ( + /* binding */ + GPTNeoXTokenizer + ), + /* harmony export */ + GemmaTokenizer: () => ( + /* binding */ + GemmaTokenizer + ), + /* harmony export */ + Grok1Tokenizer: () => ( + /* binding */ + Grok1Tokenizer + ), + /* harmony export */ + HerbertTokenizer: () => ( + /* binding */ + HerbertTokenizer + ), + /* harmony export */ + LlamaTokenizer: () => ( + /* binding */ + LlamaTokenizer + ), + /* harmony export */ + M2M100Tokenizer: () => ( + /* binding */ + M2M100Tokenizer + ), + /* harmony export */ + MBart50Tokenizer: () => ( + /* binding */ + MBart50Tokenizer + ), + /* harmony export */ + MBartTokenizer: () => ( + /* binding */ + MBartTokenizer + ), + /* harmony export */ + MPNetTokenizer: () => ( + /* binding */ + MPNetTokenizer + ), + /* harmony export */ + MarianTokenizer: () => ( + /* binding */ + MarianTokenizer + ), + /* harmony export */ + MgpstrTokenizer: () => ( + /* binding */ + MgpstrTokenizer + ), + /* harmony export */ + MobileBertTokenizer: () => ( + /* binding */ + MobileBertTokenizer + ), + /* harmony export */ + NllbTokenizer: () => ( + /* binding */ + NllbTokenizer + ), + /* harmony export */ + NougatTokenizer: () => ( + /* binding */ + NougatTokenizer + ), + /* harmony export */ + PreTrainedTokenizer: () => ( + /* binding */ + PreTrainedTokenizer + ), + /* harmony export */ + Qwen2Tokenizer: () => ( + /* binding */ + Qwen2Tokenizer + ), + /* harmony export */ + RoFormerTokenizer: () => ( + /* binding */ + RoFormerTokenizer + ), + /* harmony export */ + RobertaTokenizer: () => ( + /* binding */ + RobertaTokenizer + ), + /* harmony export */ + SiglipTokenizer: () => ( + /* binding */ + SiglipTokenizer + ), + /* harmony export */ + SpeechT5Tokenizer: () => ( + /* binding */ + SpeechT5Tokenizer + ), + /* harmony export */ + SqueezeBertTokenizer: () => ( + /* binding */ + SqueezeBertTokenizer + ), + /* harmony export */ + T5Tokenizer: () => ( + /* binding */ + T5Tokenizer + ), + /* harmony export */ + TokenizerModel: () => ( + /* binding */ + TokenizerModel + ), + /* harmony export */ + VitsTokenizer: () => ( + /* binding */ + VitsTokenizer + ), + /* harmony export */ + Wav2Vec2CTCTokenizer: () => ( + /* binding */ + Wav2Vec2CTCTokenizer + ), + /* harmony export */ + WhisperTokenizer: () => ( + /* binding */ + WhisperTokenizer + ), + /* harmony export */ + XLMRobertaTokenizer: () => ( + /* binding */ + XLMRobertaTokenizer + ), + /* harmony export */ + XLMTokenizer: () => ( + /* binding */ + XLMTokenizer + ), + /* harmony export */ + is_chinese_char: () => ( + /* binding */ + is_chinese_char + ) + /* harmony export */ + }); + var _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ./utils/generic.js */ + "./src/utils/generic.js" + ); + var _utils_core_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ./utils/core.js */ + "./src/utils/core.js" + ); + var _utils_hub_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ./utils/hub.js */ + "./src/utils/hub.js" + ); + var _utils_maths_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! ./utils/maths.js */ + "./src/utils/maths.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__2( + /*! ./utils/tensor.js */ + "./src/utils/tensor.js" + ); + var _utils_data_structures_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__2( + /*! ./utils/data-structures.js */ + "./src/utils/data-structures.js" + ); + var _huggingface_jinja__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__2( + /*! @huggingface/jinja */ + "./node_modules/@huggingface/jinja/dist/index.js" + ); + var _models_whisper_common_whisper_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__2( + /*! ./models/whisper/common_whisper.js */ + "./src/models/whisper/common_whisper.js" + ); + async function loadTokenizer(pretrained_model_name_or_path, options) { + const info = await Promise.all([ + (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_2__.getModelJSON)(pretrained_model_name_or_path, "tokenizer.json", true, options), + (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_2__.getModelJSON)(pretrained_model_name_or_path, "tokenizer_config.json", true, options) + ]); + if (options.legacy !== null) { + info[1].legacy = options.legacy; + } + return info; + } + function regexSplit(text, regex) { + const result = []; + let prev = 0; + for (const match of text.matchAll(regex)) { + const fullMatch = match[0]; + if (prev < match.index) { + result.push(text.slice(prev, match.index)); + } + if (fullMatch.length > 0) { + result.push(fullMatch); + } + prev = match.index + fullMatch.length; + } + if (prev < text.length) { + result.push(text.slice(prev)); + } + return result; + } + function createPattern(pattern, invert = true) { + if (pattern.Regex !== void 0) { + let regex = pattern.Regex.replace(/\\([#&~])/g, "$1"); + for (const [key, value] of PROBLEMATIC_REGEX_MAP) { + regex = regex.replaceAll(key, value); + } + return new RegExp(regex, "gu"); + } else if (pattern.String !== void 0) { + const escaped = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_1__.escapeRegExp)(pattern.String); + return new RegExp(invert ? escaped : `(${escaped})`, "gu"); + } else { + console.warn("Unknown pattern type:", pattern); + return null; + } + } + function objectToMap(obj) { + return new Map(Object.entries(obj)); + } + function prepareTensorForDecode(tensor) { + const dims = tensor.dims; + switch (dims.length) { + case 1: + return tensor.tolist(); + case 2: + if (dims[0] !== 1) { + throw new Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs."); + } + return tensor.tolist()[0]; + default: + throw new Error(`Expected tensor to have 1-2 dimensions, got ${dims.length}.`); + } + } + function clean_up_tokenization(text) { + return text.replace(/ \./g, ".").replace(/ \?/g, "?").replace(/ \!/g, "!").replace(/ ,/g, ",").replace(/ \' /g, "'").replace(/ n\'t/g, "n't").replace(/ \'m/g, "'m").replace(/ \'s/g, "'s").replace(/ \'ve/g, "'ve").replace(/ \'re/g, "'re"); + } + function remove_accents(text) { + return text.replace(/\p{M}/gu, ""); + } + function lowercase_and_remove_accent(text) { + return remove_accents(text.toLowerCase()); + } + function is_chinese_char(cp) { + return cp >= 19968 && cp <= 40959 || cp >= 13312 && cp <= 19903 || cp >= 131072 && cp <= 173791 || cp >= 173824 && cp <= 177983 || cp >= 177984 && cp <= 178207 || cp >= 178208 && cp <= 183983 || cp >= 63744 && cp <= 64255 || cp >= 194560 && cp <= 195103; + } + function fuse_unk(arr, tokens_to_ids, unk_token_id) { + const fused = []; + let i = 0; + while (i < arr.length) { + fused.push(arr[i]); + if ((tokens_to_ids.get(arr[i]) ?? unk_token_id) !== unk_token_id) { + ++i; + continue; + } + while (++i < arr.length && (tokens_to_ids.get(arr[i]) ?? unk_token_id) === unk_token_id) { + if (tokens_to_ids.get(fused.at(-1)) !== unk_token_id) { + fused[fused.length - 1] += arr[i]; + } + } + } + return fused; + } + function whitespace_split(text) { + return text.match(/\S+/g) || []; + } + const PUNCTUATION_REGEX = "\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E"; + const PUNCTUATION_ONLY_REGEX = new RegExp(`^[${PUNCTUATION_REGEX}]+$`, "gu"); + const BLOOM_SPLIT_CHARS = ".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C"; + const PROBLEMATIC_REGEX_MAP = /* @__PURE__ */ new Map([ + // These use the case insensitive group modifier, which is not supported in JavaScript. + // When parsing the regex, an "Invalid group" error is thrown. + ["(?i:'s|'t|'re|'ve|'m|'ll|'d)", "(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"], + ["(?i:[sdmt]|ll|ve|re)", "(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"], + // JS doesn't support possessive quantifiers (these are used in recent OpenAI tokenizers). + ["[^\\r\\n\\p{L}\\p{N}]?+", "[^\\r\\n\\p{L}\\p{N}]?"], + ["[^\\s\\p{L}\\p{N}]++", "[^\\s\\p{L}\\p{N}]+"], + // Used to override the default (invalid) regex of the bloom pretokenizer. + // For more information, see https://github.com/huggingface/transformers.js/issues/94 + [` ?[^(\\s|[${BLOOM_SPLIT_CHARS}])]+`, ` ?[^\\s${BLOOM_SPLIT_CHARS}]+`] + ]); + class AddedToken { + /** + * Creates a new instance of AddedToken. + * @param {Object} config Added token configuration object. + * @param {string} config.content The content of the added token. + * @param {number} config.id The id of the added token. + * @param {boolean} [config.single_word=false] Whether this token must be a single word or can break words. + * @param {boolean} [config.lstrip=false] Whether this token should strip whitespaces on its left. + * @param {boolean} [config.rstrip=false] Whether this token should strip whitespaces on its right. + * @param {boolean} [config.normalized=false] Whether this token should be normalized. + * @param {boolean} [config.special=false] Whether this token is special. + */ + constructor(config) { + this.content = config.content; + this.id = config.id; + this.single_word = config.single_word ?? false; + this.lstrip = config.lstrip ?? false; + this.rstrip = config.rstrip ?? false; + this.special = config.special ?? false; + this.normalized = config.normalized ?? null; + } + } + class TokenizerModel extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { + /** + * Creates a new instance of TokenizerModel. + * @param {Object} config The configuration object for the TokenizerModel. + */ + constructor(config) { + super(); + this.config = config; + this.vocab = []; + this.tokens_to_ids = /* @__PURE__ */ new Map(); + this.unk_token_id = void 0; + this.unk_token = void 0; + this.end_of_word_suffix = void 0; + this.fuse_unk = this.config.fuse_unk ?? false; + } + /** + * Instantiates a new TokenizerModel instance based on the configuration object provided. + * @param {Object} config The configuration object for the TokenizerModel. + * @param {...*} args Optional arguments to pass to the specific TokenizerModel constructor. + * @returns {TokenizerModel} A new instance of a TokenizerModel. + * @throws Will throw an error if the TokenizerModel type in the config is not recognized. + */ + static fromConfig(config, ...args) { + switch (config.type) { + case "WordPiece": + return new WordPieceTokenizer(config); + case "Unigram": + return new Unigram(config, ...args); + case "BPE": + return new BPE(config); + default: + if (config.vocab) { + if (Array.isArray(config.vocab)) { + return new Unigram(config, ...args); + } else if (Object.hasOwn(config, "continuing_subword_prefix") && Object.hasOwn(config, "unk_token")) { + if (Object.hasOwn(config, "merges")) { + return new BPE(config); + } else { + return new WordPieceTokenizer(config); + } + } else { + return new LegacyTokenizerModel(config, ...args); + } + } + throw new Error(`Unknown TokenizerModel type: ${config.type}`); + } + } + /** + * Internal function to call the TokenizerModel instance. + * @param {string[]} tokens The tokens to encode. + * @returns {string[]} The encoded tokens. + */ + _call(tokens) { + tokens = this.encode(tokens); + if (this.fuse_unk) { + tokens = fuse_unk(tokens, this.tokens_to_ids, this.unk_token_id); + } + return tokens; + } + /** + * Encodes a list of tokens into a list of token IDs. + * @param {string[]} tokens The tokens to encode. + * @returns {string[]} The encoded tokens. + * @throws Will throw an error if not implemented in a subclass. + */ + encode(tokens) { + throw Error("encode should be implemented in subclass."); + } + /** + * Converts a list of tokens into a list of token IDs. + * @param {string[]} tokens The tokens to convert. + * @returns {number[]} The converted token IDs. + */ + convert_tokens_to_ids(tokens) { + return tokens.map((t) => this.tokens_to_ids.get(t) ?? this.unk_token_id); + } + /** + * Converts a list of token IDs into a list of tokens. + * @param {number[]|bigint[]} ids The token IDs to convert. + * @returns {string[]} The converted tokens. + */ + convert_ids_to_tokens(ids) { + return ids.map((i) => this.vocab[i] ?? this.unk_token); + } + } + class WordPieceTokenizer extends TokenizerModel { + /** + * @param {Object} config The configuration object. + * @param {Object} config.vocab A mapping of tokens to ids. + * @param {string} config.unk_token The unknown token string. + * @param {string} config.continuing_subword_prefix The prefix to use for continuing subwords. + * @param {number} [config.max_input_chars_per_word=100] The maximum number of characters per word. + */ + constructor(config) { + super(config); + this.tokens_to_ids = objectToMap(config.vocab); + this.unk_token_id = this.tokens_to_ids.get(config.unk_token); + this.unk_token = config.unk_token; + this.max_input_chars_per_word = config.max_input_chars_per_word ?? 100; + this.vocab = new Array(this.tokens_to_ids.size); + for (const [key, value] of this.tokens_to_ids) { + this.vocab[value] = key; + } + } + /** + * Encodes an array of tokens using WordPiece encoding. + * @param {string[]} tokens The tokens to encode. + * @returns {string[]} An array of encoded tokens. + */ + encode(tokens) { + const outputTokens = []; + for (const token of tokens) { + const chars = [...token]; + if (chars.length > this.max_input_chars_per_word) { + outputTokens.push(this.unk_token); + continue; + } + let isUnknown = false; + let start = 0; + const subTokens = []; + while (start < chars.length) { + let end = chars.length; + let currentSubstring = null; + while (start < end) { + let substr = chars.slice(start, end).join(""); + if (start > 0) { + substr = this.config.continuing_subword_prefix + substr; + } + if (this.tokens_to_ids.has(substr)) { + currentSubstring = substr; + break; + } + --end; + } + if (currentSubstring === null) { + isUnknown = true; + break; + } + subTokens.push(currentSubstring); + start = end; + } + if (isUnknown) { + outputTokens.push(this.unk_token); + } else { + outputTokens.push(...subTokens); + } + } + return outputTokens; + } + } + class Unigram extends TokenizerModel { + /** + * Create a new Unigram tokenizer model. + * @param {Object} config The configuration object for the Unigram model. + * @param {number} config.unk_id The ID of the unknown token + * @param {[string, number][]} config.vocab A 2D array representing a mapping of tokens to scores. + * @param {Object} moreConfig Additional configuration object for the Unigram model. + */ + constructor(config, moreConfig) { + super(config); + const vocabSize = config.vocab.length; + this.vocab = new Array(vocabSize); + this.scores = new Array(vocabSize); + for (let i = 0; i < vocabSize; ++i) { + [this.vocab[i], this.scores[i]] = config.vocab[i]; + } + this.unk_token_id = config.unk_id; + this.unk_token = this.vocab[config.unk_id]; + this.tokens_to_ids = new Map(this.vocab.map((x, i) => [x, i])); + this.bos_token = " "; + this.bos_token_id = this.tokens_to_ids.get(this.bos_token); + this.eos_token = moreConfig.eos_token; + this.eos_token_id = this.tokens_to_ids.get(this.eos_token); + this.unk_token = this.vocab[this.unk_token_id]; + this.minScore = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_3__.min)(this.scores)[0]; + this.unk_score = this.minScore - 10; + this.scores[this.unk_token_id] = this.unk_score; + this.trie = new _utils_data_structures_js__WEBPACK_IMPORTED_MODULE_5__.CharTrie(); + this.trie.extend(this.vocab); + this.fuse_unk = true; + } + /** + * Populates lattice nodes. + * @param {TokenLattice} lattice The token lattice to populate with nodes. + */ + populateNodes(lattice) { + const chars = lattice.chars; + const mblen = 1; + let beginPos = 0; + while (beginPos < chars.length) { + let hasSingleNode = false; + const tokens = []; + const sliced = chars.slice(beginPos).join(""); + const prefixedTokens = this.trie.commonPrefixSearch(sliced); + for (const token of prefixedTokens) { + tokens.push(token); + const tokenId = this.tokens_to_ids.get(token); + const tokenScore = this.scores[tokenId]; + const n = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_1__.len)(token); + lattice.insert(beginPos, n, tokenScore, tokenId); + if (!hasSingleNode && n === mblen) { + hasSingleNode = true; + } + } + if (!hasSingleNode) { + lattice.insert(beginPos, mblen, this.unk_score, this.unk_token_id); + } + beginPos += mblen; + } + } + /** + * Encodes an array of tokens into an array of subtokens using the unigram model. + * + * @param {string} normalized The normalized string. + * @returns {string[]} An array of subtokens obtained by encoding the input tokens using the unigram model. + */ + tokenize(normalized) { + const lattice = new _utils_data_structures_js__WEBPACK_IMPORTED_MODULE_5__.TokenLattice(normalized, this.bos_token_id, this.eos_token_id); + this.populateNodes(lattice); + return lattice.tokens(); + } + /** + * Encodes an array of tokens using Unigram encoding. + * @param {string[]} tokens The tokens to encode. + * @returns {string[]} An array of encoded tokens. + */ + encode(tokens) { + const toReturn = []; + for (const token of tokens) { + const tokenized = this.tokenize(token); + toReturn.push(...tokenized); + } + return toReturn; + } + } + const BYTES_TO_UNICODE = (() => { + const bs2 = [ + ...Array.from({ length: "~".charCodeAt(0) - "!".charCodeAt(0) + 1 }, (_, i) => i + "!".charCodeAt(0)), + ...Array.from({ length: "\xAC".charCodeAt(0) - "\xA1".charCodeAt(0) + 1 }, (_, i) => i + "\xA1".charCodeAt(0)), + ...Array.from({ length: "\xFF".charCodeAt(0) - "\xAE".charCodeAt(0) + 1 }, (_, i) => i + "\xAE".charCodeAt(0)) + ]; + const cs2 = bs2.slice(); + let n = 0; + for (let b = 0; b < 256; ++b) { + if (!bs2.includes(b)) { + bs2.push(b); + cs2.push(256 + n); + n += 1; + } + } + const ccs = cs2.map((n2) => String.fromCharCode(n2)); + return Object.fromEntries(bs2.map((b, i) => [b, ccs[i]])); + })(); + const UNICODE_TO_BYTES = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_1__.reverseDictionary)(BYTES_TO_UNICODE); + class BPE extends TokenizerModel { + /** + * Create a BPE instance. + * @param {Object} config The configuration object for BPE. + * @param {Object} config.vocab A mapping of tokens to ids. + * @param {string[]|[string, string][]} config.merges An array of BPE merges as strings. + * @param {string} config.unk_token The unknown token used for out of vocabulary words. + * @param {string} config.end_of_word_suffix The suffix to place at the end of each word. + * @param {string} [config.continuing_subword_suffix] The suffix to insert between words. + * @param {boolean} [config.byte_fallback=false] Whether to use spm byte-fallback trick (defaults to False) + * @param {boolean} [config.ignore_merges=false] Whether or not to match tokens with the vocab before using merges. + */ + constructor(config) { + super(config); + this.tokens_to_ids = objectToMap(config.vocab); + this.unk_token_id = this.tokens_to_ids.get(config.unk_token); + this.unk_token = config.unk_token; + this.vocab = new Array(this.tokens_to_ids.size); + for (const [key, value] of this.tokens_to_ids) { + this.vocab[value] = key; + } + const use_new_merge_format = Array.isArray(config.merges[0]); + this.merges = use_new_merge_format ? ( + /** @type {[string, string][]} */ + config.merges + ) : ( + /** @type {string[]} */ + config.merges.map((x) => ( + /** @type {[string, string]} */ + x.split(" ", 2) + )) + ); + this.bpe_ranks = new Map(this.merges.map((x, i) => [JSON.stringify(x), i])); + this.end_of_word_suffix = config.end_of_word_suffix; + this.continuing_subword_suffix = config.continuing_subword_suffix ?? null; + this.byte_fallback = this.config.byte_fallback ?? false; + if (this.byte_fallback) { + this.text_encoder = new TextEncoder(); + } + this.ignore_merges = this.config.ignore_merges ?? false; + this.max_length_to_cache = 256; + this.cache_capacity = 1e4; + this.cache = new _utils_data_structures_js__WEBPACK_IMPORTED_MODULE_5__.LRUCache(this.cache_capacity); + } + /** + * Clears the cache. + */ + clear_cache() { + this.cache.clear(); + } + /** + * Apply Byte-Pair-Encoding (BPE) to a given token. Efficient heap-based priority + * queue implementation adapted from https://github.com/belladoreai/llama-tokenizer-js. + * @param {string} token The token to encode. + * @returns {string[]} The BPE encoded tokens. + */ + bpe(token) { + if (token.length === 0) { + return []; + } + const cached = this.cache.get(token); + if (cached !== void 0) { + return cached; + } + const word = Array.from(token); + if (this.end_of_word_suffix) { + word[word.length - 1] += this.end_of_word_suffix; + } + let result = []; + if (word.length > 1) { + const queue = new _utils_data_structures_js__WEBPACK_IMPORTED_MODULE_5__.PriorityQueue((a, b) => a.score < b.score); + let startingNode = { + token: word[0], + bias: 0, + prev: null, + next: null + }; + let previousNode = startingNode; + for (let i = 1; i < word.length; ++i) { + const currentNode = { + bias: i / word.length, + // Add fractional component to break ties + token: word[i], + prev: previousNode, + next: null + }; + previousNode.next = currentNode; + this._add_node(queue, previousNode); + previousNode = currentNode; + } + while (!queue.isEmpty()) { + const node = queue.pop(); + if (node.deleted || !node.next || node.next.deleted) continue; + node.deleted = true; + node.next.deleted = true; + if (node.prev) { + const newPreviousNode = { ...node.prev }; + node.prev.deleted = true; + node.prev = newPreviousNode; + if (newPreviousNode.prev) { + newPreviousNode.prev.next = newPreviousNode; + } else { + startingNode = newPreviousNode; + } + } + const merged = { + token: node.token + node.next.token, + bias: node.bias, + prev: node.prev, + next: node.next.next + }; + if (merged.prev) { + merged.prev.next = merged; + this._add_node(queue, merged.prev); + } else { + startingNode = merged; + } + if (merged.next) { + merged.next.prev = merged; + this._add_node(queue, merged); + } + } + for (let currentNode = startingNode; currentNode !== null; currentNode = currentNode.next) { + result.push(currentNode.token); + } + } else { + result = word; + } + if (this.continuing_subword_suffix) { + for (let i = 0; i < result.length - 1; ++i) { + result[i] += this.continuing_subword_suffix; + } + } + if (token.length < this.max_length_to_cache) { + this.cache.put(token, result); + } + return result; + } + /** + * Helper function to add a node to the priority queue. + * @param {PriorityQueue} queue + * @param {BPENode} node + * @private + */ + _add_node(queue, node) { + const rank = this.bpe_ranks.get(JSON.stringify([node.token, node.next.token])); + if (rank !== void 0) { + node.score = rank + node.bias; + queue.push(node); + } + } + /** + * Encodes the input sequence of tokens using the BPE algorithm and returns the resulting subword tokens. + * @param {string[]} tokens The input sequence of tokens to encode. + * @returns {string[]} The resulting subword tokens after applying the BPE algorithm to the input sequence of tokens. + */ + encode(tokens) { + const outputTokens = []; + for (const token of tokens) { + if (this.ignore_merges && this.tokens_to_ids.has(token)) { + outputTokens.push(token); + continue; + } + const bpe_token_list = this.bpe(token); + for (const t of bpe_token_list) { + if (this.tokens_to_ids.has(t)) { + outputTokens.push(t); + } else if (this.byte_fallback) { + const byteTokens = Array.from(this.text_encoder.encode(t)).map((x) => `<0x${x.toString(16).toUpperCase().padStart(2, "0")}>`); + if (byteTokens.every((x) => this.tokens_to_ids.has(x))) { + outputTokens.push(...byteTokens); + } else { + outputTokens.push(this.unk_token); + } + } else { + outputTokens.push(this.unk_token); + } + } + } + return outputTokens; + } + } + class LegacyTokenizerModel extends TokenizerModel { + /** + * Create a LegacyTokenizerModel instance. + * @param {Object} config The configuration object for LegacyTokenizerModel. + * @param {Object} config.vocab A (possibly nested) mapping of tokens to ids. + * @param {Object} moreConfig Additional configuration object for the LegacyTokenizerModel model. + */ + constructor(config, moreConfig) { + super(config); + this.tokens_to_ids = objectToMap( + moreConfig.target_lang ? config.vocab[moreConfig.target_lang] : config.vocab + ); + this.bos_token = moreConfig.bos_token; + this.bos_token_id = this.tokens_to_ids.get(this.bos_token); + this.eos_token = moreConfig.eos_token; + this.eos_token_id = this.tokens_to_ids.get(this.eos_token); + this.pad_token = moreConfig.pad_token; + this.pad_token_id = this.tokens_to_ids.get(this.pad_token); + this.unk_token = moreConfig.unk_token; + this.unk_token_id = this.tokens_to_ids.get(this.unk_token); + this.vocab = new Array(this.tokens_to_ids.size); + for (const [key, value] of this.tokens_to_ids) { + this.vocab[value] = key; + } + } + encode(tokens) { + return tokens; + } + } + class Normalizer extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { + /** + * @param {Object} config The configuration object for the normalizer. + */ + constructor(config) { + super(); + this.config = config; + } + /** + * Factory method for creating normalizers from config objects. + * @static + * @param {Object} config The configuration object for the normalizer. + * @returns {Normalizer} A Normalizer object. + * @throws {Error} If an unknown Normalizer type is specified in the config. + */ + static fromConfig(config) { + if (config === null) return null; + switch (config.type) { + case "BertNormalizer": + return new BertNormalizer(config); + case "Precompiled": + return new Precompiled(config); + case "Sequence": + return new NormalizerSequence(config); + case "Replace": + return new Replace(config); + case "NFC": + return new NFC(config); + case "NFD": + return new NFD(config); + case "NFKC": + return new NFKC(config); + case "NFKD": + return new NFKD(config); + case "Strip": + return new StripNormalizer(config); + case "StripAccents": + return new StripAccents(config); + case "Lowercase": + return new Lowercase(config); + case "Prepend": + return new Prepend(config); + default: + throw new Error(`Unknown Normalizer type: ${config.type}`); + } + } + /** + * Normalize the input text. + * @abstract + * @param {string} text The text to normalize. + * @returns {string} The normalized text. + * @throws {Error} If this method is not implemented in a subclass. + */ + normalize(text) { + throw Error("normalize should be implemented in subclass."); + } + /** + * Alias for {@link Normalizer#normalize}. + * @param {string} text The text to normalize. + * @returns {string} The normalized text. + */ + _call(text) { + return this.normalize(text); + } + } + class Replace extends Normalizer { + /** + * Normalize the input text by replacing the pattern with the content. + * @param {string} text The input text to be normalized. + * @returns {string} The normalized text after replacing the pattern with the content. + */ + normalize(text) { + const pattern = createPattern(this.config.pattern); + return pattern === null ? text : text.replaceAll(pattern, this.config.content); + } + } + class UnicodeNormalizer extends Normalizer { + /** + * @type {string} The Unicode normalization form to apply. + * Should be one of: 'NFC', 'NFD', 'NFKC', or 'NFKD'. + */ + form = void 0; + /** + * Normalize the input text by applying Unicode normalization. + * @param {string} text The input text to be normalized. + * @returns {string} The normalized text. + */ + normalize(text) { + text = text.normalize(this.form); + return text; + } + } + class NFC extends UnicodeNormalizer { + form = "NFC"; + } + class NFD extends UnicodeNormalizer { + form = "NFD"; + } + class NFKC extends UnicodeNormalizer { + form = "NFKC"; + } + class NFKD extends UnicodeNormalizer { + form = "NFKD"; + } + class StripNormalizer extends Normalizer { + /** + * Strip leading and/or trailing whitespace from the input text. + * @param {string} text The input text. + * @returns {string} The normalized text. + */ + normalize(text) { + if (this.config.strip_left && this.config.strip_right) { + text = text.trim(); + } else { + if (this.config.strip_left) { + text = text.trimStart(); + } + if (this.config.strip_right) { + text = text.trimEnd(); + } + } + return text; + } + } + class StripAccents extends Normalizer { + /** + * Remove all accents from the text. + * @param {string} text The input text. + * @returns {string} The normalized text without accents. + */ + normalize(text) { + text = remove_accents(text); + return text; + } + } + class Lowercase extends Normalizer { + /** + * Lowercases the input string. + * @param {string} text The text to normalize. + * @returns {string} The normalized text. + */ + normalize(text) { + text = text.toLowerCase(); + return text; + } + } + class Prepend extends Normalizer { + /** + * Prepends the input string. + * @param {string} text The text to normalize. + * @returns {string} The normalized text. + */ + normalize(text) { + text = this.config.prepend + text; + return text; + } + } + class NormalizerSequence extends Normalizer { + /** + * Create a new instance of NormalizerSequence. + * @param {Object} config The configuration object. + * @param {Object[]} config.normalizers An array of Normalizer configuration objects. + */ + constructor(config) { + super(config); + this.normalizers = config.normalizers.map((x) => Normalizer.fromConfig(x)); + } + /** + * Apply a sequence of Normalizers to the input text. + * @param {string} text The text to normalize. + * @returns {string} The normalized text. + */ + normalize(text) { + return this.normalizers.reduce((t, normalizer) => { + return normalizer.normalize(t); + }, text); + } + } + class BertNormalizer extends Normalizer { + /** + * Adds whitespace around any CJK (Chinese, Japanese, or Korean) character in the input text. + * + * @param {string} text The input text to tokenize. + * @returns {string} The tokenized text with whitespace added around CJK characters. + */ + _tokenize_chinese_chars(text) { + const output = []; + for (let i = 0; i < text.length; ++i) { + const char = text[i]; + const cp = char.charCodeAt(0); + if (is_chinese_char(cp)) { + output.push(" "); + output.push(char); + output.push(" "); + } else { + output.push(char); + } + } + return output.join(""); + } + /** + * Strips accents from the given text. + * @param {string} text The text to strip accents from. + * @returns {string} The text with accents removed. + */ + stripAccents(text) { + return text.normalize("NFD").replace(/\p{Mn}/gu, ""); + } + /** + * Checks whether `char` is a control character. + * @param {string} char The character to check. + * @returns {boolean} Whether `char` is a control character. + * @private + */ + _is_control(char) { + switch (char) { + case " ": + case "\n": + case "\r": + return false; + default: + return /^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(char); + } + } + /** + * Performs invalid character removal and whitespace cleanup on text. + * @param {string} text The text to clean. + * @returns {string} The cleaned text. + * @private + */ + _clean_text(text) { + const output = []; + for (const char of text) { + const cp = char.charCodeAt(0); + if (cp === 0 || cp === 65533 || this._is_control(char)) { + continue; + } + if (/^\s$/.test(char)) { + output.push(" "); + } else { + output.push(char); + } + } + return output.join(""); + } + /** + * Normalizes the given text based on the configuration. + * @param {string} text The text to normalize. + * @returns {string} The normalized text. + */ + normalize(text) { + if (this.config.clean_text) { + text = this._clean_text(text); + } + if (this.config.handle_chinese_chars) { + text = this._tokenize_chinese_chars(text); + } + if (this.config.lowercase) { + text = text.toLowerCase(); + if (this.config.strip_accents !== false) { + text = this.stripAccents(text); + } + } else if (this.config.strip_accents) { + text = this.stripAccents(text); + } + return text; + } + } + class PreTokenizer extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { + /** + * Factory method that returns an instance of a subclass of `PreTokenizer` based on the provided configuration. + * + * @static + * @param {Object} config A configuration object for the pre-tokenizer. + * @returns {PreTokenizer} An instance of a subclass of `PreTokenizer`. + * @throws {Error} If the provided configuration object does not correspond to any known pre-tokenizer. + */ + static fromConfig(config) { + if (config === null) return null; + switch (config.type) { + case "BertPreTokenizer": + return new BertPreTokenizer(config); + case "Sequence": + return new PreTokenizerSequence(config); + case "Whitespace": + return new WhitespacePreTokenizer(config); + case "WhitespaceSplit": + return new WhitespaceSplit(config); + case "Metaspace": + return new MetaspacePreTokenizer(config); + case "ByteLevel": + return new ByteLevelPreTokenizer(config); + case "Split": + return new SplitPreTokenizer(config); + case "Punctuation": + return new PunctuationPreTokenizer(config); + case "Digits": + return new DigitsPreTokenizer(config); + case "Replace": + return new ReplacePreTokenizer(config); + case "FixedLength": + return new FixedLengthPreTokenizer(config); + default: + throw new Error(`Unknown PreTokenizer type: ${config.type}`); + } + } + /** + * Method that should be implemented by subclasses to define the specific pre-tokenization logic. + * + * @abstract + * @param {string} text The text to pre-tokenize. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} The pre-tokenized text. + * @throws {Error} If the method is not implemented in the subclass. + */ + pre_tokenize_text(text, options) { + throw Error("pre_tokenize_text should be implemented in subclass."); + } + /** + * Tokenizes the given text into pre-tokens. + * @param {string|string[]} text The text or array of texts to pre-tokenize. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} An array of pre-tokens. + */ + pre_tokenize(text, options) { + return (Array.isArray(text) ? text.map((x) => this.pre_tokenize_text(x, options)) : this.pre_tokenize_text(text, options)).flat(); + } + /** + * Alias for {@link PreTokenizer#pre_tokenize}. + * @param {string|string[]} text The text or array of texts to pre-tokenize. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} An array of pre-tokens. + */ + _call(text, options) { + return this.pre_tokenize(text, options); + } + } + class BertPreTokenizer extends PreTokenizer { + /** + * A PreTokenizer that splits text into wordpieces using a basic tokenization scheme + * similar to that used in the original implementation of BERT. + * + * @param {Object} config The configuration object. + */ + constructor(config) { + super(); + this.pattern = new RegExp(`[^\\s${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]`, "gu"); + } + /** + * Tokenizes a single text using the BERT pre-tokenization scheme. + * + * @param {string} text The text to tokenize. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} An array of tokens. + */ + pre_tokenize_text(text, options) { + return text.trim().match(this.pattern) || []; + } + } + class ByteLevelPreTokenizer extends PreTokenizer { + /** + * Creates a new instance of the `ByteLevelPreTokenizer` class. + * @param {Object} config The configuration object. + */ + constructor(config) { + super(); + this.config = config; + this.add_prefix_space = this.config.add_prefix_space; + this.trim_offsets = this.config.trim_offsets; + this.use_regex = this.config.use_regex ?? true; + this.pattern = /'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu; + this.byte_encoder = BYTES_TO_UNICODE; + this.text_encoder = new TextEncoder(); + } + /** + * Tokenizes a single piece of text using byte-level tokenization. + * @param {string} text The text to tokenize. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} An array of tokens. + */ + pre_tokenize_text(text, options) { + if (this.add_prefix_space && !text.startsWith(" ")) { + text = " " + text; + } + const tokens = this.use_regex ? text.match(this.pattern) || [] : [text]; + return tokens.map( + (token) => Array.from(this.text_encoder.encode(token), (byte) => this.byte_encoder[byte]).join("") + ); + } + } + class SplitPreTokenizer extends PreTokenizer { + /** + * @param {Object} config The configuration options for the pre-tokenizer. + * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object. + * @param {string|undefined} config.pattern.String The string to use for splitting. Only defined if the pattern is a string. + * @param {string|undefined} config.pattern.Regex The regex to use for splitting. Only defined if the pattern is a regex. + * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting. + * @param {boolean} config.invert Whether to split (invert=false) or match (invert=true) the pattern. + */ + constructor(config) { + super(); + this.config = config; + this.pattern = createPattern(this.config.pattern, this.config.invert); + } + /** + * Tokenizes text by splitting it using the given pattern. + * @param {string} text The text to tokenize. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} An array of tokens. + */ + pre_tokenize_text(text, options) { + if (this.pattern === null) { + return []; + } + if (this.config.invert) { + return text.match(this.pattern) || []; + } else if (this.config.behavior?.toLowerCase() === "removed") { + return text.split(this.pattern).filter((x) => x); + } else { + return regexSplit(text, this.pattern); + } + } + } + class PunctuationPreTokenizer extends PreTokenizer { + /** + * @param {Object} config The configuration options for the pre-tokenizer. + * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting. + */ + constructor(config) { + super(); + this.config = config; + this.pattern = new RegExp(`[^${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]+`, "gu"); + } + /** + * Tokenizes text by splitting it using the given pattern. + * @param {string} text The text to tokenize. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} An array of tokens. + */ + pre_tokenize_text(text, options) { + return text.match(this.pattern) || []; + } + } + class DigitsPreTokenizer extends PreTokenizer { + /** + * @param {Object} config The configuration options for the pre-tokenizer. + * @param {boolean} config.individual_digits Whether to split on individual digits. + */ + constructor(config) { + super(); + this.config = config; + const digit_pattern = `[^\\d]+|\\d${this.config.individual_digits ? "" : "+"}`; + this.pattern = new RegExp(digit_pattern, "gu"); + } + /** + * Tokenizes text by splitting it using the given pattern. + * @param {string} text The text to tokenize. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} An array of tokens. + */ + pre_tokenize_text(text, options) { + return text.match(this.pattern) || []; + } + } + class PostProcessor extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { + /** + * @param {Object} config The configuration for the post-processor. + */ + constructor(config) { + super(); + this.config = config; + } + /** + * Factory method to create a PostProcessor object from a configuration object. + * + * @param {Object} config Configuration object representing a PostProcessor. + * @returns {PostProcessor} A PostProcessor object created from the given configuration. + * @throws {Error} If an unknown PostProcessor type is encountered. + */ + static fromConfig(config) { + if (config === null) return null; + switch (config.type) { + case "TemplateProcessing": + return new TemplateProcessing(config); + case "ByteLevel": + return new ByteLevelPostProcessor(config); + case "RobertaProcessing": + return new RobertaProcessing(config); + case "BertProcessing": + return new BertProcessing(config); + case "Sequence": + return new PostProcessorSequence(config); + default: + throw new Error(`Unknown PostProcessor type: ${config.type}`); + } + } + /** + * Method to be implemented in subclass to apply post-processing on the given tokens. + * + * @param {Array} tokens The input tokens to be post-processed. + * @param {...*} args Additional arguments required by the post-processing logic. + * @returns {PostProcessedOutput} The post-processed tokens. + * @throws {Error} If the method is not implemented in subclass. + */ + post_process(tokens, ...args) { + throw Error("post_process should be implemented in subclass."); + } + /** + * Alias for {@link PostProcessor#post_process}. + * @param {Array} tokens The text or array of texts to post-process. + * @param {...*} args Additional arguments required by the post-processing logic. + * @returns {PostProcessedOutput} The post-processed tokens. + */ + _call(tokens, ...args) { + return this.post_process(tokens, ...args); + } + } + class BertProcessing extends PostProcessor { + /** + * @param {Object} config The configuration for the post-processor. + * @param {string[]} config.cls The special tokens to add to the beginning of the input. + * @param {string[]} config.sep The special tokens to add to the end of the input. + */ + constructor(config) { + super(config); + this.cls = config.cls[0]; + this.sep = config.sep[0]; + } + /** + * Adds the special tokens to the beginning and end of the input. + * @param {string[]} tokens The input tokens. + * @param {string[]} [tokens_pair=null] An optional second set of input tokens. + * @returns {PostProcessedOutput} The post-processed tokens with the special tokens added to the beginning and end. + */ + post_process(tokens, tokens_pair = null, { + add_special_tokens = true + } = {}) { + if (add_special_tokens) { + tokens = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)([this.cls], tokens, [this.sep]); + } + let token_type_ids = new Array(tokens.length).fill(0); + if (tokens_pair !== null) { + const middle = add_special_tokens && this instanceof RobertaProcessing ? [this.sep] : []; + const after = add_special_tokens ? [this.sep] : []; + tokens = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(tokens, middle, tokens_pair, after); + token_type_ids = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(token_type_ids, new Array(tokens_pair.length + middle.length + after.length).fill(1)); + } + return { tokens, token_type_ids }; + } + } + class RobertaProcessing extends BertProcessing { + } + class TemplateProcessing extends PostProcessor { + /** + * Creates a new instance of `TemplateProcessing`. + * @param {Object} config The configuration options for the post processor. + * @param {Array} config.single The template for a single sequence of tokens. + * @param {Array} config.pair The template for a pair of sequences of tokens. + */ + constructor(config) { + super(config); + this.single = config.single; + this.pair = config.pair; + } + /** + * Replaces special tokens in the template with actual tokens. + * @param {string[]} tokens The list of tokens for the first sequence. + * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional). + * @returns {PostProcessedOutput} An object containing the list of tokens with the special tokens replaced with actual tokens. + */ + post_process(tokens, tokens_pair = null, { + add_special_tokens = true + } = {}) { + const type = tokens_pair === null ? this.single : this.pair; + let processedTokens = []; + let types = []; + for (const item of type) { + if ("SpecialToken" in item) { + if (add_special_tokens) { + processedTokens.push(item.SpecialToken.id); + types.push(item.SpecialToken.type_id); + } + } else if ("Sequence" in item) { + if (item.Sequence.id === "A") { + processedTokens = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(processedTokens, tokens); + types = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(types, new Array(tokens.length).fill(item.Sequence.type_id)); + } else if (item.Sequence.id === "B") { + processedTokens = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(processedTokens, tokens_pair); + types = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(types, new Array(tokens_pair.length).fill(item.Sequence.type_id)); + } + } + } + return { tokens: processedTokens, token_type_ids: types }; + } + } + class ByteLevelPostProcessor extends PostProcessor { + /** + * Post process the given tokens. + * @param {string[]} tokens The list of tokens for the first sequence. + * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional). + * @returns {PostProcessedOutput} An object containing the post-processed tokens. + */ + post_process(tokens, tokens_pair = null) { + if (tokens_pair) { + tokens = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(tokens, tokens_pair); + } + return { tokens }; + } + } + class PostProcessorSequence extends PostProcessor { + /** + * Creates a new instance of PostProcessorSequence. + * @param {Object} config The configuration object. + * @param {Object[]} config.processors The list of post-processors to apply. + */ + constructor(config) { + super(config); + this.processors = config.processors.map((x) => PostProcessor.fromConfig(x)); + } + /** + * Post process the given tokens. + * @param {string[]} tokens The list of tokens for the first sequence. + * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional). + * @returns {PostProcessedOutput} An object containing the post-processed tokens. + */ + post_process(tokens, tokens_pair = null, options = {}) { + let token_type_ids; + for (const processor of this.processors) { + if (processor instanceof ByteLevelPostProcessor) { + const output = processor.post_process(tokens); + tokens = output.tokens; + if (tokens_pair) { + const pair_output = processor.post_process(tokens_pair); + tokens_pair = pair_output.tokens; + } + } else { + const output = processor.post_process(tokens, tokens_pair, options); + tokens = output.tokens; + token_type_ids = output.token_type_ids; + } + } + return { tokens, token_type_ids }; + } + } + class Decoder extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { + /** + * Creates an instance of `Decoder`. + * + * @param {Object} config The configuration object. + */ + constructor(config) { + super(); + this.config = config; + this.added_tokens = []; + this.end_of_word_suffix = null; + this.trim_offsets = config.trim_offsets; + } + /** + * Creates a decoder instance based on the provided configuration. + * + * @param {Object} config The configuration object. + * @returns {Decoder} A decoder instance. + * @throws {Error} If an unknown decoder type is provided. + */ + static fromConfig(config) { + if (config === null) return null; + switch (config.type) { + case "WordPiece": + return new WordPieceDecoder(config); + case "Metaspace": + return new MetaspaceDecoder(config); + case "ByteLevel": + return new ByteLevelDecoder(config); + case "Replace": + return new ReplaceDecoder(config); + case "ByteFallback": + return new ByteFallback(config); + case "Fuse": + return new FuseDecoder(config); + case "Strip": + return new StripDecoder(config); + case "Sequence": + return new DecoderSequence(config); + case "CTC": + return new CTCDecoder(config); + case "BPEDecoder": + return new BPEDecoder(config); + default: + throw new Error(`Unknown Decoder type: ${config.type}`); + } + } + /** + * Calls the `decode` method. + * + * @param {string[]} tokens The list of tokens. + * @returns {string} The decoded string. + */ + _call(tokens) { + return this.decode(tokens); + } + /** + * Decodes a list of tokens. + * @param {string[]} tokens The list of tokens. + * @returns {string} The decoded string. + */ + decode(tokens) { + return this.decode_chain(tokens).join(""); + } + /** + * Apply the decoder to a list of tokens. + * + * @param {string[]} tokens The list of tokens. + * @returns {string[]} The decoded list of tokens. + * @throws {Error} If the `decode_chain` method is not implemented in the subclass. + */ + decode_chain(tokens) { + throw Error("`decode_chain` should be implemented in subclass."); + } + } + class ReplaceDecoder extends Decoder { + /** @type {Decoder['decode_chain']} */ + decode_chain(tokens) { + const pattern = createPattern(this.config.pattern); + return pattern === null ? tokens : tokens.map((token) => token.replaceAll(pattern, this.config.content)); + } + } + class ByteFallback extends Decoder { + constructor(config) { + super(config); + this.text_decoder = new TextDecoder(); + } + /** @type {Decoder['decode_chain']} */ + decode_chain(tokens) { + const new_tokens = []; + let previous_byte_tokens = []; + for (const token of tokens) { + let bytes = null; + if (token.length === 6 && token.startsWith("<0x") && token.endsWith(">")) { + const byte = parseInt(token.slice(3, 5), 16); + if (!isNaN(byte)) { + bytes = byte; + } + } + if (bytes !== null) { + previous_byte_tokens.push(bytes); + } else { + if (previous_byte_tokens.length > 0) { + const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens)); + new_tokens.push(string); + previous_byte_tokens = []; + } + new_tokens.push(token); + } + } + if (previous_byte_tokens.length > 0) { + const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens)); + new_tokens.push(string); + previous_byte_tokens = []; + } + return new_tokens; + } + } + class FuseDecoder extends Decoder { + /** @type {Decoder['decode_chain']} */ + decode_chain(tokens) { + return [tokens.join("")]; + } + } + class StripDecoder extends Decoder { + constructor(config) { + super(config); + this.content = this.config.content; + this.start = this.config.start; + this.stop = this.config.stop; + } + /** @type {Decoder['decode_chain']} */ + decode_chain(tokens) { + return tokens.map((token) => { + let start_cut = 0; + for (let i = 0; i < this.start; ++i) { + if (token[i] === this.content) { + start_cut = i + 1; + continue; + } else { + break; + } + } + let stop_cut = token.length; + for (let i = 0; i < this.stop; ++i) { + const index = token.length - i - 1; + if (token[index] === this.content) { + stop_cut = index; + continue; + } else { + break; + } + } + return token.slice(start_cut, stop_cut); + }); + } + } + class WordPieceDecoder extends Decoder { + /** + * Creates a new instance of WordPieceDecoder. + * @param {Object} config The configuration object. + * @param {string} config.prefix The prefix used for WordPiece encoding. + * @param {boolean} config.cleanup Whether to cleanup the decoded string. + */ + constructor(config) { + super(config); + this.cleanup = config.cleanup; + } + /** @type {Decoder['decode_chain']} */ + decode_chain(tokens) { + return tokens.map((token, i) => { + if (i !== 0) { + if (token.startsWith(this.config.prefix)) { + token = token.replace(this.config.prefix, ""); + } else { + token = " " + token; + } + } + if (this.cleanup) { + token = clean_up_tokenization(token); + } + return token; + }); + } + } + class ByteLevelDecoder extends Decoder { + /** + * Create a `ByteLevelDecoder` object. + * @param {Object} config Configuration object. + */ + constructor(config) { + super(config); + this.byte_decoder = UNICODE_TO_BYTES; + this.text_decoder = new TextDecoder("utf-8", { + fatal: false, + ignoreBOM: true + }); + this.end_of_word_suffix = null; + } + /** + * Convert an array of tokens to string by decoding each byte. + * @param {string[]} tokens Array of tokens to be decoded. + * @returns {string} The decoded string. + */ + convert_tokens_to_string(tokens) { + const text = tokens.join(""); + const byteArray = new Uint8Array([...text].map((c) => this.byte_decoder[c])); + const decoded_text = this.text_decoder.decode(byteArray); + return decoded_text; + } + /** @type {Decoder['decode_chain']} */ + decode_chain(tokens) { + const sub_texts = []; + let current_sub_text = []; + for (const token of tokens) { + if (this.added_tokens.find((x) => x.content === token) !== void 0) { + if (current_sub_text.length > 0) { + sub_texts.push(this.convert_tokens_to_string(current_sub_text)); + current_sub_text = []; + } + sub_texts.push(token); + } else { + current_sub_text.push(token); + } + } + if (current_sub_text.length > 0) { + sub_texts.push(this.convert_tokens_to_string(current_sub_text)); + } + return sub_texts; + } + } + class CTCDecoder extends Decoder { + constructor(config) { + super(config); + this.pad_token = this.config.pad_token; + this.word_delimiter_token = this.config.word_delimiter_token; + this.cleanup = this.config.cleanup; + } + /** + * Converts a connectionist-temporal-classification (CTC) output tokens into a single string. + * @param {string[]} tokens Array of tokens to be decoded. + * @returns {string} The decoded string. + */ + convert_tokens_to_string(tokens) { + if (tokens.length === 0) return ""; + const grouped_tokens = [tokens[0]]; + for (let i = 1; i < tokens.length; ++i) { + if (tokens[i] !== grouped_tokens.at(-1)) { + grouped_tokens.push(tokens[i]); + } + } + const filtered_tokens = grouped_tokens.filter((token) => token !== this.pad_token); + let text = filtered_tokens.join(""); + if (this.cleanup) { + text = clean_up_tokenization(text).replaceAll(this.word_delimiter_token, " ").trim(); + } + return text; + } + /** @type {Decoder['decode_chain']} */ + decode_chain(tokens) { + return [this.convert_tokens_to_string(tokens)]; + } + } + class DecoderSequence extends Decoder { + /** + * Creates a new instance of DecoderSequence. + * @param {Object} config The configuration object. + * @param {Object[]} config.decoders The list of decoders to apply. + */ + constructor(config) { + super(config); + this.decoders = config.decoders.map((x) => Decoder.fromConfig(x)); + } + /** @type {Decoder['decode_chain']} */ + decode_chain(tokens) { + return this.decoders.reduce((toks, decoder) => { + return decoder.decode_chain(toks); + }, tokens); + } + } + class BPEDecoder extends Decoder { + constructor(config) { + super(config); + this.suffix = this.config.suffix; + } + /** @type {Decoder['decode_chain']} */ + decode_chain(tokens) { + return tokens.map((token, i) => { + return token.replaceAll(this.suffix, i === tokens.length - 1 ? "" : " "); + }); + } + } + class VitsDecoder extends Decoder { + /** @type {Decoder['decode_chain']} */ + decode_chain(tokens) { + let decoded = ""; + for (let i = 1; i < tokens.length; i += 2) { + decoded += tokens[i]; + } + return [decoded]; + } + } + class MetaspacePreTokenizer extends PreTokenizer { + /** + * @param {Object} config The configuration object for the MetaspacePreTokenizer. + * @param {string} config.replacement The character to replace spaces with. + * @param {string} [config.str_rep=config.replacement] An optional string representation of the replacement character. + * @param {'first'|'never'|'always'} [config.prepend_scheme='always'] The metaspace prepending scheme. + */ + constructor(config) { + super(); + this.replacement = config.replacement; + this.strRep = config.str_rep || this.replacement; + this.prepend_scheme = config.prepend_scheme ?? "always"; + } + /** + * This method takes a string, replaces spaces with the replacement character, + * adds a prefix space if requested, and returns a new list of tokens. + * @param {string} text The text to pre-tokenize. + * @param {Object} [options] The options for the pre-tokenization. + * @param {number} [options.section_index] The index of the section to pre-tokenize. + * @returns {string[]} A new list of pre-tokenized tokens. + */ + pre_tokenize_text(text, { + section_index = void 0 + } = {}) { + let normalized = text.replaceAll(" ", this.strRep); + if ( + // We add a prefix space if: + // (1) The normalized token does not already start with the replacement character. + !normalized.startsWith(this.replacement) && (this.prepend_scheme === "always" || this.prepend_scheme === "first" && section_index === 0) + ) { + normalized = this.strRep + normalized; + } + return [normalized]; + } + } + class MetaspaceDecoder extends Decoder { + /** + * Constructs a new MetaspaceDecoder object. + * @param {Object} config The configuration object for the MetaspaceDecoder. + * @param {string} config.replacement The string to replace spaces with. + */ + constructor(config) { + super(config); + this.replacement = config.replacement; + } + /** @type {Decoder['decode_chain']} */ + decode_chain(tokens) { + const result = []; + for (let i = 0; i < tokens.length; ++i) { + let normalized = tokens[i].replaceAll(this.replacement, " "); + if (i == 0 && normalized.startsWith(" ")) { + normalized = normalized.substring(1); + } + result.push(normalized); + } + return result; + } + } + class Precompiled extends Normalizer { + /** + * Create a new instance of Precompiled normalizer. + * @param {Object} config The configuration object. + * @param {any} config.precompiled_charsmap Precompiled chars mapping. + */ + constructor(config) { + super(config); + this.charsmap = config.precompiled_charsmap; + } + /** + * Normalizes the given text by applying the precompiled charsmap. + * @param {string} text The text to normalize. + * @returns {string} The normalized text. + */ + normalize(text) { + text = text.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm, ""); + text = text.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm, " "); + if (text.includes("\uFF5E")) { + const parts = text.split("\uFF5E"); + text = parts.map((part) => part.normalize("NFKC")).join("\uFF5E"); + } else { + text = text.normalize("NFKC"); + } + return text; + } + } + class PreTokenizerSequence extends PreTokenizer { + /** + * Creates an instance of PreTokenizerSequence. + * @param {Object} config The configuration object for the pre-tokenizer sequence. + * @param {Object[]} config.pretokenizers An array of pre-tokenizer configurations. + */ + constructor(config) { + super(); + this.tokenizers = config.pretokenizers.map((x) => PreTokenizer.fromConfig(x)); + } + /** + * Applies each pre-tokenizer in the sequence to the input text in turn. + * @param {string} text The text to pre-tokenize. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} The pre-tokenized text. + */ + pre_tokenize_text(text, options) { + return this.tokenizers.reduce((preTokenizedText, tokenizer) => { + return tokenizer.pre_tokenize(preTokenizedText, options); + }, [text]); + } + } + class WhitespacePreTokenizer extends PreTokenizer { + /** + * Creates an instance of WhitespacePreTokenizer. + * @param {Object} config The configuration object for the pre-tokenizer. + */ + constructor(config) { + super(); + } + /** + * Pre-tokenizes the input text by splitting it on word boundaries. + * @param {string} text The text to be pre-tokenized. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} An array of tokens produced by splitting the input text on whitespace. + */ + pre_tokenize_text(text, options) { + return text.match(/\w+|[^\w\s]+/g) || []; + } + } + class WhitespaceSplit extends PreTokenizer { + /** + * Creates an instance of WhitespaceSplit. + * @param {Object} config The configuration object for the pre-tokenizer. + */ + constructor(config) { + super(); + } + /** + * Pre-tokenizes the input text by splitting it on whitespace characters. + * @param {string} text The text to be pre-tokenized. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} An array of tokens produced by splitting the input text on whitespace. + */ + pre_tokenize_text(text, options) { + return whitespace_split(text); + } + } + class ReplacePreTokenizer extends PreTokenizer { + /** + * @param {Object} config The configuration options for the pre-tokenizer. + * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object. + * @param {string} config.content What to replace the pattern with. + */ + constructor(config) { + super(); + this.config = config; + this.pattern = createPattern(this.config.pattern); + this.content = this.config.content; + } + /** + * Pre-tokenizes the input text by replacing certain characters. + * @param {string} text The text to be pre-tokenized. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} An array of tokens produced by replacing certain characters. + */ + pre_tokenize_text(text, options) { + if (this.pattern === null) { + return [text]; + } + return [text.replaceAll(this.pattern, this.config.content)]; + } + } + class FixedLengthPreTokenizer extends PreTokenizer { + /** + * @param {Object} config The configuration options for the pre-tokenizer. + * @param {number} config.length The fixed length to split the text into. + */ + constructor(config) { + super(); + this._length = config.length; + } + /** + * Pre-tokenizes the input text by splitting it into fixed-length tokens. + * @param {string} text The text to be pre-tokenized. + * @param {Object} [options] Additional options for the pre-tokenization logic. + * @returns {string[]} An array of tokens produced by splitting the input text into fixed-length tokens. + */ + pre_tokenize_text(text, options) { + const tokens = []; + for (let i = 0; i < text.length; i += this._length) { + tokens.push(text.slice(i, i + this._length)); + } + return tokens; + } + } + const SPECIAL_TOKEN_ATTRIBUTES = [ + "bos_token", + "eos_token", + "unk_token", + "sep_token", + "pad_token", + "cls_token", + "mask_token" + // additional_special_tokens (TODO) + ]; + function padHelper(item, length, value_fn, side) { + for (const key of Object.keys(item)) { + const diff = length - item[key].length; + const value = value_fn(key); + const padData = new Array(diff).fill(value); + item[key] = side === "right" ? (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(item[key], padData) : (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(padData, item[key]); + } + } + function truncateHelper(item, length) { + for (const key of Object.keys(item)) { + item[key].length = length; + } + } + class PreTrainedTokenizer extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { + return_token_type_ids = false; + padding_side = "right"; + /** + * Create a new PreTrainedTokenizer instance. + * @param {Object} tokenizerJSON The JSON of the tokenizer. + * @param {Object} tokenizerConfig The config of the tokenizer. + */ + constructor(tokenizerJSON, tokenizerConfig) { + super(); + this.config = tokenizerConfig; + this.normalizer = Normalizer.fromConfig(tokenizerJSON.normalizer); + this.pre_tokenizer = PreTokenizer.fromConfig(tokenizerJSON.pre_tokenizer); + this.model = TokenizerModel.fromConfig(tokenizerJSON.model, tokenizerConfig); + this.post_processor = PostProcessor.fromConfig(tokenizerJSON.post_processor); + this.decoder = Decoder.fromConfig(tokenizerJSON.decoder); + this.special_tokens = []; + this.all_special_ids = []; + this.added_tokens = []; + for (const addedToken of tokenizerJSON.added_tokens) { + const token = new AddedToken(addedToken); + this.added_tokens.push(token); + this.model.tokens_to_ids.set(token.content, token.id); + this.model.vocab[token.id] = token.content; + if (token.special) { + this.special_tokens.push(token.content); + this.all_special_ids.push(token.id); + } + } + this.additional_special_tokens = tokenizerConfig.additional_special_tokens ?? []; + this.special_tokens.push(...this.additional_special_tokens); + this.special_tokens = [...new Set(this.special_tokens)]; + if (this.decoder) { + this.decoder.added_tokens = this.added_tokens; + this.decoder.end_of_word_suffix = this.model.end_of_word_suffix; + } + this.added_tokens_splitter = new _utils_data_structures_js__WEBPACK_IMPORTED_MODULE_5__.DictionarySplitter( + this.added_tokens.map((x) => x.content) + ); + this.added_tokens_map = new Map(this.added_tokens.map((x) => [x.content, x])); + this.mask_token = this.getToken("mask_token"); + this.mask_token_id = this.model.tokens_to_ids.get(this.mask_token); + this.pad_token = this.getToken("pad_token", "eos_token"); + this.pad_token_id = this.model.tokens_to_ids.get(this.pad_token); + this.sep_token = this.getToken("sep_token"); + this.sep_token_id = this.model.tokens_to_ids.get(this.sep_token); + this.unk_token = this.getToken("unk_token"); + this.unk_token_id = this.model.tokens_to_ids.get(this.unk_token); + this.bos_token = this.getToken("bos_token"); + this.bos_token_id = this.model.tokens_to_ids.get(this.bos_token); + this.eos_token = this.getToken("eos_token"); + this.eos_token_id = this.model.tokens_to_ids.get(this.eos_token); + this.model_max_length = tokenizerConfig.model_max_length; + this.remove_space = tokenizerConfig.remove_space; + this.clean_up_tokenization_spaces = tokenizerConfig.clean_up_tokenization_spaces ?? true; + this.do_lowercase_and_remove_accent = tokenizerConfig.do_lowercase_and_remove_accent ?? false; + if (tokenizerConfig.padding_side) { + this.padding_side = tokenizerConfig.padding_side; + } + this.add_bos_token = tokenizerConfig.add_bos_token; + this.add_eos_token = tokenizerConfig.add_eos_token; + this.legacy = false; + this.chat_template = tokenizerConfig.chat_template ?? null; + if (Array.isArray(this.chat_template)) { + const chat_template = /* @__PURE__ */ Object.create(null); + for (const { name, template } of this.chat_template) { + if (typeof name !== "string" || typeof template !== "string") { + throw new Error('Chat template must be a list of objects with "name" and "template" properties'); + } + chat_template[name] = template; + } + this.chat_template = chat_template; + } + this._compiled_template_cache = /* @__PURE__ */ new Map(); + } + /** + * Returns the value of the first matching key in the tokenizer config object. + * @param {...string} keys One or more keys to search for in the tokenizer config object. + * @returns {string|null} The value associated with the first matching key, or null if no match is found. + * @throws {Error} If an object is found for a matching key and its __type property is not "AddedToken". + * @private + */ + getToken(...keys) { + for (const key of keys) { + const item = this.config[key]; + if (!item) continue; + if (typeof item === "object") { + if (item.__type === "AddedToken") { + return item.content; + } else { + throw Error(`Unknown token: ${item}`); + } + } else { + return item; + } + } + return null; + } + /** + * Loads a pre-trained tokenizer from the given `pretrained_model_name_or_path`. + * + * @param {string} pretrained_model_name_or_path The path to the pre-trained tokenizer. + * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer. + * + * @throws {Error} Throws an error if the tokenizer.json or tokenizer_config.json files are not found in the `pretrained_model_name_or_path`. + * @returns {Promise} A new instance of the `PreTrainedTokenizer` class. + */ + static async from_pretrained(pretrained_model_name_or_path, { + progress_callback = null, + config = null, + cache_dir = null, + local_files_only = false, + revision = "main", + legacy = null + } = {}) { + const info = await loadTokenizer(pretrained_model_name_or_path, { + progress_callback, + config, + cache_dir, + local_files_only, + revision, + legacy + }); + return new this(...info); + } + /** + * @typedef {number[]|number[][]|Tensor} BatchEncodingItem + * + * @typedef {Object} BatchEncoding Holds the output of the tokenizer's call function. + * @property {BatchEncodingItem} input_ids List of token ids to be fed to a model. + * @property {BatchEncodingItem} attention_mask List of indices specifying which tokens should be attended to by the model. + * @property {BatchEncodingItem} [token_type_ids] List of token type ids to be fed to a model. + */ + /** + * Encode/tokenize the given text(s). + * @param {string|string[]} text The text to tokenize. + * @param {Object} options An optional object containing the following properties: + * @param {string|string[]} [options.text_pair=null] Optional second sequence to be encoded. If set, must be the same type as text. + * @param {boolean|'max_length'} [options.padding=false] Whether to pad the input sequences. + * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model. + * @param {boolean} [options.truncation=null] Whether to truncate the input sequences. + * @param {number} [options.max_length=null] Maximum length of the returned list and optionally padding length. + * @param {boolean} [options.return_tensor=true] Whether to return the results as Tensors or arrays. + * @param {boolean} [options.return_token_type_ids=null] Whether to return the token type ids. + * @returns {BatchEncoding} Object to be passed to the model. + */ + _call(text, { + text_pair = null, + add_special_tokens = true, + padding = false, + truncation = null, + max_length = null, + return_tensor = true, + // Different to HF + return_token_type_ids = null + } = {}) { + const isBatched = Array.isArray(text); + let encodedTokens; + if (isBatched) { + if (text.length === 0) { + throw Error("text array must be non-empty"); + } + if (text_pair !== null) { + if (!Array.isArray(text_pair)) { + throw Error("text_pair must also be an array"); + } else if (text.length !== text_pair.length) { + throw Error("text and text_pair must have the same length"); + } + encodedTokens = text.map( + (t, i) => this._encode_plus(t, { text_pair: text_pair[i], add_special_tokens, return_token_type_ids }) + ); + } else { + encodedTokens = text.map((x) => this._encode_plus(x, { add_special_tokens, return_token_type_ids })); + } + } else { + if (text === null || text === void 0) { + throw Error("text may not be null or undefined"); + } + if (Array.isArray(text_pair)) { + throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array)."); + } + encodedTokens = [this._encode_plus(text, { text_pair, add_special_tokens, return_token_type_ids })]; + } + if (max_length === null) { + max_length = this.model_max_length; + } else if (truncation === null) { + if (padding === true) { + console.warn( + "`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`." + ); + max_length = this.model_max_length; + } else if (padding === false) { + console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."); + truncation = true; + } + } + if (padding === true) { + max_length = Math.min((0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_3__.max)(encodedTokens.map((x) => x.input_ids.length))[0], max_length ?? Infinity); + } + max_length = Math.min(max_length, this.model_max_length ?? Infinity); + if (padding || truncation) { + for (let i = 0; i < encodedTokens.length; ++i) { + if (encodedTokens[i].input_ids.length === max_length) { + continue; + } else if (encodedTokens[i].input_ids.length > max_length) { + if (truncation) { + truncateHelper(encodedTokens[i], max_length); + } + } else { + if (padding) { + padHelper( + encodedTokens[i], + max_length, + (key) => key === "input_ids" ? this.pad_token_id : 0, + this.padding_side + ); + } + } + } + } + const result = {}; + if (return_tensor) { + if (!(padding && truncation)) { + if (encodedTokens.some((x) => { + for (const key of Object.keys(x)) { + if (x[key].length !== encodedTokens[0][key]?.length) { + return true; + } + } + return false; + })) { + throw Error( + "Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length." + ); + } + } + const dims = [encodedTokens.length, encodedTokens[0].input_ids.length]; + for (const key of Object.keys(encodedTokens[0])) { + result[key] = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor( + "int64", + BigInt64Array.from(encodedTokens.flatMap((x) => x[key]).map(BigInt)), + dims + ); + } + } else { + for (const key of Object.keys(encodedTokens[0])) { + result[key] = encodedTokens.map((x) => x[key]); + } + if (!isBatched) { + for (const key of Object.keys(result)) { + result[key] = result[key][0]; + } + } + } + return ( + /** @type {BatchEncoding} */ + result + ); + } + /** + * Encodes a single text using the preprocessor pipeline of the tokenizer. + * + * @param {string|null} text The text to encode. + * @returns {string[]|null} The encoded tokens. + */ + _encode_text(text) { + if (text === null) return null; + const sections = this.added_tokens_splitter.split(text); + for (let i = 0; i < sections.length; ++i) { + const addedToken = this.added_tokens_map.get(sections[i]); + if (addedToken) { + if (addedToken.lstrip && i > 0) { + sections[i - 1] = sections[i - 1].trimEnd(); + } + if (addedToken.rstrip && i < sections.length - 1) { + sections[i + 1] = sections[i + 1].trimStart(); + } + } + } + const tokens = sections.flatMap((x, section_index) => { + if (x.length === 0) return []; + if (this.added_tokens_map.has(x)) return [x]; + if (this.remove_space === true) { + x = x.trim().split(/\s+/).join(" "); + } + if (this.do_lowercase_and_remove_accent) { + x = lowercase_and_remove_accent(x); + } + if (this.normalizer !== null) { + x = this.normalizer(x); + } + if (x.length === 0) { + return []; + } + const sectionTokens = this.pre_tokenizer !== null ? this.pre_tokenizer(x, { + section_index + }) : [x]; + const tokens2 = this.model(sectionTokens); + return tokens2; + }); + return tokens; + } + /** + * Encodes a single text or a pair of texts using the model's tokenizer. + * + * @param {string} text The text to encode. + * @param {Object} options An optional object containing the following properties: + * @param {string} [options.text_pair=null] The optional second text to encode. + * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model. + * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids. + * @returns {EncodingSingle} An object containing the encoded text. + * @private + */ + _encode_plus(text, { + text_pair = null, + add_special_tokens = true, + return_token_type_ids = null + } = {}) { + const { tokens, token_type_ids } = this._tokenize_helper(text, { pair: text_pair, add_special_tokens }); + const input_ids = this.model.convert_tokens_to_ids(tokens); + const result = { + input_ids, + attention_mask: new Array(input_ids.length).fill(1) + }; + if ((return_token_type_ids ?? this.return_token_type_ids) && token_type_ids) { + result.token_type_ids = token_type_ids; + } + return result; + } + /** + * Internal helper function to tokenize a text, and optionally a pair of texts. + * @param {string} text The text to tokenize. + * @param {Object} options An optional object containing the following properties: + * @param {string} [options.pair=null] The optional second text to tokenize. + * @param {boolean} [options.add_special_tokens=false] Whether or not to add the special tokens associated with the corresponding model. + * @returns {{tokens: string[], token_type_ids?: number[]}} An object containing the tokens and optionally the token type IDs. + */ + _tokenize_helper(text, { + pair = null, + add_special_tokens = false + } = {}) { + const tokens = this._encode_text(text); + const tokens2 = this._encode_text(pair); + return this.post_processor ? this.post_processor(tokens, tokens2, { add_special_tokens }) : { tokens: (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(tokens ?? [], tokens2 ?? []) }; + } + /** + * Converts a string into a sequence of tokens. + * @param {string} text The sequence to be encoded. + * @param {Object} options An optional object containing the following properties: + * @param {string} [options.pair] A second sequence to be encoded with the first. + * @param {boolean} [options.add_special_tokens=false] Whether or not to add the special tokens associated with the corresponding model. + * @returns {string[]} The list of tokens. + */ + tokenize(text, { + pair = null, + add_special_tokens = false + } = {}) { + return this._tokenize_helper(text, { pair, add_special_tokens }).tokens; + } + /** + * Encodes a single text or a pair of texts using the model's tokenizer. + * + * @param {string} text The text to encode. + * @param {Object} options An optional object containing the following properties: + * @param {string} [options.text_pair=null] The optional second text to encode. + * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model. + * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids. + * @returns {number[]} An array of token IDs representing the encoded text(s). + */ + encode(text, { + text_pair = null, + add_special_tokens = true, + return_token_type_ids = null + } = {}) { + return this._encode_plus(text, { + text_pair, + add_special_tokens, + return_token_type_ids + }).input_ids; + } + /** + * Decode a batch of tokenized sequences. + * @param {number[][]|Tensor} batch List/Tensor of tokenized input sequences. + * @param {Object} decode_args (Optional) Object with decoding arguments. + * @returns {string[]} List of decoded sequences. + */ + batch_decode(batch, decode_args = {}) { + if (batch instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor) { + batch = batch.tolist(); + } + return batch.map((x) => this.decode(x, decode_args)); + } + /** + * Decodes a sequence of token IDs back to a string. + * + * @param {number[]|bigint[]|Tensor} token_ids List/Tensor of token IDs to decode. + * @param {Object} [decode_args={}] + * @param {boolean} [decode_args.skip_special_tokens=false] If true, special tokens are removed from the output string. + * @param {boolean} [decode_args.clean_up_tokenization_spaces=true] If true, spaces before punctuations and abbreviated forms are removed. + * + * @returns {string} The decoded string. + * @throws {Error} If `token_ids` is not a non-empty array of integers. + */ + decode(token_ids, decode_args = {}) { + if (token_ids instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor) { + token_ids = prepareTensorForDecode(token_ids); + } + if (!Array.isArray(token_ids) || token_ids.length === 0 || !(0, _utils_core_js__WEBPACK_IMPORTED_MODULE_1__.isIntegralNumber)(token_ids[0])) { + throw Error("token_ids must be a non-empty array of integers."); + } + return this.decode_single(token_ids, decode_args); + } + /** + * Decode a single list of token ids to a string. + * @param {number[]|bigint[]} token_ids List of token ids to decode + * @param {Object} decode_args Optional arguments for decoding + * @param {boolean} [decode_args.skip_special_tokens=false] Whether to skip special tokens during decoding + * @param {boolean} [decode_args.clean_up_tokenization_spaces=null] Whether to clean up tokenization spaces during decoding. + * If null, the value is set to `this.decoder.cleanup` if it exists, falling back to `this.clean_up_tokenization_spaces` if it exists, falling back to `true`. + * @returns {string} The decoded string + */ + decode_single(token_ids, { + skip_special_tokens = false, + clean_up_tokenization_spaces = null + }) { + let tokens = this.model.convert_ids_to_tokens(token_ids); + if (skip_special_tokens) { + tokens = tokens.filter((x) => !this.special_tokens.includes(x)); + } + let decoded = this.decoder ? this.decoder(tokens) : tokens.join(" "); + if (this.decoder && this.decoder.end_of_word_suffix) { + decoded = decoded.replaceAll(this.decoder.end_of_word_suffix, " "); + if (skip_special_tokens) { + decoded = decoded.trim(); + } + } + if (clean_up_tokenization_spaces ?? this.clean_up_tokenization_spaces) { + decoded = clean_up_tokenization(decoded); + } + return decoded; + } + /** + * Retrieve the chat template string used for tokenizing chat messages. This template is used + * internally by the `apply_chat_template` method and can also be used externally to retrieve the model's chat + * template for better generation tracking. + * + * @param {Object} options An optional object containing the following properties: + * @param {string} [options.chat_template=null] + * A Jinja template or the name of a template to use for this conversion. + * It is usually not necessary to pass anything to this argument, + * as the model's template will be used by default. + * @param {Object[]} [options.tools=null] + * A list of tools (callable functions) that will be accessible to the model. If the template does not + * support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema, + * giving the name, description and argument types for the tool. See our + * [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use) + * for more information. + * @returns {string} The chat template string. + */ + get_chat_template({ + chat_template = null, + tools = null + } = {}) { + if (this.chat_template && typeof this.chat_template === "object") { + const template_dict = this.chat_template; + if (chat_template !== null && Object.hasOwn(template_dict, chat_template)) { + chat_template = template_dict[chat_template]; + } else if (chat_template === null) { + if (tools !== null && "tool_use" in template_dict) { + chat_template = template_dict["tool_use"]; + } else if ("default" in template_dict) { + chat_template = template_dict["default"]; + } else { + throw Error( + `This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(template_dict).sort()}.` + ); + } + } + } else if (chat_template === null) { + if (this.chat_template) { + chat_template = this.chat_template; + } else { + throw Error( + "Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating" + ); + } + } + return chat_template; + } + /** + * Converts a list of message objects with `"role"` and `"content"` keys to a list of token + * ids. This method is intended for use with chat models, and will read the tokenizer's chat_template attribute to + * determine the format and control tokens to use when converting. + * + * See [here](https://huggingface.co/docs/transformers/chat_templating) for more information. + * + * **Example:** Applying a chat template to a conversation. + * + * ```javascript + * import { AutoTokenizer } from "@huggingface/transformers"; + * + * const tokenizer = await AutoTokenizer.from_pretrained("Xenova/mistral-tokenizer-v1"); + * + * const chat = [ + * { "role": "user", "content": "Hello, how are you?" }, + * { "role": "assistant", "content": "I'm doing great. How can I help you today?" }, + * { "role": "user", "content": "I'd like to show off how chat templating works!" }, + * ] + * + * const text = tokenizer.apply_chat_template(chat, { tokenize: false }); + * // "[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today? [INST] I'd like to show off how chat templating works! [/INST]" + * + * const input_ids = tokenizer.apply_chat_template(chat, { tokenize: true, return_tensor: false }); + * // [1, 733, 16289, 28793, 22557, 28725, 910, 460, 368, 28804, 733, 28748, 16289, 28793, 28737, 28742, 28719, 2548, 1598, 28723, 1602, 541, 315, 1316, 368, 3154, 28804, 2, 28705, 733, 16289, 28793, 315, 28742, 28715, 737, 298, 1347, 805, 910, 10706, 5752, 1077, 3791, 28808, 733, 28748, 16289, 28793] + * ``` + * + * @param {Message[]} conversation A list of message objects with `"role"` and `"content"` keys, + * representing the chat history so far. + * @param {Object} options An optional object containing the following properties: + * @param {string} [options.chat_template=null] A Jinja template to use for this conversion. If + * this is not passed, the model's chat template will be used instead. + * @param {Object[]} [options.tools=null] + * A list of tools (callable functions) that will be accessible to the model. If the template does not + * support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema, + * giving the name, description and argument types for the tool. See our + * [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use) + * for more information. + * @param {Record[]} [options.documents=null] + * A list of dicts representing documents that will be accessible to the model if it is performing RAG + * (retrieval-augmented generation). If the template does not support RAG, this argument will have no + * effect. We recommend that each document should be a dict containing "title" and "text" keys. Please + * see the RAG section of the [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#arguments-for-RAG) + * for examples of passing documents with chat templates. + * @param {boolean} [options.add_generation_prompt=false] Whether to end the prompt with the token(s) that indicate + * the start of an assistant message. This is useful when you want to generate a response from the model. + * Note that this argument will be passed to the chat template, and so it must be supported in the + * template for this argument to have any effect. + * @param {boolean} [options.tokenize=true] Whether to tokenize the output. If false, the output will be a string. + * @param {boolean} [options.padding=false] Whether to pad sequences to the maximum length. Has no effect if tokenize is false. + * @param {boolean} [options.truncation=false] Whether to truncate sequences to the maximum length. Has no effect if tokenize is false. + * @param {number} [options.max_length=null] Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is false. + * If not specified, the tokenizer's `max_length` attribute will be used as a default. + * @param {boolean} [options.return_tensor=true] Whether to return the output as a Tensor or an Array. Has no effect if tokenize is false. + * @param {boolean} [options.return_dict=true] Whether to return a dictionary with named outputs. Has no effect if tokenize is false. + * @param {Object} [options.tokenizer_kwargs={}] Additional options to pass to the tokenizer. + * @returns {string | Tensor | number[]| number[][]|BatchEncoding} The tokenized output. + */ + apply_chat_template(conversation, { + tools = null, + documents = null, + chat_template = null, + add_generation_prompt = false, + tokenize = true, + padding = false, + truncation = false, + max_length = null, + return_tensor = true, + return_dict = false, + tokenizer_kwargs = {}, + ...kwargs + } = {}) { + chat_template = this.get_chat_template({ chat_template, tools }); + if (typeof chat_template !== "string") { + throw Error(`chat_template must be a string, but got ${typeof chat_template}`); + } + let compiledTemplate = this._compiled_template_cache.get(chat_template); + if (compiledTemplate === void 0) { + compiledTemplate = new _huggingface_jinja__WEBPACK_IMPORTED_MODULE_6__.Template(chat_template); + this._compiled_template_cache.set(chat_template, compiledTemplate); + } + const special_tokens_map = /* @__PURE__ */ Object.create(null); + for (const key of SPECIAL_TOKEN_ATTRIBUTES) { + const value = this.getToken(key); + if (value) { + special_tokens_map[key] = value; + } + } + const rendered = compiledTemplate.render({ + messages: conversation, + add_generation_prompt, + tools, + documents, + ...special_tokens_map, + ...kwargs + }); + if (tokenize) { + const out = this._call(rendered, { + add_special_tokens: false, + padding, + truncation, + max_length, + return_tensor, + ...tokenizer_kwargs + }); + return return_dict ? out : out.input_ids; + } + return rendered; + } + } + class BertTokenizer extends PreTrainedTokenizer { + return_token_type_ids = true; + } + class AlbertTokenizer extends PreTrainedTokenizer { + return_token_type_ids = true; + } + class MobileBertTokenizer extends PreTrainedTokenizer { + return_token_type_ids = true; + } + class SqueezeBertTokenizer extends PreTrainedTokenizer { + return_token_type_ids = true; + } + class DebertaTokenizer extends PreTrainedTokenizer { + return_token_type_ids = true; + } + class DebertaV2Tokenizer extends PreTrainedTokenizer { + return_token_type_ids = true; + } + class HerbertTokenizer extends PreTrainedTokenizer { + return_token_type_ids = true; + } + class ConvBertTokenizer extends PreTrainedTokenizer { + return_token_type_ids = true; + } + class RoFormerTokenizer extends PreTrainedTokenizer { + return_token_type_ids = true; + } + class DistilBertTokenizer extends PreTrainedTokenizer { + } + class CamembertTokenizer extends PreTrainedTokenizer { + } + class XLMTokenizer extends PreTrainedTokenizer { + return_token_type_ids = true; + constructor(tokenizerJSON, tokenizerConfig) { + super(tokenizerJSON, tokenizerConfig); + console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.'); + } + } + class ElectraTokenizer extends PreTrainedTokenizer { + return_token_type_ids = true; + } + class T5Tokenizer extends PreTrainedTokenizer { + } + class GPT2Tokenizer extends PreTrainedTokenizer { + } + class BartTokenizer extends PreTrainedTokenizer { + } + class MBartTokenizer extends PreTrainedTokenizer { + constructor(tokenizerJSON, tokenizerConfig) { + super(tokenizerJSON, tokenizerConfig); + this.languageRegex = /^[a-z]{2}_[A-Z]{2}$/; + this.language_codes = this.special_tokens.filter((x) => this.languageRegex.test(x)); + this.lang_to_token = (x) => x; + } + /** + * Helper function to build translation inputs for an `MBartTokenizer`. + * @param {string|string[]} raw_inputs The text to tokenize. + * @param {Object} tokenizer_options Options to be sent to the tokenizer + * @param {Object} generate_kwargs Generation options. + * @returns {Object} Object to be passed to the model. + */ + _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) { + return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs); + } + } + class MBart50Tokenizer extends MBartTokenizer { + } + class RobertaTokenizer extends PreTrainedTokenizer { + } + class BloomTokenizer extends PreTrainedTokenizer { + } + const SPIECE_UNDERLINE = "\u2581"; + class LlamaTokenizer extends PreTrainedTokenizer { + padding_side = "left"; + constructor(tokenizerJSON, tokenizerConfig) { + super(tokenizerJSON, tokenizerConfig); + this.legacy = tokenizerConfig.legacy ?? true; + if (!this.legacy) { + this.normalizer = null; + this.pre_tokenizer = new MetaspacePreTokenizer({ + replacement: SPIECE_UNDERLINE, + prepend_scheme: "first" + }); + } + } + /** + * Helper function to handle legacy encoding of SPM tokenizers. + * Adapted from https://github.com/huggingface/transformers/blob/e6dcf8abd6f65bb4b6dfc1831b20d9ba49ce00e2/src/transformers/models/t5/tokenization_t5.py#L374-L387 + * @param {string} text The text to encode. + * @returns {string[]} The encoded tokens. + */ + _encode_text(text) { + if (text === null) return null; + if (this.legacy || text.length === 0) { + return super._encode_text(text); + } + let tokens = super._encode_text(SPIECE_UNDERLINE + text.replaceAll(SPIECE_UNDERLINE, " ")); + if (tokens.length > 1 && tokens[0] === SPIECE_UNDERLINE && this.special_tokens.includes(tokens[1])) { + tokens = tokens.slice(1); + } + return tokens; + } + } + class CodeLlamaTokenizer extends PreTrainedTokenizer { + } + class XLMRobertaTokenizer extends PreTrainedTokenizer { + } + class MPNetTokenizer extends PreTrainedTokenizer { + } + class FalconTokenizer extends PreTrainedTokenizer { + } + class GPTNeoXTokenizer extends PreTrainedTokenizer { + } + class EsmTokenizer extends PreTrainedTokenizer { + } + class Qwen2Tokenizer extends PreTrainedTokenizer { + } + class GemmaTokenizer extends PreTrainedTokenizer { + } + class Grok1Tokenizer extends PreTrainedTokenizer { + } + function _build_translation_inputs(self2, raw_inputs, tokenizer_options, generate_kwargs) { + if (!("language_codes" in self2) || !Array.isArray(self2.language_codes)) { + throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids."); + } + if (!("languageRegex" in self2) || !(self2.languageRegex instanceof RegExp)) { + throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression."); + } + if (!("lang_to_token" in self2) || typeof self2.lang_to_token !== "function") { + throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function."); + } + const src_lang_token = generate_kwargs.src_lang; + const tgt_lang_token = generate_kwargs.tgt_lang; + if (!self2.language_codes.includes(tgt_lang_token)) { + throw new Error(`Target language code "${tgt_lang_token}" is not valid. Must be one of: {${self2.language_codes.join(", ")}}`); + } + if (src_lang_token !== void 0) { + if (!self2.language_codes.includes(src_lang_token)) { + throw new Error(`Source language code "${src_lang_token}" is not valid. Must be one of: {${self2.language_codes.join(", ")}}`); + } + for (const item of self2.post_processor.config.single) { + if ("SpecialToken" in item && self2.languageRegex.test(item.SpecialToken.id)) { + item.SpecialToken.id = self2.lang_to_token(src_lang_token); + break; + } + } + } + generate_kwargs.forced_bos_token_id = self2.model.convert_tokens_to_ids([self2.lang_to_token(tgt_lang_token)])[0]; + return self2._call(raw_inputs, tokenizer_options); + } + class NllbTokenizer extends PreTrainedTokenizer { + constructor(tokenizerJSON, tokenizerConfig) { + super(tokenizerJSON, tokenizerConfig); + this.languageRegex = /^[a-z]{3}_[A-Z][a-z]{3}$/; + this.language_codes = this.special_tokens.filter((x) => this.languageRegex.test(x)); + this.lang_to_token = (x) => x; + } + /** + * Helper function to build translation inputs for an `NllbTokenizer`. + * @param {string|string[]} raw_inputs The text to tokenize. + * @param {Object} tokenizer_options Options to be sent to the tokenizer + * @param {Object} generate_kwargs Generation options. + * @returns {Object} Object to be passed to the model. + */ + _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) { + return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs); + } + } + class M2M100Tokenizer extends PreTrainedTokenizer { + constructor(tokenizerJSON, tokenizerConfig) { + super(tokenizerJSON, tokenizerConfig); + this.languageRegex = /^__[a-z]{2,3}__$/; + this.language_codes = this.special_tokens.filter((x) => this.languageRegex.test(x)).map((x) => x.slice(2, -2)); + this.lang_to_token = (x) => `__${x}__`; + } + /** + * Helper function to build translation inputs for an `M2M100Tokenizer`. + * @param {string|string[]} raw_inputs The text to tokenize. + * @param {Object} tokenizer_options Options to be sent to the tokenizer + * @param {Object} generate_kwargs Generation options. + * @returns {Object} Object to be passed to the model. + */ + _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) { + return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs); + } + } + class WhisperTokenizer extends PreTrainedTokenizer { + get timestamp_begin() { + return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0] + 1; + } + /** + * Decodes automatic speech recognition (ASR) sequences. + * @param {Array<{tokens: bigint[], token_timestamps?: number[], stride: number[]}>} sequences The sequences to decode. + * @param {Object} options The options to use for decoding. + * @returns {Array, text: string}>}>} The decoded sequences. + */ + _decode_asr(sequences, { + return_timestamps = false, + return_language = false, + time_precision = null, + force_full_sequences = true + } = {}) { + if (time_precision === null) { + throw Error("Must specify time_precision"); + } + let last_language = null; + const returnWordTimestamps = return_timestamps === "word"; + function new_chunk() { + return { "language": last_language, "timestamp": [null, null], "text": "" }; + } + const chunks = []; + let chunk = new_chunk(); + let time_offset = 0; + const timestamp_begin = this.timestamp_begin; + const total_timestamp_tokens = 1500; + const timestamp_end = timestamp_begin + total_timestamp_tokens; + let previous_tokens = []; + let previous_token_timestamps = []; + let skip = false; + let right_stride_start = null; + const all_special_ids = new Set(this.all_special_ids); + for (const output of sequences) { + const token_ids = output.tokens; + const token_timestamps = returnWordTimestamps ? output.token_timestamps : null; + let last_timestamp = null; + let first_timestamp = timestamp_begin; + if ("stride" in output) { + const [chunk_len, stride_left, stride_right] = output.stride; + time_offset -= stride_left; + right_stride_start = chunk_len - stride_right; + if (stride_left) { + first_timestamp = stride_left / time_precision + timestamp_begin; + } + if (stride_right) { + for (let i = token_ids.length - 1; i >= 0; --i) { + const token = Number(token_ids[i]); + if (token >= timestamp_begin) { + if (last_timestamp !== null && (token - timestamp_begin) * time_precision < right_stride_start) { + break; + } + last_timestamp = token; + } + } + } + } + let current_tokens = []; + let current_token_timestamps = []; + for (let i = 0; i < token_ids.length; ++i) { + const token = Number(token_ids[i]); + if (all_special_ids.has(token)) { + const text = this.decode([token]); + const language = _models_whisper_common_whisper_js__WEBPACK_IMPORTED_MODULE_7__.WHISPER_LANGUAGE_MAPPING.get(text.slice(2, -2)); + if (language !== void 0) { + if (last_language !== null && language !== last_language && !return_timestamps) { + previous_tokens.push(current_tokens); + const resolved_tokens = this.findLongestCommonSequence(previous_tokens)[0]; + const resolved_text = this.decode(resolved_tokens); + chunk.text = resolved_text; + chunks.push(chunk); + previous_tokens = []; + current_tokens = []; + chunk = new_chunk(); + } + last_language = chunk.language = language; + } else { + } + } else if (token >= timestamp_begin && token <= timestamp_end) { + const time = (token - timestamp_begin) * time_precision + time_offset; + const rounded_time = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_3__.round)(time, 2); + if (last_timestamp !== null && token >= last_timestamp) { + skip = true; + } else if (skip || previous_tokens.length > 0 && token < first_timestamp) { + skip = false; + } else if (chunk.timestamp[0] === null) { + chunk.timestamp[0] = rounded_time; + } else { + if (rounded_time === chunk.timestamp[0]) { + } else { + chunk.timestamp[1] = rounded_time; + previous_tokens.push(current_tokens); + if (returnWordTimestamps) { + previous_token_timestamps.push(current_token_timestamps); + } + const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence( + previous_tokens, + previous_token_timestamps + ); + const resolved_text = this.decode(resolved_tokens); + chunk.text = resolved_text; + if (returnWordTimestamps) { + chunk.words = this.collateWordTimestamps( + resolved_tokens, + resolved_token_timestamps, + last_language + ); + } + chunks.push(chunk); + previous_tokens = []; + current_tokens = []; + previous_token_timestamps = []; + current_token_timestamps = []; + chunk = new_chunk(); + } + } + } else { + current_tokens.push(token); + if (returnWordTimestamps) { + let start_time = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_3__.round)(token_timestamps[i] + time_offset, 2); + let end_time; + if (i + 1 < token_timestamps.length) { + end_time = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_3__.round)(token_timestamps[i + 1] + time_offset, 2); + const decoded_text = this.decode([token]); + if (PUNCTUATION_ONLY_REGEX.test(decoded_text)) { + end_time = (0, _utils_maths_js__WEBPACK_IMPORTED_MODULE_3__.round)(Math.min(start_time + time_precision, end_time), 2); + } + } else { + end_time = null; + } + current_token_timestamps.push([start_time, end_time]); + } + } + } + if ("stride" in output) { + const [chunk_len, stride_left, stride_right] = output.stride; + time_offset += chunk_len - stride_right; + } + if (current_tokens.length > 0) { + previous_tokens.push(current_tokens); + if (returnWordTimestamps) { + previous_token_timestamps.push(current_token_timestamps); + } + } else if (previous_tokens.every((p) => p.length === 0)) { + chunk = new_chunk(); + previous_tokens = []; + current_tokens = []; + previous_token_timestamps = []; + current_token_timestamps = []; + } + } + if (previous_tokens.length > 0) { + if (force_full_sequences && return_timestamps) { + throw new Error( + "Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation." + ); + } + const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence(previous_tokens, previous_token_timestamps); + const resolved_text = this.decode(resolved_tokens); + chunk.text = resolved_text; + if (returnWordTimestamps) { + chunk.words = this.collateWordTimestamps( + resolved_tokens, + resolved_token_timestamps, + last_language + ); + } + chunks.push(chunk); + } + let optional = /* @__PURE__ */ Object.create(null); + const full_text = chunks.map((chunk2) => chunk2.text).join(""); + if (return_timestamps || return_language) { + for (let i = 0; i < chunks.length; ++i) { + const chunk2 = chunks[i]; + if (!return_timestamps) { + delete chunk2["timestamp"]; + } + if (!return_language) { + delete chunk2["language"]; + } + } + if (returnWordTimestamps) { + const new_chunks = []; + for (const chunk2 of chunks) { + for (const word of chunk2.words) { + new_chunks.push(word); + } + } + optional = { "chunks": new_chunks }; + } else { + optional = { "chunks": chunks }; + } + } + return [full_text, optional]; + } + /** + * Finds the longest common sequence among the provided sequences. + * @param {number[][]} sequences An array of sequences of token ids to compare. + * @returns {number[][]} The longest common sequence found. + * @throws {Error} If there is a bug within the function. + * @private + */ + findLongestCommonSequence(sequences, token_timestamp_sequences = null) { + let leftSequence = sequences[0]; + let leftLength = leftSequence.length; + let totalSequence = []; + const use_token_timestamp_sequences = Array.isArray(token_timestamp_sequences) && token_timestamp_sequences.length > 0; + let total_token_timestamp_sequence = use_token_timestamp_sequences ? [] : null; + let left_token_timestamp_sequence = use_token_timestamp_sequences ? token_timestamp_sequences[0] : null; + for (let i = 1; i < sequences.length; ++i) { + const rightSequence = sequences[i]; + let max = 0; + let maxIndices = [leftLength, leftLength, 0, 0]; + const rightLength = rightSequence.length; + for (let j = 1; j < leftLength + rightLength; ++j) { + const leftStart2 = Math.max(0, leftLength - j); + const leftStop2 = Math.min(leftLength, leftLength + rightLength - j); + const left = leftSequence.slice(leftStart2, leftStop2); + const rightStart2 = Math.max(0, j - leftLength); + const rightStop2 = Math.min(rightLength, j); + const right = rightSequence.slice(rightStart2, rightStop2); + if (left.length !== right.length) { + throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference."); + } + let matches; + if (use_token_timestamp_sequences) { + matches = left.filter((elem, idx) => elem === right[idx] && left_token_timestamp_sequence[leftStart2 + idx] <= token_timestamp_sequences[i][rightStart2 + idx]).length; + } else { + matches = left.filter((elem, idx) => elem === right[idx]).length; + } + const eps = j / 1e4; + const matching = matches / j + eps; + if (matches > 1 && matching > max) { + max = matching; + maxIndices = [leftStart2, leftStop2, rightStart2, rightStop2]; + } + } + const [leftStart, leftStop, rightStart, rightStop] = maxIndices; + const leftMid = Math.floor((leftStop + leftStart) / 2); + const rightMid = Math.floor((rightStop + rightStart) / 2); + totalSequence.push(...leftSequence.slice(0, leftMid)); + leftSequence = rightSequence.slice(rightMid); + leftLength = leftSequence.length; + if (use_token_timestamp_sequences) { + total_token_timestamp_sequence.push(...left_token_timestamp_sequence.slice(0, leftMid)); + left_token_timestamp_sequence = token_timestamp_sequences[i].slice(rightMid); + } + } + totalSequence.push(...leftSequence); + if (use_token_timestamp_sequences) { + total_token_timestamp_sequence.push(...left_token_timestamp_sequence); + return [totalSequence, total_token_timestamp_sequence]; + } else { + return [totalSequence, []]; + } + } + /** @private */ + collateWordTimestamps(tokens, token_timestamps, language) { + const [words, _, token_indices] = this.combineTokensIntoWords(tokens, language); + const timings = []; + for (let i = 0; i < words.length; ++i) { + const indices = token_indices[i]; + timings.push({ + text: words[i], + timestamp: [ + token_timestamps[indices.at(0)][0], + token_timestamps[indices.at(-1)][1] + ] + }); + } + return timings; + } + /** + * Groups tokens by word. Returns a tuple containing a list of strings with the words, + * and a list of `token_id` sequences with the tokens making up each word. + * @param {number[]} tokens + * @param {string} [language] + * @param {string} prepend_punctionations + * @param {string} append_punctuations + * + * @private + */ + combineTokensIntoWords(tokens, language, prepend_punctionations = `"'\u201C\xA1\xBF([{-`, append_punctuations = `"'.\u3002,\uFF0C!\uFF01?\uFF1F:\uFF1A\u201D)]}\u3001`) { + language = language ?? "english"; + let words, word_tokens, token_indices; + if (["chinese", "japanese", "thai", "lao", "myanmar"].includes(language)) { + [words, word_tokens, token_indices] = this.splitTokensOnUnicode(tokens); + } else { + [words, word_tokens, token_indices] = this.splitTokensOnSpaces(tokens); + } + return this.mergePunctuations(words, word_tokens, token_indices, prepend_punctionations, append_punctuations); + } + /** @type {PreTrainedTokenizer['decode']} */ + decode(token_ids, decode_args) { + let text; + if (decode_args?.decode_with_timestamps) { + if (token_ids instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor) { + token_ids = prepareTensorForDecode(token_ids); + } + text = this.decodeWithTimestamps(token_ids, decode_args); + } else { + text = super.decode(token_ids, decode_args); + } + return text; + } + /** + * @param {number[]|bigint[]} token_ids List of token IDs to decode. + * @param {Object} decode_args Optional arguments for decoding + * @private + */ + decodeWithTimestamps(token_ids, decode_args) { + const time_precision = decode_args?.time_precision ?? 0.02; + const timestamp_begin = Array.from(this.all_special_ids).at(-1) + 1; + let outputs = [[]]; + for (let token of token_ids) { + token = Number(token); + if (token >= timestamp_begin) { + const timestamp = ((token - timestamp_begin) * time_precision).toFixed(2); + outputs.push(`<|${timestamp}|>`); + outputs.push([]); + } else { + outputs[outputs.length - 1].push(token); + } + } + outputs = outputs.map( + (s) => typeof s === "string" ? s : super.decode(s, decode_args) + ); + return outputs.join(""); + } + /** + * Combine tokens into words by splitting at any position where the tokens are decoded as valid unicode points. + * @param {number[]} tokens + * @returns {*} + * @private + */ + splitTokensOnUnicode(tokens) { + const decoded_full = this.decode(tokens, { + // @ts-ignore + decode_with_timestamps: true + }); + const replacement_char = "\uFFFD"; + const words = []; + const word_tokens = []; + const token_indices = []; + let current_tokens = []; + let current_indices = []; + let unicode_offset = 0; + for (let token_idx = 0; token_idx < tokens.length; ++token_idx) { + const token = tokens[token_idx]; + current_tokens.push(token); + current_indices.push(token_idx); + const decoded = this.decode(current_tokens, { + // @ts-ignore + decode_with_timestamps: true + }); + if (!decoded.includes(replacement_char) || decoded_full[unicode_offset + decoded.indexOf(replacement_char)] === replacement_char) { + words.push(decoded); + word_tokens.push(current_tokens); + token_indices.push(current_indices); + current_tokens = []; + current_indices = []; + unicode_offset += decoded.length; + } + } + return [words, word_tokens, token_indices]; + } + /** + * Combine tokens into words by splitting at whitespace and punctuation tokens. + * @param {number[]} tokens + * @private + */ + splitTokensOnSpaces(tokens) { + const [subwords, subword_tokens_list, subword_indices_list] = this.splitTokensOnUnicode(tokens); + const words = []; + const word_tokens = []; + const token_indices = []; + const punctuationRegex = new RegExp(`^[${PUNCTUATION_REGEX}]$`, "gu"); + for (let i = 0; i < subwords.length; ++i) { + const subword = subwords[i]; + const subword_tokens = subword_tokens_list[i]; + const subword_indices = subword_indices_list[i]; + const special = subword_tokens[0] >= this.model.tokens_to_ids.get("<|endoftext|>"); + const with_space = subword.startsWith(" "); + const trimmed = subword.trim(); + const punctuation = punctuationRegex.test(trimmed); + if (special || with_space || punctuation || words.length === 0) { + words.push(subword); + word_tokens.push(subword_tokens); + token_indices.push(subword_indices); + } else { + const ix = words.length - 1; + words[ix] += subword; + word_tokens[ix].push(...subword_tokens); + token_indices[ix].push(...subword_indices); + } + } + return [words, word_tokens, token_indices]; + } + /** + * Merges punctuation tokens with neighboring words. + * @param {string[]} words + * @param {number[][]} tokens + * @param {number[][]} indices + * @param {string} prepended + * @param {string} appended + * @private + */ + mergePunctuations(words, tokens, indices, prepended, appended) { + const newWords = structuredClone(words); + const newTokens = structuredClone(tokens); + const newIndices = structuredClone(indices); + let i = newWords.length - 2; + let j = newWords.length - 1; + while (i >= 0) { + if (newWords[i].startsWith(" ") && prepended.includes(newWords[i].trim())) { + newWords[j] = newWords[i] + newWords[j]; + newTokens[j] = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(newTokens[i], newTokens[j]); + newIndices[j] = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(newIndices[i], newIndices[j]); + newWords[i] = ""; + newTokens[i] = []; + newIndices[i] = []; + } else { + j = i; + } + --i; + } + i = 0; + j = 1; + while (j < newWords.length) { + if (!newWords[i].endsWith(" ") && appended.includes(newWords[j])) { + newWords[i] += newWords[j]; + newTokens[i] = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(newTokens[i], newTokens[j]); + newIndices[i] = (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(newIndices[i], newIndices[j]); + newWords[j] = ""; + newTokens[j] = []; + newIndices[j] = []; + } else { + i = j; + } + ++j; + } + return [ + newWords.filter((x) => x), + newTokens.filter((x) => x.length > 0), + newIndices.filter((x) => x.length > 0) + ]; + } + } + class CodeGenTokenizer extends PreTrainedTokenizer { + } + class CLIPTokenizer extends PreTrainedTokenizer { + } + class SiglipTokenizer extends PreTrainedTokenizer { + } + class MarianTokenizer extends PreTrainedTokenizer { + /** + * Create a new MarianTokenizer instance. + * @param {Object} tokenizerJSON The JSON of the tokenizer. + * @param {Object} tokenizerConfig The config of the tokenizer. + */ + constructor(tokenizerJSON, tokenizerConfig) { + super(tokenizerJSON, tokenizerConfig); + this.languageRegex = /^(>>\w+<<)\s*/g; + this.supported_language_codes = this.model.vocab.filter( + (x) => this.languageRegex.test(x) + ); + console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.'); + } + /** + * Encodes a single text. Overriding this method is necessary since the language codes + * must be removed before encoding with sentencepiece model. + * @see https://github.com/huggingface/transformers/blob/12d51db243a00726a548a43cc333390ebae731e3/src/transformers/models/marian/tokenization_marian.py#L204-L213 + * + * @param {string|null} text The text to encode. + * @returns {Array} The encoded tokens. + */ + _encode_text(text) { + if (text === null) return null; + const [matchInfo, ...remainder] = text.trim().split(this.languageRegex); + if (remainder.length === 0) { + return super._encode_text(matchInfo); + } else if (remainder.length === 2) { + const [language, text2] = remainder; + if (!this.supported_language_codes.includes(language)) { + console.warn(`Unsupported language code "${language}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`); + } + return (0, _utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)([language], super._encode_text(text2)); + } + } + } + class Wav2Vec2CTCTokenizer extends PreTrainedTokenizer { + } + class BlenderbotTokenizer extends PreTrainedTokenizer { + } + class BlenderbotSmallTokenizer extends PreTrainedTokenizer { + } + class SpeechT5Tokenizer extends PreTrainedTokenizer { + } + class NougatTokenizer extends PreTrainedTokenizer { + } + class VitsTokenizer extends PreTrainedTokenizer { + constructor(tokenizerJSON, tokenizerConfig) { + super(tokenizerJSON, tokenizerConfig); + this.decoder = new VitsDecoder({}); + } + } + class CohereTokenizer extends PreTrainedTokenizer { + } + class MgpstrTokenizer extends PreTrainedTokenizer { + } + class AutoTokenizer { + static TOKENIZER_CLASS_MAPPING = { + T5Tokenizer, + DistilBertTokenizer, + CamembertTokenizer, + DebertaTokenizer, + DebertaV2Tokenizer, + BertTokenizer, + HerbertTokenizer, + ConvBertTokenizer, + RoFormerTokenizer, + XLMTokenizer, + ElectraTokenizer, + MobileBertTokenizer, + SqueezeBertTokenizer, + AlbertTokenizer, + GPT2Tokenizer, + BartTokenizer, + MBartTokenizer, + MBart50Tokenizer, + RobertaTokenizer, + WhisperTokenizer, + CodeGenTokenizer, + CLIPTokenizer, + SiglipTokenizer, + MarianTokenizer, + BloomTokenizer, + NllbTokenizer, + M2M100Tokenizer, + LlamaTokenizer, + CodeLlamaTokenizer, + XLMRobertaTokenizer, + MPNetTokenizer, + FalconTokenizer, + GPTNeoXTokenizer, + EsmTokenizer, + Wav2Vec2CTCTokenizer, + BlenderbotTokenizer, + BlenderbotSmallTokenizer, + SpeechT5Tokenizer, + NougatTokenizer, + VitsTokenizer, + Qwen2Tokenizer, + GemmaTokenizer, + Grok1Tokenizer, + CohereTokenizer, + MgpstrTokenizer, + // Base case: + PreTrainedTokenizer + }; + /** + * Instantiate one of the tokenizer classes of the library from a pretrained model. + * + * The tokenizer class to instantiate is selected based on the `tokenizer_class` property of the config object + * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) + * + * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: + * - A string, the *model id* of a pretrained tokenizer hosted inside a model repo on huggingface.co. + * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a + * user or organization name, like `dbmdz/bert-base-german-cased`. + * - A path to a *directory* containing tokenizer files, e.g., `./my_model_directory/`. + * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer. + * + * @returns {Promise} A new instance of the PreTrainedTokenizer class. + */ + static async from_pretrained(pretrained_model_name_or_path, { + progress_callback = null, + config = null, + cache_dir = null, + local_files_only = false, + revision = "main", + legacy = null + } = {}) { + const [tokenizerJSON, tokenizerConfig] = await loadTokenizer(pretrained_model_name_or_path, { + progress_callback, + config, + cache_dir, + local_files_only, + revision, + legacy + }); + const tokenizerName = tokenizerConfig.tokenizer_class?.replace(/Fast$/, "") ?? "PreTrainedTokenizer"; + let cls = this.TOKENIZER_CLASS_MAPPING[tokenizerName]; + if (!cls) { + console.warn(`Unknown tokenizer class "${tokenizerName}", attempting to construct from base class.`); + cls = PreTrainedTokenizer; + } + return new cls(tokenizerJSON, tokenizerConfig); + } + } + }) + ), + /***/ + "./src/utils/audio.js": ( + /*!****************************!*\ + !*** ./src/utils/audio.js ***! + \****************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + RawAudio: () => ( + /* binding */ + RawAudio + ), + /* harmony export */ + hamming: () => ( + /* binding */ + hamming + ), + /* harmony export */ + hanning: () => ( + /* binding */ + hanning + ), + /* harmony export */ + mel_filter_bank: () => ( + /* binding */ + mel_filter_bank + ), + /* harmony export */ + read_audio: () => ( + /* binding */ + read_audio + ), + /* harmony export */ + spectrogram: () => ( + /* binding */ + spectrogram + ), + /* harmony export */ + window_function: () => ( + /* binding */ + window_function + ) + /* harmony export */ + }); + var _hub_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ./hub.js */ + "./src/utils/hub.js" + ); + var _maths_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ./maths.js */ + "./src/utils/maths.js" + ); + var _core_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ./core.js */ + "./src/utils/core.js" + ); + var _env_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! ../env.js */ + "./src/env.js" + ); + var _tensor_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__2( + /*! ./tensor.js */ + "./src/utils/tensor.js" + ); + var node_fs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__2( + /*! node:fs */ + "?7992" + ); + async function read_audio(url, sampling_rate) { + if (typeof AudioContext === "undefined") { + throw Error( + "Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing." + ); + } + const response = await (await (0, _hub_js__WEBPACK_IMPORTED_MODULE_0__.getFile)(url)).arrayBuffer(); + const audioCTX = new AudioContext({ sampleRate: sampling_rate }); + if (typeof sampling_rate === "undefined") { + console.warn(`No sampling rate provided, using default of ${audioCTX.sampleRate}Hz.`); + } + const decoded = await audioCTX.decodeAudioData(response); + let audio; + if (decoded.numberOfChannels === 2) { + const SCALING_FACTOR = Math.sqrt(2); + const left = decoded.getChannelData(0); + const right = decoded.getChannelData(1); + audio = new Float32Array(left.length); + for (let i = 0; i < decoded.length; ++i) { + audio[i] = SCALING_FACTOR * (left[i] + right[i]) / 2; + } + } else { + audio = decoded.getChannelData(0); + } + return audio; + } + function generalized_cosine_window(M2, a_0) { + if (M2 < 1) { + return new Float64Array(); + } + if (M2 === 1) { + return new Float64Array([1]); + } + const a_1 = 1 - a_0; + const factor = 2 * Math.PI / (M2 - 1); + const cos_vals = new Float64Array(M2); + for (let i = 0; i < M2; ++i) { + cos_vals[i] = a_0 - a_1 * Math.cos(i * factor); + } + return cos_vals; + } + function hanning(M2) { + return generalized_cosine_window(M2, 0.5); + } + function hamming(M2) { + return generalized_cosine_window(M2, 0.54); + } + const HERTZ_TO_MEL_MAPPING = { + "htk": (freq) => 2595 * Math.log10(1 + freq / 700), + "kaldi": (freq) => 1127 * Math.log(1 + freq / 700), + "slaney": (freq, min_log_hertz = 1e3, min_log_mel = 15, logstep = 27 / Math.log(6.4)) => freq >= min_log_hertz ? min_log_mel + Math.log(freq / min_log_hertz) * logstep : 3 * freq / 200 + }; + function hertz_to_mel(freq, mel_scale = "htk") { + const fn = HERTZ_TO_MEL_MAPPING[mel_scale]; + if (!fn) { + throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".'); + } + return typeof freq === "number" ? fn(freq) : freq.map((x) => fn(x)); + } + const MEL_TO_HERTZ_MAPPING = { + "htk": (mels) => 700 * (10 ** (mels / 2595) - 1), + "kaldi": (mels) => 700 * (Math.exp(mels / 1127) - 1), + "slaney": (mels, min_log_hertz = 1e3, min_log_mel = 15, logstep = Math.log(6.4) / 27) => mels >= min_log_mel ? min_log_hertz * Math.exp(logstep * (mels - min_log_mel)) : 200 * mels / 3 + }; + function mel_to_hertz(mels, mel_scale = "htk") { + const fn = MEL_TO_HERTZ_MAPPING[mel_scale]; + if (!fn) { + throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".'); + } + return typeof mels === "number" ? fn(mels) : mels.map((x) => fn(x)); + } + function _create_triangular_filter_bank(fft_freqs, filter_freqs) { + const filter_diff = Float64Array.from( + { length: filter_freqs.length - 1 }, + (_, i) => filter_freqs[i + 1] - filter_freqs[i] + ); + const slopes = Array.from({ + length: fft_freqs.length + }, () => new Array(filter_freqs.length)); + for (let j = 0; j < fft_freqs.length; ++j) { + const slope = slopes[j]; + for (let i = 0; i < filter_freqs.length; ++i) { + slope[i] = filter_freqs[i] - fft_freqs[j]; + } + } + const numFreqs = filter_freqs.length - 2; + const ret = Array.from({ length: numFreqs }, () => new Array(fft_freqs.length)); + for (let j = 0; j < fft_freqs.length; ++j) { + const slope = slopes[j]; + for (let i = 0; i < numFreqs; ++i) { + const down = -slope[i] / filter_diff[i]; + const up = slope[i + 2] / filter_diff[i + 1]; + ret[i][j] = Math.max(0, Math.min(down, up)); + } + } + return ret; + } + function linspace(start, end, num) { + const step = (end - start) / (num - 1); + return Float64Array.from({ length: num }, (_, i) => start + step * i); + } + function mel_filter_bank(num_frequency_bins, num_mel_filters, min_frequency, max_frequency, sampling_rate, norm = null, mel_scale = "htk", triangularize_in_mel_space = false) { + if (norm !== null && norm !== "slaney") { + throw new Error('norm must be one of null or "slaney"'); + } + if (num_frequency_bins < 2) { + throw new Error(`Require num_frequency_bins: ${num_frequency_bins} >= 2`); + } + if (min_frequency > max_frequency) { + throw new Error(`Require min_frequency: ${min_frequency} <= max_frequency: ${max_frequency}`); + } + const mel_min = hertz_to_mel(min_frequency, mel_scale); + const mel_max = hertz_to_mel(max_frequency, mel_scale); + const mel_freqs = linspace(mel_min, mel_max, num_mel_filters + 2); + let filter_freqs = mel_to_hertz(mel_freqs, mel_scale); + let fft_freqs; + if (triangularize_in_mel_space) { + const fft_bin_width = sampling_rate / ((num_frequency_bins - 1) * 2); + fft_freqs = hertz_to_mel(Float64Array.from({ length: num_frequency_bins }, (_, i) => i * fft_bin_width), mel_scale); + filter_freqs = mel_freqs; + } else { + fft_freqs = linspace(0, Math.floor(sampling_rate / 2), num_frequency_bins); + } + const mel_filters = _create_triangular_filter_bank(fft_freqs, filter_freqs); + if (norm !== null && norm === "slaney") { + for (let i = 0; i < num_mel_filters; ++i) { + const filter = mel_filters[i]; + const enorm = 2 / (filter_freqs[i + 2] - filter_freqs[i]); + for (let j = 0; j < num_frequency_bins; ++j) { + filter[j] *= enorm; + } + } + } + return mel_filters; + } + function padReflect(array, left, right) { + const padded = new array.constructor(array.length + left + right); + const w = array.length - 1; + for (let i = 0; i < array.length; ++i) { + padded[left + i] = array[i]; + } + for (let i = 1; i <= left; ++i) { + padded[left - i] = array[(0, _core_js__WEBPACK_IMPORTED_MODULE_2__.calculateReflectOffset)(i, w)]; + } + for (let i = 1; i <= right; ++i) { + padded[w + left + i] = array[(0, _core_js__WEBPACK_IMPORTED_MODULE_2__.calculateReflectOffset)(w - i, w)]; + } + return padded; + } + function _db_conversion_helper(spectrogram2, factor, reference, min_value, db_range) { + if (reference <= 0) { + throw new Error("reference must be greater than zero"); + } + if (min_value <= 0) { + throw new Error("min_value must be greater than zero"); + } + reference = Math.max(min_value, reference); + const logReference = Math.log10(reference); + for (let i = 0; i < spectrogram2.length; ++i) { + spectrogram2[i] = factor * Math.log10(Math.max(min_value, spectrogram2[i]) - logReference); + } + if (db_range !== null) { + if (db_range <= 0) { + throw new Error("db_range must be greater than zero"); + } + const maxValue = (0, _maths_js__WEBPACK_IMPORTED_MODULE_1__.max)(spectrogram2)[0] - db_range; + for (let i = 0; i < spectrogram2.length; ++i) { + spectrogram2[i] = Math.max(spectrogram2[i], maxValue); + } + } + return spectrogram2; + } + function amplitude_to_db(spectrogram2, reference = 1, min_value = 1e-5, db_range = null) { + return _db_conversion_helper(spectrogram2, 20, reference, min_value, db_range); + } + function power_to_db(spectrogram2, reference = 1, min_value = 1e-10, db_range = null) { + return _db_conversion_helper(spectrogram2, 10, reference, min_value, db_range); + } + async function spectrogram(waveform, window2, frame_length, hop_length, { + fft_length = null, + power = 1, + center = true, + pad_mode = "reflect", + onesided = true, + preemphasis = null, + preemphasis_htk_flavor = true, + mel_filters = null, + mel_floor = 1e-10, + log_mel = null, + reference = 1, + min_value = 1e-10, + db_range = null, + remove_dc_offset = null, + // Custom parameters for efficiency reasons + min_num_frames = null, + max_num_frames = null, + do_pad = true, + transpose = false, + mel_offset = 0 + } = {}) { + const window_length = window2.length; + if (fft_length === null) { + fft_length = frame_length; + } + if (frame_length > fft_length) { + throw Error(`frame_length (${frame_length}) may not be larger than fft_length (${fft_length})`); + } + if (window_length !== frame_length) { + throw new Error(`Length of the window (${window_length}) must equal frame_length (${frame_length})`); + } + if (hop_length <= 0) { + throw new Error("hop_length must be greater than zero"); + } + if (power === null && mel_filters !== null) { + throw new Error( + "You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue." + ); + } + if (!preemphasis_htk_flavor) { + throw new Error( + "`preemphasis_htk_flavor=false` is not currently supported." + ); + } + if (center) { + switch (pad_mode) { + case "reflect": { + const half_window = Math.floor((fft_length - 1) / 2) + 1; + waveform = padReflect(waveform, half_window, half_window); + break; + } + case "constant": { + const padding = Math.floor(fft_length / 2); + const padded = new waveform.constructor(waveform.length + 2 * padding); + padded.set(waveform, padding); + waveform = padded; + break; + } + default: + throw new Error(`pad_mode="${pad_mode}" not implemented yet.`); + } + } + let num_frames = Math.floor(1 + Math.floor((waveform.length - frame_length) / hop_length)); + if (min_num_frames !== null && num_frames < min_num_frames) { + num_frames = min_num_frames; + } + const num_frequency_bins = onesided ? Math.floor(fft_length / 2) + 1 : fft_length; + let d1 = num_frames; + let d1Max = num_frames; + if (max_num_frames !== null) { + if (max_num_frames > num_frames) { + if (do_pad) { + d1Max = max_num_frames; + } + } else { + d1Max = d1 = max_num_frames; + } + } + const fft = new _maths_js__WEBPACK_IMPORTED_MODULE_1__.FFT(fft_length); + const inputBuffer = new Float64Array(fft_length); + const outputBuffer = new Float64Array(fft.outputBufferSize); + const transposedMagnitudeData = new Float32Array(num_frequency_bins * d1Max); + for (let i = 0; i < d1; ++i) { + const offset = i * hop_length; + const buffer_size = Math.min(waveform.length - offset, frame_length); + if (buffer_size !== frame_length) { + inputBuffer.fill(0, 0, frame_length); + } + for (let j = 0; j < buffer_size; ++j) { + inputBuffer[j] = waveform[offset + j]; + } + if (remove_dc_offset) { + let sum = 0; + for (let j = 0; j < buffer_size; ++j) { + sum += inputBuffer[j]; + } + const mean = sum / buffer_size; + for (let j = 0; j < buffer_size; ++j) { + inputBuffer[j] -= mean; + } + } + if (preemphasis !== null) { + for (let j = buffer_size - 1; j >= 1; --j) { + inputBuffer[j] -= preemphasis * inputBuffer[j - 1]; + } + inputBuffer[0] *= 1 - preemphasis; + } + for (let j = 0; j < window2.length; ++j) { + inputBuffer[j] *= window2[j]; + } + fft.realTransform(outputBuffer, inputBuffer); + for (let j = 0; j < num_frequency_bins; ++j) { + const j2 = j << 1; + transposedMagnitudeData[j * d1Max + i] = outputBuffer[j2] ** 2 + outputBuffer[j2 + 1] ** 2; + } + } + if (power !== null && power !== 2) { + const pow = power / 2; + for (let i = 0; i < transposedMagnitudeData.length; ++i) { + transposedMagnitudeData[i] **= pow; + } + } + const num_mel_filters = mel_filters.length; + let mel_spec = await (0, _tensor_js__WEBPACK_IMPORTED_MODULE_4__.matmul)( + // TODO: Make `mel_filters` a Tensor during initialization + new _tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor("float32", mel_filters.flat(), [num_mel_filters, num_frequency_bins]), + new _tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor("float32", transposedMagnitudeData, [num_frequency_bins, d1Max]) + ); + if (transpose) { + mel_spec = mel_spec.transpose(1, 0); + } + const mel_spec_data = ( + /** @type {Float32Array} */ + mel_spec.data + ); + for (let i = 0; i < mel_spec_data.length; ++i) { + mel_spec_data[i] = mel_offset + Math.max(mel_floor, mel_spec_data[i]); + } + if (power !== null && log_mel !== null) { + const o = Math.min(mel_spec_data.length, d1 * num_mel_filters); + switch (log_mel) { + case "log": + for (let i = 0; i < o; ++i) { + mel_spec_data[i] = Math.log(mel_spec_data[i]); + } + break; + case "log10": + for (let i = 0; i < o; ++i) { + mel_spec_data[i] = Math.log10(mel_spec_data[i]); + } + break; + case "dB": + if (power === 1) { + amplitude_to_db(mel_spec_data, reference, min_value, db_range); + } else if (power === 2) { + power_to_db(mel_spec_data, reference, min_value, db_range); + } else { + throw new Error(`Cannot use log_mel option '${log_mel}' with power ${power}`); + } + break; + default: + throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${log_mel}'`); + } + } + return mel_spec; + } + function window_function(window_length, name, { + periodic = true, + frame_length = null, + center = true + } = {}) { + const length = periodic ? window_length + 1 : window_length; + let window2; + switch (name) { + case "boxcar": + window2 = new Float64Array(length).fill(1); + break; + case "hann": + case "hann_window": + window2 = hanning(length); + break; + case "hamming": + window2 = hamming(length); + break; + case "povey": + window2 = hanning(length).map((x) => Math.pow(x, 0.85)); + break; + default: + throw new Error(`Unknown window type ${name}.`); + } + if (periodic) { + window2 = window2.subarray(0, window_length); + } + if (frame_length === null) { + return window2; + } + if (window_length > frame_length) { + throw new Error(`Length of the window (${window_length}) may not be larger than frame_length (${frame_length})`); + } + return window2; + } + function encodeWAV(samples, rate) { + let offset = 44; + const buffer = new ArrayBuffer(offset + samples.length * 4); + const view = new DataView(buffer); + writeString(view, 0, "RIFF"); + view.setUint32(4, 36 + samples.length * 4, true); + writeString(view, 8, "WAVE"); + writeString(view, 12, "fmt "); + view.setUint32(16, 16, true); + view.setUint16(20, 3, true); + view.setUint16(22, 1, true); + view.setUint32(24, rate, true); + view.setUint32(28, rate * 4, true); + view.setUint16(32, 4, true); + view.setUint16(34, 32, true); + writeString(view, 36, "data"); + view.setUint32(40, samples.length * 4, true); + for (let i = 0; i < samples.length; ++i, offset += 4) { + view.setFloat32(offset, samples[i], true); + } + return buffer; + } + function writeString(view, offset, string) { + for (let i = 0; i < string.length; ++i) { + view.setUint8(offset + i, string.charCodeAt(i)); + } + } + class RawAudio { + /** + * Create a new `RawAudio` object. + * @param {Float32Array} audio Audio data + * @param {number} sampling_rate Sampling rate of the audio data + */ + constructor(audio, sampling_rate) { + this.audio = audio; + this.sampling_rate = sampling_rate; + } + /** + * Convert the audio to a wav file buffer. + * @returns {ArrayBuffer} The WAV file. + */ + toWav() { + return encodeWAV(this.audio, this.sampling_rate); + } + /** + * Convert the audio to a blob. + * @returns {Blob} + */ + toBlob() { + const wav = this.toWav(); + const blob = new Blob([wav], { type: "audio/wav" }); + return blob; + } + /** + * Save the audio to a wav file. + * @param {string} path + */ + async save(path) { + let fn; + if (_env_js__WEBPACK_IMPORTED_MODULE_3__.apis.IS_BROWSER_ENV) { + if (_env_js__WEBPACK_IMPORTED_MODULE_3__.apis.IS_WEBWORKER_ENV) { + throw new Error("Unable to save a file from a Web Worker."); + } + fn = _core_js__WEBPACK_IMPORTED_MODULE_2__.saveBlob; + } else if (_env_js__WEBPACK_IMPORTED_MODULE_3__.apis.IS_FS_AVAILABLE) { + fn = async (path2, blob) => { + let buffer = await blob.arrayBuffer(); + node_fs__WEBPACK_IMPORTED_MODULE_5__.writeFileSync(path2, Buffer.from(buffer)); + }; + } else { + throw new Error("Unable to save because filesystem is disabled in this environment."); + } + await fn(path, this.toBlob()); + } + } + }) + ), + /***/ + "./src/utils/constants.js": ( + /*!********************************!*\ + !*** ./src/utils/constants.js ***! + \********************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + CHAT_TEMPLATE_NAME: () => ( + /* binding */ + CHAT_TEMPLATE_NAME + ), + /* harmony export */ + CONFIG_NAME: () => ( + /* binding */ + CONFIG_NAME + ), + /* harmony export */ + FEATURE_EXTRACTOR_NAME: () => ( + /* binding */ + FEATURE_EXTRACTOR_NAME + ), + /* harmony export */ + GENERATION_CONFIG_NAME: () => ( + /* binding */ + GENERATION_CONFIG_NAME + ), + /* harmony export */ + GITHUB_ISSUE_URL: () => ( + /* binding */ + GITHUB_ISSUE_URL + ), + /* harmony export */ + IMAGE_PROCESSOR_NAME: () => ( + /* binding */ + IMAGE_PROCESSOR_NAME + ), + /* harmony export */ + PROCESSOR_NAME: () => ( + /* binding */ + PROCESSOR_NAME + ) + /* harmony export */ + }); + const GITHUB_ISSUE_URL = "https://github.com/huggingface/transformers.js/issues/new/choose"; + const CONFIG_NAME = "config.json"; + const FEATURE_EXTRACTOR_NAME = "preprocessor_config.json"; + const IMAGE_PROCESSOR_NAME = FEATURE_EXTRACTOR_NAME; + const PROCESSOR_NAME = "processor_config.json"; + const CHAT_TEMPLATE_NAME = "chat_template.jinja"; + const GENERATION_CONFIG_NAME = "generation_config.json"; + }) + ), + /***/ + "./src/utils/core.js": ( + /*!***************************!*\ + !*** ./src/utils/core.js ***! + \***************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + calculateDimensions: () => ( + /* binding */ + calculateDimensions + ), + /* harmony export */ + calculateReflectOffset: () => ( + /* binding */ + calculateReflectOffset + ), + /* harmony export */ + count: () => ( + /* binding */ + count + ), + /* harmony export */ + dispatchCallback: () => ( + /* binding */ + dispatchCallback + ), + /* harmony export */ + escapeRegExp: () => ( + /* binding */ + escapeRegExp + ), + /* harmony export */ + isIntegralNumber: () => ( + /* binding */ + isIntegralNumber + ), + /* harmony export */ + isNullishDimension: () => ( + /* binding */ + isNullishDimension + ), + /* harmony export */ + isTypedArray: () => ( + /* binding */ + isTypedArray + ), + /* harmony export */ + len: () => ( + /* binding */ + len + ), + /* harmony export */ + mergeArrays: () => ( + /* binding */ + mergeArrays + ), + /* harmony export */ + pick: () => ( + /* binding */ + pick + ), + /* harmony export */ + pop: () => ( + /* binding */ + pop + ), + /* harmony export */ + product: () => ( + /* binding */ + product + ), + /* harmony export */ + reverseDictionary: () => ( + /* binding */ + reverseDictionary + ), + /* harmony export */ + saveBlob: () => ( + /* binding */ + saveBlob + ) + /* harmony export */ + }); + function dispatchCallback(progress_callback, data) { + if (progress_callback) progress_callback(data); + } + function reverseDictionary(data) { + return Object.fromEntries(Object.entries(data).map(([key, value]) => [value, key])); + } + function escapeRegExp(string) { + return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + } + function isTypedArray(val) { + return val?.prototype?.__proto__?.constructor?.name === "TypedArray"; + } + function isIntegralNumber(x) { + return Number.isInteger(x) || typeof x === "bigint"; + } + function isNullishDimension(x) { + return x === null || x === void 0 || x === -1; + } + function calculateDimensions(arr) { + const dimensions = []; + let current = arr; + while (Array.isArray(current)) { + dimensions.push(current.length); + current = current[0]; + } + return dimensions; + } + function pop(obj, key, defaultValue = void 0) { + const value = obj[key]; + if (value !== void 0) { + delete obj[key]; + return value; + } + if (defaultValue === void 0) { + throw Error(`Key ${key} does not exist in object.`); + } + return defaultValue; + } + function mergeArrays(...arrs) { + return Array.prototype.concat.apply([], arrs); + } + function product(...a) { + return a.reduce((a2, b) => a2.flatMap((d) => b.map((e) => [d, e]))); + } + function calculateReflectOffset(i, w) { + return Math.abs((i + w) % (2 * w) - w); + } + function saveBlob(path, blob) { + const dataURL = URL.createObjectURL(blob); + const downloadLink = document.createElement("a"); + downloadLink.href = dataURL; + downloadLink.download = path; + downloadLink.click(); + downloadLink.remove(); + URL.revokeObjectURL(dataURL); + } + function pick(o, props) { + return Object.assign( + {}, + ...props.map((prop) => { + if (o[prop] !== void 0) { + return { [prop]: o[prop] }; + } + }) + ); + } + function len(s) { + let length = 0; + for (const c of s) ++length; + return length; + } + function count(arr, value) { + let count2 = 0; + for (const v of arr) { + if (v === value) ++count2; + } + return count2; + } + }) + ), + /***/ + "./src/utils/data-structures.js": ( + /*!**************************************!*\ + !*** ./src/utils/data-structures.js ***! + \**************************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + CharTrie: () => ( + /* binding */ + CharTrie + ), + /* harmony export */ + DictionarySplitter: () => ( + /* binding */ + DictionarySplitter + ), + /* harmony export */ + LRUCache: () => ( + /* binding */ + LRUCache + ), + /* harmony export */ + PriorityQueue: () => ( + /* binding */ + PriorityQueue + ), + /* harmony export */ + TokenLattice: () => ( + /* binding */ + TokenLattice + ) + /* harmony export */ + }); + class PriorityQueue { + /** + * Create a new PriorityQueue. + * @param {function(any, any): boolean} comparator Comparator function to determine priority. Defaults to a MaxHeap. + */ + constructor(comparator = (a, b) => a > b, maxSize = Infinity) { + this._heap = []; + this._comparator = comparator; + this._maxSize = maxSize; + } + /** + * The size of the queue + */ + get size() { + return this._heap.length; + } + /** + * Check if the queue is empty. + * @returns {boolean} `true` if the queue is empty, `false` otherwise. + */ + isEmpty() { + return this.size === 0; + } + /** + * Return the element with the highest priority in the queue. + * @returns {any} The highest priority element in the queue. + */ + peek() { + return this._heap[0]; + } + /** + * Add one or more elements to the queue. + * @param {...any} values The values to push into the queue. + * @returns {number} The new size of the queue. + */ + push(...values) { + return this.extend(values); + } + /** + * Add multiple elements to the queue. + * @param {any[]} values The values to push into the queue. + * @returns {number} The new size of the queue. + */ + extend(values) { + for (const value of values) { + if (this.size < this._maxSize) { + this._heap.push(value); + this._siftUp(); + } else { + const smallest = this._smallest(); + if (this._comparator(value, this._heap[smallest])) { + this._heap[smallest] = value; + this._siftUpFrom(smallest); + } + } + } + return this.size; + } + /** + * Remove and return the element with the highest priority in the queue. + * @returns {any} The element with the highest priority in the queue. + */ + pop() { + const poppedValue = this.peek(); + const bottom = this.size - 1; + if (bottom > 0) { + this._swap(0, bottom); + } + this._heap.pop(); + this._siftDown(); + return poppedValue; + } + /** + * Replace the element with the highest priority in the queue with a new value. + * @param {*} value The new value. + * @returns {*} The replaced value. + */ + replace(value) { + const replacedValue = this.peek(); + this._heap[0] = value; + this._siftDown(); + return replacedValue; + } + /** + * Compute the index for the parent of the node at index `i`. + * @param {number} i The index of the node to get the parent of. + * @returns {number} The index of the parent node. + * @private + */ + _parent(i) { + return (i + 1 >>> 1) - 1; + } + /** + * Compute the index for the left child of the node at index `i`. + * @param {number} i The index of the node to get the left child of. + * @returns {number} The index of the left child. + * @private + */ + _left(i) { + return (i << 1) + 1; + } + /** + * Compute the index for the right child of the node at index `i`. + * @param {number} i The index of the node to get the right child of. + * @returns {number} The index of the right child. + * @private + */ + _right(i) { + return i + 1 << 1; + } + /** + * Check if the element at index `i` is greater than the element at index `j`. + * @param {number} i The index of the first element to compare. + * @param {number} j The index of the second element to compare. + * @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise. + * @private + */ + _greater(i, j) { + return this._comparator(this._heap[i], this._heap[j]); + } + /** + * Swap the elements at indices `i` and `j`. + * @param {number} i The index of the first element to swap. + * @param {number} j The index of the second element to swap. + * @private + */ + _swap(i, j) { + const temp = this._heap[i]; + this._heap[i] = this._heap[j]; + this._heap[j] = temp; + } + /** + * Maintain the heap property by updating positions in the heap, + * starting at the last element and moving up the heap. + * @private + */ + _siftUp() { + this._siftUpFrom(this.size - 1); + } + /** + * Helper function to sift up from a given node. + * @param {number} node The index of the node to start sifting up from. + */ + _siftUpFrom(node) { + while (node > 0 && this._greater(node, this._parent(node))) { + this._swap(node, this._parent(node)); + node = this._parent(node); + } + } + /** + * Maintain the heap property by updating positions in the heap, + * starting at the first element and moving down the heap. + * @private + */ + _siftDown() { + let node = 0; + while (this._left(node) < this.size && this._greater(this._left(node), node) || this._right(node) < this.size && this._greater(this._right(node), node)) { + const maxChild = this._right(node) < this.size && this._greater(this._right(node), this._left(node)) ? this._right(node) : this._left(node); + this._swap(node, maxChild); + node = maxChild; + } + } + /** + * Get the index of the smallest element in the heap. Since we use an array-based heap, + * the index can be computed without needing to traverse the heap. + * @private + */ + _smallest() { + return 2 ** Math.floor(Math.log2(this.size)) - 1; + } + } + class CharTrie { + constructor() { + this.root = CharTrieNode.default(); + } + /** + * Adds one or more `texts` to the trie. + * @param {string[]} texts The strings to add to the trie. + */ + extend(texts) { + for (const text of texts) { + this.push(text); + } + } + /** + * Adds text to the trie. + * @param {string} text The string to add to the trie. + */ + push(text) { + let node = this.root; + for (const ch2 of text) { + let child = node.children.get(ch2); + if (child === void 0) { + child = CharTrieNode.default(); + node.children.set(ch2, child); + } + node = child; + } + node.isLeaf = true; + } + /** + * Searches the trie for all strings with a common prefix of `text`. + * @param {string} text The common prefix to search for. + * @yields {string} Each string in the trie that has `text` as a prefix. + */ + *commonPrefixSearch(text) { + let node = this.root; + if (node === void 0) return; + let prefix = ""; + for (const ch2 of text) { + prefix += ch2; + node = node.children.get(ch2); + if (node === void 0) return; + if (node.isLeaf) { + yield prefix; + } + } + } + } + class CharTrieNode { + /** + * Create a new CharTrieNode. + * @param {boolean} isLeaf Whether the node is a leaf node or not. + * @param {Map} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`. + */ + constructor(isLeaf, children) { + this.isLeaf = isLeaf; + this.children = children; + } + /** + * Returns a new `CharTrieNode` instance with default values. + * @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map. + */ + static default() { + return new CharTrieNode(false, /* @__PURE__ */ new Map()); + } + } + class TokenLattice { + /** + * Creates a new TokenLattice instance. + * + * @param {string} sentence The input sentence to be tokenized. + * @param {number} bosTokenId The beginning-of-sequence token ID. + * @param {number} eosTokenId The end-of-sequence token ID. + */ + constructor(sentence, bosTokenId, eosTokenId) { + this.chars = Array.from(sentence); + this.len = this.chars.length; + this.bosTokenId = bosTokenId; + this.eosTokenId = eosTokenId; + this.nodes = []; + this.beginNodes = Array.from({ length: this.len + 1 }, () => []); + this.endNodes = Array.from({ length: this.len + 1 }, () => []); + const bos = new TokenLatticeNode(this.bosTokenId, 0, 0, 0, 0); + const eos = new TokenLatticeNode(this.eosTokenId, 1, this.len, 0, 0); + this.nodes.push(bos.clone()); + this.nodes.push(eos.clone()); + this.beginNodes[this.len].push(eos); + this.endNodes[0].push(bos); + } + /** + * Inserts a new token node into the token lattice. + * + * @param {number} pos The starting position of the token. + * @param {number} length The length of the token. + * @param {number} score The score of the token. + * @param {number} tokenId The token ID of the token. + */ + insert(pos, length, score, tokenId) { + const nodeId = this.nodes.length; + const node = new TokenLatticeNode(tokenId, nodeId, pos, length, score); + this.beginNodes[pos].push(node); + this.endNodes[pos + length].push(node); + this.nodes.push(node); + } + /** + * Implements the Viterbi algorithm to compute the most likely sequence of tokens. + * + * @returns {TokenLatticeNode[]} The most likely sequence of tokens. + */ + viterbi() { + const len = this.len; + let pos = 0; + while (pos <= len) { + if (this.beginNodes[pos].length == 0) { + return []; + } + for (let rnode of this.beginNodes[pos]) { + rnode.prev = null; + let bestScore = 0; + let bestNode = null; + for (let lnode of this.endNodes[pos]) { + const score = lnode.backtraceScore + rnode.score; + if (bestNode === null || score > bestScore) { + bestNode = lnode.clone(); + bestScore = score; + } + } + if (bestNode !== null) { + rnode.prev = bestNode; + rnode.backtraceScore = bestScore; + } else { + return []; + } + } + ++pos; + } + const results = []; + const root = this.beginNodes[len][0]; + const prev = root.prev; + if (prev === null) { + return []; + } + let node = prev.clone(); + while (node.prev !== null) { + results.push(node.clone()); + const n = node.clone(); + node = n.prev.clone(); + } + results.reverse(); + return results; + } + /** + * @param {TokenLatticeNode} node + * @returns {string} The array of nodes representing the most likely sequence of tokens. + */ + piece(node) { + return this.chars.slice(node.pos, node.pos + node.length).join(""); + } + /** + * @returns {string[]} The most likely sequence of tokens. + */ + tokens() { + const nodes = this.viterbi(); + return nodes.map((x) => this.piece(x)); + } + /** + * @returns {number[]} The most likely sequence of token ids. + */ + tokenIds() { + const nodes = this.viterbi(); + return nodes.map((x) => x.tokenId); + } + } + class TokenLatticeNode { + /** + * Represents a node in a token lattice for a given sentence. + * @param {number} tokenId The ID of the token associated with this node. + * @param {number} nodeId The ID of this node. + * @param {number} pos The starting position of the token in the sentence. + * @param {number} length The length of the token. + * @param {number} score The score associated with the token. + */ + constructor(tokenId, nodeId, pos, length, score) { + this.tokenId = tokenId; + this.nodeId = nodeId; + this.pos = pos; + this.length = length; + this.score = score; + this.prev = null; + this.backtraceScore = 0; + } + /** + * Returns a clone of this node. + * @returns {TokenLatticeNode} A clone of this node. + */ + clone() { + const n = new TokenLatticeNode(this.tokenId, this.nodeId, this.pos, this.length, this.score); + n.prev = this.prev; + n.backtraceScore = this.backtraceScore; + return n; + } + } + class DictionarySplitter { + /** + * @param {string[]} dictionary The dictionary of words to use for splitting. + */ + constructor(dictionary) { + this.trie = this._buildTrie(dictionary); + } + /** + * Builds a trie from the given dictionary. + * @param {string[]} dictionary The dictionary of words to build the trie from. + * @returns {Object} The root node of the trie. + * @private + */ + _buildTrie(dictionary) { + const trie = /* @__PURE__ */ Object.create(null); + for (const word of dictionary) { + let node = trie; + for (let i = 0; i < word.length; ++i) { + node = node[word[i]] ??= /* @__PURE__ */ Object.create(null); + } + node.end = word; + } + return trie; + } + /** + * Splits the input text into tokens based on the dictionary. + * @param {string} text The input text to split. + * @returns {string[]} An array of tokens. + */ + split(text) { + const result = []; + const n = text.length; + let start = 0; + let i = 0; + while (i < n) { + let node = this.trie; + let match = null; + let j = i; + while (j < n && (node = node[text[j]])) { + if (node.end) { + match = node.end; + } + ++j; + } + if (match) { + if (i > start) { + result.push(text.slice(start, i)); + } + result.push(match); + i += match.length; + start = i; + } else { + ++i; + } + } + if (start < n) { + result.push(text.slice(start)); + } + return result; + } + } + class LRUCache { + /** + * Creates an LRUCache instance. + * @param {number} capacity The maximum number of items the cache can hold. + */ + constructor(capacity) { + this.capacity = capacity; + this.cache = /* @__PURE__ */ new Map(); + } + /** + * Retrieves the value associated with the given key and marks the key as recently used. + * @param {any} key The key to retrieve. + * @returns {any} The value associated with the key, or undefined if the key does not exist. + */ + get(key) { + if (!this.cache.has(key)) return void 0; + const value = this.cache.get(key); + this.cache.delete(key); + this.cache.set(key, value); + return value; + } + /** + * Inserts or updates the key-value pair in the cache. + * If the key already exists, it is updated and marked as recently used. + * If the cache exceeds its capacity, the least recently used item is evicted. + * @param {any} key The key to add or update. + * @param {any} value The value to associate with the key. + */ + put(key, value) { + if (this.cache.has(key)) { + this.cache.delete(key); + } + this.cache.set(key, value); + if (this.cache.size > this.capacity) { + this.cache.delete(this.cache.keys().next().value); + } + } + /** + * Clears the cache. + */ + clear() { + this.cache.clear(); + } + } + }) + ), + /***/ + "./src/utils/devices.js": ( + /*!******************************!*\ + !*** ./src/utils/devices.js ***! + \******************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + DEVICE_TYPES: () => ( + /* binding */ + DEVICE_TYPES + ) + /* harmony export */ + }); + const DEVICE_TYPES = Object.freeze({ + auto: "auto", + // Auto-detect based on device and environment + gpu: "gpu", + // Auto-detect GPU + cpu: "cpu", + // CPU + wasm: "wasm", + // WebAssembly + webgpu: "webgpu", + // WebGPU + cuda: "cuda", + // CUDA + dml: "dml", + // DirectML + webnn: "webnn", + // WebNN (default) + "webnn-npu": "webnn-npu", + // WebNN NPU + "webnn-gpu": "webnn-gpu", + // WebNN GPU + "webnn-cpu": "webnn-cpu" + // WebNN CPU + }); + }) + ), + /***/ + "./src/utils/dtypes.js": ( + /*!*****************************!*\ + !*** ./src/utils/dtypes.js ***! + \*****************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + DATA_TYPES: () => ( + /* binding */ + DATA_TYPES + ), + /* harmony export */ + DEFAULT_DEVICE_DTYPE_MAPPING: () => ( + /* binding */ + DEFAULT_DEVICE_DTYPE_MAPPING + ), + /* harmony export */ + DEFAULT_DTYPE_SUFFIX_MAPPING: () => ( + /* binding */ + DEFAULT_DTYPE_SUFFIX_MAPPING + ), + /* harmony export */ + isWebGpuFp16Supported: () => ( + /* binding */ + isWebGpuFp16Supported + ) + /* harmony export */ + }); + var _env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ../env.js */ + "./src/env.js" + ); + var _devices_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ./devices.js */ + "./src/utils/devices.js" + ); + const isWebGpuFp16Supported = /* @__PURE__ */ (function() { + let cachedResult; + return async function() { + if (cachedResult === void 0) { + if (!_env_js__WEBPACK_IMPORTED_MODULE_0__.apis.IS_WEBGPU_AVAILABLE) { + cachedResult = false; + } else { + try { + const adapter = await navigator.gpu.requestAdapter(); + cachedResult = adapter.features.has("shader-f16"); + } catch (e) { + cachedResult = false; + } + } + } + return cachedResult; + }; + })(); + const DATA_TYPES = Object.freeze({ + auto: "auto", + // Auto-detect based on environment + fp32: "fp32", + fp16: "fp16", + q8: "q8", + int8: "int8", + uint8: "uint8", + q4: "q4", + bnb4: "bnb4", + q4f16: "q4f16" + // fp16 model with int4 block weight quantization + }); + const DEFAULT_DEVICE_DTYPE_MAPPING = Object.freeze({ + // NOTE: If not specified, will default to fp32 + [_devices_js__WEBPACK_IMPORTED_MODULE_1__.DEVICE_TYPES.wasm]: DATA_TYPES.q8 + }); + const DEFAULT_DTYPE_SUFFIX_MAPPING = Object.freeze({ + [DATA_TYPES.fp32]: "", + [DATA_TYPES.fp16]: "_fp16", + [DATA_TYPES.int8]: "_int8", + [DATA_TYPES.uint8]: "_uint8", + [DATA_TYPES.q8]: "_quantized", + [DATA_TYPES.q4]: "_q4", + [DATA_TYPES.q4f16]: "_q4f16", + [DATA_TYPES.bnb4]: "_bnb4" + }); + }) + ), + /***/ + "./src/utils/generic.js": ( + /*!******************************!*\ + !*** ./src/utils/generic.js ***! + \******************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + Callable: () => ( + /* binding */ + Callable + ) + /* harmony export */ + }); + const Callable = ( + /** @type {any} */ + class { + /** + * Creates a new instance of the Callable class. + */ + constructor() { + let closure = function(...args) { + return closure._call(...args); + }; + return Object.setPrototypeOf(closure, new.target.prototype); + } + /** + * This method should be implemented in subclasses to provide the + * functionality of the callable object. + * + * @param {any[]} args + * @throws {Error} If the subclass does not implement the `_call` method. + */ + _call(...args) { + throw Error("Must implement _call method in subclass"); + } + } + ); + }) + ), + /***/ + "./src/utils/hub.js": ( + /*!**************************!*\ + !*** ./src/utils/hub.js ***! + \**************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + MAX_EXTERNAL_DATA_CHUNKS: () => ( + /* binding */ + MAX_EXTERNAL_DATA_CHUNKS + ), + /* harmony export */ + getFile: () => ( + /* binding */ + getFile + ), + /* harmony export */ + getModelFile: () => ( + /* binding */ + getModelFile + ), + /* harmony export */ + getModelJSON: () => ( + /* binding */ + getModelJSON + ), + /* harmony export */ + getModelText: () => ( + /* binding */ + getModelText + ) + /* harmony export */ + }); + var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! node:fs */ + "?7992" + ); + var node_path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! node:path */ + "?5af5" + ); + var _env_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../env.js */ + "./src/env.js" + ); + var _core_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! ./core.js */ + "./src/utils/core.js" + ); + const MAX_EXTERNAL_DATA_CHUNKS = 100; + const CONTENT_TYPE_MAP = { + "txt": "text/plain", + "html": "text/html", + "css": "text/css", + "js": "text/javascript", + "json": "application/json", + "png": "image/png", + "jpg": "image/jpeg", + "jpeg": "image/jpeg", + "gif": "image/gif" + }; + class FileResponse { + /** + * Creates a new `FileResponse` object. + * @param {string} filePath + */ + constructor(filePath) { + this.filePath = filePath; + this.headers = new Headers(); + this.exists = node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(filePath); + if (this.exists) { + this.status = 200; + this.statusText = "OK"; + let stats = node_fs__WEBPACK_IMPORTED_MODULE_0__.statSync(filePath); + this.headers.set("content-length", stats.size.toString()); + this.updateContentType(); + const stream = node_fs__WEBPACK_IMPORTED_MODULE_0__.createReadStream(filePath); + this.body = new ReadableStream({ + start(controller) { + stream.on("data", (chunk) => controller.enqueue(chunk)); + stream.on("end", () => controller.close()); + stream.on("error", (err) => controller.error(err)); + }, + cancel() { + stream.destroy(); + } + }); + } else { + this.status = 404; + this.statusText = "Not Found"; + this.body = null; + } + } + /** + * Updates the 'content-type' header property of the response based on the extension of + * the file specified by the filePath property of the current object. + * @returns {void} + */ + updateContentType() { + const extension = this.filePath.toString().split(".").pop().toLowerCase(); + this.headers.set("content-type", CONTENT_TYPE_MAP[extension] ?? "application/octet-stream"); + } + /** + * Clone the current FileResponse object. + * @returns {FileResponse} A new FileResponse object with the same properties as the current object. + */ + clone() { + let response = new FileResponse(this.filePath); + response.exists = this.exists; + response.status = this.status; + response.statusText = this.statusText; + response.headers = new Headers(this.headers); + return response; + } + /** + * Reads the contents of the file specified by the filePath property and returns a Promise that + * resolves with an ArrayBuffer containing the file's contents. + * @returns {Promise} A Promise that resolves with an ArrayBuffer containing the file's contents. + * @throws {Error} If the file cannot be read. + */ + async arrayBuffer() { + const data = await node_fs__WEBPACK_IMPORTED_MODULE_0__.promises.readFile(this.filePath); + return ( + /** @type {ArrayBuffer} */ + data.buffer + ); + } + /** + * Reads the contents of the file specified by the filePath property and returns a Promise that + * resolves with a Blob containing the file's contents. + * @returns {Promise} A Promise that resolves with a Blob containing the file's contents. + * @throws {Error} If the file cannot be read. + */ + async blob() { + const data = await node_fs__WEBPACK_IMPORTED_MODULE_0__.promises.readFile(this.filePath); + return new Blob([data], { type: this.headers.get("content-type") }); + } + /** + * Reads the contents of the file specified by the filePath property and returns a Promise that + * resolves with a string containing the file's contents. + * @returns {Promise} A Promise that resolves with a string containing the file's contents. + * @throws {Error} If the file cannot be read. + */ + async text() { + const data = await node_fs__WEBPACK_IMPORTED_MODULE_0__.promises.readFile(this.filePath, "utf8"); + return data; + } + /** + * Reads the contents of the file specified by the filePath property and returns a Promise that + * resolves with a parsed JavaScript object containing the file's contents. + * + * @returns {Promise} A Promise that resolves with a parsed JavaScript object containing the file's contents. + * @throws {Error} If the file cannot be read. + */ + async json() { + return JSON.parse(await this.text()); + } + } + function isValidUrl(string, protocols = null, validHosts = null) { + let url; + try { + url = new URL(string); + } catch (_) { + return false; + } + if (protocols && !protocols.includes(url.protocol)) { + return false; + } + if (validHosts && !validHosts.includes(url.hostname)) { + return false; + } + return true; + } + const REPO_ID_REGEX = /^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/; + function isValidHfModelId(string) { + if (!REPO_ID_REGEX.test(string)) return false; + if (string.includes("..") || string.includes("--")) return false; + if (string.endsWith(".git") || string.endsWith(".ipynb")) return false; + return true; + } + async function getFile(urlOrPath) { + if (_env_js__WEBPACK_IMPORTED_MODULE_2__.env.useFS && !isValidUrl(urlOrPath, ["http:", "https:", "blob:"])) { + return new FileResponse( + urlOrPath instanceof URL ? urlOrPath.protocol === "file:" ? urlOrPath.pathname : urlOrPath.toString() : urlOrPath + ); + } else if (typeof process !== "undefined" && process?.release?.name === "node") { + const IS_CI = !!process.env?.TESTING_REMOTELY; + const version2 = _env_js__WEBPACK_IMPORTED_MODULE_2__.env.version; + const headers = new Headers(); + headers.set("User-Agent", `transformers.js/${version2}; is_ci/${IS_CI};`); + const isHFURL = isValidUrl(urlOrPath, ["http:", "https:"], ["huggingface.co", "hf.co"]); + if (isHFURL) { + const token = process.env?.HF_TOKEN ?? process.env?.HF_ACCESS_TOKEN; + if (token) { + headers.set("Authorization", `Bearer ${token}`); + } + } + return fetch(urlOrPath, { headers }); + } else { + return fetch(urlOrPath); + } + } + const ERROR_MAPPING = { + // 4xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses) + 400: "Bad request error occurred while trying to load file", + 401: "Unauthorized access to file", + 403: "Forbidden access to file", + 404: "Could not locate file", + 408: "Request timeout error occurred while trying to load file", + // 5xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#server_error_responses) + 500: "Internal server error error occurred while trying to load file", + 502: "Bad gateway error occurred while trying to load file", + 503: "Service unavailable error occurred while trying to load file", + 504: "Gateway timeout error occurred while trying to load file" + }; + function handleError(status, remoteURL, fatal) { + if (!fatal) { + return null; + } + const message = ERROR_MAPPING[status] ?? `Error (${status}) occurred while trying to load file`; + throw Error(`${message}: "${remoteURL}".`); + } + class FileCache { + /** + * Instantiate a `FileCache` object. + * @param {string} path + */ + constructor(path) { + this.path = path; + } + /** + * Checks whether the given request is in the cache. + * @param {string} request + * @returns {Promise} + */ + async match(request) { + let filePath = node_path__WEBPACK_IMPORTED_MODULE_1__.join(this.path, request); + let file = new FileResponse(filePath); + if (file.exists) { + return file; + } else { + return void 0; + } + } + /** + * Adds the given response to the cache. + * @param {string} request + * @param {Response} response + * @param {(data: {progress: number, loaded: number, total: number}) => void} [progress_callback] Optional. + * The function to call with progress updates + * @returns {Promise} + */ + async put(request, response, progress_callback = void 0) { + let filePath = node_path__WEBPACK_IMPORTED_MODULE_1__.join(this.path, request); + try { + const contentLength = response.headers.get("Content-Length"); + const total = parseInt(contentLength ?? "0"); + let loaded = 0; + await node_fs__WEBPACK_IMPORTED_MODULE_0__.promises.mkdir(node_path__WEBPACK_IMPORTED_MODULE_1__.dirname(filePath), { recursive: true }); + const fileStream = node_fs__WEBPACK_IMPORTED_MODULE_0__.createWriteStream(filePath); + const reader = response.body.getReader(); + while (true) { + const { done, value } = await reader.read(); + if (done) { + break; + } + await new Promise((resolve, reject) => { + fileStream.write(value, (err) => { + if (err) { + reject(err); + return; + } + resolve(); + }); + }); + loaded += value.length; + const progress = total ? loaded / total * 100 : 0; + progress_callback?.({ progress, loaded, total }); + } + fileStream.close(); + } catch (error) { + try { + await node_fs__WEBPACK_IMPORTED_MODULE_0__.promises.unlink(filePath); + } catch { + } + throw error; + } + } + // TODO add the rest? + // addAll(requests: RequestInfo[]): Promise; + // delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; + // keys(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>; + // match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; + // matchAll(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>; + } + async function tryCache(cache, ...names) { + for (let name of names) { + try { + let result = await cache.match(name); + if (result) return result; + } catch (e) { + continue; + } + } + return void 0; + } + async function getModelFile(path_or_repo_id, filename, fatal = true, options = {}, return_path = false) { + if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.env.allowLocalModels) { + if (options.local_files_only) { + throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`)."); + } else if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.env.allowRemoteModels) { + throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`."); + } + } + (0, _core_js__WEBPACK_IMPORTED_MODULE_3__.dispatchCallback)(options.progress_callback, { + status: "initiate", + name: path_or_repo_id, + file: filename + }); + let cache; + if (!cache && _env_js__WEBPACK_IMPORTED_MODULE_2__.env.useCustomCache) { + if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.env.customCache) { + throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined."); + } + if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.env.customCache.match || !_env_js__WEBPACK_IMPORTED_MODULE_2__.env.customCache.put) { + throw new Error( + "`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache" + ); + } + cache = _env_js__WEBPACK_IMPORTED_MODULE_2__.env.customCache; + } + if (!cache && _env_js__WEBPACK_IMPORTED_MODULE_2__.env.useBrowserCache) { + if (typeof caches === "undefined") { + throw Error("Browser cache is not available in this environment."); + } + try { + cache = await caches.open("transformers-cache"); + } catch (e) { + console.warn("An error occurred while opening the browser cache:", e); + } + } + if (!cache && _env_js__WEBPACK_IMPORTED_MODULE_2__.env.useFSCache) { + if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_FS_AVAILABLE) { + throw Error("File System Cache is not available in this environment."); + } + cache = new FileCache(options.cache_dir ?? _env_js__WEBPACK_IMPORTED_MODULE_2__.env.cacheDir); + } + const revision = options.revision ?? "main"; + const requestURL = pathJoin(path_or_repo_id, filename); + const validModelId = isValidHfModelId(path_or_repo_id); + const localPath = validModelId ? pathJoin(_env_js__WEBPACK_IMPORTED_MODULE_2__.env.localModelPath, requestURL) : requestURL; + const remoteURL = pathJoin( + _env_js__WEBPACK_IMPORTED_MODULE_2__.env.remoteHost, + _env_js__WEBPACK_IMPORTED_MODULE_2__.env.remotePathTemplate.replaceAll("{model}", path_or_repo_id).replaceAll("{revision}", encodeURIComponent(revision)), + filename + ); + let cacheKey; + const proposedCacheKey = cache instanceof FileCache ? revision === "main" ? requestURL : pathJoin(path_or_repo_id, revision, filename) : remoteURL; + let toCacheResponse = false; + let response; + if (cache) { + response = await tryCache(cache, localPath, proposedCacheKey); + } + const cacheHit = response !== void 0; + if (response === void 0) { + if (_env_js__WEBPACK_IMPORTED_MODULE_2__.env.allowLocalModels) { + const isURL = isValidUrl(requestURL, ["http:", "https:"]); + if (!isURL) { + try { + response = await getFile(localPath); + cacheKey = localPath; + } catch (e) { + console.warn(`Unable to load from local path "${localPath}": "${e}"`); + } + } else if (options.local_files_only) { + throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${requestURL}.`); + } else if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.env.allowRemoteModels) { + throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${requestURL}.`); + } + } + if (response === void 0 || response.status === 404) { + if (options.local_files_only || !_env_js__WEBPACK_IMPORTED_MODULE_2__.env.allowRemoteModels) { + if (fatal) { + throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${localPath}".`); + } else { + return null; + } + } + if (!validModelId) { + throw Error(`Local file missing at "${localPath}" and download aborted due to invalid model ID "${path_or_repo_id}".`); + } + response = await getFile(remoteURL); + if (response.status !== 200) { + return handleError(response.status, remoteURL, fatal); + } + cacheKey = proposedCacheKey; + } + toCacheResponse = cache && typeof Response !== "undefined" && response instanceof Response && response.status === 200; + } + (0, _core_js__WEBPACK_IMPORTED_MODULE_3__.dispatchCallback)(options.progress_callback, { + status: "download", + name: path_or_repo_id, + file: filename + }); + let result; + if (!(_env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_NODE_ENV && return_path)) { + let buffer; + if (!options.progress_callback) { + buffer = new Uint8Array(await response.arrayBuffer()); + } else if (cacheHit && typeof navigator !== "undefined" && /firefox/i.test(navigator.userAgent)) { + buffer = new Uint8Array(await response.arrayBuffer()); + (0, _core_js__WEBPACK_IMPORTED_MODULE_3__.dispatchCallback)(options.progress_callback, { + status: "progress", + name: path_or_repo_id, + file: filename, + progress: 100, + loaded: buffer.length, + total: buffer.length + }); + } else { + buffer = await readResponse(response, (data) => { + (0, _core_js__WEBPACK_IMPORTED_MODULE_3__.dispatchCallback)(options.progress_callback, { + status: "progress", + name: path_or_repo_id, + file: filename, + ...data + }); + }); + } + result = buffer; + } + if ( + // Only cache web responses + // i.e., do not cache FileResponses (prevents duplication) + toCacheResponse && cacheKey && // Check again whether request is in cache. If not, we add the response to the cache + await cache.match(cacheKey) === void 0 + ) { + if (!result) { + const wrapped_progress = options.progress_callback ? (data) => (0, _core_js__WEBPACK_IMPORTED_MODULE_3__.dispatchCallback)(options.progress_callback, { + status: "progress", + name: path_or_repo_id, + file: filename, + ...data + }) : void 0; + await cache.put( + cacheKey, + /** @type {Response} */ + response, + wrapped_progress + ); + } else { + await cache.put(cacheKey, new Response(result, { + headers: response.headers + })).catch((err) => { + console.warn(`Unable to add response to browser cache: ${err}.`); + }); + } + } + (0, _core_js__WEBPACK_IMPORTED_MODULE_3__.dispatchCallback)(options.progress_callback, { + status: "done", + name: path_or_repo_id, + file: filename + }); + if (result) { + if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_NODE_ENV && return_path) { + throw new Error("Cannot return path in a browser environment."); + } + return result; + } + if (response instanceof FileResponse) { + return response.filePath; + } + const cachedResponse = await cache?.match(cacheKey); + if (cachedResponse instanceof FileResponse) { + return cachedResponse.filePath; + } else if (cachedResponse instanceof Response) { + return new Uint8Array(await cachedResponse.arrayBuffer()); + } else if (typeof cachedResponse === "string") { + return cachedResponse; + } + throw new Error("Unable to get model file path or buffer."); + } + async function getModelText(modelPath, fileName, fatal = true, options = {}) { + const buffer = await getModelFile(modelPath, fileName, fatal, options, false); + if (buffer === null) { + return null; + } + const decoder = new TextDecoder("utf-8"); + return decoder.decode( + /** @type {Uint8Array} */ + buffer + ); + } + async function getModelJSON(modelPath, fileName, fatal = true, options = {}) { + const text = await getModelText(modelPath, fileName, fatal, options); + if (text === null) { + return {}; + } + return JSON.parse(text); + } + async function readResponse(response, progress_callback) { + const contentLength = response.headers.get("Content-Length"); + if (contentLength === null) { + console.warn("Unable to determine content-length from response headers. Will expand buffer when needed."); + } + let total = parseInt(contentLength ?? "0"); + let buffer = new Uint8Array(total); + let loaded = 0; + const reader = response.body.getReader(); + async function read() { + const { done, value } = await reader.read(); + if (done) return; + const newLoaded = loaded + value.length; + if (newLoaded > total) { + total = newLoaded; + const newBuffer = new Uint8Array(total); + newBuffer.set(buffer); + buffer = newBuffer; + } + buffer.set(value, loaded); + loaded = newLoaded; + const progress = loaded / total * 100; + progress_callback({ progress, loaded, total }); + return read(); + } + await read(); + return buffer; + } + function pathJoin(...parts) { + parts = parts.map((part, index) => { + if (index) { + part = part.replace(new RegExp("^/"), ""); + } + if (index !== parts.length - 1) { + part = part.replace(new RegExp("/$"), ""); + } + return part; + }); + return parts.join("/"); + } + }) + ), + /***/ + "./src/utils/image.js": ( + /*!****************************!*\ + !*** ./src/utils/image.js ***! + \****************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + RawImage: () => ( + /* binding */ + RawImage + ), + /* harmony export */ + load_image: () => ( + /* binding */ + load_image + ) + /* harmony export */ + }); + var _core_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ./core.js */ + "./src/utils/core.js" + ); + var _hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ./hub.js */ + "./src/utils/hub.js" + ); + var _env_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../env.js */ + "./src/env.js" + ); + var _tensor_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__2( + /*! ./tensor.js */ + "./src/utils/tensor.js" + ); + var sharp__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__2( + /*! sharp */ + "?2b25" + ); + let createCanvasFunction; + let ImageDataClass; + let loadImageFunction; + const IS_BROWSER_OR_WEBWORKER = _env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_BROWSER_ENV || _env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_WEBWORKER_ENV; + if (IS_BROWSER_OR_WEBWORKER) { + createCanvasFunction = (width, height) => { + if (!self.OffscreenCanvas) { + throw new Error("OffscreenCanvas not supported by this browser."); + } + return new self.OffscreenCanvas(width, height); + }; + loadImageFunction = self.createImageBitmap; + ImageDataClass = self.ImageData; + } else if (sharp__WEBPACK_IMPORTED_MODULE_4__) { + loadImageFunction = async (img) => { + const metadata = await img.metadata(); + const rawChannels = metadata.channels; + const { data, info } = await img.rotate().raw().toBuffer({ resolveWithObject: true }); + const newImage = new RawImage(new Uint8ClampedArray(data), info.width, info.height, info.channels); + if (rawChannels !== void 0 && rawChannels !== info.channels) { + newImage.convert(rawChannels); + } + return newImage; + }; + } else { + throw new Error("Unable to load image processing library."); + } + const RESAMPLING_MAPPING = { + 0: "nearest", + 1: "lanczos", + 2: "bilinear", + 3: "bicubic", + 4: "box", + 5: "hamming" + }; + const CONTENT_TYPE_MAP = /* @__PURE__ */ new Map([ + ["png", "image/png"], + ["jpg", "image/jpeg"], + ["jpeg", "image/jpeg"], + ["gif", "image/gif"] + ]); + class RawImage { + /** + * Create a new `RawImage` object. + * @param {Uint8ClampedArray|Uint8Array} data The pixel data. + * @param {number} width The width of the image. + * @param {number} height The height of the image. + * @param {1|2|3|4} channels The number of channels. + */ + constructor(data, width, height, channels) { + this.data = data; + this.width = width; + this.height = height; + this.channels = channels; + } + /** + * Returns the size of the image (width, height). + * @returns {[number, number]} The size of the image (width, height). + */ + get size() { + return [this.width, this.height]; + } + /** + * Helper method for reading an image from a variety of input types. + * @param {RawImage|string|URL|Blob|HTMLCanvasElement|OffscreenCanvas} input + * @returns The image object. + * + * **Example:** Read image from a URL. + * ```javascript + * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg'); + * // RawImage { + * // "data": Uint8ClampedArray [ 25, 25, 25, 19, 19, 19, ... ], + * // "width": 800, + * // "height": 533, + * // "channels": 3 + * // } + * ``` + */ + static async read(input) { + if (input instanceof RawImage) { + return input; + } else if (typeof input === "string" || input instanceof URL) { + return await this.fromURL(input); + } else if (input instanceof Blob) { + return await this.fromBlob(input); + } else if (typeof HTMLCanvasElement !== "undefined" && input instanceof HTMLCanvasElement || typeof OffscreenCanvas !== "undefined" && input instanceof OffscreenCanvas) { + return this.fromCanvas(input); + } else { + throw new Error(`Unsupported input type: ${typeof input}`); + } + } + /** + * Read an image from a canvas. + * @param {HTMLCanvasElement|OffscreenCanvas} canvas The canvas to read the image from. + * @returns {RawImage} The image object. + */ + static fromCanvas(canvas) { + if (!IS_BROWSER_OR_WEBWORKER) { + throw new Error("fromCanvas() is only supported in browser environments."); + } + const ctx = ( + /** @type {CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D} */ + canvas.getContext("2d") + ); + const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data; + return new RawImage(data, canvas.width, canvas.height, 4); + } + /** + * Read an image from a URL or file path. + * @param {string|URL} url The URL or file path to read the image from. + * @returns {Promise} The image object. + */ + static async fromURL(url) { + const response = await (0, _hub_js__WEBPACK_IMPORTED_MODULE_1__.getFile)(url); + if (response.status !== 200) { + throw new Error(`Unable to read image from "${url}" (${response.status} ${response.statusText})`); + } + const blob = await response.blob(); + return this.fromBlob(blob); + } + /** + * Helper method to create a new Image from a blob. + * @param {Blob} blob The blob to read the image from. + * @returns {Promise} The image object. + */ + static async fromBlob(blob) { + if (IS_BROWSER_OR_WEBWORKER) { + const img = await loadImageFunction(blob); + const ctx = createCanvasFunction(img.width, img.height).getContext("2d"); + ctx.drawImage(img, 0, 0); + return new this(ctx.getImageData(0, 0, img.width, img.height).data, img.width, img.height, 4); + } else { + const img = sharp__WEBPACK_IMPORTED_MODULE_4__(await blob.arrayBuffer()); + return await loadImageFunction(img); + } + } + /** + * Helper method to create a new Image from a tensor + * @param {Tensor} tensor + */ + static fromTensor(tensor, channel_format = "CHW") { + if (tensor.dims.length !== 3) { + throw new Error(`Tensor should have 3 dimensions, but has ${tensor.dims.length} dimensions.`); + } + if (channel_format === "CHW") { + tensor = tensor.transpose(1, 2, 0); + } else if (channel_format === "HWC") { + } else { + throw new Error(`Unsupported channel format: ${channel_format}`); + } + if (!(tensor.data instanceof Uint8ClampedArray || tensor.data instanceof Uint8Array)) { + throw new Error(`Unsupported tensor type: ${tensor.type}`); + } + switch (tensor.dims[2]) { + case 1: + case 2: + case 3: + case 4: + return new RawImage(tensor.data, tensor.dims[1], tensor.dims[0], tensor.dims[2]); + default: + throw new Error(`Unsupported number of channels: ${tensor.dims[2]}`); + } + } + /** + * Convert the image to grayscale format. + * @returns {RawImage} `this` to support chaining. + */ + grayscale() { + if (this.channels === 1) { + return this; + } + const newData = new Uint8ClampedArray(this.width * this.height * 1); + switch (this.channels) { + case 3: + // rgb to grayscale + case 4: + for (let i = 0, offset = 0; i < this.data.length; i += this.channels) { + const red = this.data[i]; + const green = this.data[i + 1]; + const blue = this.data[i + 2]; + newData[offset++] = Math.round(0.2989 * red + 0.587 * green + 0.114 * blue); + } + break; + default: + throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); + } + return this._update(newData, this.width, this.height, 1); + } + /** + * Convert the image to RGB format. + * @returns {RawImage} `this` to support chaining. + */ + rgb() { + if (this.channels === 3) { + return this; + } + const newData = new Uint8ClampedArray(this.width * this.height * 3); + switch (this.channels) { + case 1: + for (let i = 0, offset = 0; i < this.data.length; ++i) { + newData[offset++] = this.data[i]; + newData[offset++] = this.data[i]; + newData[offset++] = this.data[i]; + } + break; + case 4: + for (let i = 0, offset = 0; i < this.data.length; i += 4) { + newData[offset++] = this.data[i]; + newData[offset++] = this.data[i + 1]; + newData[offset++] = this.data[i + 2]; + } + break; + default: + throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); + } + return this._update(newData, this.width, this.height, 3); + } + /** + * Convert the image to RGBA format. + * @returns {RawImage} `this` to support chaining. + */ + rgba() { + if (this.channels === 4) { + return this; + } + const newData = new Uint8ClampedArray(this.width * this.height * 4); + switch (this.channels) { + case 1: + for (let i = 0, offset = 0; i < this.data.length; ++i) { + newData[offset++] = this.data[i]; + newData[offset++] = this.data[i]; + newData[offset++] = this.data[i]; + newData[offset++] = 255; + } + break; + case 3: + for (let i = 0, offset = 0; i < this.data.length; i += 3) { + newData[offset++] = this.data[i]; + newData[offset++] = this.data[i + 1]; + newData[offset++] = this.data[i + 2]; + newData[offset++] = 255; + } + break; + default: + throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); + } + return this._update(newData, this.width, this.height, 4); + } + /** + * Apply an alpha mask to the image. Operates in place. + * @param {RawImage} mask The mask to apply. It should have a single channel. + * @returns {RawImage} The masked image. + * @throws {Error} If the mask is not the same size as the image. + * @throws {Error} If the image does not have 4 channels. + * @throws {Error} If the mask is not a single channel. + */ + putAlpha(mask) { + if (mask.width !== this.width || mask.height !== this.height) { + throw new Error(`Expected mask size to be ${this.width}x${this.height}, but got ${mask.width}x${mask.height}`); + } + if (mask.channels !== 1) { + throw new Error(`Expected mask to have 1 channel, but got ${mask.channels}`); + } + const this_data = this.data; + const mask_data = mask.data; + const num_pixels = this.width * this.height; + if (this.channels === 3) { + const newData = new Uint8ClampedArray(num_pixels * 4); + for (let i = 0, in_offset = 0, out_offset = 0; i < num_pixels; ++i) { + newData[out_offset++] = this_data[in_offset++]; + newData[out_offset++] = this_data[in_offset++]; + newData[out_offset++] = this_data[in_offset++]; + newData[out_offset++] = mask_data[i]; + } + return this._update(newData, this.width, this.height, 4); + } else if (this.channels === 4) { + for (let i = 0; i < num_pixels; ++i) { + this_data[4 * i + 3] = mask_data[i]; + } + return this; + } + throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`); + } + /** + * Resize the image to the given dimensions. This method uses the canvas API to perform the resizing. + * @param {number} width The width of the new image. `null` or `-1` will preserve the aspect ratio. + * @param {number} height The height of the new image. `null` or `-1` will preserve the aspect ratio. + * @param {Object} options Additional options for resizing. + * @param {0|1|2|3|4|5|string} [options.resample] The resampling method to use. + * @returns {Promise} `this` to support chaining. + */ + async resize(width, height, { + resample = 2 + } = {}) { + if (this.width === width && this.height === height) { + return this; + } + let resampleMethod = RESAMPLING_MAPPING[resample] ?? resample; + const nullish_width = (0, _core_js__WEBPACK_IMPORTED_MODULE_0__.isNullishDimension)(width); + const nullish_height = (0, _core_js__WEBPACK_IMPORTED_MODULE_0__.isNullishDimension)(height); + if (nullish_width && nullish_height) { + return this; + } else if (nullish_width) { + width = height / this.height * this.width; + } else if (nullish_height) { + height = width / this.width * this.height; + } + if (IS_BROWSER_OR_WEBWORKER) { + const numChannels = this.channels; + const canvas = this.toCanvas(); + const ctx = createCanvasFunction(width, height).getContext("2d"); + ctx.drawImage(canvas, 0, 0, width, height); + const resizedImage = new RawImage(ctx.getImageData(0, 0, width, height).data, width, height, 4); + return resizedImage.convert(numChannels); + } else { + let img = this.toSharp(); + switch (resampleMethod) { + case "box": + case "hamming": + if (resampleMethod === "box" || resampleMethod === "hamming") { + console.warn(`Resampling method ${resampleMethod} is not yet supported. Using bilinear instead.`); + resampleMethod = "bilinear"; + } + case "nearest": + case "bilinear": + case "bicubic": + img = img.affine([width / this.width, 0, 0, height / this.height], { + interpolator: resampleMethod + }); + break; + case "lanczos": + img = img.resize({ + width, + height, + fit: "fill", + kernel: "lanczos3" + // PIL Lanczos uses a kernel size of 3 + }); + break; + default: + throw new Error(`Resampling method ${resampleMethod} is not supported.`); + } + return await loadImageFunction(img); + } + } + async pad([left, right, top, bottom]) { + left = Math.max(left, 0); + right = Math.max(right, 0); + top = Math.max(top, 0); + bottom = Math.max(bottom, 0); + if (left === 0 && right === 0 && top === 0 && bottom === 0) { + return this; + } + if (IS_BROWSER_OR_WEBWORKER) { + const numChannels = this.channels; + const canvas = this.toCanvas(); + const newWidth = this.width + left + right; + const newHeight = this.height + top + bottom; + const ctx = createCanvasFunction(newWidth, newHeight).getContext("2d"); + ctx.drawImage( + canvas, + 0, + 0, + this.width, + this.height, + left, + top, + this.width, + this.height + ); + const paddedImage = new RawImage( + ctx.getImageData(0, 0, newWidth, newHeight).data, + newWidth, + newHeight, + 4 + ); + return paddedImage.convert(numChannels); + } else { + const img = this.toSharp().extend({ left, right, top, bottom }); + return await loadImageFunction(img); + } + } + async crop([x_min, y_min, x_max, y_max]) { + x_min = Math.max(x_min, 0); + y_min = Math.max(y_min, 0); + x_max = Math.min(x_max, this.width - 1); + y_max = Math.min(y_max, this.height - 1); + if (x_min === 0 && y_min === 0 && x_max === this.width - 1 && y_max === this.height - 1) { + return this; + } + const crop_width = x_max - x_min + 1; + const crop_height = y_max - y_min + 1; + if (IS_BROWSER_OR_WEBWORKER) { + const numChannels = this.channels; + const canvas = this.toCanvas(); + const ctx = createCanvasFunction(crop_width, crop_height).getContext("2d"); + ctx.drawImage( + canvas, + x_min, + y_min, + crop_width, + crop_height, + 0, + 0, + crop_width, + crop_height + ); + const resizedImage = new RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4); + return resizedImage.convert(numChannels); + } else { + const img = this.toSharp().extract({ + left: x_min, + top: y_min, + width: crop_width, + height: crop_height + }); + return await loadImageFunction(img); + } + } + async center_crop(crop_width, crop_height) { + if (this.width === crop_width && this.height === crop_height) { + return this; + } + const width_offset = (this.width - crop_width) / 2; + const height_offset = (this.height - crop_height) / 2; + if (IS_BROWSER_OR_WEBWORKER) { + const numChannels = this.channels; + const canvas = this.toCanvas(); + const ctx = createCanvasFunction(crop_width, crop_height).getContext("2d"); + let sourceX = 0; + let sourceY = 0; + let destX = 0; + let destY = 0; + if (width_offset >= 0) { + sourceX = width_offset; + } else { + destX = -width_offset; + } + if (height_offset >= 0) { + sourceY = height_offset; + } else { + destY = -height_offset; + } + ctx.drawImage( + canvas, + sourceX, + sourceY, + crop_width, + crop_height, + destX, + destY, + crop_width, + crop_height + ); + const resizedImage = new RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4); + return resizedImage.convert(numChannels); + } else { + let img = this.toSharp(); + if (width_offset >= 0 && height_offset >= 0) { + img = img.extract({ + left: Math.floor(width_offset), + top: Math.floor(height_offset), + width: crop_width, + height: crop_height + }); + } else if (width_offset <= 0 && height_offset <= 0) { + const top = Math.floor(-height_offset); + const left = Math.floor(-width_offset); + img = img.extend({ + top, + left, + // Ensures the resulting image has the desired dimensions + right: crop_width - this.width - left, + bottom: crop_height - this.height - top + }); + } else { + let y_padding = [0, 0]; + let y_extract = 0; + if (height_offset < 0) { + y_padding[0] = Math.floor(-height_offset); + y_padding[1] = crop_height - this.height - y_padding[0]; + } else { + y_extract = Math.floor(height_offset); + } + let x_padding = [0, 0]; + let x_extract = 0; + if (width_offset < 0) { + x_padding[0] = Math.floor(-width_offset); + x_padding[1] = crop_width - this.width - x_padding[0]; + } else { + x_extract = Math.floor(width_offset); + } + img = img.extend({ + top: y_padding[0], + bottom: y_padding[1], + left: x_padding[0], + right: x_padding[1] + }).extract({ + left: x_extract, + top: y_extract, + width: crop_width, + height: crop_height + }); + } + return await loadImageFunction(img); + } + } + async toBlob(type = "image/png", quality = 1) { + if (!IS_BROWSER_OR_WEBWORKER) { + throw new Error("toBlob() is only supported in browser environments."); + } + const canvas = this.toCanvas(); + return await canvas.convertToBlob({ type, quality }); + } + toTensor(channel_format = "CHW") { + let tensor = new _tensor_js__WEBPACK_IMPORTED_MODULE_3__.Tensor( + "uint8", + new Uint8Array(this.data), + [this.height, this.width, this.channels] + ); + if (channel_format === "HWC") { + } else if (channel_format === "CHW") { + tensor = tensor.permute(2, 0, 1); + } else { + throw new Error(`Unsupported channel format: ${channel_format}`); + } + return tensor; + } + toCanvas() { + if (!IS_BROWSER_OR_WEBWORKER) { + throw new Error("toCanvas() is only supported in browser environments."); + } + const cloned = this.clone().rgba(); + const clonedCanvas = createCanvasFunction(cloned.width, cloned.height); + const data = new ImageDataClass(cloned.data, cloned.width, cloned.height); + clonedCanvas.getContext("2d").putImageData(data, 0, 0); + return clonedCanvas; + } + /** + * Split this image into individual bands. This method returns an array of individual image bands from an image. + * For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue). + * + * Inspired by PIL's `Image.split()` [function](https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.split). + * @returns {RawImage[]} An array containing bands. + */ + split() { + const { data, width, height, channels } = this; + const data_type = ( + /** @type {any} */ + data.constructor + ); + const per_channel_length = data.length / channels; + const split_data = Array.from( + { length: channels }, + () => new data_type(per_channel_length) + ); + for (let i = 0; i < per_channel_length; ++i) { + const data_offset = channels * i; + for (let j = 0; j < channels; ++j) { + split_data[j][i] = data[data_offset + j]; + } + } + return split_data.map((data2) => new RawImage(data2, width, height, 1)); + } + /** + * Helper method to update the image data. + * @param {Uint8ClampedArray} data The new image data. + * @param {number} width The new width of the image. + * @param {number} height The new height of the image. + * @param {1|2|3|4|null} [channels] The new number of channels of the image. + * @private + */ + _update(data, width, height, channels = null) { + this.data = data; + this.width = width; + this.height = height; + if (channels !== null) { + this.channels = channels; + } + return this; + } + /** + * Clone the image + * @returns {RawImage} The cloned image + */ + clone() { + return new RawImage(this.data.slice(), this.width, this.height, this.channels); + } + /** + * Helper method for converting image to have a certain number of channels + * @param {number} numChannels The number of channels. Must be 1, 3, or 4. + * @returns {RawImage} `this` to support chaining. + */ + convert(numChannels) { + if (this.channels === numChannels) return this; + switch (numChannels) { + case 1: + this.grayscale(); + break; + case 3: + this.rgb(); + break; + case 4: + this.rgba(); + break; + default: + throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); + } + return this; + } + /** + * Save the image to the given path. + * @param {string} path The path to save the image to. + */ + async save(path) { + if (IS_BROWSER_OR_WEBWORKER) { + if (_env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_WEBWORKER_ENV) { + throw new Error("Unable to save an image from a Web Worker."); + } + const extension = path.split(".").pop().toLowerCase(); + const mime = CONTENT_TYPE_MAP.get(extension) ?? "image/png"; + const blob = await this.toBlob(mime); + (0, _core_js__WEBPACK_IMPORTED_MODULE_0__.saveBlob)(path, blob); + } else if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_FS_AVAILABLE) { + throw new Error("Unable to save the image because filesystem is disabled in this environment."); + } else { + const img = this.toSharp(); + return await img.toFile(path); + } + } + toSharp() { + if (IS_BROWSER_OR_WEBWORKER) { + throw new Error("toSharp() is only supported in server-side environments."); + } + return sharp__WEBPACK_IMPORTED_MODULE_4__(this.data, { + raw: { + width: this.width, + height: this.height, + channels: this.channels + } + }); + } + } + const load_image = RawImage.read.bind(RawImage); + }) + ), + /***/ + "./src/utils/maths.js": ( + /*!****************************!*\ + !*** ./src/utils/maths.js ***! + \****************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + FFT: () => ( + /* binding */ + FFT + ), + /* harmony export */ + bankers_round: () => ( + /* binding */ + bankers_round + ), + /* harmony export */ + cos_sim: () => ( + /* binding */ + cos_sim + ), + /* harmony export */ + dot: () => ( + /* binding */ + dot + ), + /* harmony export */ + dynamic_time_warping: () => ( + /* binding */ + dynamic_time_warping + ), + /* harmony export */ + interpolate_data: () => ( + /* binding */ + interpolate_data + ), + /* harmony export */ + log_softmax: () => ( + /* binding */ + log_softmax + ), + /* harmony export */ + magnitude: () => ( + /* binding */ + magnitude + ), + /* harmony export */ + max: () => ( + /* binding */ + max + ), + /* harmony export */ + medianFilter: () => ( + /* binding */ + medianFilter + ), + /* harmony export */ + min: () => ( + /* binding */ + min + ), + /* harmony export */ + permute_data: () => ( + /* binding */ + permute_data + ), + /* harmony export */ + round: () => ( + /* binding */ + round + ), + /* harmony export */ + softmax: () => ( + /* binding */ + softmax + ) + /* harmony export */ + }); + function interpolate_data(input, [in_channels, in_height, in_width], [out_height, out_width], mode = "bilinear", align_corners = false) { + const x_scale = out_width / in_width; + const y_scale = out_height / in_height; + const out_img = new input.constructor(out_height * out_width * in_channels); + const inStride = in_height * in_width; + const outStride = out_height * out_width; + for (let i = 0; i < out_height; ++i) { + for (let j = 0; j < out_width; ++j) { + const outOffset = i * out_width + j; + const x = (j + 0.5) / x_scale - 0.5; + const y = (i + 0.5) / y_scale - 0.5; + let x1 = Math.floor(x); + let y1 = Math.floor(y); + const x2 = Math.min(x1 + 1, in_width - 1); + const y2 = Math.min(y1 + 1, in_height - 1); + x1 = Math.max(x1, 0); + y1 = Math.max(y1, 0); + const s = x - x1; + const t = y - y1; + const w1 = (1 - s) * (1 - t); + const w2 = s * (1 - t); + const w3 = (1 - s) * t; + const w4 = s * t; + const yStride = y1 * in_width; + const xStride = y2 * in_width; + const idx1 = yStride + x1; + const idx2 = yStride + x2; + const idx3 = xStride + x1; + const idx4 = xStride + x2; + for (let k2 = 0; k2 < in_channels; ++k2) { + const cOffset = k2 * inStride; + out_img[k2 * outStride + outOffset] = w1 * input[cOffset + idx1] + w2 * input[cOffset + idx2] + w3 * input[cOffset + idx3] + w4 * input[cOffset + idx4]; + } + } + } + return out_img; + } + function permute_data(array, dims, axes) { + const shape = new Array(axes.length); + const stride = new Array(axes.length); + for (let i = axes.length - 1, s = 1; i >= 0; --i) { + stride[i] = s; + shape[i] = dims[axes[i]]; + s *= shape[i]; + } + const invStride = axes.map((_, i) => stride[axes.indexOf(i)]); + const permutedData = new array.constructor(array.length); + for (let i = 0; i < array.length; ++i) { + let newIndex = 0; + for (let j = dims.length - 1, k2 = i; j >= 0; --j) { + newIndex += k2 % dims[j] * invStride[j]; + k2 = Math.floor(k2 / dims[j]); + } + permutedData[newIndex] = array[i]; + } + return [permutedData, shape]; + } + function softmax(arr) { + const maxVal = max(arr)[0]; + const exps = arr.map((x) => Math.exp(x - maxVal)); + const sumExps = exps.reduce((acc, val) => acc + val, 0); + const softmaxArr = exps.map((x) => x / sumExps); + return ( + /** @type {T} */ + softmaxArr + ); + } + function log_softmax(arr) { + const maxVal = max(arr)[0]; + let sumExps = 0; + for (let i = 0; i < arr.length; ++i) { + sumExps += Math.exp(arr[i] - maxVal); + } + const logSum = Math.log(sumExps); + const logSoftmaxArr = arr.map((x) => x - maxVal - logSum); + return ( + /** @type {T} */ + logSoftmaxArr + ); + } + function dot(arr1, arr2) { + let result = 0; + for (let i = 0; i < arr1.length; ++i) { + result += arr1[i] * arr2[i]; + } + return result; + } + function cos_sim(arr1, arr2) { + const dotProduct = dot(arr1, arr2); + const magnitudeA = magnitude(arr1); + const magnitudeB = magnitude(arr2); + const cosineSimilarity = dotProduct / (magnitudeA * magnitudeB); + return cosineSimilarity; + } + function magnitude(arr) { + return Math.sqrt(arr.reduce((acc, val) => acc + val * val, 0)); + } + function min(arr) { + if (arr.length === 0) throw Error("Array must not be empty"); + let min2 = arr[0]; + let indexOfMin = 0; + for (let i = 1; i < arr.length; ++i) { + if (arr[i] < min2) { + min2 = arr[i]; + indexOfMin = i; + } + } + return ( + /** @type {T extends bigint[]|BigTypedArray ? [bigint, number] : [number, number]} */ + [min2, indexOfMin] + ); + } + function max(arr) { + if (arr.length === 0) throw Error("Array must not be empty"); + let max2 = arr[0]; + let indexOfMax = 0; + for (let i = 1; i < arr.length; ++i) { + if (arr[i] > max2) { + max2 = arr[i]; + indexOfMax = i; + } + } + return ( + /** @type {T extends bigint[]|BigTypedArray ? [bigint, number] : [number, number]} */ + [max2, indexOfMax] + ); + } + function isPowerOfTwo(number) { + return number > 0 && (number & number - 1) === 0; + } + class P2FFT { + /** + * @param {number} size The size of the input array. Must be a power of two larger than 1. + * @throws {Error} FFT size must be a power of two larger than 1. + */ + constructor(size) { + this.size = size | 0; + if (this.size <= 1 || !isPowerOfTwo(this.size)) + throw new Error("FFT size must be a power of two larger than 1"); + this._csize = size << 1; + this.table = new Float64Array(this.size * 2); + for (let i = 0; i < this.table.length; i += 2) { + const angle = Math.PI * i / this.size; + this.table[i] = Math.cos(angle); + this.table[i + 1] = -Math.sin(angle); + } + let power = 0; + for (let t = 1; this.size > t; t <<= 1) + ++power; + this._width = power % 2 === 0 ? power - 1 : power; + this._bitrev = new Int32Array(1 << this._width); + for (let j = 0; j < this._bitrev.length; ++j) { + this._bitrev[j] = 0; + for (let shift = 0; shift < this._width; shift += 2) { + const revShift = this._width - shift - 2; + this._bitrev[j] |= (j >>> shift & 3) << revShift; + } + } + } + /** + * Create a complex number array with size `2 * size` + * + * @returns {Float64Array} A complex number array with size `2 * size` + */ + createComplexArray() { + return new Float64Array(this._csize); + } + /** + * Converts a complex number representation stored in a Float64Array to an array of real numbers. + * + * @param {Float64Array} complex The complex number representation to be converted. + * @param {number[]} [storage] An optional array to store the result in. + * @returns {number[]} An array of real numbers representing the input complex number representation. + */ + fromComplexArray(complex, storage) { + const res = storage || new Array(complex.length >>> 1); + for (let i = 0; i < complex.length; i += 2) + res[i >>> 1] = complex[i]; + return res; + } + /** + * Convert a real-valued input array to a complex-valued output array. + * @param {Float64Array} input The real-valued input array. + * @param {Float64Array} [storage] Optional buffer to store the output array. + * @returns {Float64Array} The complex-valued output array. + */ + toComplexArray(input, storage) { + const res = storage || this.createComplexArray(); + for (let i = 0; i < res.length; i += 2) { + res[i] = input[i >>> 1]; + res[i + 1] = 0; + } + return res; + } + /** + * Performs a Fast Fourier Transform (FFT) on the given input data and stores the result in the output buffer. + * + * @param {Float64Array} out The output buffer to store the result. + * @param {Float64Array} data The input data to transform. + * + * @throws {Error} Input and output buffers must be different. + * + * @returns {void} + */ + transform(out, data) { + if (out === data) + throw new Error("Input and output buffers must be different"); + this._transform4( + out, + data, + 1 + /* DONE */ + ); + } + /** + * Performs a real-valued forward FFT on the given input buffer and stores the result in the given output buffer. + * The input buffer must contain real values only, while the output buffer will contain complex values. The input and + * output buffers must be different. + * + * @param {Float64Array} out The output buffer. + * @param {Float64Array} data The input buffer containing real values. + * + * @throws {Error} If the input and output buffers are the same. + */ + realTransform(out, data) { + if (out === data) + throw new Error("Input and output buffers must be different"); + this._realTransform4( + out, + data, + 1 + /* DONE */ + ); + } + /** + * Performs an inverse FFT transformation on the given `data` array, and stores the result in `out`. + * The `out` array must be a different buffer than the `data` array. The `out` array will contain the + * result of the transformation. The `data` array will not be modified. + * + * @param {Float64Array} out The output buffer for the transformed data. + * @param {Float64Array} data The input data to transform. + * @throws {Error} If `out` and `data` refer to the same buffer. + * @returns {void} + */ + inverseTransform(out, data) { + if (out === data) + throw new Error("Input and output buffers must be different"); + this._transform4( + out, + data, + -1 + /* DONE */ + ); + for (let i = 0; i < out.length; ++i) + out[i] /= this.size; + } + /** + * Performs a radix-4 implementation of a discrete Fourier transform on a given set of data. + * + * @param {Float64Array} out The output buffer for the transformed data. + * @param {Float64Array} data The input buffer of data to be transformed. + * @param {number} inv A scaling factor to apply to the transform. + * @returns {void} + */ + _transform4(out, data, inv) { + const size = this._csize; + const width = this._width; + let step = 1 << width; + let len = size / step << 1; + let outOff; + let t; + const bitrev = this._bitrev; + if (len === 4) { + for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) { + const off = bitrev[t]; + this._singleTransform2(data, out, outOff, off, step); + } + } else { + for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) { + const off = bitrev[t]; + this._singleTransform4(data, out, outOff, off, step, inv); + } + } + const table = this.table; + for (step >>= 2; step >= 2; step >>= 2) { + len = size / step << 1; + const quarterLen = len >>> 2; + for (outOff = 0; outOff < size; outOff += len) { + const limit = outOff + quarterLen - 1; + for (let i = outOff, k2 = 0; i < limit; i += 2, k2 += step) { + const A = i; + const B = A + quarterLen; + const C = B + quarterLen; + const D = C + quarterLen; + const Ar2 = out[A]; + const Ai = out[A + 1]; + const Br2 = out[B]; + const Bi = out[B + 1]; + const Cr2 = out[C]; + const Ci = out[C + 1]; + const Dr2 = out[D]; + const Di = out[D + 1]; + const tableBr = table[k2]; + const tableBi = inv * table[k2 + 1]; + const MBr = Br2 * tableBr - Bi * tableBi; + const MBi = Br2 * tableBi + Bi * tableBr; + const tableCr = table[2 * k2]; + const tableCi = inv * table[2 * k2 + 1]; + const MCr = Cr2 * tableCr - Ci * tableCi; + const MCi = Cr2 * tableCi + Ci * tableCr; + const tableDr = table[3 * k2]; + const tableDi = inv * table[3 * k2 + 1]; + const MDr = Dr2 * tableDr - Di * tableDi; + const MDi = Dr2 * tableDi + Di * tableDr; + const T0r = Ar2 + MCr; + const T0i = Ai + MCi; + const T1r = Ar2 - MCr; + const T1i = Ai - MCi; + const T2r = MBr + MDr; + const T2i = MBi + MDi; + const T3r = inv * (MBr - MDr); + const T3i = inv * (MBi - MDi); + out[A] = T0r + T2r; + out[A + 1] = T0i + T2i; + out[B] = T1r + T3i; + out[B + 1] = T1i - T3r; + out[C] = T0r - T2r; + out[C + 1] = T0i - T2i; + out[D] = T1r - T3i; + out[D + 1] = T1i + T3r; + } + } + } + } + /** + * Performs a radix-2 implementation of a discrete Fourier transform on a given set of data. + * + * @param {Float64Array} data The input buffer of data to be transformed. + * @param {Float64Array} out The output buffer for the transformed data. + * @param {number} outOff The offset at which to write the output data. + * @param {number} off The offset at which to begin reading the input data. + * @param {number} step The step size for indexing the input data. + * @returns {void} + */ + _singleTransform2(data, out, outOff, off, step) { + const evenR = data[off]; + const evenI = data[off + 1]; + const oddR = data[off + step]; + const oddI = data[off + step + 1]; + out[outOff] = evenR + oddR; + out[outOff + 1] = evenI + oddI; + out[outOff + 2] = evenR - oddR; + out[outOff + 3] = evenI - oddI; + } + /** + * Performs radix-4 transformation on input data of length 8 + * + * @param {Float64Array} data Input data array of length 8 + * @param {Float64Array} out Output data array of length 8 + * @param {number} outOff Index of output array to start writing from + * @param {number} off Index of input array to start reading from + * @param {number} step Step size between elements in input array + * @param {number} inv Scaling factor for inverse transform + * + * @returns {void} + */ + _singleTransform4(data, out, outOff, off, step, inv) { + const step2 = step * 2; + const step3 = step * 3; + const Ar2 = data[off]; + const Ai = data[off + 1]; + const Br2 = data[off + step]; + const Bi = data[off + step + 1]; + const Cr2 = data[off + step2]; + const Ci = data[off + step2 + 1]; + const Dr2 = data[off + step3]; + const Di = data[off + step3 + 1]; + const T0r = Ar2 + Cr2; + const T0i = Ai + Ci; + const T1r = Ar2 - Cr2; + const T1i = Ai - Ci; + const T2r = Br2 + Dr2; + const T2i = Bi + Di; + const T3r = inv * (Br2 - Dr2); + const T3i = inv * (Bi - Di); + out[outOff] = T0r + T2r; + out[outOff + 1] = T0i + T2i; + out[outOff + 2] = T1r + T3i; + out[outOff + 3] = T1i - T3r; + out[outOff + 4] = T0r - T2r; + out[outOff + 5] = T0i - T2i; + out[outOff + 6] = T1r - T3i; + out[outOff + 7] = T1i + T3r; + } + /** + * Real input radix-4 implementation + * @param {Float64Array} out Output array for the transformed data + * @param {Float64Array} data Input array of real data to be transformed + * @param {number} inv The scale factor used to normalize the inverse transform + */ + _realTransform4(out, data, inv) { + const size = this._csize; + const width = this._width; + let step = 1 << width; + let len = size / step << 1; + let outOff; + let t; + const bitrev = this._bitrev; + if (len === 4) { + for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) { + const off = bitrev[t]; + this._singleRealTransform2(data, out, outOff, off >>> 1, step >>> 1); + } + } else { + for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) { + const off = bitrev[t]; + this._singleRealTransform4(data, out, outOff, off >>> 1, step >>> 1, inv); + } + } + const table = this.table; + for (step >>= 2; step >= 2; step >>= 2) { + len = size / step << 1; + const halfLen = len >>> 1; + const quarterLen = halfLen >>> 1; + const hquarterLen = quarterLen >>> 1; + for (outOff = 0; outOff < size; outOff += len) { + for (let i = 0, k2 = 0; i <= hquarterLen; i += 2, k2 += step) { + const A = outOff + i; + const B = A + quarterLen; + const C = B + quarterLen; + const D = C + quarterLen; + const Ar2 = out[A]; + const Ai = out[A + 1]; + const Br2 = out[B]; + const Bi = out[B + 1]; + const Cr2 = out[C]; + const Ci = out[C + 1]; + const Dr2 = out[D]; + const Di = out[D + 1]; + const MAr = Ar2; + const MAi = Ai; + const tableBr = table[k2]; + const tableBi = inv * table[k2 + 1]; + const MBr = Br2 * tableBr - Bi * tableBi; + const MBi = Br2 * tableBi + Bi * tableBr; + const tableCr = table[2 * k2]; + const tableCi = inv * table[2 * k2 + 1]; + const MCr = Cr2 * tableCr - Ci * tableCi; + const MCi = Cr2 * tableCi + Ci * tableCr; + const tableDr = table[3 * k2]; + const tableDi = inv * table[3 * k2 + 1]; + const MDr = Dr2 * tableDr - Di * tableDi; + const MDi = Dr2 * tableDi + Di * tableDr; + const T0r = MAr + MCr; + const T0i = MAi + MCi; + const T1r = MAr - MCr; + const T1i = MAi - MCi; + const T2r = MBr + MDr; + const T2i = MBi + MDi; + const T3r = inv * (MBr - MDr); + const T3i = inv * (MBi - MDi); + out[A] = T0r + T2r; + out[A + 1] = T0i + T2i; + out[B] = T1r + T3i; + out[B + 1] = T1i - T3r; + if (i === 0) { + out[C] = T0r - T2r; + out[C + 1] = T0i - T2i; + continue; + } + if (i === hquarterLen) + continue; + const SA = outOff + quarterLen - i; + const SB = outOff + halfLen - i; + out[SA] = T1r - inv * T3i; + out[SA + 1] = -T1i - inv * T3r; + out[SB] = T0r - inv * T2r; + out[SB + 1] = -T0i + inv * T2i; + } + } + } + const half = size >>> 1; + for (let i = 2; i < half; i += 2) { + out[size - i] = out[i]; + out[size - i + 1] = -out[i + 1]; + } + } + /** + * Performs a single real input radix-2 transformation on the provided data + * + * @param {Float64Array} data The input data array + * @param {Float64Array} out The output data array + * @param {number} outOff The output offset + * @param {number} off The input offset + * @param {number} step The step + * + * @returns {void} + */ + _singleRealTransform2(data, out, outOff, off, step) { + const evenR = data[off]; + const oddR = data[off + step]; + out[outOff] = evenR + oddR; + out[outOff + 1] = 0; + out[outOff + 2] = evenR - oddR; + out[outOff + 3] = 0; + } + /** + * Computes a single real-valued transform using radix-4 algorithm. + * This method is only called for len=8. + * + * @param {Float64Array} data The input data array. + * @param {Float64Array} out The output data array. + * @param {number} outOff The offset into the output array. + * @param {number} off The offset into the input array. + * @param {number} step The step size for the input array. + * @param {number} inv The value of inverse. + */ + _singleRealTransform4(data, out, outOff, off, step, inv) { + const step2 = step * 2; + const step3 = step * 3; + const Ar2 = data[off]; + const Br2 = data[off + step]; + const Cr2 = data[off + step2]; + const Dr2 = data[off + step3]; + const T0r = Ar2 + Cr2; + const T1r = Ar2 - Cr2; + const T2r = Br2 + Dr2; + const T3r = inv * (Br2 - Dr2); + out[outOff] = T0r + T2r; + out[outOff + 1] = 0; + out[outOff + 2] = T1r; + out[outOff + 3] = -T3r; + out[outOff + 4] = T0r - T2r; + out[outOff + 5] = 0; + out[outOff + 6] = T1r; + out[outOff + 7] = T3r; + } + } + class NP2FFT { + /** + * Constructs a new NP2FFT object. + * @param {number} fft_length The length of the FFT + */ + constructor(fft_length) { + const a = 2 * (fft_length - 1); + const b = 2 * (2 * fft_length - 1); + const nextP2 = 2 ** Math.ceil(Math.log2(b)); + this.bufferSize = nextP2; + this._a = a; + const chirp = new Float64Array(b); + const ichirp = new Float64Array(nextP2); + this._chirpBuffer = new Float64Array(nextP2); + this._buffer1 = new Float64Array(nextP2); + this._buffer2 = new Float64Array(nextP2); + this._outBuffer1 = new Float64Array(nextP2); + this._outBuffer2 = new Float64Array(nextP2); + const theta = -2 * Math.PI / fft_length; + const baseR = Math.cos(theta); + const baseI = Math.sin(theta); + for (let i = 0; i < b >> 1; ++i) { + const e = (i + 1 - fft_length) ** 2 / 2; + const result_mod = Math.sqrt(baseR ** 2 + baseI ** 2) ** e; + const result_arg = e * Math.atan2(baseI, baseR); + const i2 = 2 * i; + chirp[i2] = result_mod * Math.cos(result_arg); + chirp[i2 + 1] = result_mod * Math.sin(result_arg); + ichirp[i2] = chirp[i2]; + ichirp[i2 + 1] = -chirp[i2 + 1]; + } + this._slicedChirpBuffer = chirp.subarray(a, b); + this._f = new P2FFT(nextP2 >> 1); + this._f.transform(this._chirpBuffer, ichirp); + } + _transform(output, input, real) { + const ib1 = this._buffer1; + const ib2 = this._buffer2; + const ob2 = this._outBuffer1; + const ob3 = this._outBuffer2; + const cb = this._chirpBuffer; + const sb = this._slicedChirpBuffer; + const a = this._a; + if (real) { + for (let j = 0; j < sb.length; j += 2) { + const j2 = j + 1; + const j3 = j >> 1; + const a_real = input[j3]; + ib1[j] = a_real * sb[j]; + ib1[j2] = a_real * sb[j2]; + } + } else { + for (let j = 0; j < sb.length; j += 2) { + const j2 = j + 1; + ib1[j] = input[j] * sb[j] - input[j2] * sb[j2]; + ib1[j2] = input[j] * sb[j2] + input[j2] * sb[j]; + } + } + this._f.transform(ob2, ib1); + for (let j = 0; j < cb.length; j += 2) { + const j2 = j + 1; + ib2[j] = ob2[j] * cb[j] - ob2[j2] * cb[j2]; + ib2[j2] = ob2[j] * cb[j2] + ob2[j2] * cb[j]; + } + this._f.inverseTransform(ob3, ib2); + for (let j = 0; j < ob3.length; j += 2) { + const a_real = ob3[j + a]; + const a_imag = ob3[j + a + 1]; + const b_real = sb[j]; + const b_imag = sb[j + 1]; + output[j] = a_real * b_real - a_imag * b_imag; + output[j + 1] = a_real * b_imag + a_imag * b_real; + } + } + transform(output, input) { + this._transform(output, input, false); + } + realTransform(output, input) { + this._transform(output, input, true); + } + } + class FFT { + constructor(fft_length) { + this.fft_length = fft_length; + this.isPowerOfTwo = isPowerOfTwo(fft_length); + if (this.isPowerOfTwo) { + this.fft = new P2FFT(fft_length); + this.outputBufferSize = 2 * fft_length; + } else { + this.fft = new NP2FFT(fft_length); + this.outputBufferSize = this.fft.bufferSize; + } + } + realTransform(out, input) { + this.fft.realTransform(out, input); + } + transform(out, input) { + this.fft.transform(out, input); + } + } + function medianFilter(data, windowSize) { + if (windowSize % 2 === 0 || windowSize <= 0) { + throw new Error("Window size must be a positive odd number"); + } + const outputArray = new data.constructor(data.length); + const buffer = new data.constructor(windowSize); + const halfWindowSize = Math.floor(windowSize / 2); + for (let i = 0; i < data.length; ++i) { + let valuesIndex = 0; + for (let j = -halfWindowSize; j <= halfWindowSize; ++j) { + let index = i + j; + if (index < 0) { + index = Math.abs(index); + } else if (index >= data.length) { + index = 2 * (data.length - 1) - index; + } + buffer[valuesIndex++] = data[index]; + } + buffer.sort(); + outputArray[i] = buffer[halfWindowSize]; + } + return outputArray; + } + function round(num, decimals) { + const pow = Math.pow(10, decimals); + return Math.round(num * pow) / pow; + } + function bankers_round(x) { + const r = Math.round(x); + const br2 = Math.abs(x) % 1 === 0.5 ? r % 2 === 0 ? r : r - 1 : r; + return br2; + } + function dynamic_time_warping(matrix) { + const output_length = matrix.length; + const input_length = matrix[0].length; + const outputShape = [output_length + 1, input_length + 1]; + const cost = Array.from( + { length: outputShape[0] }, + () => Array(outputShape[1]).fill(Infinity) + ); + cost[0][0] = 0; + const trace = Array.from( + { length: outputShape[0] }, + () => Array(outputShape[1]).fill(-1) + ); + for (let j2 = 1; j2 < outputShape[1]; ++j2) { + for (let i2 = 1; i2 < outputShape[0]; ++i2) { + const c0 = cost[i2 - 1][j2 - 1]; + const c1 = cost[i2 - 1][j2]; + const c2 = cost[i2][j2 - 1]; + let c, t; + if (c0 < c1 && c0 < c2) { + c = c0; + t = 0; + } else if (c1 < c0 && c1 < c2) { + c = c1; + t = 1; + } else { + c = c2; + t = 2; + } + cost[i2][j2] = matrix[i2 - 1][j2 - 1] + c; + trace[i2][j2] = t; + } + } + for (let i2 = 0; i2 < outputShape[1]; ++i2) { + trace[0][i2] = 2; + } + for (let i2 = 0; i2 < outputShape[0]; ++i2) { + trace[i2][0] = 1; + } + let i = output_length; + let j = input_length; + let text_indices = []; + let time_indices = []; + while (i > 0 || j > 0) { + text_indices.push(i - 1); + time_indices.push(j - 1); + switch (trace[i][j]) { + case 0: + --i; + --j; + break; + case 1: + --i; + break; + case 2: + --j; + break; + default: + throw new Error( + `Internal error in dynamic time warping. Unexpected trace[${i}, ${j}]. Please file a bug report.` + ); + } + } + text_indices.reverse(); + time_indices.reverse(); + return [text_indices, time_indices]; + } + }) + ), + /***/ + "./src/utils/tensor.js": ( + /*!*****************************!*\ + !*** ./src/utils/tensor.js ***! + \*****************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + DataTypeMap: () => ( + /* binding */ + DataTypeMap + ), + /* harmony export */ + Tensor: () => ( + /* binding */ + Tensor3 + ), + /* harmony export */ + cat: () => ( + /* binding */ + cat + ), + /* harmony export */ + full: () => ( + /* binding */ + full + ), + /* harmony export */ + full_like: () => ( + /* binding */ + full_like + ), + /* harmony export */ + interpolate: () => ( + /* binding */ + interpolate + ), + /* harmony export */ + interpolate_4d: () => ( + /* binding */ + interpolate_4d + ), + /* harmony export */ + layer_norm: () => ( + /* binding */ + layer_norm + ), + /* harmony export */ + matmul: () => ( + /* binding */ + matmul + ), + /* harmony export */ + mean: () => ( + /* binding */ + mean + ), + /* harmony export */ + mean_pooling: () => ( + /* binding */ + mean_pooling + ), + /* harmony export */ + ones: () => ( + /* binding */ + ones + ), + /* harmony export */ + ones_like: () => ( + /* binding */ + ones_like + ), + /* harmony export */ + permute: () => ( + /* binding */ + permute + ), + /* harmony export */ + quantize_embeddings: () => ( + /* binding */ + quantize_embeddings + ), + /* harmony export */ + rand: () => ( + /* binding */ + rand + ), + /* harmony export */ + randn: () => ( + /* binding */ + randn + ), + /* harmony export */ + rfft: () => ( + /* binding */ + rfft + ), + /* harmony export */ + slice: () => ( + /* binding */ + slice + ), + /* harmony export */ + stack: () => ( + /* binding */ + stack + ), + /* harmony export */ + std_mean: () => ( + /* binding */ + std_mean + ), + /* harmony export */ + topk: () => ( + /* binding */ + topk + ), + /* harmony export */ + zeros: () => ( + /* binding */ + zeros + ), + /* harmony export */ + zeros_like: () => ( + /* binding */ + zeros_like + ) + /* harmony export */ + }); + var _maths_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ./maths.js */ + "./src/utils/maths.js" + ); + var _backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../backends/onnx.js */ + "./src/backends/onnx.js" + ); + var _ops_registry_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__2( + /*! ../ops/registry.js */ + "./src/ops/registry.js" + ); + const DataTypeMap = Object.freeze({ + float32: Float32Array, + // @ts-ignore ts(2552) Limited availability of Float16Array across browsers: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float16Array + float16: typeof Float16Array !== "undefined" ? Float16Array : Uint16Array, + float64: Float64Array, + string: Array, + // string[] + int8: Int8Array, + uint8: Uint8Array, + int16: Int16Array, + uint16: Uint16Array, + int32: Int32Array, + uint32: Uint32Array, + int64: BigInt64Array, + uint64: BigUint64Array, + bool: Uint8Array, + uint4: Uint8Array, + int4: Int8Array + }); + class Tensor3 { + /** @type {number[]} Dimensions of the tensor. */ + get dims() { + return this.ort_tensor.dims; + } + set dims(value) { + this.ort_tensor.dims = value; + } + /** @type {DataType} Type of the tensor. */ + get type() { + return this.ort_tensor.type; + } + /** @type {DataArray} The data stored in the tensor. */ + get data() { + return this.ort_tensor.data; + } + /** @type {number} The number of elements in the tensor. */ + get size() { + return this.ort_tensor.size; + } + /** @type {string} The location of the tensor data. */ + get location() { + return this.ort_tensor.location; + } + ort_tensor; + /** + * Create a new Tensor or copy an existing Tensor. + * @param {[DataType, DataArray, number[]]|[ONNXTensor]} args + */ + constructor(...args) { + if ((0, _backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__.isONNXTensor)(args[0])) { + this.ort_tensor = /** @type {ONNXTensor} */ + args[0]; + } else { + this.ort_tensor = new _backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__.Tensor( + /** @type {DataType} */ + args[0], + // @ts-expect-error ts(2769) Type 'number' is not assignable to type 'bigint'. + /** @type {Exclude} */ + args[1], + args[2] + ); + } + return new Proxy(this, { + get: (obj, key) => { + if (typeof key === "string") { + let index = Number(key); + if (Number.isInteger(index)) { + return obj._getitem(index); + } + } + return obj[key]; + }, + set: (obj, key, value) => { + return obj[key] = value; + } + }); + } + dispose() { + this.ort_tensor.dispose(); + } + /** + * Returns an iterator object for iterating over the tensor data in row-major order. + * If the tensor has more than one dimension, the iterator will yield subarrays. + * @returns {Iterator} An iterator object for iterating over the tensor data in row-major order. + */ + *[Symbol.iterator]() { + const [iterLength, ...iterDims] = this.dims; + if (iterDims.length > 0) { + const iterSize = iterDims.reduce((a, b) => a * b); + for (let i = 0; i < iterLength; ++i) { + yield this._subarray(i, iterSize, iterDims); + } + } else { + yield* this.data; + } + } + /** + * Index into a Tensor object. + * @param {number} index The index to access. + * @returns {Tensor} The data at the specified index. + */ + _getitem(index) { + const [iterLength, ...iterDims] = this.dims; + index = safeIndex(index, iterLength); + if (iterDims.length > 0) { + const iterSize = iterDims.reduce((a, b) => a * b); + return this._subarray(index, iterSize, iterDims); + } else { + return new Tensor3(this.type, [this.data[index]], iterDims); + } + } + /** + * @param {number|bigint} item The item to search for in the tensor + * @returns {number} The index of the first occurrence of item in the tensor data. + */ + indexOf(item) { + const this_data = this.data; + for (let index = 0; index < this_data.length; ++index) { + if (this_data[index] == item) { + return index; + } + } + return -1; + } + /** + * @param {number} index + * @param {number} iterSize + * @param {any} iterDims + * @returns {Tensor} + */ + _subarray(index, iterSize, iterDims) { + const o1 = index * iterSize; + const o2 = (index + 1) * iterSize; + const data = "subarray" in this.data ? this.data.subarray(o1, o2) : this.data.slice(o1, o2); + return new Tensor3(this.type, data, iterDims); + } + /** + * Returns the value of this tensor as a standard JavaScript Number. This only works + * for tensors with one element. For other cases, see `Tensor.tolist()`. + * @returns {number|bigint} The value of this tensor as a standard JavaScript Number. + * @throws {Error} If the tensor has more than one element. + */ + item() { + const this_data = this.data; + if (this_data.length !== 1) { + throw new Error(`a Tensor with ${this_data.length} elements cannot be converted to Scalar`); + } + return this_data[0]; + } + /** + * Convert tensor data to a n-dimensional JS list + * @returns {Array} + */ + tolist() { + return reshape(this.data, this.dims); + } + /** + * Return a new Tensor with the sigmoid function applied to each element. + * @returns {Tensor} The tensor with the sigmoid function applied. + */ + sigmoid() { + return this.clone().sigmoid_(); + } + /** + * Applies the sigmoid function to the tensor in place. + * @returns {Tensor} Returns `this`. + */ + sigmoid_() { + const this_data = this.data; + for (let i = 0; i < this_data.length; ++i) { + this_data[i] = 1 / (1 + Math.exp(-this_data[i])); + } + return this; + } + /** + * Return a new Tensor with a callback function applied to each element. + * @param {Function} callback - The function to apply to each element. It should take three arguments: + * the current element, its index, and the tensor's data array. + * @returns {Tensor} A new Tensor with the callback function applied to each element. + */ + map(callback) { + return this.clone().map_(callback); + } + /** + * Apply a callback function to each element of the tensor in place. + * @param {Function} callback - The function to apply to each element. It should take three arguments: + * the current element, its index, and the tensor's data array. + * @returns {Tensor} Returns `this`. + */ + map_(callback) { + const this_data = this.data; + for (let i = 0; i < this_data.length; ++i) { + this_data[i] = callback(this_data[i], i, this_data); + } + return this; + } + /** + * Return a new Tensor with every element multiplied by a constant. + * @param {number} val The value to multiply by. + * @returns {Tensor} The new tensor. + */ + mul(val) { + return this.clone().mul_(val); + } + /** + * Multiply the tensor by a constant in place. + * @param {number} val The value to multiply by. + * @returns {Tensor} Returns `this`. + */ + mul_(val) { + const this_data = this.data; + for (let i = 0; i < this_data.length; ++i) { + this_data[i] *= val; + } + return this; + } + /** + * Return a new Tensor with every element divided by a constant. + * @param {number} val The value to divide by. + * @returns {Tensor} The new tensor. + */ + div(val) { + return this.clone().div_(val); + } + /** + * Divide the tensor by a constant in place. + * @param {number} val The value to divide by. + * @returns {Tensor} Returns `this`. + */ + div_(val) { + const this_data = this.data; + for (let i = 0; i < this_data.length; ++i) { + this_data[i] /= val; + } + return this; + } + /** + * Return a new Tensor with every element added by a constant. + * @param {number} val The value to add by. + * @returns {Tensor} The new tensor. + */ + add(val) { + return this.clone().add_(val); + } + /** + * Add the tensor by a constant in place. + * @param {number} val The value to add by. + * @returns {Tensor} Returns `this`. + */ + add_(val) { + const this_data = this.data; + for (let i = 0; i < this_data.length; ++i) { + this_data[i] += val; + } + return this; + } + /** + * Return a new Tensor with every element subtracted by a constant. + * @param {number} val The value to subtract by. + * @returns {Tensor} The new tensor. + */ + sub(val) { + return this.clone().sub_(val); + } + /** + * Subtract the tensor by a constant in place. + * @param {number} val The value to subtract by. + * @returns {Tensor} Returns `this`. + */ + sub_(val) { + const this_data = this.data; + for (let i = 0; i < this_data.length; ++i) { + this_data[i] -= val; + } + return this; + } + /** + * Creates a deep copy of the current Tensor. + * @returns {Tensor} A new Tensor with the same type, data, and dimensions as the original. + */ + clone() { + return new Tensor3(this.type, this.data.slice(), this.dims.slice()); + } + /** + * Performs a slice operation on the Tensor along specified dimensions. + * + * Consider a Tensor that has a dimension of [4, 7]: + * ``` + * [ 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] + * ``` + * We can slice against the two dims of row and column, for instance in this + * case we can start at the second element, and return to the second last, + * like this: + * ``` + * tensor.slice([1, -1], [1, -1]); + * ``` + * which would return: + * ``` + * [ 9, 10, 11, 12, 13 ] + * [ 16, 17, 18, 19, 20 ] + * ``` + * + * @param {...(number|number[]|null)} slices The slice specifications for each dimension. + * - If a number is given, then a single element is selected. + * - If an array of two numbers is given, then a range of elements [start, end (exclusive)] is selected. + * - If null is given, then the entire dimension is selected. + * @returns {Tensor} A new Tensor containing the selected elements. + * @throws {Error} If the slice input is invalid. + */ + slice(...slices) { + const newTensorDims = []; + const newOffsets = []; + for (let sliceIndex = 0; sliceIndex < this.dims.length; ++sliceIndex) { + let slice2 = slices[sliceIndex]; + if (slice2 === null || slice2 === void 0) { + newOffsets.push([0, this.dims[sliceIndex]]); + newTensorDims.push(this.dims[sliceIndex]); + } else if (typeof slice2 === "number") { + slice2 = safeIndex(slice2, this.dims[sliceIndex], sliceIndex); + newOffsets.push([slice2, slice2 + 1]); + } else if (Array.isArray(slice2) && slice2.length === 2) { + let [start, end] = slice2; + start = start === null ? 0 : safeIndex(start, this.dims[sliceIndex], sliceIndex, false); + end = end === null ? this.dims[sliceIndex] : safeIndex(end, this.dims[sliceIndex], sliceIndex, false); + if (start > end) { + throw new Error(`Invalid slice: ${slice2}`); + } + const offsets = [ + Math.max(start, 0), + Math.min(end, this.dims[sliceIndex]) + ]; + newOffsets.push(offsets); + newTensorDims.push(offsets[1] - offsets[0]); + } else { + throw new Error(`Invalid slice: ${slice2}`); + } + } + const newDims = newOffsets.map(([start, end]) => end - start); + const newBufferSize = newDims.reduce((a, b) => a * b); + const this_data = this.data; + const data = new this_data.constructor(newBufferSize); + const stride = this.stride(); + let isContiguous = true; + for (let i = 1; i < newDims.length; ++i) { + if (newOffsets[i][0] !== 0 || newOffsets[i][1] !== this.dims[i]) { + isContiguous = false; + break; + } + } + if (isContiguous) { + const start = newOffsets[0][0] * stride[0]; + const end = newOffsets[0][1] * stride[0]; + if (ArrayBuffer.isView(this_data)) { + data.set(this_data.subarray(start, end)); + } else if (Array.isArray(this_data)) { + const slicedData = this_data.slice(start, end); + for (let i = 0; i < slicedData.length; ++i) { + data[i] = slicedData[i]; + } + } else { + throw new Error("Unsupported data type for slicing"); + } + } else { + for (let i = 0; i < newBufferSize; ++i) { + let originalIndex = 0; + for (let j = newDims.length - 1, num = i; j >= 0; --j) { + const size = newDims[j]; + originalIndex += (num % size + newOffsets[j][0]) * stride[j]; + num = Math.floor(num / size); + } + data[i] = this_data[originalIndex]; + } + } + return new Tensor3(this.type, data, newTensorDims); + } + /** + * Return a permuted version of this Tensor, according to the provided dimensions. + * @param {...number} dims Dimensions to permute. + * @returns {Tensor} The permuted tensor. + */ + permute(...dims) { + return permute(this, dims); + } + // TODO: implement transpose. For now (backwards compatibility), it's just an alias for permute() + transpose(...dims) { + return this.permute(...dims); + } + /** + * Returns the sum of each row of the input tensor in the given dimension dim. + * + * @param {number} [dim=null] The dimension or dimensions to reduce. If `null`, all dimensions are reduced. + * @param {boolean} keepdim Whether the output tensor has `dim` retained or not. + * @returns The summed tensor + */ + sum(dim = null, keepdim = false) { + return this.norm(1, dim, keepdim); + } + /** + * Returns the matrix norm or vector norm of a given tensor. + * @param {number|string} [p='fro'] The order of norm + * @param {number} [dim=null] Specifies which dimension of the tensor to calculate the norm across. + * If dim is None, the norm will be calculated across all dimensions of input. + * @param {boolean} [keepdim=false] Whether the output tensors have dim retained or not. + * @returns {Tensor} The norm of the tensor. + */ + norm(p = "fro", dim = null, keepdim = false) { + if (p === "fro") { + p = 2; + } else if (typeof p === "string") { + throw Error(`Unsupported norm: ${p}`); + } + const this_data = this.data; + const fn = (a, b) => a + b ** p; + if (dim === null) { + const val = this_data.reduce(fn, 0) ** (1 / p); + return new Tensor3(this.type, [val], []); + } + const [type, result, resultDims] = reduce_helper(fn, this, dim, keepdim); + if (p !== 1) { + for (let i = 0; i < result.length; ++i) { + result[i] = result[i] ** (1 / p); + } + } + return new Tensor3(type, result, resultDims); + } + /** + * Performs `L_p` normalization of inputs over specified dimension. Operates in place. + * @param {number} [p=2] The exponent value in the norm formulation + * @param {number} [dim=1] The dimension to reduce + * @returns {Tensor} `this` for operation chaining. + */ + normalize_(p = 2, dim = 1) { + dim = safeIndex(dim, this.dims.length); + const norm = this.norm(p, dim, true); + const this_data = this.data; + const norm_data = norm.data; + for (let i = 0; i < this_data.length; ++i) { + let resultIndex = 0; + for (let j = this.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) { + const size = this.dims[j]; + if (j !== dim) { + const index = num % size; + resultIndex += index * resultMultiplier; + resultMultiplier *= this.dims[j]; + } + num = Math.floor(num / size); + } + this_data[i] /= norm_data[resultIndex]; + } + return this; + } + /** + * Performs `L_p` normalization of inputs over specified dimension. + * @param {number} [p=2] The exponent value in the norm formulation + * @param {number} [dim=1] The dimension to reduce + * @returns {Tensor} The normalized tensor. + */ + normalize(p = 2, dim = 1) { + return this.clone().normalize_(p, dim); + } + /** + * Compute and return the stride of this tensor. + * Stride is the jump necessary to go from one element to the next one in the specified dimension dim. + * @returns {number[]} The stride of this tensor. + */ + stride() { + return dimsToStride(this.dims); + } + /** + * Returns a tensor with all specified dimensions of input of size 1 removed. + * + * NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other. + * If you would like a copy, use `tensor.clone()` before squeezing. + * + * @param {number|number[]} [dim=null] If given, the input will be squeezed only in the specified dimensions. + * @returns {Tensor} The squeezed tensor + */ + squeeze(dim = null) { + return new Tensor3( + this.type, + this.data, + calc_squeeze_dims(this.dims, dim) + ); + } + /** + * In-place version of @see {@link Tensor.squeeze} + */ + squeeze_(dim = null) { + this.dims = calc_squeeze_dims(this.dims, dim); + return this; + } + /** + * Returns a new tensor with a dimension of size one inserted at the specified position. + * + * NOTE: The returned tensor shares the same underlying data with this tensor. + * + * @param {number} dim The index at which to insert the singleton dimension + * @returns {Tensor} The unsqueezed tensor + */ + unsqueeze(dim = null) { + return new Tensor3( + this.type, + this.data, + calc_unsqueeze_dims(this.dims, dim) + ); + } + /** + * In-place version of @see {@link Tensor.unsqueeze} + */ + unsqueeze_(dim = null) { + this.dims = calc_unsqueeze_dims(this.dims, dim); + return this; + } + /** + * In-place version of @see {@link Tensor.flatten} + */ + flatten_(start_dim = 0, end_dim = -1) { + end_dim = (end_dim + this.dims.length) % this.dims.length; + let dimsToKeepBefore = this.dims.slice(0, start_dim); + let dimsToFlatten = this.dims.slice(start_dim, end_dim + 1); + let dimsToKeepAfter = this.dims.slice(end_dim + 1); + this.dims = [...dimsToKeepBefore, dimsToFlatten.reduce((a, b) => a * b, 1), ...dimsToKeepAfter]; + return this; + } + /** + * Flattens input by reshaping it into a one-dimensional tensor. + * If `start_dim` or `end_dim` are passed, only dimensions starting with `start_dim` + * and ending with `end_dim` are flattened. The order of elements in input is unchanged. + * @param {number} start_dim the first dim to flatten + * @param {number} end_dim the last dim to flatten + * @returns {Tensor} The flattened tensor. + */ + flatten(start_dim = 0, end_dim = -1) { + return this.clone().flatten_(start_dim, end_dim); + } + /** + * Returns a new tensor with the same data as the `self` tensor but of a different `shape`. + * @param {...number} dims the desired size + * @returns {Tensor} The tensor with the same data but different shape + */ + view(...dims) { + let inferredIndex = -1; + for (let i = 0; i < dims.length; ++i) { + if (dims[i] === -1) { + if (inferredIndex !== -1) { + throw new Error("Only one dimension can be inferred"); + } + inferredIndex = i; + } + } + const this_data = this.data; + if (inferredIndex !== -1) { + const productOther = dims.reduce((product, curr, index) => { + return index !== inferredIndex ? product * curr : product; + }, 1); + dims[inferredIndex] = this_data.length / productOther; + } + return new Tensor3(this.type, this_data, dims); + } + neg_() { + const this_data = this.data; + for (let i = 0; i < this_data.length; ++i) { + this_data[i] = -this_data[i]; + } + return this; + } + neg() { + return this.clone().neg_(); + } + /** + * Computes input > val element-wise. + * @param {number} val The value to compare with. + * @returns {Tensor} A boolean tensor that is `true` where input is greater than other and `false` elsewhere. + */ + gt(val) { + const mask = new Uint8Array(this.data.length); + const this_data = this.data; + for (let i = 0; i < this_data.length; ++i) { + mask[i] = this_data[i] > val ? 1 : 0; + } + return new Tensor3("bool", mask, this.dims); + } + /** + * Computes input < val element-wise. + * @param {number} val The value to compare with. + * @returns {Tensor} A boolean tensor that is `true` where input is less than other and `false` elsewhere. + */ + lt(val) { + const mask = new Uint8Array(this.data.length); + const this_data = this.data; + for (let i = 0; i < this_data.length; ++i) { + mask[i] = this_data[i] < val ? 1 : 0; + } + return new Tensor3("bool", mask, this.dims); + } + /** + * In-place version of @see {@link Tensor.clamp} + */ + clamp_(min, max) { + const this_data = this.data; + for (let i = 0; i < this_data.length; ++i) { + this_data[i] = Math.min(Math.max(this_data[i], min), max); + } + return this; + } + /** + * Clamps all elements in input into the range [ min, max ] + * @param {number} min lower-bound of the range to be clamped to + * @param {number} max upper-bound of the range to be clamped to + * @returns {Tensor} the output tensor. + */ + clamp(min, max) { + return this.clone().clamp_(min, max); + } + /** + * In-place version of @see {@link Tensor.round} + */ + round_() { + const this_data = this.data; + for (let i = 0; i < this_data.length; ++i) { + this_data[i] = Math.round(this_data[i]); + } + return this; + } + /** + * Rounds elements of input to the nearest integer. + * @returns {Tensor} the output tensor. + */ + round() { + return this.clone().round_(); + } + mean(dim = null, keepdim = false) { + return mean(this, dim, keepdim); + } + min(dim = null, keepdim = false) { + if (dim === null) { + const val = (0, _maths_js__WEBPACK_IMPORTED_MODULE_0__.min)(this.data)[0]; + return new Tensor3(this.type, [val], [ + /* scalar */ + ]); + } + const [type, result, resultDims] = reduce_helper((a, b) => Math.min(a, b), this, dim, keepdim, Infinity); + return new Tensor3(type, result, resultDims); + } + max(dim = null, keepdim = false) { + if (dim === null) { + const val = (0, _maths_js__WEBPACK_IMPORTED_MODULE_0__.max)(this.data)[0]; + return new Tensor3(this.type, [val], [ + /* scalar */ + ]); + } + const [type, result, resultDims] = reduce_helper((a, b) => Math.max(a, b), this, dim, keepdim, -Infinity); + return new Tensor3(type, result, resultDims); + } + argmin(dim = null, keepdim = false) { + if (dim !== null) { + throw new Error("`dim !== null` not yet implemented."); + } + const index = (0, _maths_js__WEBPACK_IMPORTED_MODULE_0__.min)(this.data)[1]; + return new Tensor3("int64", [BigInt(index)], []); + } + argmax(dim = null, keepdim = false) { + if (dim !== null) { + throw new Error("`dim !== null` not yet implemented."); + } + const index = (0, _maths_js__WEBPACK_IMPORTED_MODULE_0__.max)(this.data)[1]; + return new Tensor3("int64", [BigInt(index)], []); + } + /** + * Performs Tensor dtype conversion. + * @param {DataType} type The desired data type. + * @returns {Tensor} The converted tensor. + */ + to(type) { + if (this.type === type) return this; + if (!DataTypeMap.hasOwnProperty(type)) { + throw new Error(`Unsupported type: ${type}`); + } + let map_fn; + const is_source_bigint = ["int64", "uint64"].includes(this.type); + const is_dest_bigint = ["int64", "uint64"].includes(type); + if (is_source_bigint && !is_dest_bigint) { + map_fn = Number; + } else if (!is_source_bigint && is_dest_bigint) { + if (["float16", "float32", "float64"].includes(this.type)) { + map_fn = (x) => BigInt(Math.floor(x)); + } else { + map_fn = BigInt; + } + } + return new Tensor3(type, DataTypeMap[type].from(this.data, map_fn), this.dims); + } + } + function reshape(data, dimensions) { + const totalElements = data.length; + const dimensionSize = dimensions.reduce((a, b) => a * b); + if (totalElements !== dimensionSize) { + throw Error(`cannot reshape array of size ${totalElements} into shape (${dimensions})`); + } + let reshapedArray = data; + for (let i = dimensions.length - 1; i >= 0; i--) { + reshapedArray = reshapedArray.reduce((acc, val) => { + let lastArray = acc[acc.length - 1]; + if (lastArray.length < dimensions[i]) { + lastArray.push(val); + } else { + acc.push([val]); + } + return acc; + }, [[]]); + } + return reshapedArray[0]; + } + function permute(tensor, axes) { + const [permutedData, shape] = (0, _maths_js__WEBPACK_IMPORTED_MODULE_0__.permute_data)(tensor.data, tensor.dims, axes); + return new Tensor3(tensor.type, permutedData, shape); + } + function interpolate(input, [out_height, out_width], mode = "bilinear", align_corners = false) { + const in_channels = input.dims.at(-3) ?? 1; + const in_height = input.dims.at(-2); + const in_width = input.dims.at(-1); + let output = (0, _maths_js__WEBPACK_IMPORTED_MODULE_0__.interpolate_data)( + /** @type {import('./maths.js').TypedArray}*/ + input.data, + [in_channels, in_height, in_width], + [out_height, out_width], + mode, + align_corners + ); + return new Tensor3(input.type, output, [in_channels, out_height, out_width]); + } + async function interpolate_4d(input, { + size = null, + mode = "bilinear" + } = {}) { + if (input.dims.length !== 4) { + throw new Error("`interpolate_4d` currently only supports 4D input."); + } + if (!size) { + throw new Error("`interpolate_4d` requires a `size` argument."); + } + let targetDims; + if (size.length === 2) { + targetDims = [...input.dims.slice(0, 2), ...size]; + } else if (size.length === 3) { + targetDims = [input.dims[0], ...size]; + } else if (size.length === 4) { + targetDims = size; + } else { + throw new Error("`size` must be of length 2, 3, or 4."); + } + let op; + if (mode === "nearest") { + op = await _ops_registry_js__WEBPACK_IMPORTED_MODULE_2__.TensorOpRegistry.nearest_interpolate_4d; + } else if (mode === "bilinear") { + op = await _ops_registry_js__WEBPACK_IMPORTED_MODULE_2__.TensorOpRegistry.bilinear_interpolate_4d; + } else if (mode === "bicubic") { + op = await _ops_registry_js__WEBPACK_IMPORTED_MODULE_2__.TensorOpRegistry.bicubic_interpolate_4d; + } else { + throw new Error(`Unsupported mode: ${mode}`); + } + const sizeTensor = new Tensor3("int64", new BigInt64Array(targetDims.map(BigInt)), [targetDims.length]); + return await op({ x: input, s: sizeTensor }); + } + async function matmul(a, b) { + const op = await _ops_registry_js__WEBPACK_IMPORTED_MODULE_2__.TensorOpRegistry.matmul; + return await op({ a, b }); + } + async function rfft(x, a) { + const op = await _ops_registry_js__WEBPACK_IMPORTED_MODULE_2__.TensorOpRegistry.rfft; + return await op({ x, a }); + } + async function topk(x, k2) { + const op = await _ops_registry_js__WEBPACK_IMPORTED_MODULE_2__.TensorOpRegistry.top_k; + if (k2 == null) { + k2 = x.dims.at(-1); + } else { + k2 = Math.min(k2, x.dims.at(-1)); + } + return await op({ + x, + k: new Tensor3( + "int64", + [BigInt(k2)], + [1] + ) + }); + } + const arrayToIndexTensor = (array) => new Tensor3("int64", array, [array.length]); + async function slice(data, starts, ends, axes, steps) { + const op = await _ops_registry_js__WEBPACK_IMPORTED_MODULE_2__.TensorOpRegistry.slice; + return await op({ + x: data, + s: arrayToIndexTensor(starts), + e: arrayToIndexTensor(ends), + a: arrayToIndexTensor(axes), + t: arrayToIndexTensor(steps ?? new Array(axes.length).fill(1)) + }); + } + function mean_pooling(last_hidden_state, attention_mask) { + const lastHiddenStateData = last_hidden_state.data; + const attentionMaskData = attention_mask.data; + const shape = [last_hidden_state.dims[0], last_hidden_state.dims[2]]; + const returnedData = new lastHiddenStateData.constructor(shape[0] * shape[1]); + const [batchSize, seqLength, embedDim] = last_hidden_state.dims; + let outIndex = 0; + for (let i = 0; i < batchSize; ++i) { + const offset = i * embedDim * seqLength; + for (let k2 = 0; k2 < embedDim; ++k2) { + let sum = 0; + let count = 0; + const attnMaskOffset = i * seqLength; + const offset2 = offset + k2; + for (let j = 0; j < seqLength; ++j) { + const attn = Number(attentionMaskData[attnMaskOffset + j]); + count += attn; + sum += lastHiddenStateData[offset2 + j * embedDim] * attn; + } + const avg = sum / count; + returnedData[outIndex++] = avg; + } + } + return new Tensor3( + last_hidden_state.type, + returnedData, + shape + ); + } + function layer_norm(input, normalized_shape, { + eps = 1e-5 + } = {}) { + if (input.dims.length !== 2) { + throw new Error("`layer_norm` currently only supports 2D input."); + } + const [batchSize, featureDim] = input.dims; + if (normalized_shape.length !== 1 && normalized_shape[0] !== featureDim) { + throw new Error("`normalized_shape` must be a 1D array with shape `[input.dims[1]]`."); + } + const [std, mean2] = std_mean(input, 1, 0, true); + const stdData = ( + /** @type {Float32Array} */ + std.data + ); + const meanData = ( + /** @type {Float32Array} */ + mean2.data + ); + const inputData = ( + /** @type {Float32Array} */ + input.data + ); + const returnedData = new inputData.constructor(inputData.length); + for (let i = 0; i < batchSize; ++i) { + const offset = i * featureDim; + for (let j = 0; j < featureDim; ++j) { + const offset2 = offset + j; + returnedData[offset2] = (inputData[offset2] - meanData[i]) / (stdData[i] + eps); + } + } + return new Tensor3(input.type, returnedData, input.dims); + } + function calc_squeeze_dims(dims, dim) { + dims = dims.slice(); + if (dim === null) { + dims = dims.filter((d) => d !== 1); + } else if (typeof dim === "number") { + if (dims[dim] === 1) { + dims.splice(dim, 1); + } + } else if (Array.isArray(dim)) { + dims = dims.filter((x, i) => { + return x !== 1 || !dim.includes(i); + }); + } + return dims; + } + function calc_unsqueeze_dims(dims, dim) { + dim = safeIndex(dim, dims.length + 1); + dims = dims.slice(); + dims.splice(dim, 0, 1); + return dims; + } + function safeIndex(index, size, dimension = null, boundsCheck = true) { + if (index < -size || index >= size) { + if (boundsCheck) { + throw new Error(`IndexError: index ${index} is out of bounds for dimension${dimension === null ? "" : " " + dimension} with size ${size}`); + } else { + return index < -size ? 0 : size; + } + } + if (index < 0) { + index = (index % size + size) % size; + } + return index; + } + function cat(tensors, dim = 0) { + dim = safeIndex(dim, tensors[0].dims.length); + const resultDims = tensors[0].dims.slice(); + resultDims[dim] = tensors.reduce((a, b) => a + b.dims[dim], 0); + const resultSize = resultDims.reduce((a, b) => a * b, 1); + const result = new tensors[0].data.constructor(resultSize); + const resultType = tensors[0].type; + if (dim === 0) { + let offset = 0; + for (const tensor of tensors) { + const tensorData = tensor.data; + result.set(tensorData, offset); + offset += tensorData.length; + } + } else { + let currentDim = 0; + for (let t = 0; t < tensors.length; ++t) { + const { data, dims } = tensors[t]; + for (let i = 0; i < data.length; ++i) { + let resultIndex = 0; + for (let j = dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) { + const size = dims[j]; + let index = num % size; + if (j === dim) { + index += currentDim; + } + resultIndex += index * resultMultiplier; + resultMultiplier *= resultDims[j]; + num = Math.floor(num / size); + } + result[resultIndex] = data[i]; + } + currentDim += dims[dim]; + } + } + return new Tensor3(resultType, result, resultDims); + } + function stack(tensors, dim = 0) { + return cat(tensors.map((t) => t.unsqueeze(dim)), dim); + } + function reduce_helper(callbackfn, input, dim = null, keepdim = false, initialValue = null) { + const inputData = input.data; + const inputDims = input.dims; + dim = safeIndex(dim, inputDims.length); + const resultDims = inputDims.slice(); + resultDims[dim] = 1; + const result = new inputData.constructor(inputData.length / inputDims[dim]); + if (initialValue !== null) { + result.fill(initialValue); + } + for (let i = 0; i < inputData.length; ++i) { + let resultIndex = 0; + for (let j = inputDims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) { + const size = inputDims[j]; + if (j !== dim) { + const index = num % size; + resultIndex += index * resultMultiplier; + resultMultiplier *= resultDims[j]; + } + num = Math.floor(num / size); + } + result[resultIndex] = callbackfn(result[resultIndex], inputData[i], i, resultIndex); + } + if (!keepdim) resultDims.splice(dim, 1); + return [input.type, result, resultDims]; + } + function std_mean(input, dim = null, correction = 1, keepdim = false) { + const inputData = ( + /** @type {Float32Array} */ + input.data + ); + const inputDims = input.dims; + if (dim === null) { + const sum = inputData.reduce((a, b) => a + b, 0); + const mean2 = sum / inputData.length; + const std = Math.sqrt(inputData.reduce((a, b) => a + (b - mean2) ** 2, 0) / (inputData.length - correction)); + const meanTensor2 = new Tensor3(input.type, [mean2], [ + /* scalar */ + ]); + const stdTensor2 = new Tensor3(input.type, [std], [ + /* scalar */ + ]); + return [stdTensor2, meanTensor2]; + } + dim = safeIndex(dim, inputDims.length); + const meanTensor = mean(input, dim, keepdim); + const meanTensorData = meanTensor.data; + const [type, result, resultDims] = reduce_helper((a, b, i, j) => a + (b - meanTensorData[j]) ** 2, input, dim, keepdim); + for (let i = 0; i < result.length; ++i) { + result[i] = Math.sqrt(result[i] / (inputDims[dim] - correction)); + } + const stdTensor = new Tensor3(type, result, resultDims); + return [stdTensor, meanTensor]; + } + function mean(input, dim = null, keepdim = false) { + const inputDims = input.dims; + const inputData = ( + /** @type {Float32Array} */ + input.data + ); + if (dim === null) { + const val = inputData.reduce((a, b) => a + b, 0); + return new Tensor3(input.type, [val / inputData.length], [ + /* scalar */ + ]); + } + dim = safeIndex(dim, inputDims.length); + const [type, result, resultDims] = reduce_helper((a, b) => a + b, input, dim, keepdim); + if (inputDims[dim] !== 1) { + for (let i = 0; i < result.length; ++i) { + result[i] /= inputDims[dim]; + } + } + return new Tensor3(type, result, resultDims); + } + function dimsToStride(dims) { + const stride = new Array(dims.length); + for (let i = dims.length - 1, s2 = 1; i >= 0; --i) { + stride[i] = s2; + s2 *= dims[i]; + } + return stride; + } + function fullHelper(size, fill_value, dtype, cls) { + const numElements = size.reduce((a, b) => a * b, 1); + return new Tensor3( + dtype, + new cls(numElements).fill(fill_value), + size + ); + } + function full(size, fill_value) { + let dtype; + let typedArrayCls; + if (typeof fill_value === "number") { + dtype = "float32"; + typedArrayCls = Float32Array; + } else if (typeof fill_value === "bigint") { + dtype = "int64"; + typedArrayCls = BigInt64Array; + } else if (typeof fill_value === "boolean") { + dtype = "bool"; + typedArrayCls = Uint8Array; + } else { + throw new Error(`Unsupported data type: ${typeof fill_value}`); + } + return fullHelper(size, fill_value, dtype, typedArrayCls); + } + function full_like(tensor, fill_value) { + return full(tensor.dims, fill_value); + } + function ones(size) { + return fullHelper(size, 1n, "int64", BigInt64Array); + } + function ones_like(tensor) { + return ones(tensor.dims); + } + function zeros(size) { + return fullHelper(size, 0n, "int64", BigInt64Array); + } + function zeros_like(tensor) { + return zeros(tensor.dims); + } + function rand(size) { + const length = size.reduce((a, b) => a * b, 1); + return new Tensor3( + "float32", + Float32Array.from({ length }, () => Math.random()), + size + ); + } + function randn(size) { + const length = size.reduce((a, b) => a * b, 1); + function boxMullerRandom() { + const u = 1 - Math.random(); + const v = 1 - Math.random(); + return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v); + } + return new Tensor3( + "float32", + Float32Array.from({ length }, () => boxMullerRandom()), + size + ); + } + function quantize_embeddings(tensor, precision) { + if (tensor.dims.length !== 2) { + throw new Error("The tensor must have 2 dimensions"); + } + if (tensor.dims.at(-1) % 8 !== 0) { + throw new Error("The last dimension of the tensor must be a multiple of 8"); + } + if (!["binary", "ubinary"].includes(precision)) { + throw new Error("The precision must be either 'binary' or 'ubinary'"); + } + const signed = precision === "binary"; + const dtype = signed ? "int8" : "uint8"; + const cls = signed ? Int8Array : Uint8Array; + const inputData = tensor.data; + const outputData = new cls(inputData.length / 8); + for (let i = 0; i < inputData.length; ++i) { + const bit = inputData[i] > 0 ? 1 : 0; + const arrayIndex = Math.floor(i / 8); + const bitPosition = i % 8; + outputData[arrayIndex] |= bit << 7 - bitPosition; + if (signed && bitPosition === 0) { + outputData[arrayIndex] -= 128; + } + } + ; + return new Tensor3(dtype, outputData, [tensor.dims[0], tensor.dims[1] / 8]); + } + }) + ), + /***/ + "./src/utils/video.js": ( + /*!****************************!*\ + !*** ./src/utils/video.js ***! + \****************************/ + /***/ + ((__unused_webpack___webpack_module__, __webpack_exports__2, __webpack_require__2) => { + __webpack_require__2.r(__webpack_exports__2); + __webpack_require__2.d(__webpack_exports__2, { + /* harmony export */ + RawVideo: () => ( + /* binding */ + RawVideo + ), + /* harmony export */ + RawVideoFrame: () => ( + /* binding */ + RawVideoFrame + ), + /* harmony export */ + load_video: () => ( + /* binding */ + load_video + ) + /* harmony export */ + }); + var _image_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__2( + /*! ./image.js */ + "./src/utils/image.js" + ); + var _env_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__2( + /*! ../env.js */ + "./src/env.js" + ); + class RawVideoFrame { + /** + * @param {RawImage} image + * @param {number} timestamp + */ + constructor(image, timestamp) { + this.image = image; + this.timestamp = timestamp; + } + } + class RawVideo { + /** + * @param {RawVideoFrame[]|RawImage[]} frames + * @param {number} duration + */ + constructor(frames, duration) { + if (frames.length > 0 && frames[0] instanceof _image_js__WEBPACK_IMPORTED_MODULE_0__.RawImage) { + frames = frames.map((image, i) => new RawVideoFrame(image, (i + 1) / (frames.length + 1) * duration)); + } + this.frames = /** @type {RawVideoFrame[]} */ + frames; + this.duration = duration; + } + get width() { + return this.frames[0].image.width; + } + get height() { + return this.frames[0].image.height; + } + get fps() { + return this.frames.length / this.duration; + } + } + async function load_video(src, { num_frames = null, fps = null } = {}) { + if (!_env_js__WEBPACK_IMPORTED_MODULE_1__.apis.IS_BROWSER_ENV) { + throw new Error("`load_video` is currently only supported in browser environments."); + } + if (num_frames == null && fps == null) { + throw new Error("Either num_frames or fps must be provided."); + } + const frames = []; + const video = document.createElement("video"); + video.crossOrigin = "anonymous"; + video.muted = true; + if (typeof src === "string") { + video.src = src; + } else if (src instanceof Blob) { + video.src = URL.createObjectURL(src); + } else if (src instanceof HTMLVideoElement) { + video.src = src.src; + } else { + throw new Error("Invalid URL or video element provided."); + } + await new Promise((resolve) => video.onloadedmetadata = resolve); + if (video.seekable.start(0) === video.seekable.end(0)) { + const response = await fetch(video.src); + const blob = await response.blob(); + video.src = URL.createObjectURL(blob); + await new Promise((resolve) => video.onloadedmetadata = resolve); + } + const duration = video.duration; + let count, step; + if (num_frames != null) { + count = num_frames; + step = num_frames === 1 ? 0 : duration / (num_frames - 1); + } else { + step = 1 / fps; + count = Math.floor(duration / step); + } + let sampleTimes = []; + for (let i = 0; i < count; ++i) { + sampleTimes.push(num_frames === 1 ? duration / 2 : i * step); + } + const canvas = document.createElement("canvas"); + canvas.width = video.videoWidth; + canvas.height = video.videoHeight; + const ctx = canvas.getContext("2d", { willReadFrequently: true }); + for (const t of sampleTimes) { + video.currentTime = t; + await new Promise((resolve) => { + video.onseeked = resolve; + }); + ctx.drawImage(video, 0, 0, canvas.width, canvas.height); + const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); + const frameData = new _image_js__WEBPACK_IMPORTED_MODULE_0__.RawImage(imageData.data, canvas.width, canvas.height, 4); + const frame = new RawVideoFrame(frameData, t); + frames.push(frame); + } + video.remove(); + return new RawVideo(frames, duration); + } + }) + ) + /******/ + }; + var __webpack_module_cache__ = {}; + function __webpack_require__(moduleId) { + var cachedModule = __webpack_module_cache__[moduleId]; + if (cachedModule !== void 0) { + return cachedModule.exports; + } + var module = __webpack_module_cache__[moduleId] = { + /******/ + // no module.id needed + /******/ + // no module.loaded needed + /******/ + exports: {} + /******/ + }; + __webpack_modules__[moduleId](module, module.exports, __webpack_require__); + return module.exports; + } + (() => { + var getProto = Object.getPrototypeOf ? (obj) => Object.getPrototypeOf(obj) : (obj) => obj.__proto__; + var leafPrototypes; + __webpack_require__.t = function(value, mode) { + if (mode & 1) value = this(value); + if (mode & 8) return value; + if (typeof value === "object" && value) { + if (mode & 4 && value.__esModule) return value; + if (mode & 16 && typeof value.then === "function") return value; + } + var ns2 = /* @__PURE__ */ Object.create(null); + __webpack_require__.r(ns2); + var def = {}; + leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)]; + for (var current = mode & 2 && value; typeof current == "object" && !~leafPrototypes.indexOf(current); current = getProto(current)) { + Object.getOwnPropertyNames(current).forEach((key) => def[key] = () => value[key]); + } + def["default"] = () => value; + __webpack_require__.d(ns2, def); + return ns2; + }; + })(); + (() => { + __webpack_require__.d = (exports, definition) => { + for (var key in definition) { + if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { + Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); + } + } + }; + })(); + (() => { + __webpack_require__.o = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop); + })(); + (() => { + __webpack_require__.r = (exports) => { + if (typeof Symbol !== "undefined" && Symbol.toStringTag) { + Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); + } + Object.defineProperty(exports, "__esModule", { value: true }); + }; + })(); + var __webpack_exports__ = {}; + (() => { + __webpack_require__.r(__webpack_exports__); + __webpack_require__.d(__webpack_exports__, { + /* harmony export */ + ASTFeatureExtractor: () => ( + /* reexport safe */ + _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.ASTFeatureExtractor + ), + /* harmony export */ + ASTForAudioClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ASTForAudioClassification + ), + /* harmony export */ + ASTModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ASTModel + ), + /* harmony export */ + ASTPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ASTPreTrainedModel + ), + /* harmony export */ + AlbertForMaskedLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AlbertForMaskedLM + ), + /* harmony export */ + AlbertForQuestionAnswering: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AlbertForQuestionAnswering + ), + /* harmony export */ + AlbertForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AlbertForSequenceClassification + ), + /* harmony export */ + AlbertModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AlbertModel + ), + /* harmony export */ + AlbertPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AlbertPreTrainedModel + ), + /* harmony export */ + AlbertTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.AlbertTokenizer + ), + /* harmony export */ + ArceeForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ArceeForCausalLM + ), + /* harmony export */ + ArceeModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ArceeModel + ), + /* harmony export */ + ArceePreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ArceePreTrainedModel + ), + /* harmony export */ + AudioClassificationPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.AudioClassificationPipeline + ), + /* harmony export */ + AutoConfig: () => ( + /* reexport safe */ + _configs_js__WEBPACK_IMPORTED_MODULE_4__.AutoConfig + ), + /* harmony export */ + AutoFeatureExtractor: () => ( + /* reexport safe */ + _models_auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_12__.AutoFeatureExtractor + ), + /* harmony export */ + AutoImageProcessor: () => ( + /* reexport safe */ + _models_auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_15__.AutoImageProcessor + ), + /* harmony export */ + AutoModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModel + ), + /* harmony export */ + AutoModelForAudioClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForAudioClassification + ), + /* harmony export */ + AutoModelForAudioFrameClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForAudioFrameClassification + ), + /* harmony export */ + AutoModelForAudioTextToText: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForAudioTextToText + ), + /* harmony export */ + AutoModelForCTC: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForCTC + ), + /* harmony export */ + AutoModelForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForCausalLM + ), + /* harmony export */ + AutoModelForDepthEstimation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForDepthEstimation + ), + /* harmony export */ + AutoModelForDocumentQuestionAnswering: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForDocumentQuestionAnswering + ), + /* harmony export */ + AutoModelForImageClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForImageClassification + ), + /* harmony export */ + AutoModelForImageFeatureExtraction: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForImageFeatureExtraction + ), + /* harmony export */ + AutoModelForImageMatting: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForImageMatting + ), + /* harmony export */ + AutoModelForImageSegmentation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForImageSegmentation + ), + /* harmony export */ + AutoModelForImageTextToText: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForImageTextToText + ), + /* harmony export */ + AutoModelForImageToImage: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForImageToImage + ), + /* harmony export */ + AutoModelForMaskGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForMaskGeneration + ), + /* harmony export */ + AutoModelForMaskedLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForMaskedLM + ), + /* harmony export */ + AutoModelForNormalEstimation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForNormalEstimation + ), + /* harmony export */ + AutoModelForObjectDetection: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForObjectDetection + ), + /* harmony export */ + AutoModelForPoseEstimation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForPoseEstimation + ), + /* harmony export */ + AutoModelForQuestionAnswering: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForQuestionAnswering + ), + /* harmony export */ + AutoModelForSemanticSegmentation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForSemanticSegmentation + ), + /* harmony export */ + AutoModelForSeq2SeqLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForSeq2SeqLM + ), + /* harmony export */ + AutoModelForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForSequenceClassification + ), + /* harmony export */ + AutoModelForSpeechSeq2Seq: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForSpeechSeq2Seq + ), + /* harmony export */ + AutoModelForTextToSpectrogram: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForTextToSpectrogram + ), + /* harmony export */ + AutoModelForTextToWaveform: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForTextToWaveform + ), + /* harmony export */ + AutoModelForTokenClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForTokenClassification + ), + /* harmony export */ + AutoModelForUniversalSegmentation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForUniversalSegmentation + ), + /* harmony export */ + AutoModelForVision2Seq: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForVision2Seq + ), + /* harmony export */ + AutoModelForXVector: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForXVector + ), + /* harmony export */ + AutoModelForZeroShotObjectDetection: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForZeroShotObjectDetection + ), + /* harmony export */ + AutoProcessor: () => ( + /* reexport safe */ + _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_18__.AutoProcessor + ), + /* harmony export */ + AutoTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.AutoTokenizer + ), + /* harmony export */ + AutomaticSpeechRecognitionPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.AutomaticSpeechRecognitionPipeline + ), + /* harmony export */ + BackgroundRemovalPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.BackgroundRemovalPipeline + ), + /* harmony export */ + BartForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.BartForConditionalGeneration + ), + /* harmony export */ + BartForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.BartForSequenceClassification + ), + /* harmony export */ + BartModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.BartModel + ), + /* harmony export */ + BartPretrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.BartPretrainedModel + ), + /* harmony export */ + BartTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.BartTokenizer + ), + /* harmony export */ + BaseModelOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.BaseModelOutput + ), + /* harmony export */ + BaseStreamer: () => ( + /* reexport safe */ + _generation_streamers_js__WEBPACK_IMPORTED_MODULE_19__.BaseStreamer + ), + /* harmony export */ + BeitFeatureExtractor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.BeitFeatureExtractor + ), + /* harmony export */ + BeitForImageClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.BeitForImageClassification + ), + /* harmony export */ + BeitModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.BeitModel + ), + /* harmony export */ + BeitPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.BeitPreTrainedModel + ), + /* harmony export */ + BertForMaskedLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.BertForMaskedLM + ), + /* harmony export */ + BertForQuestionAnswering: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.BertForQuestionAnswering + ), + /* harmony export */ + BertForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.BertForSequenceClassification + ), + /* harmony export */ + BertForTokenClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.BertForTokenClassification + ), + /* harmony export */ + BertModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.BertModel + ), + /* harmony export */ + BertPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.BertPreTrainedModel + ), + /* harmony export */ + BertTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.BertTokenizer + ), + /* harmony export */ + BitImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.BitImageProcessor + ), + /* harmony export */ + BlenderbotForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.BlenderbotForConditionalGeneration + ), + /* harmony export */ + BlenderbotModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.BlenderbotModel + ), + /* harmony export */ + BlenderbotPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.BlenderbotPreTrainedModel + ), + /* harmony export */ + BlenderbotSmallForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.BlenderbotSmallForConditionalGeneration + ), + /* harmony export */ + BlenderbotSmallModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.BlenderbotSmallModel + ), + /* harmony export */ + BlenderbotSmallPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.BlenderbotSmallPreTrainedModel + ), + /* harmony export */ + BlenderbotSmallTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.BlenderbotSmallTokenizer + ), + /* harmony export */ + BlenderbotTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.BlenderbotTokenizer + ), + /* harmony export */ + BloomForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.BloomForCausalLM + ), + /* harmony export */ + BloomModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.BloomModel + ), + /* harmony export */ + BloomPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.BloomPreTrainedModel + ), + /* harmony export */ + BloomTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.BloomTokenizer + ), + /* harmony export */ + CLIPFeatureExtractor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.CLIPFeatureExtractor + ), + /* harmony export */ + CLIPImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.CLIPImageProcessor + ), + /* harmony export */ + CLIPModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPModel + ), + /* harmony export */ + CLIPPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPPreTrainedModel + ), + /* harmony export */ + CLIPSegForImageSegmentation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPSegForImageSegmentation + ), + /* harmony export */ + CLIPSegModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPSegModel + ), + /* harmony export */ + CLIPSegPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPSegPreTrainedModel + ), + /* harmony export */ + CLIPTextModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPTextModel + ), + /* harmony export */ + CLIPTextModelWithProjection: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPTextModelWithProjection + ), + /* harmony export */ + CLIPTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.CLIPTokenizer + ), + /* harmony export */ + CLIPVisionModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPVisionModel + ), + /* harmony export */ + CLIPVisionModelWithProjection: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPVisionModelWithProjection + ), + /* harmony export */ + CamembertForMaskedLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.CamembertForMaskedLM + ), + /* harmony export */ + CamembertForQuestionAnswering: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.CamembertForQuestionAnswering + ), + /* harmony export */ + CamembertForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.CamembertForSequenceClassification + ), + /* harmony export */ + CamembertForTokenClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.CamembertForTokenClassification + ), + /* harmony export */ + CamembertModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.CamembertModel + ), + /* harmony export */ + CamembertPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.CamembertPreTrainedModel + ), + /* harmony export */ + CamembertTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.CamembertTokenizer + ), + /* harmony export */ + CausalLMOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.CausalLMOutput + ), + /* harmony export */ + CausalLMOutputWithPast: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.CausalLMOutputWithPast + ), + /* harmony export */ + ChineseCLIPFeatureExtractor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.ChineseCLIPFeatureExtractor + ), + /* harmony export */ + ChineseCLIPModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ChineseCLIPModel + ), + /* harmony export */ + ChineseCLIPPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ChineseCLIPPreTrainedModel + ), + /* harmony export */ + ClapAudioModelWithProjection: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ClapAudioModelWithProjection + ), + /* harmony export */ + ClapFeatureExtractor: () => ( + /* reexport safe */ + _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.ClapFeatureExtractor + ), + /* harmony export */ + ClapModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ClapModel + ), + /* harmony export */ + ClapPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ClapPreTrainedModel + ), + /* harmony export */ + ClapTextModelWithProjection: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ClapTextModelWithProjection + ), + /* harmony export */ + ClassifierFreeGuidanceLogitsProcessor: () => ( + /* reexport safe */ + _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.ClassifierFreeGuidanceLogitsProcessor + ), + /* harmony export */ + CodeGenForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.CodeGenForCausalLM + ), + /* harmony export */ + CodeGenModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.CodeGenModel + ), + /* harmony export */ + CodeGenPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.CodeGenPreTrainedModel + ), + /* harmony export */ + CodeGenTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.CodeGenTokenizer + ), + /* harmony export */ + CodeLlamaTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.CodeLlamaTokenizer + ), + /* harmony export */ + CohereForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.CohereForCausalLM + ), + /* harmony export */ + CohereModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.CohereModel + ), + /* harmony export */ + CoherePreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.CoherePreTrainedModel + ), + /* harmony export */ + CohereTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.CohereTokenizer + ), + /* harmony export */ + ConvBertForMaskedLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvBertForMaskedLM + ), + /* harmony export */ + ConvBertForQuestionAnswering: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvBertForQuestionAnswering + ), + /* harmony export */ + ConvBertForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvBertForSequenceClassification + ), + /* harmony export */ + ConvBertForTokenClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvBertForTokenClassification + ), + /* harmony export */ + ConvBertModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvBertModel + ), + /* harmony export */ + ConvBertPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvBertPreTrainedModel + ), + /* harmony export */ + ConvBertTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.ConvBertTokenizer + ), + /* harmony export */ + ConvNextFeatureExtractor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.ConvNextFeatureExtractor + ), + /* harmony export */ + ConvNextForImageClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvNextForImageClassification + ), + /* harmony export */ + ConvNextImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.ConvNextImageProcessor + ), + /* harmony export */ + ConvNextModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvNextModel + ), + /* harmony export */ + ConvNextPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvNextPreTrainedModel + ), + /* harmony export */ + ConvNextV2ForImageClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvNextV2ForImageClassification + ), + /* harmony export */ + ConvNextV2Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvNextV2Model + ), + /* harmony export */ + ConvNextV2PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvNextV2PreTrainedModel + ), + /* harmony export */ + DFineForObjectDetection: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DFineForObjectDetection + ), + /* harmony export */ + DFineModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DFineModel + ), + /* harmony export */ + DFinePreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DFinePreTrainedModel + ), + /* harmony export */ + DINOv3ConvNextModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DINOv3ConvNextModel + ), + /* harmony export */ + DINOv3ConvNextPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DINOv3ConvNextPreTrainedModel + ), + /* harmony export */ + DINOv3ViTImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.DINOv3ViTImageProcessor + ), + /* harmony export */ + DINOv3ViTModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DINOv3ViTModel + ), + /* harmony export */ + DINOv3ViTPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DINOv3ViTPreTrainedModel + ), + /* harmony export */ + DPTFeatureExtractor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.DPTFeatureExtractor + ), + /* harmony export */ + DPTForDepthEstimation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DPTForDepthEstimation + ), + /* harmony export */ + DPTImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.DPTImageProcessor + ), + /* harmony export */ + DPTModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DPTModel + ), + /* harmony export */ + DPTPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DPTPreTrainedModel + ), + /* harmony export */ + DacDecoderModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DacDecoderModel + ), + /* harmony export */ + DacDecoderOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DacDecoderOutput + ), + /* harmony export */ + DacEncoderModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DacEncoderModel + ), + /* harmony export */ + DacEncoderOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DacEncoderOutput + ), + /* harmony export */ + DacFeatureExtractor: () => ( + /* reexport safe */ + _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.DacFeatureExtractor + ), + /* harmony export */ + DacModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DacModel + ), + /* harmony export */ + DacPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DacPreTrainedModel + ), + /* harmony export */ + DataTypeMap: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.DataTypeMap + ), + /* harmony export */ + DebertaForMaskedLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaForMaskedLM + ), + /* harmony export */ + DebertaForQuestionAnswering: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaForQuestionAnswering + ), + /* harmony export */ + DebertaForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaForSequenceClassification + ), + /* harmony export */ + DebertaForTokenClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaForTokenClassification + ), + /* harmony export */ + DebertaModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaModel + ), + /* harmony export */ + DebertaPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaPreTrainedModel + ), + /* harmony export */ + DebertaTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.DebertaTokenizer + ), + /* harmony export */ + DebertaV2ForMaskedLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaV2ForMaskedLM + ), + /* harmony export */ + DebertaV2ForQuestionAnswering: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaV2ForQuestionAnswering + ), + /* harmony export */ + DebertaV2ForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaV2ForSequenceClassification + ), + /* harmony export */ + DebertaV2ForTokenClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaV2ForTokenClassification + ), + /* harmony export */ + DebertaV2Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaV2Model + ), + /* harmony export */ + DebertaV2PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaV2PreTrainedModel + ), + /* harmony export */ + DebertaV2Tokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.DebertaV2Tokenizer + ), + /* harmony export */ + DecisionTransformerModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DecisionTransformerModel + ), + /* harmony export */ + DecisionTransformerPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DecisionTransformerPreTrainedModel + ), + /* harmony export */ + DeiTFeatureExtractor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.DeiTFeatureExtractor + ), + /* harmony export */ + DeiTForImageClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DeiTForImageClassification + ), + /* harmony export */ + DeiTImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.DeiTImageProcessor + ), + /* harmony export */ + DeiTModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DeiTModel + ), + /* harmony export */ + DeiTPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DeiTPreTrainedModel + ), + /* harmony export */ + DepthAnythingForDepthEstimation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DepthAnythingForDepthEstimation + ), + /* harmony export */ + DepthAnythingPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DepthAnythingPreTrainedModel + ), + /* harmony export */ + DepthEstimationPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.DepthEstimationPipeline + ), + /* harmony export */ + DepthProForDepthEstimation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DepthProForDepthEstimation + ), + /* harmony export */ + DepthProPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DepthProPreTrainedModel + ), + /* harmony export */ + DetrFeatureExtractor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.DetrFeatureExtractor + ), + /* harmony export */ + DetrForObjectDetection: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DetrForObjectDetection + ), + /* harmony export */ + DetrForSegmentation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DetrForSegmentation + ), + /* harmony export */ + DetrImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.DetrImageProcessor + ), + /* harmony export */ + DetrModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DetrModel + ), + /* harmony export */ + DetrObjectDetectionOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DetrObjectDetectionOutput + ), + /* harmony export */ + DetrPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DetrPreTrainedModel + ), + /* harmony export */ + DetrSegmentationOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DetrSegmentationOutput + ), + /* harmony export */ + Dinov2ForImageClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Dinov2ForImageClassification + ), + /* harmony export */ + Dinov2Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Dinov2Model + ), + /* harmony export */ + Dinov2PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Dinov2PreTrainedModel + ), + /* harmony export */ + Dinov2WithRegistersForImageClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Dinov2WithRegistersForImageClassification + ), + /* harmony export */ + Dinov2WithRegistersModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Dinov2WithRegistersModel + ), + /* harmony export */ + Dinov2WithRegistersPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Dinov2WithRegistersPreTrainedModel + ), + /* harmony export */ + DistilBertForMaskedLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DistilBertForMaskedLM + ), + /* harmony export */ + DistilBertForQuestionAnswering: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DistilBertForQuestionAnswering + ), + /* harmony export */ + DistilBertForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DistilBertForSequenceClassification + ), + /* harmony export */ + DistilBertForTokenClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DistilBertForTokenClassification + ), + /* harmony export */ + DistilBertModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DistilBertModel + ), + /* harmony export */ + DistilBertPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DistilBertPreTrainedModel + ), + /* harmony export */ + DistilBertTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.DistilBertTokenizer + ), + /* harmony export */ + DocumentQuestionAnsweringPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.DocumentQuestionAnsweringPipeline + ), + /* harmony export */ + DonutFeatureExtractor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.DonutFeatureExtractor + ), + /* harmony export */ + DonutImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.DonutImageProcessor + ), + /* harmony export */ + DonutSwinModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DonutSwinModel + ), + /* harmony export */ + DonutSwinPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.DonutSwinPreTrainedModel + ), + /* harmony export */ + EdgeTamModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.EdgeTamModel + ), + /* harmony export */ + EfficientNetForImageClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.EfficientNetForImageClassification + ), + /* harmony export */ + EfficientNetImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.EfficientNetImageProcessor + ), + /* harmony export */ + EfficientNetModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.EfficientNetModel + ), + /* harmony export */ + EfficientNetPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.EfficientNetPreTrainedModel + ), + /* harmony export */ + ElectraForMaskedLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ElectraForMaskedLM + ), + /* harmony export */ + ElectraForQuestionAnswering: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ElectraForQuestionAnswering + ), + /* harmony export */ + ElectraForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ElectraForSequenceClassification + ), + /* harmony export */ + ElectraForTokenClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ElectraForTokenClassification + ), + /* harmony export */ + ElectraModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ElectraModel + ), + /* harmony export */ + ElectraPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ElectraPreTrainedModel + ), + /* harmony export */ + ElectraTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.ElectraTokenizer + ), + /* harmony export */ + EncodecFeatureExtractor: () => ( + /* reexport safe */ + _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.EncodecFeatureExtractor + ), + /* harmony export */ + EosTokenCriteria: () => ( + /* reexport safe */ + _generation_stopping_criteria_js__WEBPACK_IMPORTED_MODULE_20__.EosTokenCriteria + ), + /* harmony export */ + Ernie4_5ForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Ernie4_5ForCausalLM + ), + /* harmony export */ + Ernie4_5Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Ernie4_5Model + ), + /* harmony export */ + Ernie4_5PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Ernie4_5PreTrainedModel + ), + /* harmony export */ + EsmForMaskedLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.EsmForMaskedLM + ), + /* harmony export */ + EsmForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.EsmForSequenceClassification + ), + /* harmony export */ + EsmForTokenClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.EsmForTokenClassification + ), + /* harmony export */ + EsmModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.EsmModel + ), + /* harmony export */ + EsmPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.EsmPreTrainedModel + ), + /* harmony export */ + EsmTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.EsmTokenizer + ), + /* harmony export */ + ExaoneForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ExaoneForCausalLM + ), + /* harmony export */ + ExaoneModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ExaoneModel + ), + /* harmony export */ + ExaonePreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ExaonePreTrainedModel + ), + /* harmony export */ + FFT: () => ( + /* reexport safe */ + _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.FFT + ), + /* harmony export */ + FalconForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.FalconForCausalLM + ), + /* harmony export */ + FalconModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.FalconModel + ), + /* harmony export */ + FalconPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.FalconPreTrainedModel + ), + /* harmony export */ + FalconTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.FalconTokenizer + ), + /* harmony export */ + FastViTForImageClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.FastViTForImageClassification + ), + /* harmony export */ + FastViTModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.FastViTModel + ), + /* harmony export */ + FastViTPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.FastViTPreTrainedModel + ), + /* harmony export */ + FeatureExtractionPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.FeatureExtractionPipeline + ), + /* harmony export */ + FeatureExtractor: () => ( + /* reexport safe */ + _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_10__.FeatureExtractor + ), + /* harmony export */ + FillMaskPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.FillMaskPipeline + ), + /* harmony export */ + Florence2ForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Florence2ForConditionalGeneration + ), + /* harmony export */ + Florence2PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Florence2PreTrainedModel + ), + /* harmony export */ + Florence2Processor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.Florence2Processor + ), + /* harmony export */ + ForcedBOSTokenLogitsProcessor: () => ( + /* reexport safe */ + _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.ForcedBOSTokenLogitsProcessor + ), + /* harmony export */ + ForcedEOSTokenLogitsProcessor: () => ( + /* reexport safe */ + _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.ForcedEOSTokenLogitsProcessor + ), + /* harmony export */ + GLPNFeatureExtractor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.GLPNFeatureExtractor + ), + /* harmony export */ + GLPNForDepthEstimation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GLPNForDepthEstimation + ), + /* harmony export */ + GLPNModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GLPNModel + ), + /* harmony export */ + GLPNPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GLPNPreTrainedModel + ), + /* harmony export */ + GPT2LMHeadModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GPT2LMHeadModel + ), + /* harmony export */ + GPT2Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GPT2Model + ), + /* harmony export */ + GPT2PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GPT2PreTrainedModel + ), + /* harmony export */ + GPT2Tokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.GPT2Tokenizer + ), + /* harmony export */ + GPTBigCodeForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTBigCodeForCausalLM + ), + /* harmony export */ + GPTBigCodeModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTBigCodeModel + ), + /* harmony export */ + GPTBigCodePreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTBigCodePreTrainedModel + ), + /* harmony export */ + GPTJForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTJForCausalLM + ), + /* harmony export */ + GPTJModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTJModel + ), + /* harmony export */ + GPTJPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTJPreTrainedModel + ), + /* harmony export */ + GPTNeoForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTNeoForCausalLM + ), + /* harmony export */ + GPTNeoModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTNeoModel + ), + /* harmony export */ + GPTNeoPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTNeoPreTrainedModel + ), + /* harmony export */ + GPTNeoXForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTNeoXForCausalLM + ), + /* harmony export */ + GPTNeoXModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTNeoXModel + ), + /* harmony export */ + GPTNeoXPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTNeoXPreTrainedModel + ), + /* harmony export */ + GPTNeoXTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.GPTNeoXTokenizer + ), + /* harmony export */ + Gemma2ForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Gemma2ForCausalLM + ), + /* harmony export */ + Gemma2Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Gemma2Model + ), + /* harmony export */ + Gemma2PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Gemma2PreTrainedModel + ), + /* harmony export */ + Gemma3ForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Gemma3ForCausalLM + ), + /* harmony export */ + Gemma3Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Gemma3Model + ), + /* harmony export */ + Gemma3PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Gemma3PreTrainedModel + ), + /* harmony export */ + Gemma3nAudioFeatureExtractor: () => ( + /* reexport safe */ + _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.Gemma3nAudioFeatureExtractor + ), + /* harmony export */ + Gemma3nForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Gemma3nForConditionalGeneration + ), + /* harmony export */ + Gemma3nPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Gemma3nPreTrainedModel + ), + /* harmony export */ + Gemma3nProcessor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.Gemma3nProcessor + ), + /* harmony export */ + GemmaForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GemmaForCausalLM + ), + /* harmony export */ + GemmaModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GemmaModel + ), + /* harmony export */ + GemmaPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GemmaPreTrainedModel + ), + /* harmony export */ + GemmaTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.GemmaTokenizer + ), + /* harmony export */ + GlmForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GlmForCausalLM + ), + /* harmony export */ + GlmModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GlmModel + ), + /* harmony export */ + GlmPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GlmPreTrainedModel + ), + /* harmony export */ + GraniteForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GraniteForCausalLM + ), + /* harmony export */ + GraniteModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GraniteModel + ), + /* harmony export */ + GraniteMoeHybridForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GraniteMoeHybridForCausalLM + ), + /* harmony export */ + GraniteMoeHybridModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GraniteMoeHybridModel + ), + /* harmony export */ + GraniteMoeHybridPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GraniteMoeHybridPreTrainedModel + ), + /* harmony export */ + GranitePreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GranitePreTrainedModel + ), + /* harmony export */ + Grok1Tokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.Grok1Tokenizer + ), + /* harmony export */ + GroundingDinoForObjectDetection: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GroundingDinoForObjectDetection + ), + /* harmony export */ + GroundingDinoImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.GroundingDinoImageProcessor + ), + /* harmony export */ + GroundingDinoPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GroundingDinoPreTrainedModel + ), + /* harmony export */ + GroundingDinoProcessor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.GroundingDinoProcessor + ), + /* harmony export */ + GroupViTModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GroupViTModel + ), + /* harmony export */ + GroupViTPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.GroupViTPreTrainedModel + ), + /* harmony export */ + HeliumForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.HeliumForCausalLM + ), + /* harmony export */ + HeliumModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.HeliumModel + ), + /* harmony export */ + HeliumPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.HeliumPreTrainedModel + ), + /* harmony export */ + HerbertTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.HerbertTokenizer + ), + /* harmony export */ + HieraForImageClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.HieraForImageClassification + ), + /* harmony export */ + HieraModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.HieraModel + ), + /* harmony export */ + HieraPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.HieraPreTrainedModel + ), + /* harmony export */ + HubertForCTC: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.HubertForCTC + ), + /* harmony export */ + HubertForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.HubertForSequenceClassification + ), + /* harmony export */ + HubertModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.HubertModel + ), + /* harmony export */ + HubertPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.HubertPreTrainedModel + ), + /* harmony export */ + IJepaForImageClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.IJepaForImageClassification + ), + /* harmony export */ + IJepaModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.IJepaModel + ), + /* harmony export */ + IJepaPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.IJepaPreTrainedModel + ), + /* harmony export */ + Idefics3ForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Idefics3ForConditionalGeneration + ), + /* harmony export */ + Idefics3ImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.Idefics3ImageProcessor + ), + /* harmony export */ + Idefics3PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Idefics3PreTrainedModel + ), + /* harmony export */ + Idefics3Processor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.Idefics3Processor + ), + /* harmony export */ + ImageClassificationPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.ImageClassificationPipeline + ), + /* harmony export */ + ImageFeatureExtractionPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.ImageFeatureExtractionPipeline + ), + /* harmony export */ + ImageFeatureExtractor: () => ( + /* reexport safe */ + _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.ImageFeatureExtractor + ), + /* harmony export */ + ImageMattingOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ImageMattingOutput + ), + /* harmony export */ + ImageProcessor: () => ( + /* reexport safe */ + _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_13__.ImageProcessor + ), + /* harmony export */ + ImageSegmentationPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.ImageSegmentationPipeline + ), + /* harmony export */ + ImageToImagePipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.ImageToImagePipeline + ), + /* harmony export */ + ImageToTextPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.ImageToTextPipeline + ), + /* harmony export */ + InterruptableStoppingCriteria: () => ( + /* reexport safe */ + _generation_stopping_criteria_js__WEBPACK_IMPORTED_MODULE_20__.InterruptableStoppingCriteria + ), + /* harmony export */ + JAISLMHeadModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.JAISLMHeadModel + ), + /* harmony export */ + JAISModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.JAISModel + ), + /* harmony export */ + JAISPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.JAISPreTrainedModel + ), + /* harmony export */ + JinaCLIPImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.JinaCLIPImageProcessor + ), + /* harmony export */ + JinaCLIPModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.JinaCLIPModel + ), + /* harmony export */ + JinaCLIPPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.JinaCLIPPreTrainedModel + ), + /* harmony export */ + JinaCLIPProcessor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.JinaCLIPProcessor + ), + /* harmony export */ + JinaCLIPTextModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.JinaCLIPTextModel + ), + /* harmony export */ + JinaCLIPVisionModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.JinaCLIPVisionModel + ), + /* harmony export */ + Lfm2ForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Lfm2ForCausalLM + ), + /* harmony export */ + Lfm2Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Lfm2Model + ), + /* harmony export */ + Lfm2PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Lfm2PreTrainedModel + ), + /* harmony export */ + LiteWhisperForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.LiteWhisperForConditionalGeneration + ), + /* harmony export */ + Llama4ForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Llama4ForCausalLM + ), + /* harmony export */ + Llama4PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Llama4PreTrainedModel + ), + /* harmony export */ + LlamaForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.LlamaForCausalLM + ), + /* harmony export */ + LlamaModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.LlamaModel + ), + /* harmony export */ + LlamaPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.LlamaPreTrainedModel + ), + /* harmony export */ + LlamaTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.LlamaTokenizer + ), + /* harmony export */ + LlavaForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.LlavaForConditionalGeneration + ), + /* harmony export */ + LlavaOnevisionForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.LlavaOnevisionForConditionalGeneration + ), + /* harmony export */ + LlavaOnevisionImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.LlavaOnevisionImageProcessor + ), + /* harmony export */ + LlavaPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.LlavaPreTrainedModel + ), + /* harmony export */ + LlavaProcessor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.LlavaProcessor + ), + /* harmony export */ + LlavaQwen2ForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.LlavaQwen2ForCausalLM + ), + /* harmony export */ + LogitsProcessor: () => ( + /* reexport safe */ + _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.LogitsProcessor + ), + /* harmony export */ + LogitsProcessorList: () => ( + /* reexport safe */ + _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.LogitsProcessorList + ), + /* harmony export */ + LogitsWarper: () => ( + /* reexport safe */ + _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.LogitsWarper + ), + /* harmony export */ + LongT5ForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.LongT5ForConditionalGeneration + ), + /* harmony export */ + LongT5Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.LongT5Model + ), + /* harmony export */ + LongT5PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.LongT5PreTrainedModel + ), + /* harmony export */ + M2M100ForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.M2M100ForConditionalGeneration + ), + /* harmony export */ + M2M100Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.M2M100Model + ), + /* harmony export */ + M2M100PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.M2M100PreTrainedModel + ), + /* harmony export */ + M2M100Tokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.M2M100Tokenizer + ), + /* harmony export */ + MBart50Tokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.MBart50Tokenizer + ), + /* harmony export */ + MBartForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MBartForCausalLM + ), + /* harmony export */ + MBartForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MBartForConditionalGeneration + ), + /* harmony export */ + MBartForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MBartForSequenceClassification + ), + /* harmony export */ + MBartModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MBartModel + ), + /* harmony export */ + MBartPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MBartPreTrainedModel + ), + /* harmony export */ + MBartTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.MBartTokenizer + ), + /* harmony export */ + MPNetForMaskedLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MPNetForMaskedLM + ), + /* harmony export */ + MPNetForQuestionAnswering: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MPNetForQuestionAnswering + ), + /* harmony export */ + MPNetForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MPNetForSequenceClassification + ), + /* harmony export */ + MPNetForTokenClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MPNetForTokenClassification + ), + /* harmony export */ + MPNetModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MPNetModel + ), + /* harmony export */ + MPNetPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MPNetPreTrainedModel + ), + /* harmony export */ + MPNetTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.MPNetTokenizer + ), + /* harmony export */ + MT5ForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MT5ForConditionalGeneration + ), + /* harmony export */ + MT5Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MT5Model + ), + /* harmony export */ + MT5PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MT5PreTrainedModel + ), + /* harmony export */ + MarianMTModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MarianMTModel + ), + /* harmony export */ + MarianModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MarianModel + ), + /* harmony export */ + MarianPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MarianPreTrainedModel + ), + /* harmony export */ + MarianTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.MarianTokenizer + ), + /* harmony export */ + Mask2FormerImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.Mask2FormerImageProcessor + ), + /* harmony export */ + MaskFormerFeatureExtractor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MaskFormerFeatureExtractor + ), + /* harmony export */ + MaskFormerForInstanceSegmentation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MaskFormerForInstanceSegmentation + ), + /* harmony export */ + MaskFormerImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MaskFormerImageProcessor + ), + /* harmony export */ + MaskFormerModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MaskFormerModel + ), + /* harmony export */ + MaskFormerPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MaskFormerPreTrainedModel + ), + /* harmony export */ + MaskedLMOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MaskedLMOutput + ), + /* harmony export */ + MaxLengthCriteria: () => ( + /* reexport safe */ + _generation_stopping_criteria_js__WEBPACK_IMPORTED_MODULE_20__.MaxLengthCriteria + ), + /* harmony export */ + Metric3DForDepthEstimation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Metric3DForDepthEstimation + ), + /* harmony export */ + Metric3DPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Metric3DPreTrainedModel + ), + /* harmony export */ + Metric3Dv2ForDepthEstimation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Metric3Dv2ForDepthEstimation + ), + /* harmony export */ + Metric3Dv2PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Metric3Dv2PreTrainedModel + ), + /* harmony export */ + MgpstrForSceneTextRecognition: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MgpstrForSceneTextRecognition + ), + /* harmony export */ + MgpstrModelOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MgpstrModelOutput + ), + /* harmony export */ + MgpstrPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MgpstrPreTrainedModel + ), + /* harmony export */ + MgpstrProcessor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.MgpstrProcessor + ), + /* harmony export */ + MgpstrTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.MgpstrTokenizer + ), + /* harmony export */ + MimiDecoderModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MimiDecoderModel + ), + /* harmony export */ + MimiDecoderOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MimiDecoderOutput + ), + /* harmony export */ + MimiEncoderModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MimiEncoderModel + ), + /* harmony export */ + MimiEncoderOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MimiEncoderOutput + ), + /* harmony export */ + MimiModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MimiModel + ), + /* harmony export */ + MimiPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MimiPreTrainedModel + ), + /* harmony export */ + MinLengthLogitsProcessor: () => ( + /* reexport safe */ + _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.MinLengthLogitsProcessor + ), + /* harmony export */ + MinNewTokensLengthLogitsProcessor: () => ( + /* reexport safe */ + _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.MinNewTokensLengthLogitsProcessor + ), + /* harmony export */ + Ministral3ForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Ministral3ForCausalLM + ), + /* harmony export */ + Ministral3Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Ministral3Model + ), + /* harmony export */ + Ministral3PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Ministral3PreTrainedModel + ), + /* harmony export */ + MinistralForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MinistralForCausalLM + ), + /* harmony export */ + MinistralModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MinistralModel + ), + /* harmony export */ + MinistralPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MinistralPreTrainedModel + ), + /* harmony export */ + Mistral3ForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Mistral3ForConditionalGeneration + ), + /* harmony export */ + MistralForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MistralForCausalLM + ), + /* harmony export */ + MistralModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MistralModel + ), + /* harmony export */ + MistralPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MistralPreTrainedModel + ), + /* harmony export */ + MobileBertForMaskedLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileBertForMaskedLM + ), + /* harmony export */ + MobileBertForQuestionAnswering: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileBertForQuestionAnswering + ), + /* harmony export */ + MobileBertForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileBertForSequenceClassification + ), + /* harmony export */ + MobileBertModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileBertModel + ), + /* harmony export */ + MobileBertPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileBertPreTrainedModel + ), + /* harmony export */ + MobileBertTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.MobileBertTokenizer + ), + /* harmony export */ + MobileLLMForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileLLMForCausalLM + ), + /* harmony export */ + MobileLLMModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileLLMModel + ), + /* harmony export */ + MobileLLMPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileLLMPreTrainedModel + ), + /* harmony export */ + MobileNetV1FeatureExtractor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MobileNetV1FeatureExtractor + ), + /* harmony export */ + MobileNetV1ForImageClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV1ForImageClassification + ), + /* harmony export */ + MobileNetV1ForSemanticSegmentation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV1ForSemanticSegmentation + ), + /* harmony export */ + MobileNetV1ImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MobileNetV1ImageProcessor + ), + /* harmony export */ + MobileNetV1Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV1Model + ), + /* harmony export */ + MobileNetV1PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV1PreTrainedModel + ), + /* harmony export */ + MobileNetV2FeatureExtractor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MobileNetV2FeatureExtractor + ), + /* harmony export */ + MobileNetV2ForImageClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV2ForImageClassification + ), + /* harmony export */ + MobileNetV2ForSemanticSegmentation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV2ForSemanticSegmentation + ), + /* harmony export */ + MobileNetV2ImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MobileNetV2ImageProcessor + ), + /* harmony export */ + MobileNetV2Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV2Model + ), + /* harmony export */ + MobileNetV2PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV2PreTrainedModel + ), + /* harmony export */ + MobileNetV3FeatureExtractor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MobileNetV3FeatureExtractor + ), + /* harmony export */ + MobileNetV3ForImageClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV3ForImageClassification + ), + /* harmony export */ + MobileNetV3ForSemanticSegmentation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV3ForSemanticSegmentation + ), + /* harmony export */ + MobileNetV3ImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MobileNetV3ImageProcessor + ), + /* harmony export */ + MobileNetV3Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV3Model + ), + /* harmony export */ + MobileNetV3PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV3PreTrainedModel + ), + /* harmony export */ + MobileNetV4FeatureExtractor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MobileNetV4FeatureExtractor + ), + /* harmony export */ + MobileNetV4ForImageClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV4ForImageClassification + ), + /* harmony export */ + MobileNetV4ForSemanticSegmentation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV4ForSemanticSegmentation + ), + /* harmony export */ + MobileNetV4ImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MobileNetV4ImageProcessor + ), + /* harmony export */ + MobileNetV4Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV4Model + ), + /* harmony export */ + MobileNetV4PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV4PreTrainedModel + ), + /* harmony export */ + MobileViTFeatureExtractor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MobileViTFeatureExtractor + ), + /* harmony export */ + MobileViTForImageClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileViTForImageClassification + ), + /* harmony export */ + MobileViTImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MobileViTImageProcessor + ), + /* harmony export */ + MobileViTModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileViTModel + ), + /* harmony export */ + MobileViTPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileViTPreTrainedModel + ), + /* harmony export */ + MobileViTV2ForImageClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileViTV2ForImageClassification + ), + /* harmony export */ + MobileViTV2Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileViTV2Model + ), + /* harmony export */ + MobileViTV2PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileViTV2PreTrainedModel + ), + /* harmony export */ + ModelOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ModelOutput + ), + /* harmony export */ + ModernBertDecoderForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ModernBertDecoderForCausalLM + ), + /* harmony export */ + ModernBertDecoderModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ModernBertDecoderModel + ), + /* harmony export */ + ModernBertDecoderPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ModernBertDecoderPreTrainedModel + ), + /* harmony export */ + ModernBertForMaskedLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ModernBertForMaskedLM + ), + /* harmony export */ + ModernBertForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ModernBertForSequenceClassification + ), + /* harmony export */ + ModernBertForTokenClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ModernBertForTokenClassification + ), + /* harmony export */ + ModernBertModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ModernBertModel + ), + /* harmony export */ + ModernBertPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ModernBertPreTrainedModel + ), + /* harmony export */ + Moondream1ForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Moondream1ForConditionalGeneration + ), + /* harmony export */ + MoonshineFeatureExtractor: () => ( + /* reexport safe */ + _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.MoonshineFeatureExtractor + ), + /* harmony export */ + MoonshineForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MoonshineForConditionalGeneration + ), + /* harmony export */ + MoonshineModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MoonshineModel + ), + /* harmony export */ + MoonshinePreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MoonshinePreTrainedModel + ), + /* harmony export */ + MoonshineProcessor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.MoonshineProcessor + ), + /* harmony export */ + MptForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MptForCausalLM + ), + /* harmony export */ + MptModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MptModel + ), + /* harmony export */ + MptPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MptPreTrainedModel + ), + /* harmony export */ + MultiModalityCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MultiModalityCausalLM + ), + /* harmony export */ + MultiModalityPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MultiModalityPreTrainedModel + ), + /* harmony export */ + MusicgenForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MusicgenForCausalLM + ), + /* harmony export */ + MusicgenForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MusicgenForConditionalGeneration + ), + /* harmony export */ + MusicgenModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MusicgenModel + ), + /* harmony export */ + MusicgenPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.MusicgenPreTrainedModel + ), + /* harmony export */ + NanoChatForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.NanoChatForCausalLM + ), + /* harmony export */ + NanoChatModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.NanoChatModel + ), + /* harmony export */ + NanoChatPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.NanoChatPreTrainedModel + ), + /* harmony export */ + NeoBertForMaskedLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.NeoBertForMaskedLM + ), + /* harmony export */ + NeoBertForQuestionAnswering: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.NeoBertForQuestionAnswering + ), + /* harmony export */ + NeoBertForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.NeoBertForSequenceClassification + ), + /* harmony export */ + NeoBertForTokenClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.NeoBertForTokenClassification + ), + /* harmony export */ + NeoBertModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.NeoBertModel + ), + /* harmony export */ + NeoBertPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.NeoBertPreTrainedModel + ), + /* harmony export */ + NllbTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.NllbTokenizer + ), + /* harmony export */ + NoBadWordsLogitsProcessor: () => ( + /* reexport safe */ + _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.NoBadWordsLogitsProcessor + ), + /* harmony export */ + NoRepeatNGramLogitsProcessor: () => ( + /* reexport safe */ + _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.NoRepeatNGramLogitsProcessor + ), + /* harmony export */ + NomicBertModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.NomicBertModel + ), + /* harmony export */ + NomicBertPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.NomicBertPreTrainedModel + ), + /* harmony export */ + NougatImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.NougatImageProcessor + ), + /* harmony export */ + NougatTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.NougatTokenizer + ), + /* harmony export */ + OPTForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.OPTForCausalLM + ), + /* harmony export */ + OPTModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.OPTModel + ), + /* harmony export */ + OPTPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.OPTPreTrainedModel + ), + /* harmony export */ + ObjectDetectionPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.ObjectDetectionPipeline + ), + /* harmony export */ + Olmo2ForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Olmo2ForCausalLM + ), + /* harmony export */ + Olmo2Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Olmo2Model + ), + /* harmony export */ + Olmo2PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Olmo2PreTrainedModel + ), + /* harmony export */ + OlmoForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.OlmoForCausalLM + ), + /* harmony export */ + OlmoModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.OlmoModel + ), + /* harmony export */ + OlmoPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.OlmoPreTrainedModel + ), + /* harmony export */ + OpenELMForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.OpenELMForCausalLM + ), + /* harmony export */ + OpenELMModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.OpenELMModel + ), + /* harmony export */ + OpenELMPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.OpenELMPreTrainedModel + ), + /* harmony export */ + OwlViTFeatureExtractor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.OwlViTFeatureExtractor + ), + /* harmony export */ + OwlViTForObjectDetection: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.OwlViTForObjectDetection + ), + /* harmony export */ + OwlViTImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.OwlViTImageProcessor + ), + /* harmony export */ + OwlViTModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.OwlViTModel + ), + /* harmony export */ + OwlViTPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.OwlViTPreTrainedModel + ), + /* harmony export */ + OwlViTProcessor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.OwlViTProcessor + ), + /* harmony export */ + Owlv2ForObjectDetection: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Owlv2ForObjectDetection + ), + /* harmony export */ + Owlv2ImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.Owlv2ImageProcessor + ), + /* harmony export */ + Owlv2Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Owlv2Model + ), + /* harmony export */ + Owlv2PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Owlv2PreTrainedModel + ), + /* harmony export */ + PaliGemmaForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.PaliGemmaForConditionalGeneration + ), + /* harmony export */ + PaliGemmaPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.PaliGemmaPreTrainedModel + ), + /* harmony export */ + PaliGemmaProcessor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.PaliGemmaProcessor + ), + /* harmony export */ + ParakeetFeatureExtractor: () => ( + /* reexport safe */ + _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.ParakeetFeatureExtractor + ), + /* harmony export */ + ParakeetForCTC: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ParakeetForCTC + ), + /* harmony export */ + ParakeetPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ParakeetPreTrainedModel + ), + /* harmony export */ + PatchTSMixerForPrediction: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.PatchTSMixerForPrediction + ), + /* harmony export */ + PatchTSMixerModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.PatchTSMixerModel + ), + /* harmony export */ + PatchTSMixerPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.PatchTSMixerPreTrainedModel + ), + /* harmony export */ + PatchTSTForPrediction: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.PatchTSTForPrediction + ), + /* harmony export */ + PatchTSTModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.PatchTSTModel + ), + /* harmony export */ + PatchTSTPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.PatchTSTPreTrainedModel + ), + /* harmony export */ + Phi3ForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Phi3ForCausalLM + ), + /* harmony export */ + Phi3Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Phi3Model + ), + /* harmony export */ + Phi3PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Phi3PreTrainedModel + ), + /* harmony export */ + Phi3VForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Phi3VForCausalLM + ), + /* harmony export */ + Phi3VImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.Phi3VImageProcessor + ), + /* harmony export */ + Phi3VPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Phi3VPreTrainedModel + ), + /* harmony export */ + Phi3VProcessor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.Phi3VProcessor + ), + /* harmony export */ + PhiForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.PhiForCausalLM + ), + /* harmony export */ + PhiModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.PhiModel + ), + /* harmony export */ + PhiPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.PhiPreTrainedModel + ), + /* harmony export */ + Pipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.Pipeline + ), + /* harmony export */ + PixtralImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.PixtralImageProcessor + ), + /* harmony export */ + PixtralProcessor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.PixtralProcessor + ), + /* harmony export */ + PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.PreTrainedModel + ), + /* harmony export */ + PreTrainedTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.PreTrainedTokenizer + ), + /* harmony export */ + PretrainedConfig: () => ( + /* reexport safe */ + _configs_js__WEBPACK_IMPORTED_MODULE_4__.PretrainedConfig + ), + /* harmony export */ + PretrainedMixin: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.PretrainedMixin + ), + /* harmony export */ + Processor: () => ( + /* reexport safe */ + _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_16__.Processor + ), + /* harmony export */ + PvtForImageClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.PvtForImageClassification + ), + /* harmony export */ + PvtImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.PvtImageProcessor + ), + /* harmony export */ + PvtModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.PvtModel + ), + /* harmony export */ + PvtPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.PvtPreTrainedModel + ), + /* harmony export */ + PyAnnoteFeatureExtractor: () => ( + /* reexport safe */ + _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.PyAnnoteFeatureExtractor + ), + /* harmony export */ + PyAnnoteForAudioFrameClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.PyAnnoteForAudioFrameClassification + ), + /* harmony export */ + PyAnnoteModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.PyAnnoteModel + ), + /* harmony export */ + PyAnnotePreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.PyAnnotePreTrainedModel + ), + /* harmony export */ + PyAnnoteProcessor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.PyAnnoteProcessor + ), + /* harmony export */ + QuestionAnsweringModelOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.QuestionAnsweringModelOutput + ), + /* harmony export */ + QuestionAnsweringPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.QuestionAnsweringPipeline + ), + /* harmony export */ + Qwen2ForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Qwen2ForCausalLM + ), + /* harmony export */ + Qwen2Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Qwen2Model + ), + /* harmony export */ + Qwen2PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Qwen2PreTrainedModel + ), + /* harmony export */ + Qwen2Tokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.Qwen2Tokenizer + ), + /* harmony export */ + Qwen2VLForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Qwen2VLForConditionalGeneration + ), + /* harmony export */ + Qwen2VLImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.Qwen2VLImageProcessor + ), + /* harmony export */ + Qwen2VLPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Qwen2VLPreTrainedModel + ), + /* harmony export */ + Qwen2VLProcessor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.Qwen2VLProcessor + ), + /* harmony export */ + Qwen3ForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Qwen3ForCausalLM + ), + /* harmony export */ + Qwen3Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Qwen3Model + ), + /* harmony export */ + Qwen3PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Qwen3PreTrainedModel + ), + /* harmony export */ + RFDetrForObjectDetection: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RFDetrForObjectDetection + ), + /* harmony export */ + RFDetrModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RFDetrModel + ), + /* harmony export */ + RFDetrObjectDetectionOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RFDetrObjectDetectionOutput + ), + /* harmony export */ + RFDetrPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RFDetrPreTrainedModel + ), + /* harmony export */ + RTDetrForObjectDetection: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RTDetrForObjectDetection + ), + /* harmony export */ + RTDetrImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.RTDetrImageProcessor + ), + /* harmony export */ + RTDetrModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RTDetrModel + ), + /* harmony export */ + RTDetrObjectDetectionOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RTDetrObjectDetectionOutput + ), + /* harmony export */ + RTDetrPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RTDetrPreTrainedModel + ), + /* harmony export */ + RTDetrV2ForObjectDetection: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RTDetrV2ForObjectDetection + ), + /* harmony export */ + RTDetrV2Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RTDetrV2Model + ), + /* harmony export */ + RTDetrV2ObjectDetectionOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RTDetrV2ObjectDetectionOutput + ), + /* harmony export */ + RTDetrV2PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RTDetrV2PreTrainedModel + ), + /* harmony export */ + RawAudio: () => ( + /* reexport safe */ + _utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.RawAudio + ), + /* harmony export */ + RawImage: () => ( + /* reexport safe */ + _utils_image_js__WEBPACK_IMPORTED_MODULE_6__.RawImage + ), + /* harmony export */ + RawVideo: () => ( + /* reexport safe */ + _utils_video_js__WEBPACK_IMPORTED_MODULE_7__.RawVideo + ), + /* harmony export */ + RawVideoFrame: () => ( + /* reexport safe */ + _utils_video_js__WEBPACK_IMPORTED_MODULE_7__.RawVideoFrame + ), + /* harmony export */ + RepetitionPenaltyLogitsProcessor: () => ( + /* reexport safe */ + _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.RepetitionPenaltyLogitsProcessor + ), + /* harmony export */ + ResNetForImageClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ResNetForImageClassification + ), + /* harmony export */ + ResNetModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ResNetModel + ), + /* harmony export */ + ResNetPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ResNetPreTrainedModel + ), + /* harmony export */ + RoFormerForMaskedLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RoFormerForMaskedLM + ), + /* harmony export */ + RoFormerForQuestionAnswering: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RoFormerForQuestionAnswering + ), + /* harmony export */ + RoFormerForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RoFormerForSequenceClassification + ), + /* harmony export */ + RoFormerForTokenClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RoFormerForTokenClassification + ), + /* harmony export */ + RoFormerModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RoFormerModel + ), + /* harmony export */ + RoFormerPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RoFormerPreTrainedModel + ), + /* harmony export */ + RoFormerTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.RoFormerTokenizer + ), + /* harmony export */ + RobertaForMaskedLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RobertaForMaskedLM + ), + /* harmony export */ + RobertaForQuestionAnswering: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RobertaForQuestionAnswering + ), + /* harmony export */ + RobertaForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RobertaForSequenceClassification + ), + /* harmony export */ + RobertaForTokenClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RobertaForTokenClassification + ), + /* harmony export */ + RobertaModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RobertaModel + ), + /* harmony export */ + RobertaPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.RobertaPreTrainedModel + ), + /* harmony export */ + RobertaTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.RobertaTokenizer + ), + /* harmony export */ + Sam2ImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.Sam2ImageProcessor + ), + /* harmony export */ + Sam2ImageSegmentationOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Sam2ImageSegmentationOutput + ), + /* harmony export */ + Sam2Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Sam2Model + ), + /* harmony export */ + Sam2PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Sam2PreTrainedModel + ), + /* harmony export */ + Sam2Processor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.Sam2Processor + ), + /* harmony export */ + Sam2VideoProcessor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.Sam2VideoProcessor + ), + /* harmony export */ + Sam3ImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.Sam3ImageProcessor + ), + /* harmony export */ + Sam3TrackerModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Sam3TrackerModel + ), + /* harmony export */ + SamImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.SamImageProcessor + ), + /* harmony export */ + SamImageSegmentationOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SamImageSegmentationOutput + ), + /* harmony export */ + SamModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SamModel + ), + /* harmony export */ + SamPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SamPreTrainedModel + ), + /* harmony export */ + SamProcessor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.SamProcessor + ), + /* harmony export */ + SapiensForDepthEstimation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SapiensForDepthEstimation + ), + /* harmony export */ + SapiensForNormalEstimation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SapiensForNormalEstimation + ), + /* harmony export */ + SapiensForSemanticSegmentation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SapiensForSemanticSegmentation + ), + /* harmony export */ + SapiensPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SapiensPreTrainedModel + ), + /* harmony export */ + SeamlessM4TFeatureExtractor: () => ( + /* reexport safe */ + _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.SeamlessM4TFeatureExtractor + ), + /* harmony export */ + SegformerFeatureExtractor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.SegformerFeatureExtractor + ), + /* harmony export */ + SegformerForImageClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SegformerForImageClassification + ), + /* harmony export */ + SegformerForSemanticSegmentation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SegformerForSemanticSegmentation + ), + /* harmony export */ + SegformerImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.SegformerImageProcessor + ), + /* harmony export */ + SegformerModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SegformerModel + ), + /* harmony export */ + SegformerPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SegformerPreTrainedModel + ), + /* harmony export */ + Seq2SeqLMOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Seq2SeqLMOutput + ), + /* harmony export */ + SequenceClassifierOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SequenceClassifierOutput + ), + /* harmony export */ + SiglipImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.SiglipImageProcessor + ), + /* harmony export */ + SiglipModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SiglipModel + ), + /* harmony export */ + SiglipPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SiglipPreTrainedModel + ), + /* harmony export */ + SiglipTextModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SiglipTextModel + ), + /* harmony export */ + SiglipTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.SiglipTokenizer + ), + /* harmony export */ + SiglipVisionModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SiglipVisionModel + ), + /* harmony export */ + SmolLM3ForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SmolLM3ForCausalLM + ), + /* harmony export */ + SmolLM3Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SmolLM3Model + ), + /* harmony export */ + SmolLM3PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SmolLM3PreTrainedModel + ), + /* harmony export */ + SmolVLMForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SmolVLMForConditionalGeneration + ), + /* harmony export */ + SmolVLMImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.SmolVLMImageProcessor + ), + /* harmony export */ + SmolVLMProcessor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.SmolVLMProcessor + ), + /* harmony export */ + SnacDecoderModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SnacDecoderModel + ), + /* harmony export */ + SnacEncoderModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SnacEncoderModel + ), + /* harmony export */ + SnacFeatureExtractor: () => ( + /* reexport safe */ + _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.SnacFeatureExtractor + ), + /* harmony export */ + SnacModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SnacModel + ), + /* harmony export */ + SnacPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SnacPreTrainedModel + ), + /* harmony export */ + SpeechT5FeatureExtractor: () => ( + /* reexport safe */ + _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.SpeechT5FeatureExtractor + ), + /* harmony export */ + SpeechT5ForSpeechToText: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SpeechT5ForSpeechToText + ), + /* harmony export */ + SpeechT5ForTextToSpeech: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SpeechT5ForTextToSpeech + ), + /* harmony export */ + SpeechT5HifiGan: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SpeechT5HifiGan + ), + /* harmony export */ + SpeechT5Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SpeechT5Model + ), + /* harmony export */ + SpeechT5PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SpeechT5PreTrainedModel + ), + /* harmony export */ + SpeechT5Processor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.SpeechT5Processor + ), + /* harmony export */ + SpeechT5Tokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.SpeechT5Tokenizer + ), + /* harmony export */ + SqueezeBertForMaskedLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SqueezeBertForMaskedLM + ), + /* harmony export */ + SqueezeBertForQuestionAnswering: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SqueezeBertForQuestionAnswering + ), + /* harmony export */ + SqueezeBertForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SqueezeBertForSequenceClassification + ), + /* harmony export */ + SqueezeBertModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SqueezeBertModel + ), + /* harmony export */ + SqueezeBertPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SqueezeBertPreTrainedModel + ), + /* harmony export */ + SqueezeBertTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.SqueezeBertTokenizer + ), + /* harmony export */ + StableLmForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.StableLmForCausalLM + ), + /* harmony export */ + StableLmModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.StableLmModel + ), + /* harmony export */ + StableLmPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.StableLmPreTrainedModel + ), + /* harmony export */ + Starcoder2ForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Starcoder2ForCausalLM + ), + /* harmony export */ + Starcoder2Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Starcoder2Model + ), + /* harmony export */ + Starcoder2PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Starcoder2PreTrainedModel + ), + /* harmony export */ + StoppingCriteria: () => ( + /* reexport safe */ + _generation_stopping_criteria_js__WEBPACK_IMPORTED_MODULE_20__.StoppingCriteria + ), + /* harmony export */ + StoppingCriteriaList: () => ( + /* reexport safe */ + _generation_stopping_criteria_js__WEBPACK_IMPORTED_MODULE_20__.StoppingCriteriaList + ), + /* harmony export */ + StyleTextToSpeech2Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.StyleTextToSpeech2Model + ), + /* harmony export */ + StyleTextToSpeech2PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.StyleTextToSpeech2PreTrainedModel + ), + /* harmony export */ + SummarizationPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.SummarizationPipeline + ), + /* harmony export */ + SupertonicForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SupertonicForConditionalGeneration + ), + /* harmony export */ + SupertonicPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SupertonicPreTrainedModel + ), + /* harmony export */ + SuppressTokensAtBeginLogitsProcessor: () => ( + /* reexport safe */ + _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.SuppressTokensAtBeginLogitsProcessor + ), + /* harmony export */ + Swin2SRForImageSuperResolution: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Swin2SRForImageSuperResolution + ), + /* harmony export */ + Swin2SRImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.Swin2SRImageProcessor + ), + /* harmony export */ + Swin2SRModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Swin2SRModel + ), + /* harmony export */ + Swin2SRPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Swin2SRPreTrainedModel + ), + /* harmony export */ + SwinForImageClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SwinForImageClassification + ), + /* harmony export */ + SwinForSemanticSegmentation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SwinForSemanticSegmentation + ), + /* harmony export */ + SwinModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SwinModel + ), + /* harmony export */ + SwinPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.SwinPreTrainedModel + ), + /* harmony export */ + T5ForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.T5ForConditionalGeneration + ), + /* harmony export */ + T5Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.T5Model + ), + /* harmony export */ + T5PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.T5PreTrainedModel + ), + /* harmony export */ + T5Tokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.T5Tokenizer + ), + /* harmony export */ + TableTransformerForObjectDetection: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.TableTransformerForObjectDetection + ), + /* harmony export */ + TableTransformerModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.TableTransformerModel + ), + /* harmony export */ + TableTransformerObjectDetectionOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.TableTransformerObjectDetectionOutput + ), + /* harmony export */ + TableTransformerPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.TableTransformerPreTrainedModel + ), + /* harmony export */ + TemperatureLogitsWarper: () => ( + /* reexport safe */ + _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.TemperatureLogitsWarper + ), + /* harmony export */ + Tensor: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.Tensor + ), + /* harmony export */ + Text2TextGenerationPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.Text2TextGenerationPipeline + ), + /* harmony export */ + TextClassificationPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.TextClassificationPipeline + ), + /* harmony export */ + TextGenerationPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.TextGenerationPipeline + ), + /* harmony export */ + TextStreamer: () => ( + /* reexport safe */ + _generation_streamers_js__WEBPACK_IMPORTED_MODULE_19__.TextStreamer + ), + /* harmony export */ + TextToAudioPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.TextToAudioPipeline + ), + /* harmony export */ + TokenClassificationPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.TokenClassificationPipeline + ), + /* harmony export */ + TokenClassifierOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.TokenClassifierOutput + ), + /* harmony export */ + TokenizerModel: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.TokenizerModel + ), + /* harmony export */ + TopKLogitsWarper: () => ( + /* reexport safe */ + _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.TopKLogitsWarper + ), + /* harmony export */ + TopPLogitsWarper: () => ( + /* reexport safe */ + _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.TopPLogitsWarper + ), + /* harmony export */ + TrOCRForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.TrOCRForCausalLM + ), + /* harmony export */ + TrOCRPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.TrOCRPreTrainedModel + ), + /* harmony export */ + TranslationPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.TranslationPipeline + ), + /* harmony export */ + UltravoxModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.UltravoxModel + ), + /* harmony export */ + UltravoxPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.UltravoxPreTrainedModel + ), + /* harmony export */ + UltravoxProcessor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.UltravoxProcessor + ), + /* harmony export */ + UniSpeechForCTC: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechForCTC + ), + /* harmony export */ + UniSpeechForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechForSequenceClassification + ), + /* harmony export */ + UniSpeechModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechModel + ), + /* harmony export */ + UniSpeechPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechPreTrainedModel + ), + /* harmony export */ + UniSpeechSatForAudioFrameClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechSatForAudioFrameClassification + ), + /* harmony export */ + UniSpeechSatForCTC: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechSatForCTC + ), + /* harmony export */ + UniSpeechSatForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechSatForSequenceClassification + ), + /* harmony export */ + UniSpeechSatModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechSatModel + ), + /* harmony export */ + UniSpeechSatPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechSatPreTrainedModel + ), + /* harmony export */ + VLChatProcessor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.VLChatProcessor + ), + /* harmony export */ + VLMImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.VLMImageProcessor + ), + /* harmony export */ + VaultGemmaForCausalLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.VaultGemmaForCausalLM + ), + /* harmony export */ + VaultGemmaModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.VaultGemmaModel + ), + /* harmony export */ + VaultGemmaPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.VaultGemmaPreTrainedModel + ), + /* harmony export */ + ViTFeatureExtractor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.ViTFeatureExtractor + ), + /* harmony export */ + ViTForImageClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ViTForImageClassification + ), + /* harmony export */ + ViTImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.ViTImageProcessor + ), + /* harmony export */ + ViTMAEModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ViTMAEModel + ), + /* harmony export */ + ViTMAEPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ViTMAEPreTrainedModel + ), + /* harmony export */ + ViTMSNForImageClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ViTMSNForImageClassification + ), + /* harmony export */ + ViTMSNModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ViTMSNModel + ), + /* harmony export */ + ViTMSNPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ViTMSNPreTrainedModel + ), + /* harmony export */ + ViTModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ViTModel + ), + /* harmony export */ + ViTPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.ViTPreTrainedModel + ), + /* harmony export */ + VisionEncoderDecoderModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.VisionEncoderDecoderModel + ), + /* harmony export */ + VitMatteForImageMatting: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.VitMatteForImageMatting + ), + /* harmony export */ + VitMatteImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.VitMatteImageProcessor + ), + /* harmony export */ + VitMattePreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.VitMattePreTrainedModel + ), + /* harmony export */ + VitPoseForPoseEstimation: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.VitPoseForPoseEstimation + ), + /* harmony export */ + VitPoseImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.VitPoseImageProcessor + ), + /* harmony export */ + VitPosePreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.VitPosePreTrainedModel + ), + /* harmony export */ + VitsModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.VitsModel + ), + /* harmony export */ + VitsModelOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.VitsModelOutput + ), + /* harmony export */ + VitsPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.VitsPreTrainedModel + ), + /* harmony export */ + VitsTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.VitsTokenizer + ), + /* harmony export */ + VoxtralForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.VoxtralForConditionalGeneration + ), + /* harmony export */ + VoxtralProcessor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.VoxtralProcessor + ), + /* harmony export */ + Wav2Vec2BertForCTC: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2BertForCTC + ), + /* harmony export */ + Wav2Vec2BertForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2BertForSequenceClassification + ), + /* harmony export */ + Wav2Vec2BertModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2BertModel + ), + /* harmony export */ + Wav2Vec2BertPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2BertPreTrainedModel + ), + /* harmony export */ + Wav2Vec2CTCTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.Wav2Vec2CTCTokenizer + ), + /* harmony export */ + Wav2Vec2FeatureExtractor: () => ( + /* reexport safe */ + _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.Wav2Vec2FeatureExtractor + ), + /* harmony export */ + Wav2Vec2ForAudioFrameClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2ForAudioFrameClassification + ), + /* harmony export */ + Wav2Vec2ForCTC: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2ForCTC + ), + /* harmony export */ + Wav2Vec2ForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2ForSequenceClassification + ), + /* harmony export */ + Wav2Vec2Model: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2Model + ), + /* harmony export */ + Wav2Vec2PreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2PreTrainedModel + ), + /* harmony export */ + Wav2Vec2Processor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.Wav2Vec2Processor + ), + /* harmony export */ + Wav2Vec2ProcessorWithLM: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.Wav2Vec2ProcessorWithLM + ), + /* harmony export */ + WavLMForAudioFrameClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.WavLMForAudioFrameClassification + ), + /* harmony export */ + WavLMForCTC: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.WavLMForCTC + ), + /* harmony export */ + WavLMForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.WavLMForSequenceClassification + ), + /* harmony export */ + WavLMForXVector: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.WavLMForXVector + ), + /* harmony export */ + WavLMModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.WavLMModel + ), + /* harmony export */ + WavLMPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.WavLMPreTrainedModel + ), + /* harmony export */ + WeSpeakerFeatureExtractor: () => ( + /* reexport safe */ + _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.WeSpeakerFeatureExtractor + ), + /* harmony export */ + WeSpeakerResNetModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.WeSpeakerResNetModel + ), + /* harmony export */ + WeSpeakerResNetPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.WeSpeakerResNetPreTrainedModel + ), + /* harmony export */ + WhisperFeatureExtractor: () => ( + /* reexport safe */ + _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.WhisperFeatureExtractor + ), + /* harmony export */ + WhisperForConditionalGeneration: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.WhisperForConditionalGeneration + ), + /* harmony export */ + WhisperModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.WhisperModel + ), + /* harmony export */ + WhisperPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.WhisperPreTrainedModel + ), + /* harmony export */ + WhisperProcessor: () => ( + /* reexport safe */ + _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.WhisperProcessor + ), + /* harmony export */ + WhisperTextStreamer: () => ( + /* reexport safe */ + _generation_streamers_js__WEBPACK_IMPORTED_MODULE_19__.WhisperTextStreamer + ), + /* harmony export */ + WhisperTimeStampLogitsProcessor: () => ( + /* reexport safe */ + _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.WhisperTimeStampLogitsProcessor + ), + /* harmony export */ + WhisperTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.WhisperTokenizer + ), + /* harmony export */ + XLMForQuestionAnswering: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMForQuestionAnswering + ), + /* harmony export */ + XLMForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMForSequenceClassification + ), + /* harmony export */ + XLMForTokenClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMForTokenClassification + ), + /* harmony export */ + XLMModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMModel + ), + /* harmony export */ + XLMPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMPreTrainedModel + ), + /* harmony export */ + XLMRobertaForMaskedLM: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMRobertaForMaskedLM + ), + /* harmony export */ + XLMRobertaForQuestionAnswering: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMRobertaForQuestionAnswering + ), + /* harmony export */ + XLMRobertaForSequenceClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMRobertaForSequenceClassification + ), + /* harmony export */ + XLMRobertaForTokenClassification: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMRobertaForTokenClassification + ), + /* harmony export */ + XLMRobertaModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMRobertaModel + ), + /* harmony export */ + XLMRobertaPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMRobertaPreTrainedModel + ), + /* harmony export */ + XLMRobertaTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.XLMRobertaTokenizer + ), + /* harmony export */ + XLMTokenizer: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.XLMTokenizer + ), + /* harmony export */ + XLMWithLMHeadModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMWithLMHeadModel + ), + /* harmony export */ + XVectorOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.XVectorOutput + ), + /* harmony export */ + YolosFeatureExtractor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.YolosFeatureExtractor + ), + /* harmony export */ + YolosForObjectDetection: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.YolosForObjectDetection + ), + /* harmony export */ + YolosImageProcessor: () => ( + /* reexport safe */ + _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.YolosImageProcessor + ), + /* harmony export */ + YolosModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.YolosModel + ), + /* harmony export */ + YolosObjectDetectionOutput: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.YolosObjectDetectionOutput + ), + /* harmony export */ + YolosPreTrainedModel: () => ( + /* reexport safe */ + _models_js__WEBPACK_IMPORTED_MODULE_2__.YolosPreTrainedModel + ), + /* harmony export */ + ZeroShotAudioClassificationPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.ZeroShotAudioClassificationPipeline + ), + /* harmony export */ + ZeroShotClassificationPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.ZeroShotClassificationPipeline + ), + /* harmony export */ + ZeroShotImageClassificationPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.ZeroShotImageClassificationPipeline + ), + /* harmony export */ + ZeroShotObjectDetectionPipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.ZeroShotObjectDetectionPipeline + ), + /* harmony export */ + bankers_round: () => ( + /* reexport safe */ + _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.bankers_round + ), + /* harmony export */ + cat: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.cat + ), + /* harmony export */ + cos_sim: () => ( + /* reexport safe */ + _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.cos_sim + ), + /* harmony export */ + dot: () => ( + /* reexport safe */ + _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.dot + ), + /* harmony export */ + dynamic_time_warping: () => ( + /* reexport safe */ + _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.dynamic_time_warping + ), + /* harmony export */ + env: () => ( + /* reexport safe */ + _env_js__WEBPACK_IMPORTED_MODULE_0__.env + ), + /* harmony export */ + full: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.full + ), + /* harmony export */ + full_like: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.full_like + ), + /* harmony export */ + getCacheShapes: () => ( + /* reexport safe */ + _configs_js__WEBPACK_IMPORTED_MODULE_4__.getCacheShapes + ), + /* harmony export */ + hamming: () => ( + /* reexport safe */ + _utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.hamming + ), + /* harmony export */ + hanning: () => ( + /* reexport safe */ + _utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.hanning + ), + /* harmony export */ + interpolate: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.interpolate + ), + /* harmony export */ + interpolate_4d: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.interpolate_4d + ), + /* harmony export */ + interpolate_data: () => ( + /* reexport safe */ + _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.interpolate_data + ), + /* harmony export */ + is_chinese_char: () => ( + /* reexport safe */ + _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.is_chinese_char + ), + /* harmony export */ + layer_norm: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.layer_norm + ), + /* harmony export */ + load_image: () => ( + /* reexport safe */ + _utils_image_js__WEBPACK_IMPORTED_MODULE_6__.load_image + ), + /* harmony export */ + load_video: () => ( + /* reexport safe */ + _utils_video_js__WEBPACK_IMPORTED_MODULE_7__.load_video + ), + /* harmony export */ + log_softmax: () => ( + /* reexport safe */ + _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.log_softmax + ), + /* harmony export */ + magnitude: () => ( + /* reexport safe */ + _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.magnitude + ), + /* harmony export */ + matmul: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.matmul + ), + /* harmony export */ + max: () => ( + /* reexport safe */ + _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.max + ), + /* harmony export */ + mean: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.mean + ), + /* harmony export */ + mean_pooling: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.mean_pooling + ), + /* harmony export */ + medianFilter: () => ( + /* reexport safe */ + _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.medianFilter + ), + /* harmony export */ + mel_filter_bank: () => ( + /* reexport safe */ + _utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.mel_filter_bank + ), + /* harmony export */ + min: () => ( + /* reexport safe */ + _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.min + ), + /* harmony export */ + ones: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.ones + ), + /* harmony export */ + ones_like: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.ones_like + ), + /* harmony export */ + permute: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.permute + ), + /* harmony export */ + permute_data: () => ( + /* reexport safe */ + _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.permute_data + ), + /* harmony export */ + pipeline: () => ( + /* reexport safe */ + _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.pipeline + ), + /* harmony export */ + quantize_embeddings: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.quantize_embeddings + ), + /* harmony export */ + rand: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.rand + ), + /* harmony export */ + randn: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.randn + ), + /* harmony export */ + read_audio: () => ( + /* reexport safe */ + _utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.read_audio + ), + /* harmony export */ + rfft: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.rfft + ), + /* harmony export */ + round: () => ( + /* reexport safe */ + _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.round + ), + /* harmony export */ + slice: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.slice + ), + /* harmony export */ + softmax: () => ( + /* reexport safe */ + _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.softmax + ), + /* harmony export */ + spectrogram: () => ( + /* reexport safe */ + _utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.spectrogram + ), + /* harmony export */ + stack: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.stack + ), + /* harmony export */ + std_mean: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.std_mean + ), + /* harmony export */ + topk: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.topk + ), + /* harmony export */ + window_function: () => ( + /* reexport safe */ + _utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.window_function + ), + /* harmony export */ + zeros: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.zeros + ), + /* harmony export */ + zeros_like: () => ( + /* reexport safe */ + _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.zeros_like + ) + /* harmony export */ + }); + var _env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__( + /*! ./env.js */ + "./src/env.js" + ); + var _pipelines_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__( + /*! ./pipelines.js */ + "./src/pipelines.js" + ); + var _models_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__( + /*! ./models.js */ + "./src/models.js" + ); + var _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__( + /*! ./tokenizers.js */ + "./src/tokenizers.js" + ); + var _configs_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__( + /*! ./configs.js */ + "./src/configs.js" + ); + var _utils_audio_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__( + /*! ./utils/audio.js */ + "./src/utils/audio.js" + ); + var _utils_image_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__( + /*! ./utils/image.js */ + "./src/utils/image.js" + ); + var _utils_video_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__( + /*! ./utils/video.js */ + "./src/utils/video.js" + ); + var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__( + /*! ./utils/tensor.js */ + "./src/utils/tensor.js" + ); + var _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__( + /*! ./utils/maths.js */ + "./src/utils/maths.js" + ); + var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__( + /*! ./base/feature_extraction_utils.js */ + "./src/base/feature_extraction_utils.js" + ); + var _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__( + /*! ./models/feature_extractors.js */ + "./src/models/feature_extractors.js" + ); + var _models_auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__( + /*! ./models/auto/feature_extraction_auto.js */ + "./src/models/auto/feature_extraction_auto.js" + ); + var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__( + /*! ./base/image_processors_utils.js */ + "./src/base/image_processors_utils.js" + ); + var _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__( + /*! ./models/image_processors.js */ + "./src/models/image_processors.js" + ); + var _models_auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__( + /*! ./models/auto/image_processing_auto.js */ + "./src/models/auto/image_processing_auto.js" + ); + var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__( + /*! ./base/processing_utils.js */ + "./src/base/processing_utils.js" + ); + var _models_processors_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__( + /*! ./models/processors.js */ + "./src/models/processors.js" + ); + var _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__( + /*! ./models/auto/processing_auto.js */ + "./src/models/auto/processing_auto.js" + ); + var _generation_streamers_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__( + /*! ./generation/streamers.js */ + "./src/generation/streamers.js" + ); + var _generation_stopping_criteria_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__( + /*! ./generation/stopping_criteria.js */ + "./src/generation/stopping_criteria.js" + ); + var _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__( + /*! ./generation/logits_process.js */ + "./src/generation/logits_process.js" + ); + })(); + var __webpack_exports__ASTFeatureExtractor = __webpack_exports__.ASTFeatureExtractor; + var __webpack_exports__ASTForAudioClassification = __webpack_exports__.ASTForAudioClassification; + var __webpack_exports__ASTModel = __webpack_exports__.ASTModel; + var __webpack_exports__ASTPreTrainedModel = __webpack_exports__.ASTPreTrainedModel; + var __webpack_exports__AlbertForMaskedLM = __webpack_exports__.AlbertForMaskedLM; + var __webpack_exports__AlbertForQuestionAnswering = __webpack_exports__.AlbertForQuestionAnswering; + var __webpack_exports__AlbertForSequenceClassification = __webpack_exports__.AlbertForSequenceClassification; + var __webpack_exports__AlbertModel = __webpack_exports__.AlbertModel; + var __webpack_exports__AlbertPreTrainedModel = __webpack_exports__.AlbertPreTrainedModel; + var __webpack_exports__AlbertTokenizer = __webpack_exports__.AlbertTokenizer; + var __webpack_exports__ArceeForCausalLM = __webpack_exports__.ArceeForCausalLM; + var __webpack_exports__ArceeModel = __webpack_exports__.ArceeModel; + var __webpack_exports__ArceePreTrainedModel = __webpack_exports__.ArceePreTrainedModel; + var __webpack_exports__AudioClassificationPipeline = __webpack_exports__.AudioClassificationPipeline; + var __webpack_exports__AutoConfig = __webpack_exports__.AutoConfig; + var __webpack_exports__AutoFeatureExtractor = __webpack_exports__.AutoFeatureExtractor; + var __webpack_exports__AutoImageProcessor = __webpack_exports__.AutoImageProcessor; + var __webpack_exports__AutoModel = __webpack_exports__.AutoModel; + var __webpack_exports__AutoModelForAudioClassification = __webpack_exports__.AutoModelForAudioClassification; + var __webpack_exports__AutoModelForAudioFrameClassification = __webpack_exports__.AutoModelForAudioFrameClassification; + var __webpack_exports__AutoModelForAudioTextToText = __webpack_exports__.AutoModelForAudioTextToText; + var __webpack_exports__AutoModelForCTC = __webpack_exports__.AutoModelForCTC; + var __webpack_exports__AutoModelForCausalLM = __webpack_exports__.AutoModelForCausalLM; + var __webpack_exports__AutoModelForDepthEstimation = __webpack_exports__.AutoModelForDepthEstimation; + var __webpack_exports__AutoModelForDocumentQuestionAnswering = __webpack_exports__.AutoModelForDocumentQuestionAnswering; + var __webpack_exports__AutoModelForImageClassification = __webpack_exports__.AutoModelForImageClassification; + var __webpack_exports__AutoModelForImageFeatureExtraction = __webpack_exports__.AutoModelForImageFeatureExtraction; + var __webpack_exports__AutoModelForImageMatting = __webpack_exports__.AutoModelForImageMatting; + var __webpack_exports__AutoModelForImageSegmentation = __webpack_exports__.AutoModelForImageSegmentation; + var __webpack_exports__AutoModelForImageTextToText = __webpack_exports__.AutoModelForImageTextToText; + var __webpack_exports__AutoModelForImageToImage = __webpack_exports__.AutoModelForImageToImage; + var __webpack_exports__AutoModelForMaskGeneration = __webpack_exports__.AutoModelForMaskGeneration; + var __webpack_exports__AutoModelForMaskedLM = __webpack_exports__.AutoModelForMaskedLM; + var __webpack_exports__AutoModelForNormalEstimation = __webpack_exports__.AutoModelForNormalEstimation; + var __webpack_exports__AutoModelForObjectDetection = __webpack_exports__.AutoModelForObjectDetection; + var __webpack_exports__AutoModelForPoseEstimation = __webpack_exports__.AutoModelForPoseEstimation; + var __webpack_exports__AutoModelForQuestionAnswering = __webpack_exports__.AutoModelForQuestionAnswering; + var __webpack_exports__AutoModelForSemanticSegmentation = __webpack_exports__.AutoModelForSemanticSegmentation; + var __webpack_exports__AutoModelForSeq2SeqLM = __webpack_exports__.AutoModelForSeq2SeqLM; + var __webpack_exports__AutoModelForSequenceClassification = __webpack_exports__.AutoModelForSequenceClassification; + var __webpack_exports__AutoModelForSpeechSeq2Seq = __webpack_exports__.AutoModelForSpeechSeq2Seq; + var __webpack_exports__AutoModelForTextToSpectrogram = __webpack_exports__.AutoModelForTextToSpectrogram; + var __webpack_exports__AutoModelForTextToWaveform = __webpack_exports__.AutoModelForTextToWaveform; + var __webpack_exports__AutoModelForTokenClassification = __webpack_exports__.AutoModelForTokenClassification; + var __webpack_exports__AutoModelForUniversalSegmentation = __webpack_exports__.AutoModelForUniversalSegmentation; + var __webpack_exports__AutoModelForVision2Seq = __webpack_exports__.AutoModelForVision2Seq; + var __webpack_exports__AutoModelForXVector = __webpack_exports__.AutoModelForXVector; + var __webpack_exports__AutoModelForZeroShotObjectDetection = __webpack_exports__.AutoModelForZeroShotObjectDetection; + var __webpack_exports__AutoProcessor = __webpack_exports__.AutoProcessor; + var __webpack_exports__AutoTokenizer = __webpack_exports__.AutoTokenizer; + var __webpack_exports__AutomaticSpeechRecognitionPipeline = __webpack_exports__.AutomaticSpeechRecognitionPipeline; + var __webpack_exports__BackgroundRemovalPipeline = __webpack_exports__.BackgroundRemovalPipeline; + var __webpack_exports__BartForConditionalGeneration = __webpack_exports__.BartForConditionalGeneration; + var __webpack_exports__BartForSequenceClassification = __webpack_exports__.BartForSequenceClassification; + var __webpack_exports__BartModel = __webpack_exports__.BartModel; + var __webpack_exports__BartPretrainedModel = __webpack_exports__.BartPretrainedModel; + var __webpack_exports__BartTokenizer = __webpack_exports__.BartTokenizer; + var __webpack_exports__BaseModelOutput = __webpack_exports__.BaseModelOutput; + var __webpack_exports__BaseStreamer = __webpack_exports__.BaseStreamer; + var __webpack_exports__BeitFeatureExtractor = __webpack_exports__.BeitFeatureExtractor; + var __webpack_exports__BeitForImageClassification = __webpack_exports__.BeitForImageClassification; + var __webpack_exports__BeitModel = __webpack_exports__.BeitModel; + var __webpack_exports__BeitPreTrainedModel = __webpack_exports__.BeitPreTrainedModel; + var __webpack_exports__BertForMaskedLM = __webpack_exports__.BertForMaskedLM; + var __webpack_exports__BertForQuestionAnswering = __webpack_exports__.BertForQuestionAnswering; + var __webpack_exports__BertForSequenceClassification = __webpack_exports__.BertForSequenceClassification; + var __webpack_exports__BertForTokenClassification = __webpack_exports__.BertForTokenClassification; + var __webpack_exports__BertModel = __webpack_exports__.BertModel; + var __webpack_exports__BertPreTrainedModel = __webpack_exports__.BertPreTrainedModel; + var __webpack_exports__BertTokenizer = __webpack_exports__.BertTokenizer; + var __webpack_exports__BitImageProcessor = __webpack_exports__.BitImageProcessor; + var __webpack_exports__BlenderbotForConditionalGeneration = __webpack_exports__.BlenderbotForConditionalGeneration; + var __webpack_exports__BlenderbotModel = __webpack_exports__.BlenderbotModel; + var __webpack_exports__BlenderbotPreTrainedModel = __webpack_exports__.BlenderbotPreTrainedModel; + var __webpack_exports__BlenderbotSmallForConditionalGeneration = __webpack_exports__.BlenderbotSmallForConditionalGeneration; + var __webpack_exports__BlenderbotSmallModel = __webpack_exports__.BlenderbotSmallModel; + var __webpack_exports__BlenderbotSmallPreTrainedModel = __webpack_exports__.BlenderbotSmallPreTrainedModel; + var __webpack_exports__BlenderbotSmallTokenizer = __webpack_exports__.BlenderbotSmallTokenizer; + var __webpack_exports__BlenderbotTokenizer = __webpack_exports__.BlenderbotTokenizer; + var __webpack_exports__BloomForCausalLM = __webpack_exports__.BloomForCausalLM; + var __webpack_exports__BloomModel = __webpack_exports__.BloomModel; + var __webpack_exports__BloomPreTrainedModel = __webpack_exports__.BloomPreTrainedModel; + var __webpack_exports__BloomTokenizer = __webpack_exports__.BloomTokenizer; + var __webpack_exports__CLIPFeatureExtractor = __webpack_exports__.CLIPFeatureExtractor; + var __webpack_exports__CLIPImageProcessor = __webpack_exports__.CLIPImageProcessor; + var __webpack_exports__CLIPModel = __webpack_exports__.CLIPModel; + var __webpack_exports__CLIPPreTrainedModel = __webpack_exports__.CLIPPreTrainedModel; + var __webpack_exports__CLIPSegForImageSegmentation = __webpack_exports__.CLIPSegForImageSegmentation; + var __webpack_exports__CLIPSegModel = __webpack_exports__.CLIPSegModel; + var __webpack_exports__CLIPSegPreTrainedModel = __webpack_exports__.CLIPSegPreTrainedModel; + var __webpack_exports__CLIPTextModel = __webpack_exports__.CLIPTextModel; + var __webpack_exports__CLIPTextModelWithProjection = __webpack_exports__.CLIPTextModelWithProjection; + var __webpack_exports__CLIPTokenizer = __webpack_exports__.CLIPTokenizer; + var __webpack_exports__CLIPVisionModel = __webpack_exports__.CLIPVisionModel; + var __webpack_exports__CLIPVisionModelWithProjection = __webpack_exports__.CLIPVisionModelWithProjection; + var __webpack_exports__CamembertForMaskedLM = __webpack_exports__.CamembertForMaskedLM; + var __webpack_exports__CamembertForQuestionAnswering = __webpack_exports__.CamembertForQuestionAnswering; + var __webpack_exports__CamembertForSequenceClassification = __webpack_exports__.CamembertForSequenceClassification; + var __webpack_exports__CamembertForTokenClassification = __webpack_exports__.CamembertForTokenClassification; + var __webpack_exports__CamembertModel = __webpack_exports__.CamembertModel; + var __webpack_exports__CamembertPreTrainedModel = __webpack_exports__.CamembertPreTrainedModel; + var __webpack_exports__CamembertTokenizer = __webpack_exports__.CamembertTokenizer; + var __webpack_exports__CausalLMOutput = __webpack_exports__.CausalLMOutput; + var __webpack_exports__CausalLMOutputWithPast = __webpack_exports__.CausalLMOutputWithPast; + var __webpack_exports__ChineseCLIPFeatureExtractor = __webpack_exports__.ChineseCLIPFeatureExtractor; + var __webpack_exports__ChineseCLIPModel = __webpack_exports__.ChineseCLIPModel; + var __webpack_exports__ChineseCLIPPreTrainedModel = __webpack_exports__.ChineseCLIPPreTrainedModel; + var __webpack_exports__ClapAudioModelWithProjection = __webpack_exports__.ClapAudioModelWithProjection; + var __webpack_exports__ClapFeatureExtractor = __webpack_exports__.ClapFeatureExtractor; + var __webpack_exports__ClapModel = __webpack_exports__.ClapModel; + var __webpack_exports__ClapPreTrainedModel = __webpack_exports__.ClapPreTrainedModel; + var __webpack_exports__ClapTextModelWithProjection = __webpack_exports__.ClapTextModelWithProjection; + var __webpack_exports__ClassifierFreeGuidanceLogitsProcessor = __webpack_exports__.ClassifierFreeGuidanceLogitsProcessor; + var __webpack_exports__CodeGenForCausalLM = __webpack_exports__.CodeGenForCausalLM; + var __webpack_exports__CodeGenModel = __webpack_exports__.CodeGenModel; + var __webpack_exports__CodeGenPreTrainedModel = __webpack_exports__.CodeGenPreTrainedModel; + var __webpack_exports__CodeGenTokenizer = __webpack_exports__.CodeGenTokenizer; + var __webpack_exports__CodeLlamaTokenizer = __webpack_exports__.CodeLlamaTokenizer; + var __webpack_exports__CohereForCausalLM = __webpack_exports__.CohereForCausalLM; + var __webpack_exports__CohereModel = __webpack_exports__.CohereModel; + var __webpack_exports__CoherePreTrainedModel = __webpack_exports__.CoherePreTrainedModel; + var __webpack_exports__CohereTokenizer = __webpack_exports__.CohereTokenizer; + var __webpack_exports__ConvBertForMaskedLM = __webpack_exports__.ConvBertForMaskedLM; + var __webpack_exports__ConvBertForQuestionAnswering = __webpack_exports__.ConvBertForQuestionAnswering; + var __webpack_exports__ConvBertForSequenceClassification = __webpack_exports__.ConvBertForSequenceClassification; + var __webpack_exports__ConvBertForTokenClassification = __webpack_exports__.ConvBertForTokenClassification; + var __webpack_exports__ConvBertModel = __webpack_exports__.ConvBertModel; + var __webpack_exports__ConvBertPreTrainedModel = __webpack_exports__.ConvBertPreTrainedModel; + var __webpack_exports__ConvBertTokenizer = __webpack_exports__.ConvBertTokenizer; + var __webpack_exports__ConvNextFeatureExtractor = __webpack_exports__.ConvNextFeatureExtractor; + var __webpack_exports__ConvNextForImageClassification = __webpack_exports__.ConvNextForImageClassification; + var __webpack_exports__ConvNextImageProcessor = __webpack_exports__.ConvNextImageProcessor; + var __webpack_exports__ConvNextModel = __webpack_exports__.ConvNextModel; + var __webpack_exports__ConvNextPreTrainedModel = __webpack_exports__.ConvNextPreTrainedModel; + var __webpack_exports__ConvNextV2ForImageClassification = __webpack_exports__.ConvNextV2ForImageClassification; + var __webpack_exports__ConvNextV2Model = __webpack_exports__.ConvNextV2Model; + var __webpack_exports__ConvNextV2PreTrainedModel = __webpack_exports__.ConvNextV2PreTrainedModel; + var __webpack_exports__DFineForObjectDetection = __webpack_exports__.DFineForObjectDetection; + var __webpack_exports__DFineModel = __webpack_exports__.DFineModel; + var __webpack_exports__DFinePreTrainedModel = __webpack_exports__.DFinePreTrainedModel; + var __webpack_exports__DINOv3ConvNextModel = __webpack_exports__.DINOv3ConvNextModel; + var __webpack_exports__DINOv3ConvNextPreTrainedModel = __webpack_exports__.DINOv3ConvNextPreTrainedModel; + var __webpack_exports__DINOv3ViTImageProcessor = __webpack_exports__.DINOv3ViTImageProcessor; + var __webpack_exports__DINOv3ViTModel = __webpack_exports__.DINOv3ViTModel; + var __webpack_exports__DINOv3ViTPreTrainedModel = __webpack_exports__.DINOv3ViTPreTrainedModel; + var __webpack_exports__DPTFeatureExtractor = __webpack_exports__.DPTFeatureExtractor; + var __webpack_exports__DPTForDepthEstimation = __webpack_exports__.DPTForDepthEstimation; + var __webpack_exports__DPTImageProcessor = __webpack_exports__.DPTImageProcessor; + var __webpack_exports__DPTModel = __webpack_exports__.DPTModel; + var __webpack_exports__DPTPreTrainedModel = __webpack_exports__.DPTPreTrainedModel; + var __webpack_exports__DacDecoderModel = __webpack_exports__.DacDecoderModel; + var __webpack_exports__DacDecoderOutput = __webpack_exports__.DacDecoderOutput; + var __webpack_exports__DacEncoderModel = __webpack_exports__.DacEncoderModel; + var __webpack_exports__DacEncoderOutput = __webpack_exports__.DacEncoderOutput; + var __webpack_exports__DacFeatureExtractor = __webpack_exports__.DacFeatureExtractor; + var __webpack_exports__DacModel = __webpack_exports__.DacModel; + var __webpack_exports__DacPreTrainedModel = __webpack_exports__.DacPreTrainedModel; + var __webpack_exports__DataTypeMap = __webpack_exports__.DataTypeMap; + var __webpack_exports__DebertaForMaskedLM = __webpack_exports__.DebertaForMaskedLM; + var __webpack_exports__DebertaForQuestionAnswering = __webpack_exports__.DebertaForQuestionAnswering; + var __webpack_exports__DebertaForSequenceClassification = __webpack_exports__.DebertaForSequenceClassification; + var __webpack_exports__DebertaForTokenClassification = __webpack_exports__.DebertaForTokenClassification; + var __webpack_exports__DebertaModel = __webpack_exports__.DebertaModel; + var __webpack_exports__DebertaPreTrainedModel = __webpack_exports__.DebertaPreTrainedModel; + var __webpack_exports__DebertaTokenizer = __webpack_exports__.DebertaTokenizer; + var __webpack_exports__DebertaV2ForMaskedLM = __webpack_exports__.DebertaV2ForMaskedLM; + var __webpack_exports__DebertaV2ForQuestionAnswering = __webpack_exports__.DebertaV2ForQuestionAnswering; + var __webpack_exports__DebertaV2ForSequenceClassification = __webpack_exports__.DebertaV2ForSequenceClassification; + var __webpack_exports__DebertaV2ForTokenClassification = __webpack_exports__.DebertaV2ForTokenClassification; + var __webpack_exports__DebertaV2Model = __webpack_exports__.DebertaV2Model; + var __webpack_exports__DebertaV2PreTrainedModel = __webpack_exports__.DebertaV2PreTrainedModel; + var __webpack_exports__DebertaV2Tokenizer = __webpack_exports__.DebertaV2Tokenizer; + var __webpack_exports__DecisionTransformerModel = __webpack_exports__.DecisionTransformerModel; + var __webpack_exports__DecisionTransformerPreTrainedModel = __webpack_exports__.DecisionTransformerPreTrainedModel; + var __webpack_exports__DeiTFeatureExtractor = __webpack_exports__.DeiTFeatureExtractor; + var __webpack_exports__DeiTForImageClassification = __webpack_exports__.DeiTForImageClassification; + var __webpack_exports__DeiTImageProcessor = __webpack_exports__.DeiTImageProcessor; + var __webpack_exports__DeiTModel = __webpack_exports__.DeiTModel; + var __webpack_exports__DeiTPreTrainedModel = __webpack_exports__.DeiTPreTrainedModel; + var __webpack_exports__DepthAnythingForDepthEstimation = __webpack_exports__.DepthAnythingForDepthEstimation; + var __webpack_exports__DepthAnythingPreTrainedModel = __webpack_exports__.DepthAnythingPreTrainedModel; + var __webpack_exports__DepthEstimationPipeline = __webpack_exports__.DepthEstimationPipeline; + var __webpack_exports__DepthProForDepthEstimation = __webpack_exports__.DepthProForDepthEstimation; + var __webpack_exports__DepthProPreTrainedModel = __webpack_exports__.DepthProPreTrainedModel; + var __webpack_exports__DetrFeatureExtractor = __webpack_exports__.DetrFeatureExtractor; + var __webpack_exports__DetrForObjectDetection = __webpack_exports__.DetrForObjectDetection; + var __webpack_exports__DetrForSegmentation = __webpack_exports__.DetrForSegmentation; + var __webpack_exports__DetrImageProcessor = __webpack_exports__.DetrImageProcessor; + var __webpack_exports__DetrModel = __webpack_exports__.DetrModel; + var __webpack_exports__DetrObjectDetectionOutput = __webpack_exports__.DetrObjectDetectionOutput; + var __webpack_exports__DetrPreTrainedModel = __webpack_exports__.DetrPreTrainedModel; + var __webpack_exports__DetrSegmentationOutput = __webpack_exports__.DetrSegmentationOutput; + var __webpack_exports__Dinov2ForImageClassification = __webpack_exports__.Dinov2ForImageClassification; + var __webpack_exports__Dinov2Model = __webpack_exports__.Dinov2Model; + var __webpack_exports__Dinov2PreTrainedModel = __webpack_exports__.Dinov2PreTrainedModel; + var __webpack_exports__Dinov2WithRegistersForImageClassification = __webpack_exports__.Dinov2WithRegistersForImageClassification; + var __webpack_exports__Dinov2WithRegistersModel = __webpack_exports__.Dinov2WithRegistersModel; + var __webpack_exports__Dinov2WithRegistersPreTrainedModel = __webpack_exports__.Dinov2WithRegistersPreTrainedModel; + var __webpack_exports__DistilBertForMaskedLM = __webpack_exports__.DistilBertForMaskedLM; + var __webpack_exports__DistilBertForQuestionAnswering = __webpack_exports__.DistilBertForQuestionAnswering; + var __webpack_exports__DistilBertForSequenceClassification = __webpack_exports__.DistilBertForSequenceClassification; + var __webpack_exports__DistilBertForTokenClassification = __webpack_exports__.DistilBertForTokenClassification; + var __webpack_exports__DistilBertModel = __webpack_exports__.DistilBertModel; + var __webpack_exports__DistilBertPreTrainedModel = __webpack_exports__.DistilBertPreTrainedModel; + var __webpack_exports__DistilBertTokenizer = __webpack_exports__.DistilBertTokenizer; + var __webpack_exports__DocumentQuestionAnsweringPipeline = __webpack_exports__.DocumentQuestionAnsweringPipeline; + var __webpack_exports__DonutFeatureExtractor = __webpack_exports__.DonutFeatureExtractor; + var __webpack_exports__DonutImageProcessor = __webpack_exports__.DonutImageProcessor; + var __webpack_exports__DonutSwinModel = __webpack_exports__.DonutSwinModel; + var __webpack_exports__DonutSwinPreTrainedModel = __webpack_exports__.DonutSwinPreTrainedModel; + var __webpack_exports__EdgeTamModel = __webpack_exports__.EdgeTamModel; + var __webpack_exports__EfficientNetForImageClassification = __webpack_exports__.EfficientNetForImageClassification; + var __webpack_exports__EfficientNetImageProcessor = __webpack_exports__.EfficientNetImageProcessor; + var __webpack_exports__EfficientNetModel = __webpack_exports__.EfficientNetModel; + var __webpack_exports__EfficientNetPreTrainedModel = __webpack_exports__.EfficientNetPreTrainedModel; + var __webpack_exports__ElectraForMaskedLM = __webpack_exports__.ElectraForMaskedLM; + var __webpack_exports__ElectraForQuestionAnswering = __webpack_exports__.ElectraForQuestionAnswering; + var __webpack_exports__ElectraForSequenceClassification = __webpack_exports__.ElectraForSequenceClassification; + var __webpack_exports__ElectraForTokenClassification = __webpack_exports__.ElectraForTokenClassification; + var __webpack_exports__ElectraModel = __webpack_exports__.ElectraModel; + var __webpack_exports__ElectraPreTrainedModel = __webpack_exports__.ElectraPreTrainedModel; + var __webpack_exports__ElectraTokenizer = __webpack_exports__.ElectraTokenizer; + var __webpack_exports__EncodecFeatureExtractor = __webpack_exports__.EncodecFeatureExtractor; + var __webpack_exports__EosTokenCriteria = __webpack_exports__.EosTokenCriteria; + var __webpack_exports__Ernie4_5ForCausalLM = __webpack_exports__.Ernie4_5ForCausalLM; + var __webpack_exports__Ernie4_5Model = __webpack_exports__.Ernie4_5Model; + var __webpack_exports__Ernie4_5PreTrainedModel = __webpack_exports__.Ernie4_5PreTrainedModel; + var __webpack_exports__EsmForMaskedLM = __webpack_exports__.EsmForMaskedLM; + var __webpack_exports__EsmForSequenceClassification = __webpack_exports__.EsmForSequenceClassification; + var __webpack_exports__EsmForTokenClassification = __webpack_exports__.EsmForTokenClassification; + var __webpack_exports__EsmModel = __webpack_exports__.EsmModel; + var __webpack_exports__EsmPreTrainedModel = __webpack_exports__.EsmPreTrainedModel; + var __webpack_exports__EsmTokenizer = __webpack_exports__.EsmTokenizer; + var __webpack_exports__ExaoneForCausalLM = __webpack_exports__.ExaoneForCausalLM; + var __webpack_exports__ExaoneModel = __webpack_exports__.ExaoneModel; + var __webpack_exports__ExaonePreTrainedModel = __webpack_exports__.ExaonePreTrainedModel; + var __webpack_exports__FFT = __webpack_exports__.FFT; + var __webpack_exports__FalconForCausalLM = __webpack_exports__.FalconForCausalLM; + var __webpack_exports__FalconModel = __webpack_exports__.FalconModel; + var __webpack_exports__FalconPreTrainedModel = __webpack_exports__.FalconPreTrainedModel; + var __webpack_exports__FalconTokenizer = __webpack_exports__.FalconTokenizer; + var __webpack_exports__FastViTForImageClassification = __webpack_exports__.FastViTForImageClassification; + var __webpack_exports__FastViTModel = __webpack_exports__.FastViTModel; + var __webpack_exports__FastViTPreTrainedModel = __webpack_exports__.FastViTPreTrainedModel; + var __webpack_exports__FeatureExtractionPipeline = __webpack_exports__.FeatureExtractionPipeline; + var __webpack_exports__FeatureExtractor = __webpack_exports__.FeatureExtractor; + var __webpack_exports__FillMaskPipeline = __webpack_exports__.FillMaskPipeline; + var __webpack_exports__Florence2ForConditionalGeneration = __webpack_exports__.Florence2ForConditionalGeneration; + var __webpack_exports__Florence2PreTrainedModel = __webpack_exports__.Florence2PreTrainedModel; + var __webpack_exports__Florence2Processor = __webpack_exports__.Florence2Processor; + var __webpack_exports__ForcedBOSTokenLogitsProcessor = __webpack_exports__.ForcedBOSTokenLogitsProcessor; + var __webpack_exports__ForcedEOSTokenLogitsProcessor = __webpack_exports__.ForcedEOSTokenLogitsProcessor; + var __webpack_exports__GLPNFeatureExtractor = __webpack_exports__.GLPNFeatureExtractor; + var __webpack_exports__GLPNForDepthEstimation = __webpack_exports__.GLPNForDepthEstimation; + var __webpack_exports__GLPNModel = __webpack_exports__.GLPNModel; + var __webpack_exports__GLPNPreTrainedModel = __webpack_exports__.GLPNPreTrainedModel; + var __webpack_exports__GPT2LMHeadModel = __webpack_exports__.GPT2LMHeadModel; + var __webpack_exports__GPT2Model = __webpack_exports__.GPT2Model; + var __webpack_exports__GPT2PreTrainedModel = __webpack_exports__.GPT2PreTrainedModel; + var __webpack_exports__GPT2Tokenizer = __webpack_exports__.GPT2Tokenizer; + var __webpack_exports__GPTBigCodeForCausalLM = __webpack_exports__.GPTBigCodeForCausalLM; + var __webpack_exports__GPTBigCodeModel = __webpack_exports__.GPTBigCodeModel; + var __webpack_exports__GPTBigCodePreTrainedModel = __webpack_exports__.GPTBigCodePreTrainedModel; + var __webpack_exports__GPTJForCausalLM = __webpack_exports__.GPTJForCausalLM; + var __webpack_exports__GPTJModel = __webpack_exports__.GPTJModel; + var __webpack_exports__GPTJPreTrainedModel = __webpack_exports__.GPTJPreTrainedModel; + var __webpack_exports__GPTNeoForCausalLM = __webpack_exports__.GPTNeoForCausalLM; + var __webpack_exports__GPTNeoModel = __webpack_exports__.GPTNeoModel; + var __webpack_exports__GPTNeoPreTrainedModel = __webpack_exports__.GPTNeoPreTrainedModel; + var __webpack_exports__GPTNeoXForCausalLM = __webpack_exports__.GPTNeoXForCausalLM; + var __webpack_exports__GPTNeoXModel = __webpack_exports__.GPTNeoXModel; + var __webpack_exports__GPTNeoXPreTrainedModel = __webpack_exports__.GPTNeoXPreTrainedModel; + var __webpack_exports__GPTNeoXTokenizer = __webpack_exports__.GPTNeoXTokenizer; + var __webpack_exports__Gemma2ForCausalLM = __webpack_exports__.Gemma2ForCausalLM; + var __webpack_exports__Gemma2Model = __webpack_exports__.Gemma2Model; + var __webpack_exports__Gemma2PreTrainedModel = __webpack_exports__.Gemma2PreTrainedModel; + var __webpack_exports__Gemma3ForCausalLM = __webpack_exports__.Gemma3ForCausalLM; + var __webpack_exports__Gemma3Model = __webpack_exports__.Gemma3Model; + var __webpack_exports__Gemma3PreTrainedModel = __webpack_exports__.Gemma3PreTrainedModel; + var __webpack_exports__Gemma3nAudioFeatureExtractor = __webpack_exports__.Gemma3nAudioFeatureExtractor; + var __webpack_exports__Gemma3nForConditionalGeneration = __webpack_exports__.Gemma3nForConditionalGeneration; + var __webpack_exports__Gemma3nPreTrainedModel = __webpack_exports__.Gemma3nPreTrainedModel; + var __webpack_exports__Gemma3nProcessor = __webpack_exports__.Gemma3nProcessor; + var __webpack_exports__GemmaForCausalLM = __webpack_exports__.GemmaForCausalLM; + var __webpack_exports__GemmaModel = __webpack_exports__.GemmaModel; + var __webpack_exports__GemmaPreTrainedModel = __webpack_exports__.GemmaPreTrainedModel; + var __webpack_exports__GemmaTokenizer = __webpack_exports__.GemmaTokenizer; + var __webpack_exports__GlmForCausalLM = __webpack_exports__.GlmForCausalLM; + var __webpack_exports__GlmModel = __webpack_exports__.GlmModel; + var __webpack_exports__GlmPreTrainedModel = __webpack_exports__.GlmPreTrainedModel; + var __webpack_exports__GraniteForCausalLM = __webpack_exports__.GraniteForCausalLM; + var __webpack_exports__GraniteModel = __webpack_exports__.GraniteModel; + var __webpack_exports__GraniteMoeHybridForCausalLM = __webpack_exports__.GraniteMoeHybridForCausalLM; + var __webpack_exports__GraniteMoeHybridModel = __webpack_exports__.GraniteMoeHybridModel; + var __webpack_exports__GraniteMoeHybridPreTrainedModel = __webpack_exports__.GraniteMoeHybridPreTrainedModel; + var __webpack_exports__GranitePreTrainedModel = __webpack_exports__.GranitePreTrainedModel; + var __webpack_exports__Grok1Tokenizer = __webpack_exports__.Grok1Tokenizer; + var __webpack_exports__GroundingDinoForObjectDetection = __webpack_exports__.GroundingDinoForObjectDetection; + var __webpack_exports__GroundingDinoImageProcessor = __webpack_exports__.GroundingDinoImageProcessor; + var __webpack_exports__GroundingDinoPreTrainedModel = __webpack_exports__.GroundingDinoPreTrainedModel; + var __webpack_exports__GroundingDinoProcessor = __webpack_exports__.GroundingDinoProcessor; + var __webpack_exports__GroupViTModel = __webpack_exports__.GroupViTModel; + var __webpack_exports__GroupViTPreTrainedModel = __webpack_exports__.GroupViTPreTrainedModel; + var __webpack_exports__HeliumForCausalLM = __webpack_exports__.HeliumForCausalLM; + var __webpack_exports__HeliumModel = __webpack_exports__.HeliumModel; + var __webpack_exports__HeliumPreTrainedModel = __webpack_exports__.HeliumPreTrainedModel; + var __webpack_exports__HerbertTokenizer = __webpack_exports__.HerbertTokenizer; + var __webpack_exports__HieraForImageClassification = __webpack_exports__.HieraForImageClassification; + var __webpack_exports__HieraModel = __webpack_exports__.HieraModel; + var __webpack_exports__HieraPreTrainedModel = __webpack_exports__.HieraPreTrainedModel; + var __webpack_exports__HubertForCTC = __webpack_exports__.HubertForCTC; + var __webpack_exports__HubertForSequenceClassification = __webpack_exports__.HubertForSequenceClassification; + var __webpack_exports__HubertModel = __webpack_exports__.HubertModel; + var __webpack_exports__HubertPreTrainedModel = __webpack_exports__.HubertPreTrainedModel; + var __webpack_exports__IJepaForImageClassification = __webpack_exports__.IJepaForImageClassification; + var __webpack_exports__IJepaModel = __webpack_exports__.IJepaModel; + var __webpack_exports__IJepaPreTrainedModel = __webpack_exports__.IJepaPreTrainedModel; + var __webpack_exports__Idefics3ForConditionalGeneration = __webpack_exports__.Idefics3ForConditionalGeneration; + var __webpack_exports__Idefics3ImageProcessor = __webpack_exports__.Idefics3ImageProcessor; + var __webpack_exports__Idefics3PreTrainedModel = __webpack_exports__.Idefics3PreTrainedModel; + var __webpack_exports__Idefics3Processor = __webpack_exports__.Idefics3Processor; + var __webpack_exports__ImageClassificationPipeline = __webpack_exports__.ImageClassificationPipeline; + var __webpack_exports__ImageFeatureExtractionPipeline = __webpack_exports__.ImageFeatureExtractionPipeline; + var __webpack_exports__ImageFeatureExtractor = __webpack_exports__.ImageFeatureExtractor; + var __webpack_exports__ImageMattingOutput = __webpack_exports__.ImageMattingOutput; + var __webpack_exports__ImageProcessor = __webpack_exports__.ImageProcessor; + var __webpack_exports__ImageSegmentationPipeline = __webpack_exports__.ImageSegmentationPipeline; + var __webpack_exports__ImageToImagePipeline = __webpack_exports__.ImageToImagePipeline; + var __webpack_exports__ImageToTextPipeline = __webpack_exports__.ImageToTextPipeline; + var __webpack_exports__InterruptableStoppingCriteria = __webpack_exports__.InterruptableStoppingCriteria; + var __webpack_exports__JAISLMHeadModel = __webpack_exports__.JAISLMHeadModel; + var __webpack_exports__JAISModel = __webpack_exports__.JAISModel; + var __webpack_exports__JAISPreTrainedModel = __webpack_exports__.JAISPreTrainedModel; + var __webpack_exports__JinaCLIPImageProcessor = __webpack_exports__.JinaCLIPImageProcessor; + var __webpack_exports__JinaCLIPModel = __webpack_exports__.JinaCLIPModel; + var __webpack_exports__JinaCLIPPreTrainedModel = __webpack_exports__.JinaCLIPPreTrainedModel; + var __webpack_exports__JinaCLIPProcessor = __webpack_exports__.JinaCLIPProcessor; + var __webpack_exports__JinaCLIPTextModel = __webpack_exports__.JinaCLIPTextModel; + var __webpack_exports__JinaCLIPVisionModel = __webpack_exports__.JinaCLIPVisionModel; + var __webpack_exports__Lfm2ForCausalLM = __webpack_exports__.Lfm2ForCausalLM; + var __webpack_exports__Lfm2Model = __webpack_exports__.Lfm2Model; + var __webpack_exports__Lfm2PreTrainedModel = __webpack_exports__.Lfm2PreTrainedModel; + var __webpack_exports__LiteWhisperForConditionalGeneration = __webpack_exports__.LiteWhisperForConditionalGeneration; + var __webpack_exports__Llama4ForCausalLM = __webpack_exports__.Llama4ForCausalLM; + var __webpack_exports__Llama4PreTrainedModel = __webpack_exports__.Llama4PreTrainedModel; + var __webpack_exports__LlamaForCausalLM = __webpack_exports__.LlamaForCausalLM; + var __webpack_exports__LlamaModel = __webpack_exports__.LlamaModel; + var __webpack_exports__LlamaPreTrainedModel = __webpack_exports__.LlamaPreTrainedModel; + var __webpack_exports__LlamaTokenizer = __webpack_exports__.LlamaTokenizer; + var __webpack_exports__LlavaForConditionalGeneration = __webpack_exports__.LlavaForConditionalGeneration; + var __webpack_exports__LlavaOnevisionForConditionalGeneration = __webpack_exports__.LlavaOnevisionForConditionalGeneration; + var __webpack_exports__LlavaOnevisionImageProcessor = __webpack_exports__.LlavaOnevisionImageProcessor; + var __webpack_exports__LlavaPreTrainedModel = __webpack_exports__.LlavaPreTrainedModel; + var __webpack_exports__LlavaProcessor = __webpack_exports__.LlavaProcessor; + var __webpack_exports__LlavaQwen2ForCausalLM = __webpack_exports__.LlavaQwen2ForCausalLM; + var __webpack_exports__LogitsProcessor = __webpack_exports__.LogitsProcessor; + var __webpack_exports__LogitsProcessorList = __webpack_exports__.LogitsProcessorList; + var __webpack_exports__LogitsWarper = __webpack_exports__.LogitsWarper; + var __webpack_exports__LongT5ForConditionalGeneration = __webpack_exports__.LongT5ForConditionalGeneration; + var __webpack_exports__LongT5Model = __webpack_exports__.LongT5Model; + var __webpack_exports__LongT5PreTrainedModel = __webpack_exports__.LongT5PreTrainedModel; + var __webpack_exports__M2M100ForConditionalGeneration = __webpack_exports__.M2M100ForConditionalGeneration; + var __webpack_exports__M2M100Model = __webpack_exports__.M2M100Model; + var __webpack_exports__M2M100PreTrainedModel = __webpack_exports__.M2M100PreTrainedModel; + var __webpack_exports__M2M100Tokenizer = __webpack_exports__.M2M100Tokenizer; + var __webpack_exports__MBart50Tokenizer = __webpack_exports__.MBart50Tokenizer; + var __webpack_exports__MBartForCausalLM = __webpack_exports__.MBartForCausalLM; + var __webpack_exports__MBartForConditionalGeneration = __webpack_exports__.MBartForConditionalGeneration; + var __webpack_exports__MBartForSequenceClassification = __webpack_exports__.MBartForSequenceClassification; + var __webpack_exports__MBartModel = __webpack_exports__.MBartModel; + var __webpack_exports__MBartPreTrainedModel = __webpack_exports__.MBartPreTrainedModel; + var __webpack_exports__MBartTokenizer = __webpack_exports__.MBartTokenizer; + var __webpack_exports__MPNetForMaskedLM = __webpack_exports__.MPNetForMaskedLM; + var __webpack_exports__MPNetForQuestionAnswering = __webpack_exports__.MPNetForQuestionAnswering; + var __webpack_exports__MPNetForSequenceClassification = __webpack_exports__.MPNetForSequenceClassification; + var __webpack_exports__MPNetForTokenClassification = __webpack_exports__.MPNetForTokenClassification; + var __webpack_exports__MPNetModel = __webpack_exports__.MPNetModel; + var __webpack_exports__MPNetPreTrainedModel = __webpack_exports__.MPNetPreTrainedModel; + var __webpack_exports__MPNetTokenizer = __webpack_exports__.MPNetTokenizer; + var __webpack_exports__MT5ForConditionalGeneration = __webpack_exports__.MT5ForConditionalGeneration; + var __webpack_exports__MT5Model = __webpack_exports__.MT5Model; + var __webpack_exports__MT5PreTrainedModel = __webpack_exports__.MT5PreTrainedModel; + var __webpack_exports__MarianMTModel = __webpack_exports__.MarianMTModel; + var __webpack_exports__MarianModel = __webpack_exports__.MarianModel; + var __webpack_exports__MarianPreTrainedModel = __webpack_exports__.MarianPreTrainedModel; + var __webpack_exports__MarianTokenizer = __webpack_exports__.MarianTokenizer; + var __webpack_exports__Mask2FormerImageProcessor = __webpack_exports__.Mask2FormerImageProcessor; + var __webpack_exports__MaskFormerFeatureExtractor = __webpack_exports__.MaskFormerFeatureExtractor; + var __webpack_exports__MaskFormerForInstanceSegmentation = __webpack_exports__.MaskFormerForInstanceSegmentation; + var __webpack_exports__MaskFormerImageProcessor = __webpack_exports__.MaskFormerImageProcessor; + var __webpack_exports__MaskFormerModel = __webpack_exports__.MaskFormerModel; + var __webpack_exports__MaskFormerPreTrainedModel = __webpack_exports__.MaskFormerPreTrainedModel; + var __webpack_exports__MaskedLMOutput = __webpack_exports__.MaskedLMOutput; + var __webpack_exports__MaxLengthCriteria = __webpack_exports__.MaxLengthCriteria; + var __webpack_exports__Metric3DForDepthEstimation = __webpack_exports__.Metric3DForDepthEstimation; + var __webpack_exports__Metric3DPreTrainedModel = __webpack_exports__.Metric3DPreTrainedModel; + var __webpack_exports__Metric3Dv2ForDepthEstimation = __webpack_exports__.Metric3Dv2ForDepthEstimation; + var __webpack_exports__Metric3Dv2PreTrainedModel = __webpack_exports__.Metric3Dv2PreTrainedModel; + var __webpack_exports__MgpstrForSceneTextRecognition = __webpack_exports__.MgpstrForSceneTextRecognition; + var __webpack_exports__MgpstrModelOutput = __webpack_exports__.MgpstrModelOutput; + var __webpack_exports__MgpstrPreTrainedModel = __webpack_exports__.MgpstrPreTrainedModel; + var __webpack_exports__MgpstrProcessor = __webpack_exports__.MgpstrProcessor; + var __webpack_exports__MgpstrTokenizer = __webpack_exports__.MgpstrTokenizer; + var __webpack_exports__MimiDecoderModel = __webpack_exports__.MimiDecoderModel; + var __webpack_exports__MimiDecoderOutput = __webpack_exports__.MimiDecoderOutput; + var __webpack_exports__MimiEncoderModel = __webpack_exports__.MimiEncoderModel; + var __webpack_exports__MimiEncoderOutput = __webpack_exports__.MimiEncoderOutput; + var __webpack_exports__MimiModel = __webpack_exports__.MimiModel; + var __webpack_exports__MimiPreTrainedModel = __webpack_exports__.MimiPreTrainedModel; + var __webpack_exports__MinLengthLogitsProcessor = __webpack_exports__.MinLengthLogitsProcessor; + var __webpack_exports__MinNewTokensLengthLogitsProcessor = __webpack_exports__.MinNewTokensLengthLogitsProcessor; + var __webpack_exports__Ministral3ForCausalLM = __webpack_exports__.Ministral3ForCausalLM; + var __webpack_exports__Ministral3Model = __webpack_exports__.Ministral3Model; + var __webpack_exports__Ministral3PreTrainedModel = __webpack_exports__.Ministral3PreTrainedModel; + var __webpack_exports__MinistralForCausalLM = __webpack_exports__.MinistralForCausalLM; + var __webpack_exports__MinistralModel = __webpack_exports__.MinistralModel; + var __webpack_exports__MinistralPreTrainedModel = __webpack_exports__.MinistralPreTrainedModel; + var __webpack_exports__Mistral3ForConditionalGeneration = __webpack_exports__.Mistral3ForConditionalGeneration; + var __webpack_exports__MistralForCausalLM = __webpack_exports__.MistralForCausalLM; + var __webpack_exports__MistralModel = __webpack_exports__.MistralModel; + var __webpack_exports__MistralPreTrainedModel = __webpack_exports__.MistralPreTrainedModel; + var __webpack_exports__MobileBertForMaskedLM = __webpack_exports__.MobileBertForMaskedLM; + var __webpack_exports__MobileBertForQuestionAnswering = __webpack_exports__.MobileBertForQuestionAnswering; + var __webpack_exports__MobileBertForSequenceClassification = __webpack_exports__.MobileBertForSequenceClassification; + var __webpack_exports__MobileBertModel = __webpack_exports__.MobileBertModel; + var __webpack_exports__MobileBertPreTrainedModel = __webpack_exports__.MobileBertPreTrainedModel; + var __webpack_exports__MobileBertTokenizer = __webpack_exports__.MobileBertTokenizer; + var __webpack_exports__MobileLLMForCausalLM = __webpack_exports__.MobileLLMForCausalLM; + var __webpack_exports__MobileLLMModel = __webpack_exports__.MobileLLMModel; + var __webpack_exports__MobileLLMPreTrainedModel = __webpack_exports__.MobileLLMPreTrainedModel; + var __webpack_exports__MobileNetV1FeatureExtractor = __webpack_exports__.MobileNetV1FeatureExtractor; + var __webpack_exports__MobileNetV1ForImageClassification = __webpack_exports__.MobileNetV1ForImageClassification; + var __webpack_exports__MobileNetV1ForSemanticSegmentation = __webpack_exports__.MobileNetV1ForSemanticSegmentation; + var __webpack_exports__MobileNetV1ImageProcessor = __webpack_exports__.MobileNetV1ImageProcessor; + var __webpack_exports__MobileNetV1Model = __webpack_exports__.MobileNetV1Model; + var __webpack_exports__MobileNetV1PreTrainedModel = __webpack_exports__.MobileNetV1PreTrainedModel; + var __webpack_exports__MobileNetV2FeatureExtractor = __webpack_exports__.MobileNetV2FeatureExtractor; + var __webpack_exports__MobileNetV2ForImageClassification = __webpack_exports__.MobileNetV2ForImageClassification; + var __webpack_exports__MobileNetV2ForSemanticSegmentation = __webpack_exports__.MobileNetV2ForSemanticSegmentation; + var __webpack_exports__MobileNetV2ImageProcessor = __webpack_exports__.MobileNetV2ImageProcessor; + var __webpack_exports__MobileNetV2Model = __webpack_exports__.MobileNetV2Model; + var __webpack_exports__MobileNetV2PreTrainedModel = __webpack_exports__.MobileNetV2PreTrainedModel; + var __webpack_exports__MobileNetV3FeatureExtractor = __webpack_exports__.MobileNetV3FeatureExtractor; + var __webpack_exports__MobileNetV3ForImageClassification = __webpack_exports__.MobileNetV3ForImageClassification; + var __webpack_exports__MobileNetV3ForSemanticSegmentation = __webpack_exports__.MobileNetV3ForSemanticSegmentation; + var __webpack_exports__MobileNetV3ImageProcessor = __webpack_exports__.MobileNetV3ImageProcessor; + var __webpack_exports__MobileNetV3Model = __webpack_exports__.MobileNetV3Model; + var __webpack_exports__MobileNetV3PreTrainedModel = __webpack_exports__.MobileNetV3PreTrainedModel; + var __webpack_exports__MobileNetV4FeatureExtractor = __webpack_exports__.MobileNetV4FeatureExtractor; + var __webpack_exports__MobileNetV4ForImageClassification = __webpack_exports__.MobileNetV4ForImageClassification; + var __webpack_exports__MobileNetV4ForSemanticSegmentation = __webpack_exports__.MobileNetV4ForSemanticSegmentation; + var __webpack_exports__MobileNetV4ImageProcessor = __webpack_exports__.MobileNetV4ImageProcessor; + var __webpack_exports__MobileNetV4Model = __webpack_exports__.MobileNetV4Model; + var __webpack_exports__MobileNetV4PreTrainedModel = __webpack_exports__.MobileNetV4PreTrainedModel; + var __webpack_exports__MobileViTFeatureExtractor = __webpack_exports__.MobileViTFeatureExtractor; + var __webpack_exports__MobileViTForImageClassification = __webpack_exports__.MobileViTForImageClassification; + var __webpack_exports__MobileViTImageProcessor = __webpack_exports__.MobileViTImageProcessor; + var __webpack_exports__MobileViTModel = __webpack_exports__.MobileViTModel; + var __webpack_exports__MobileViTPreTrainedModel = __webpack_exports__.MobileViTPreTrainedModel; + var __webpack_exports__MobileViTV2ForImageClassification = __webpack_exports__.MobileViTV2ForImageClassification; + var __webpack_exports__MobileViTV2Model = __webpack_exports__.MobileViTV2Model; + var __webpack_exports__MobileViTV2PreTrainedModel = __webpack_exports__.MobileViTV2PreTrainedModel; + var __webpack_exports__ModelOutput = __webpack_exports__.ModelOutput; + var __webpack_exports__ModernBertDecoderForCausalLM = __webpack_exports__.ModernBertDecoderForCausalLM; + var __webpack_exports__ModernBertDecoderModel = __webpack_exports__.ModernBertDecoderModel; + var __webpack_exports__ModernBertDecoderPreTrainedModel = __webpack_exports__.ModernBertDecoderPreTrainedModel; + var __webpack_exports__ModernBertForMaskedLM = __webpack_exports__.ModernBertForMaskedLM; + var __webpack_exports__ModernBertForSequenceClassification = __webpack_exports__.ModernBertForSequenceClassification; + var __webpack_exports__ModernBertForTokenClassification = __webpack_exports__.ModernBertForTokenClassification; + var __webpack_exports__ModernBertModel = __webpack_exports__.ModernBertModel; + var __webpack_exports__ModernBertPreTrainedModel = __webpack_exports__.ModernBertPreTrainedModel; + var __webpack_exports__Moondream1ForConditionalGeneration = __webpack_exports__.Moondream1ForConditionalGeneration; + var __webpack_exports__MoonshineFeatureExtractor = __webpack_exports__.MoonshineFeatureExtractor; + var __webpack_exports__MoonshineForConditionalGeneration = __webpack_exports__.MoonshineForConditionalGeneration; + var __webpack_exports__MoonshineModel = __webpack_exports__.MoonshineModel; + var __webpack_exports__MoonshinePreTrainedModel = __webpack_exports__.MoonshinePreTrainedModel; + var __webpack_exports__MoonshineProcessor = __webpack_exports__.MoonshineProcessor; + var __webpack_exports__MptForCausalLM = __webpack_exports__.MptForCausalLM; + var __webpack_exports__MptModel = __webpack_exports__.MptModel; + var __webpack_exports__MptPreTrainedModel = __webpack_exports__.MptPreTrainedModel; + var __webpack_exports__MultiModalityCausalLM = __webpack_exports__.MultiModalityCausalLM; + var __webpack_exports__MultiModalityPreTrainedModel = __webpack_exports__.MultiModalityPreTrainedModel; + var __webpack_exports__MusicgenForCausalLM = __webpack_exports__.MusicgenForCausalLM; + var __webpack_exports__MusicgenForConditionalGeneration = __webpack_exports__.MusicgenForConditionalGeneration; + var __webpack_exports__MusicgenModel = __webpack_exports__.MusicgenModel; + var __webpack_exports__MusicgenPreTrainedModel = __webpack_exports__.MusicgenPreTrainedModel; + var __webpack_exports__NanoChatForCausalLM = __webpack_exports__.NanoChatForCausalLM; + var __webpack_exports__NanoChatModel = __webpack_exports__.NanoChatModel; + var __webpack_exports__NanoChatPreTrainedModel = __webpack_exports__.NanoChatPreTrainedModel; + var __webpack_exports__NeoBertForMaskedLM = __webpack_exports__.NeoBertForMaskedLM; + var __webpack_exports__NeoBertForQuestionAnswering = __webpack_exports__.NeoBertForQuestionAnswering; + var __webpack_exports__NeoBertForSequenceClassification = __webpack_exports__.NeoBertForSequenceClassification; + var __webpack_exports__NeoBertForTokenClassification = __webpack_exports__.NeoBertForTokenClassification; + var __webpack_exports__NeoBertModel = __webpack_exports__.NeoBertModel; + var __webpack_exports__NeoBertPreTrainedModel = __webpack_exports__.NeoBertPreTrainedModel; + var __webpack_exports__NllbTokenizer = __webpack_exports__.NllbTokenizer; + var __webpack_exports__NoBadWordsLogitsProcessor = __webpack_exports__.NoBadWordsLogitsProcessor; + var __webpack_exports__NoRepeatNGramLogitsProcessor = __webpack_exports__.NoRepeatNGramLogitsProcessor; + var __webpack_exports__NomicBertModel = __webpack_exports__.NomicBertModel; + var __webpack_exports__NomicBertPreTrainedModel = __webpack_exports__.NomicBertPreTrainedModel; + var __webpack_exports__NougatImageProcessor = __webpack_exports__.NougatImageProcessor; + var __webpack_exports__NougatTokenizer = __webpack_exports__.NougatTokenizer; + var __webpack_exports__OPTForCausalLM = __webpack_exports__.OPTForCausalLM; + var __webpack_exports__OPTModel = __webpack_exports__.OPTModel; + var __webpack_exports__OPTPreTrainedModel = __webpack_exports__.OPTPreTrainedModel; + var __webpack_exports__ObjectDetectionPipeline = __webpack_exports__.ObjectDetectionPipeline; + var __webpack_exports__Olmo2ForCausalLM = __webpack_exports__.Olmo2ForCausalLM; + var __webpack_exports__Olmo2Model = __webpack_exports__.Olmo2Model; + var __webpack_exports__Olmo2PreTrainedModel = __webpack_exports__.Olmo2PreTrainedModel; + var __webpack_exports__OlmoForCausalLM = __webpack_exports__.OlmoForCausalLM; + var __webpack_exports__OlmoModel = __webpack_exports__.OlmoModel; + var __webpack_exports__OlmoPreTrainedModel = __webpack_exports__.OlmoPreTrainedModel; + var __webpack_exports__OpenELMForCausalLM = __webpack_exports__.OpenELMForCausalLM; + var __webpack_exports__OpenELMModel = __webpack_exports__.OpenELMModel; + var __webpack_exports__OpenELMPreTrainedModel = __webpack_exports__.OpenELMPreTrainedModel; + var __webpack_exports__OwlViTFeatureExtractor = __webpack_exports__.OwlViTFeatureExtractor; + var __webpack_exports__OwlViTForObjectDetection = __webpack_exports__.OwlViTForObjectDetection; + var __webpack_exports__OwlViTImageProcessor = __webpack_exports__.OwlViTImageProcessor; + var __webpack_exports__OwlViTModel = __webpack_exports__.OwlViTModel; + var __webpack_exports__OwlViTPreTrainedModel = __webpack_exports__.OwlViTPreTrainedModel; + var __webpack_exports__OwlViTProcessor = __webpack_exports__.OwlViTProcessor; + var __webpack_exports__Owlv2ForObjectDetection = __webpack_exports__.Owlv2ForObjectDetection; + var __webpack_exports__Owlv2ImageProcessor = __webpack_exports__.Owlv2ImageProcessor; + var __webpack_exports__Owlv2Model = __webpack_exports__.Owlv2Model; + var __webpack_exports__Owlv2PreTrainedModel = __webpack_exports__.Owlv2PreTrainedModel; + var __webpack_exports__PaliGemmaForConditionalGeneration = __webpack_exports__.PaliGemmaForConditionalGeneration; + var __webpack_exports__PaliGemmaPreTrainedModel = __webpack_exports__.PaliGemmaPreTrainedModel; + var __webpack_exports__PaliGemmaProcessor = __webpack_exports__.PaliGemmaProcessor; + var __webpack_exports__ParakeetFeatureExtractor = __webpack_exports__.ParakeetFeatureExtractor; + var __webpack_exports__ParakeetForCTC = __webpack_exports__.ParakeetForCTC; + var __webpack_exports__ParakeetPreTrainedModel = __webpack_exports__.ParakeetPreTrainedModel; + var __webpack_exports__PatchTSMixerForPrediction = __webpack_exports__.PatchTSMixerForPrediction; + var __webpack_exports__PatchTSMixerModel = __webpack_exports__.PatchTSMixerModel; + var __webpack_exports__PatchTSMixerPreTrainedModel = __webpack_exports__.PatchTSMixerPreTrainedModel; + var __webpack_exports__PatchTSTForPrediction = __webpack_exports__.PatchTSTForPrediction; + var __webpack_exports__PatchTSTModel = __webpack_exports__.PatchTSTModel; + var __webpack_exports__PatchTSTPreTrainedModel = __webpack_exports__.PatchTSTPreTrainedModel; + var __webpack_exports__Phi3ForCausalLM = __webpack_exports__.Phi3ForCausalLM; + var __webpack_exports__Phi3Model = __webpack_exports__.Phi3Model; + var __webpack_exports__Phi3PreTrainedModel = __webpack_exports__.Phi3PreTrainedModel; + var __webpack_exports__Phi3VForCausalLM = __webpack_exports__.Phi3VForCausalLM; + var __webpack_exports__Phi3VImageProcessor = __webpack_exports__.Phi3VImageProcessor; + var __webpack_exports__Phi3VPreTrainedModel = __webpack_exports__.Phi3VPreTrainedModel; + var __webpack_exports__Phi3VProcessor = __webpack_exports__.Phi3VProcessor; + var __webpack_exports__PhiForCausalLM = __webpack_exports__.PhiForCausalLM; + var __webpack_exports__PhiModel = __webpack_exports__.PhiModel; + var __webpack_exports__PhiPreTrainedModel = __webpack_exports__.PhiPreTrainedModel; + var __webpack_exports__Pipeline = __webpack_exports__.Pipeline; + var __webpack_exports__PixtralImageProcessor = __webpack_exports__.PixtralImageProcessor; + var __webpack_exports__PixtralProcessor = __webpack_exports__.PixtralProcessor; + var __webpack_exports__PreTrainedModel = __webpack_exports__.PreTrainedModel; + var __webpack_exports__PreTrainedTokenizer = __webpack_exports__.PreTrainedTokenizer; + var __webpack_exports__PretrainedConfig = __webpack_exports__.PretrainedConfig; + var __webpack_exports__PretrainedMixin = __webpack_exports__.PretrainedMixin; + var __webpack_exports__Processor = __webpack_exports__.Processor; + var __webpack_exports__PvtForImageClassification = __webpack_exports__.PvtForImageClassification; + var __webpack_exports__PvtImageProcessor = __webpack_exports__.PvtImageProcessor; + var __webpack_exports__PvtModel = __webpack_exports__.PvtModel; + var __webpack_exports__PvtPreTrainedModel = __webpack_exports__.PvtPreTrainedModel; + var __webpack_exports__PyAnnoteFeatureExtractor = __webpack_exports__.PyAnnoteFeatureExtractor; + var __webpack_exports__PyAnnoteForAudioFrameClassification = __webpack_exports__.PyAnnoteForAudioFrameClassification; + var __webpack_exports__PyAnnoteModel = __webpack_exports__.PyAnnoteModel; + var __webpack_exports__PyAnnotePreTrainedModel = __webpack_exports__.PyAnnotePreTrainedModel; + var __webpack_exports__PyAnnoteProcessor = __webpack_exports__.PyAnnoteProcessor; + var __webpack_exports__QuestionAnsweringModelOutput = __webpack_exports__.QuestionAnsweringModelOutput; + var __webpack_exports__QuestionAnsweringPipeline = __webpack_exports__.QuestionAnsweringPipeline; + var __webpack_exports__Qwen2ForCausalLM = __webpack_exports__.Qwen2ForCausalLM; + var __webpack_exports__Qwen2Model = __webpack_exports__.Qwen2Model; + var __webpack_exports__Qwen2PreTrainedModel = __webpack_exports__.Qwen2PreTrainedModel; + var __webpack_exports__Qwen2Tokenizer = __webpack_exports__.Qwen2Tokenizer; + var __webpack_exports__Qwen2VLForConditionalGeneration = __webpack_exports__.Qwen2VLForConditionalGeneration; + var __webpack_exports__Qwen2VLImageProcessor = __webpack_exports__.Qwen2VLImageProcessor; + var __webpack_exports__Qwen2VLPreTrainedModel = __webpack_exports__.Qwen2VLPreTrainedModel; + var __webpack_exports__Qwen2VLProcessor = __webpack_exports__.Qwen2VLProcessor; + var __webpack_exports__Qwen3ForCausalLM = __webpack_exports__.Qwen3ForCausalLM; + var __webpack_exports__Qwen3Model = __webpack_exports__.Qwen3Model; + var __webpack_exports__Qwen3PreTrainedModel = __webpack_exports__.Qwen3PreTrainedModel; + var __webpack_exports__RFDetrForObjectDetection = __webpack_exports__.RFDetrForObjectDetection; + var __webpack_exports__RFDetrModel = __webpack_exports__.RFDetrModel; + var __webpack_exports__RFDetrObjectDetectionOutput = __webpack_exports__.RFDetrObjectDetectionOutput; + var __webpack_exports__RFDetrPreTrainedModel = __webpack_exports__.RFDetrPreTrainedModel; + var __webpack_exports__RTDetrForObjectDetection = __webpack_exports__.RTDetrForObjectDetection; + var __webpack_exports__RTDetrImageProcessor = __webpack_exports__.RTDetrImageProcessor; + var __webpack_exports__RTDetrModel = __webpack_exports__.RTDetrModel; + var __webpack_exports__RTDetrObjectDetectionOutput = __webpack_exports__.RTDetrObjectDetectionOutput; + var __webpack_exports__RTDetrPreTrainedModel = __webpack_exports__.RTDetrPreTrainedModel; + var __webpack_exports__RTDetrV2ForObjectDetection = __webpack_exports__.RTDetrV2ForObjectDetection; + var __webpack_exports__RTDetrV2Model = __webpack_exports__.RTDetrV2Model; + var __webpack_exports__RTDetrV2ObjectDetectionOutput = __webpack_exports__.RTDetrV2ObjectDetectionOutput; + var __webpack_exports__RTDetrV2PreTrainedModel = __webpack_exports__.RTDetrV2PreTrainedModel; + var __webpack_exports__RawAudio = __webpack_exports__.RawAudio; + var __webpack_exports__RawImage = __webpack_exports__.RawImage; + var __webpack_exports__RawVideo = __webpack_exports__.RawVideo; + var __webpack_exports__RawVideoFrame = __webpack_exports__.RawVideoFrame; + var __webpack_exports__RepetitionPenaltyLogitsProcessor = __webpack_exports__.RepetitionPenaltyLogitsProcessor; + var __webpack_exports__ResNetForImageClassification = __webpack_exports__.ResNetForImageClassification; + var __webpack_exports__ResNetModel = __webpack_exports__.ResNetModel; + var __webpack_exports__ResNetPreTrainedModel = __webpack_exports__.ResNetPreTrainedModel; + var __webpack_exports__RoFormerForMaskedLM = __webpack_exports__.RoFormerForMaskedLM; + var __webpack_exports__RoFormerForQuestionAnswering = __webpack_exports__.RoFormerForQuestionAnswering; + var __webpack_exports__RoFormerForSequenceClassification = __webpack_exports__.RoFormerForSequenceClassification; + var __webpack_exports__RoFormerForTokenClassification = __webpack_exports__.RoFormerForTokenClassification; + var __webpack_exports__RoFormerModel = __webpack_exports__.RoFormerModel; + var __webpack_exports__RoFormerPreTrainedModel = __webpack_exports__.RoFormerPreTrainedModel; + var __webpack_exports__RoFormerTokenizer = __webpack_exports__.RoFormerTokenizer; + var __webpack_exports__RobertaForMaskedLM = __webpack_exports__.RobertaForMaskedLM; + var __webpack_exports__RobertaForQuestionAnswering = __webpack_exports__.RobertaForQuestionAnswering; + var __webpack_exports__RobertaForSequenceClassification = __webpack_exports__.RobertaForSequenceClassification; + var __webpack_exports__RobertaForTokenClassification = __webpack_exports__.RobertaForTokenClassification; + var __webpack_exports__RobertaModel = __webpack_exports__.RobertaModel; + var __webpack_exports__RobertaPreTrainedModel = __webpack_exports__.RobertaPreTrainedModel; + var __webpack_exports__RobertaTokenizer = __webpack_exports__.RobertaTokenizer; + var __webpack_exports__Sam2ImageProcessor = __webpack_exports__.Sam2ImageProcessor; + var __webpack_exports__Sam2ImageSegmentationOutput = __webpack_exports__.Sam2ImageSegmentationOutput; + var __webpack_exports__Sam2Model = __webpack_exports__.Sam2Model; + var __webpack_exports__Sam2PreTrainedModel = __webpack_exports__.Sam2PreTrainedModel; + var __webpack_exports__Sam2Processor = __webpack_exports__.Sam2Processor; + var __webpack_exports__Sam2VideoProcessor = __webpack_exports__.Sam2VideoProcessor; + var __webpack_exports__Sam3ImageProcessor = __webpack_exports__.Sam3ImageProcessor; + var __webpack_exports__Sam3TrackerModel = __webpack_exports__.Sam3TrackerModel; + var __webpack_exports__SamImageProcessor = __webpack_exports__.SamImageProcessor; + var __webpack_exports__SamImageSegmentationOutput = __webpack_exports__.SamImageSegmentationOutput; + var __webpack_exports__SamModel = __webpack_exports__.SamModel; + var __webpack_exports__SamPreTrainedModel = __webpack_exports__.SamPreTrainedModel; + var __webpack_exports__SamProcessor = __webpack_exports__.SamProcessor; + var __webpack_exports__SapiensForDepthEstimation = __webpack_exports__.SapiensForDepthEstimation; + var __webpack_exports__SapiensForNormalEstimation = __webpack_exports__.SapiensForNormalEstimation; + var __webpack_exports__SapiensForSemanticSegmentation = __webpack_exports__.SapiensForSemanticSegmentation; + var __webpack_exports__SapiensPreTrainedModel = __webpack_exports__.SapiensPreTrainedModel; + var __webpack_exports__SeamlessM4TFeatureExtractor = __webpack_exports__.SeamlessM4TFeatureExtractor; + var __webpack_exports__SegformerFeatureExtractor = __webpack_exports__.SegformerFeatureExtractor; + var __webpack_exports__SegformerForImageClassification = __webpack_exports__.SegformerForImageClassification; + var __webpack_exports__SegformerForSemanticSegmentation = __webpack_exports__.SegformerForSemanticSegmentation; + var __webpack_exports__SegformerImageProcessor = __webpack_exports__.SegformerImageProcessor; + var __webpack_exports__SegformerModel = __webpack_exports__.SegformerModel; + var __webpack_exports__SegformerPreTrainedModel = __webpack_exports__.SegformerPreTrainedModel; + var __webpack_exports__Seq2SeqLMOutput = __webpack_exports__.Seq2SeqLMOutput; + var __webpack_exports__SequenceClassifierOutput = __webpack_exports__.SequenceClassifierOutput; + var __webpack_exports__SiglipImageProcessor = __webpack_exports__.SiglipImageProcessor; + var __webpack_exports__SiglipModel = __webpack_exports__.SiglipModel; + var __webpack_exports__SiglipPreTrainedModel = __webpack_exports__.SiglipPreTrainedModel; + var __webpack_exports__SiglipTextModel = __webpack_exports__.SiglipTextModel; + var __webpack_exports__SiglipTokenizer = __webpack_exports__.SiglipTokenizer; + var __webpack_exports__SiglipVisionModel = __webpack_exports__.SiglipVisionModel; + var __webpack_exports__SmolLM3ForCausalLM = __webpack_exports__.SmolLM3ForCausalLM; + var __webpack_exports__SmolLM3Model = __webpack_exports__.SmolLM3Model; + var __webpack_exports__SmolLM3PreTrainedModel = __webpack_exports__.SmolLM3PreTrainedModel; + var __webpack_exports__SmolVLMForConditionalGeneration = __webpack_exports__.SmolVLMForConditionalGeneration; + var __webpack_exports__SmolVLMImageProcessor = __webpack_exports__.SmolVLMImageProcessor; + var __webpack_exports__SmolVLMProcessor = __webpack_exports__.SmolVLMProcessor; + var __webpack_exports__SnacDecoderModel = __webpack_exports__.SnacDecoderModel; + var __webpack_exports__SnacEncoderModel = __webpack_exports__.SnacEncoderModel; + var __webpack_exports__SnacFeatureExtractor = __webpack_exports__.SnacFeatureExtractor; + var __webpack_exports__SnacModel = __webpack_exports__.SnacModel; + var __webpack_exports__SnacPreTrainedModel = __webpack_exports__.SnacPreTrainedModel; + var __webpack_exports__SpeechT5FeatureExtractor = __webpack_exports__.SpeechT5FeatureExtractor; + var __webpack_exports__SpeechT5ForSpeechToText = __webpack_exports__.SpeechT5ForSpeechToText; + var __webpack_exports__SpeechT5ForTextToSpeech = __webpack_exports__.SpeechT5ForTextToSpeech; + var __webpack_exports__SpeechT5HifiGan = __webpack_exports__.SpeechT5HifiGan; + var __webpack_exports__SpeechT5Model = __webpack_exports__.SpeechT5Model; + var __webpack_exports__SpeechT5PreTrainedModel = __webpack_exports__.SpeechT5PreTrainedModel; + var __webpack_exports__SpeechT5Processor = __webpack_exports__.SpeechT5Processor; + var __webpack_exports__SpeechT5Tokenizer = __webpack_exports__.SpeechT5Tokenizer; + var __webpack_exports__SqueezeBertForMaskedLM = __webpack_exports__.SqueezeBertForMaskedLM; + var __webpack_exports__SqueezeBertForQuestionAnswering = __webpack_exports__.SqueezeBertForQuestionAnswering; + var __webpack_exports__SqueezeBertForSequenceClassification = __webpack_exports__.SqueezeBertForSequenceClassification; + var __webpack_exports__SqueezeBertModel = __webpack_exports__.SqueezeBertModel; + var __webpack_exports__SqueezeBertPreTrainedModel = __webpack_exports__.SqueezeBertPreTrainedModel; + var __webpack_exports__SqueezeBertTokenizer = __webpack_exports__.SqueezeBertTokenizer; + var __webpack_exports__StableLmForCausalLM = __webpack_exports__.StableLmForCausalLM; + var __webpack_exports__StableLmModel = __webpack_exports__.StableLmModel; + var __webpack_exports__StableLmPreTrainedModel = __webpack_exports__.StableLmPreTrainedModel; + var __webpack_exports__Starcoder2ForCausalLM = __webpack_exports__.Starcoder2ForCausalLM; + var __webpack_exports__Starcoder2Model = __webpack_exports__.Starcoder2Model; + var __webpack_exports__Starcoder2PreTrainedModel = __webpack_exports__.Starcoder2PreTrainedModel; + var __webpack_exports__StoppingCriteria = __webpack_exports__.StoppingCriteria; + var __webpack_exports__StoppingCriteriaList = __webpack_exports__.StoppingCriteriaList; + var __webpack_exports__StyleTextToSpeech2Model = __webpack_exports__.StyleTextToSpeech2Model; + var __webpack_exports__StyleTextToSpeech2PreTrainedModel = __webpack_exports__.StyleTextToSpeech2PreTrainedModel; + var __webpack_exports__SummarizationPipeline = __webpack_exports__.SummarizationPipeline; + var __webpack_exports__SupertonicForConditionalGeneration = __webpack_exports__.SupertonicForConditionalGeneration; + var __webpack_exports__SupertonicPreTrainedModel = __webpack_exports__.SupertonicPreTrainedModel; + var __webpack_exports__SuppressTokensAtBeginLogitsProcessor = __webpack_exports__.SuppressTokensAtBeginLogitsProcessor; + var __webpack_exports__Swin2SRForImageSuperResolution = __webpack_exports__.Swin2SRForImageSuperResolution; + var __webpack_exports__Swin2SRImageProcessor = __webpack_exports__.Swin2SRImageProcessor; + var __webpack_exports__Swin2SRModel = __webpack_exports__.Swin2SRModel; + var __webpack_exports__Swin2SRPreTrainedModel = __webpack_exports__.Swin2SRPreTrainedModel; + var __webpack_exports__SwinForImageClassification = __webpack_exports__.SwinForImageClassification; + var __webpack_exports__SwinForSemanticSegmentation = __webpack_exports__.SwinForSemanticSegmentation; + var __webpack_exports__SwinModel = __webpack_exports__.SwinModel; + var __webpack_exports__SwinPreTrainedModel = __webpack_exports__.SwinPreTrainedModel; + var __webpack_exports__T5ForConditionalGeneration = __webpack_exports__.T5ForConditionalGeneration; + var __webpack_exports__T5Model = __webpack_exports__.T5Model; + var __webpack_exports__T5PreTrainedModel = __webpack_exports__.T5PreTrainedModel; + var __webpack_exports__T5Tokenizer = __webpack_exports__.T5Tokenizer; + var __webpack_exports__TableTransformerForObjectDetection = __webpack_exports__.TableTransformerForObjectDetection; + var __webpack_exports__TableTransformerModel = __webpack_exports__.TableTransformerModel; + var __webpack_exports__TableTransformerObjectDetectionOutput = __webpack_exports__.TableTransformerObjectDetectionOutput; + var __webpack_exports__TableTransformerPreTrainedModel = __webpack_exports__.TableTransformerPreTrainedModel; + var __webpack_exports__TemperatureLogitsWarper = __webpack_exports__.TemperatureLogitsWarper; + var __webpack_exports__Tensor = __webpack_exports__.Tensor; + var __webpack_exports__Text2TextGenerationPipeline = __webpack_exports__.Text2TextGenerationPipeline; + var __webpack_exports__TextClassificationPipeline = __webpack_exports__.TextClassificationPipeline; + var __webpack_exports__TextGenerationPipeline = __webpack_exports__.TextGenerationPipeline; + var __webpack_exports__TextStreamer = __webpack_exports__.TextStreamer; + var __webpack_exports__TextToAudioPipeline = __webpack_exports__.TextToAudioPipeline; + var __webpack_exports__TokenClassificationPipeline = __webpack_exports__.TokenClassificationPipeline; + var __webpack_exports__TokenClassifierOutput = __webpack_exports__.TokenClassifierOutput; + var __webpack_exports__TokenizerModel = __webpack_exports__.TokenizerModel; + var __webpack_exports__TopKLogitsWarper = __webpack_exports__.TopKLogitsWarper; + var __webpack_exports__TopPLogitsWarper = __webpack_exports__.TopPLogitsWarper; + var __webpack_exports__TrOCRForCausalLM = __webpack_exports__.TrOCRForCausalLM; + var __webpack_exports__TrOCRPreTrainedModel = __webpack_exports__.TrOCRPreTrainedModel; + var __webpack_exports__TranslationPipeline = __webpack_exports__.TranslationPipeline; + var __webpack_exports__UltravoxModel = __webpack_exports__.UltravoxModel; + var __webpack_exports__UltravoxPreTrainedModel = __webpack_exports__.UltravoxPreTrainedModel; + var __webpack_exports__UltravoxProcessor = __webpack_exports__.UltravoxProcessor; + var __webpack_exports__UniSpeechForCTC = __webpack_exports__.UniSpeechForCTC; + var __webpack_exports__UniSpeechForSequenceClassification = __webpack_exports__.UniSpeechForSequenceClassification; + var __webpack_exports__UniSpeechModel = __webpack_exports__.UniSpeechModel; + var __webpack_exports__UniSpeechPreTrainedModel = __webpack_exports__.UniSpeechPreTrainedModel; + var __webpack_exports__UniSpeechSatForAudioFrameClassification = __webpack_exports__.UniSpeechSatForAudioFrameClassification; + var __webpack_exports__UniSpeechSatForCTC = __webpack_exports__.UniSpeechSatForCTC; + var __webpack_exports__UniSpeechSatForSequenceClassification = __webpack_exports__.UniSpeechSatForSequenceClassification; + var __webpack_exports__UniSpeechSatModel = __webpack_exports__.UniSpeechSatModel; + var __webpack_exports__UniSpeechSatPreTrainedModel = __webpack_exports__.UniSpeechSatPreTrainedModel; + var __webpack_exports__VLChatProcessor = __webpack_exports__.VLChatProcessor; + var __webpack_exports__VLMImageProcessor = __webpack_exports__.VLMImageProcessor; + var __webpack_exports__VaultGemmaForCausalLM = __webpack_exports__.VaultGemmaForCausalLM; + var __webpack_exports__VaultGemmaModel = __webpack_exports__.VaultGemmaModel; + var __webpack_exports__VaultGemmaPreTrainedModel = __webpack_exports__.VaultGemmaPreTrainedModel; + var __webpack_exports__ViTFeatureExtractor = __webpack_exports__.ViTFeatureExtractor; + var __webpack_exports__ViTForImageClassification = __webpack_exports__.ViTForImageClassification; + var __webpack_exports__ViTImageProcessor = __webpack_exports__.ViTImageProcessor; + var __webpack_exports__ViTMAEModel = __webpack_exports__.ViTMAEModel; + var __webpack_exports__ViTMAEPreTrainedModel = __webpack_exports__.ViTMAEPreTrainedModel; + var __webpack_exports__ViTMSNForImageClassification = __webpack_exports__.ViTMSNForImageClassification; + var __webpack_exports__ViTMSNModel = __webpack_exports__.ViTMSNModel; + var __webpack_exports__ViTMSNPreTrainedModel = __webpack_exports__.ViTMSNPreTrainedModel; + var __webpack_exports__ViTModel = __webpack_exports__.ViTModel; + var __webpack_exports__ViTPreTrainedModel = __webpack_exports__.ViTPreTrainedModel; + var __webpack_exports__VisionEncoderDecoderModel = __webpack_exports__.VisionEncoderDecoderModel; + var __webpack_exports__VitMatteForImageMatting = __webpack_exports__.VitMatteForImageMatting; + var __webpack_exports__VitMatteImageProcessor = __webpack_exports__.VitMatteImageProcessor; + var __webpack_exports__VitMattePreTrainedModel = __webpack_exports__.VitMattePreTrainedModel; + var __webpack_exports__VitPoseForPoseEstimation = __webpack_exports__.VitPoseForPoseEstimation; + var __webpack_exports__VitPoseImageProcessor = __webpack_exports__.VitPoseImageProcessor; + var __webpack_exports__VitPosePreTrainedModel = __webpack_exports__.VitPosePreTrainedModel; + var __webpack_exports__VitsModel = __webpack_exports__.VitsModel; + var __webpack_exports__VitsModelOutput = __webpack_exports__.VitsModelOutput; + var __webpack_exports__VitsPreTrainedModel = __webpack_exports__.VitsPreTrainedModel; + var __webpack_exports__VitsTokenizer = __webpack_exports__.VitsTokenizer; + var __webpack_exports__VoxtralForConditionalGeneration = __webpack_exports__.VoxtralForConditionalGeneration; + var __webpack_exports__VoxtralProcessor = __webpack_exports__.VoxtralProcessor; + var __webpack_exports__Wav2Vec2BertForCTC = __webpack_exports__.Wav2Vec2BertForCTC; + var __webpack_exports__Wav2Vec2BertForSequenceClassification = __webpack_exports__.Wav2Vec2BertForSequenceClassification; + var __webpack_exports__Wav2Vec2BertModel = __webpack_exports__.Wav2Vec2BertModel; + var __webpack_exports__Wav2Vec2BertPreTrainedModel = __webpack_exports__.Wav2Vec2BertPreTrainedModel; + var __webpack_exports__Wav2Vec2CTCTokenizer = __webpack_exports__.Wav2Vec2CTCTokenizer; + var __webpack_exports__Wav2Vec2FeatureExtractor = __webpack_exports__.Wav2Vec2FeatureExtractor; + var __webpack_exports__Wav2Vec2ForAudioFrameClassification = __webpack_exports__.Wav2Vec2ForAudioFrameClassification; + var __webpack_exports__Wav2Vec2ForCTC = __webpack_exports__.Wav2Vec2ForCTC; + var __webpack_exports__Wav2Vec2ForSequenceClassification = __webpack_exports__.Wav2Vec2ForSequenceClassification; + var __webpack_exports__Wav2Vec2Model = __webpack_exports__.Wav2Vec2Model; + var __webpack_exports__Wav2Vec2PreTrainedModel = __webpack_exports__.Wav2Vec2PreTrainedModel; + var __webpack_exports__Wav2Vec2Processor = __webpack_exports__.Wav2Vec2Processor; + var __webpack_exports__Wav2Vec2ProcessorWithLM = __webpack_exports__.Wav2Vec2ProcessorWithLM; + var __webpack_exports__WavLMForAudioFrameClassification = __webpack_exports__.WavLMForAudioFrameClassification; + var __webpack_exports__WavLMForCTC = __webpack_exports__.WavLMForCTC; + var __webpack_exports__WavLMForSequenceClassification = __webpack_exports__.WavLMForSequenceClassification; + var __webpack_exports__WavLMForXVector = __webpack_exports__.WavLMForXVector; + var __webpack_exports__WavLMModel = __webpack_exports__.WavLMModel; + var __webpack_exports__WavLMPreTrainedModel = __webpack_exports__.WavLMPreTrainedModel; + var __webpack_exports__WeSpeakerFeatureExtractor = __webpack_exports__.WeSpeakerFeatureExtractor; + var __webpack_exports__WeSpeakerResNetModel = __webpack_exports__.WeSpeakerResNetModel; + var __webpack_exports__WeSpeakerResNetPreTrainedModel = __webpack_exports__.WeSpeakerResNetPreTrainedModel; + var __webpack_exports__WhisperFeatureExtractor = __webpack_exports__.WhisperFeatureExtractor; + var __webpack_exports__WhisperForConditionalGeneration = __webpack_exports__.WhisperForConditionalGeneration; + var __webpack_exports__WhisperModel = __webpack_exports__.WhisperModel; + var __webpack_exports__WhisperPreTrainedModel = __webpack_exports__.WhisperPreTrainedModel; + var __webpack_exports__WhisperProcessor = __webpack_exports__.WhisperProcessor; + var __webpack_exports__WhisperTextStreamer = __webpack_exports__.WhisperTextStreamer; + var __webpack_exports__WhisperTimeStampLogitsProcessor = __webpack_exports__.WhisperTimeStampLogitsProcessor; + var __webpack_exports__WhisperTokenizer = __webpack_exports__.WhisperTokenizer; + var __webpack_exports__XLMForQuestionAnswering = __webpack_exports__.XLMForQuestionAnswering; + var __webpack_exports__XLMForSequenceClassification = __webpack_exports__.XLMForSequenceClassification; + var __webpack_exports__XLMForTokenClassification = __webpack_exports__.XLMForTokenClassification; + var __webpack_exports__XLMModel = __webpack_exports__.XLMModel; + var __webpack_exports__XLMPreTrainedModel = __webpack_exports__.XLMPreTrainedModel; + var __webpack_exports__XLMRobertaForMaskedLM = __webpack_exports__.XLMRobertaForMaskedLM; + var __webpack_exports__XLMRobertaForQuestionAnswering = __webpack_exports__.XLMRobertaForQuestionAnswering; + var __webpack_exports__XLMRobertaForSequenceClassification = __webpack_exports__.XLMRobertaForSequenceClassification; + var __webpack_exports__XLMRobertaForTokenClassification = __webpack_exports__.XLMRobertaForTokenClassification; + var __webpack_exports__XLMRobertaModel = __webpack_exports__.XLMRobertaModel; + var __webpack_exports__XLMRobertaPreTrainedModel = __webpack_exports__.XLMRobertaPreTrainedModel; + var __webpack_exports__XLMRobertaTokenizer = __webpack_exports__.XLMRobertaTokenizer; + var __webpack_exports__XLMTokenizer = __webpack_exports__.XLMTokenizer; + var __webpack_exports__XLMWithLMHeadModel = __webpack_exports__.XLMWithLMHeadModel; + var __webpack_exports__XVectorOutput = __webpack_exports__.XVectorOutput; + var __webpack_exports__YolosFeatureExtractor = __webpack_exports__.YolosFeatureExtractor; + var __webpack_exports__YolosForObjectDetection = __webpack_exports__.YolosForObjectDetection; + var __webpack_exports__YolosImageProcessor = __webpack_exports__.YolosImageProcessor; + var __webpack_exports__YolosModel = __webpack_exports__.YolosModel; + var __webpack_exports__YolosObjectDetectionOutput = __webpack_exports__.YolosObjectDetectionOutput; + var __webpack_exports__YolosPreTrainedModel = __webpack_exports__.YolosPreTrainedModel; + var __webpack_exports__ZeroShotAudioClassificationPipeline = __webpack_exports__.ZeroShotAudioClassificationPipeline; + var __webpack_exports__ZeroShotClassificationPipeline = __webpack_exports__.ZeroShotClassificationPipeline; + var __webpack_exports__ZeroShotImageClassificationPipeline = __webpack_exports__.ZeroShotImageClassificationPipeline; + var __webpack_exports__ZeroShotObjectDetectionPipeline = __webpack_exports__.ZeroShotObjectDetectionPipeline; + var __webpack_exports__bankers_round = __webpack_exports__.bankers_round; + var __webpack_exports__cat = __webpack_exports__.cat; + var __webpack_exports__cos_sim = __webpack_exports__.cos_sim; + var __webpack_exports__dot = __webpack_exports__.dot; + var __webpack_exports__dynamic_time_warping = __webpack_exports__.dynamic_time_warping; + var __webpack_exports__env = __webpack_exports__.env; + var __webpack_exports__full = __webpack_exports__.full; + var __webpack_exports__full_like = __webpack_exports__.full_like; + var __webpack_exports__getCacheShapes = __webpack_exports__.getCacheShapes; + var __webpack_exports__hamming = __webpack_exports__.hamming; + var __webpack_exports__hanning = __webpack_exports__.hanning; + var __webpack_exports__interpolate = __webpack_exports__.interpolate; + var __webpack_exports__interpolate_4d = __webpack_exports__.interpolate_4d; + var __webpack_exports__interpolate_data = __webpack_exports__.interpolate_data; + var __webpack_exports__is_chinese_char = __webpack_exports__.is_chinese_char; + var __webpack_exports__layer_norm = __webpack_exports__.layer_norm; + var __webpack_exports__load_image = __webpack_exports__.load_image; + var __webpack_exports__load_video = __webpack_exports__.load_video; + var __webpack_exports__log_softmax = __webpack_exports__.log_softmax; + var __webpack_exports__magnitude = __webpack_exports__.magnitude; + var __webpack_exports__matmul = __webpack_exports__.matmul; + var __webpack_exports__max = __webpack_exports__.max; + var __webpack_exports__mean = __webpack_exports__.mean; + var __webpack_exports__mean_pooling = __webpack_exports__.mean_pooling; + var __webpack_exports__medianFilter = __webpack_exports__.medianFilter; + var __webpack_exports__mel_filter_bank = __webpack_exports__.mel_filter_bank; + var __webpack_exports__min = __webpack_exports__.min; + var __webpack_exports__ones = __webpack_exports__.ones; + var __webpack_exports__ones_like = __webpack_exports__.ones_like; + var __webpack_exports__permute = __webpack_exports__.permute; + var __webpack_exports__permute_data = __webpack_exports__.permute_data; + var __webpack_exports__pipeline = __webpack_exports__.pipeline; + var __webpack_exports__quantize_embeddings = __webpack_exports__.quantize_embeddings; + var __webpack_exports__rand = __webpack_exports__.rand; + var __webpack_exports__randn = __webpack_exports__.randn; + var __webpack_exports__read_audio = __webpack_exports__.read_audio; + var __webpack_exports__rfft = __webpack_exports__.rfft; + var __webpack_exports__round = __webpack_exports__.round; + var __webpack_exports__slice = __webpack_exports__.slice; + var __webpack_exports__softmax = __webpack_exports__.softmax; + var __webpack_exports__spectrogram = __webpack_exports__.spectrogram; + var __webpack_exports__stack = __webpack_exports__.stack; + var __webpack_exports__std_mean = __webpack_exports__.std_mean; + var __webpack_exports__topk = __webpack_exports__.topk; + var __webpack_exports__window_function = __webpack_exports__.window_function; + var __webpack_exports__zeros = __webpack_exports__.zeros; + var __webpack_exports__zeros_like = __webpack_exports__.zeros_like; + + // src/embedding-worker-entry.ts + var EMBEDDING_CHROME_BASE = "chrome://browser/content/assistant/embedding-assets"; + __webpack_exports__env.allowRemoteModels = false; + __webpack_exports__env.allowLocalModels = true; + __webpack_exports__env.useBrowserCache = false; + __webpack_exports__env.localModelPath = `${EMBEDDING_CHROME_BASE}/models`; + var onnxWasm = __webpack_exports__env.backends.onnx.wasm; + onnxWasm.numThreads = 1; + onnxWasm.proxy = false; + onnxWasm.wasmPaths = `${EMBEDDING_CHROME_BASE}/ort/`; + var MODEL_NAME = "Xenova/all-MiniLM-L6-v2"; + var rootDoc = (() => { + const d = globalThis.document; + if (!d) { + throw new Error("[EmbeddingWorker] document is not available"); + } + return d; + })(); + var extractor = null; + var loadingPromise = null; + async function ensureModel() { + if (extractor) return extractor; + if (loadingPromise) return loadingPromise; + console.log("[EmbeddingWorker] Loading model..."); + console.time("[EmbeddingWorker] Model load"); + loadingPromise = __webpack_exports__pipeline("feature-extraction", MODEL_NAME, { + dtype: "q8" + }); + try { + extractor = await loadingPromise; + console.timeEnd("[EmbeddingWorker] Model load"); + console.log("[EmbeddingWorker] Model loaded successfully"); + rootDoc.dispatchEvent(new CustomEvent("embed-model-loaded")); + return extractor; + } catch (err) { + loadingPromise = null; + console.error("[EmbeddingWorker] Model load failed:", err); + throw err; + } + } + async function embed(text) { + const model = await ensureModel(); + const truncated = text.length > 512 ? text.substring(0, 512) : text; + const output = await model(truncated, { pooling: "mean", normalize: true }); + return Array.from(output.data); + } + rootDoc.addEventListener("embed-request", async (event) => { + const detail = event.detail; + const { id: id2, text } = detail; + console.log("[EmbeddingWorker] Received embed request, id:", id2); + try { + const embedding = await embed(text); + rootDoc.dispatchEvent(new CustomEvent("embed-result", { + detail: { id: id2, embedding } + })); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + rootDoc.dispatchEvent(new CustomEvent("embed-error", { + detail: { id: id2, error: message } + })); + } + }); + function signalReady() { + console.log("[EmbeddingWorker] Dispatching embed-ready event"); + rootDoc.dispatchEvent(new CustomEvent("embed-ready")); + } + signalReady(); + setTimeout(signalReady, 100); + setTimeout(signalReady, 500); + setTimeout(signalReady, 2e3); + console.log("[EmbeddingWorker] Ready, waiting for requests..."); +})(); +/*! Bundled license information: + +onnxruntime-web/dist/ort.bundle.min.mjs: + (*! + * ONNX Runtime Web v1.22.0-dev.20250409-89f8206ba4 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + *) + +onnxruntime-web/dist/ort.bundle.min.mjs: + (** + * @license + * Copyright 2021 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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. + * ============================================================================= + *) + (** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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. + * ============================================================================= + *) + (** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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. + * ============================================================================= + *) + +@huggingface/transformers/dist/transformers.web.js: + (*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************) +*/ diff --git a/browser/base/content/assistant/embedding-worker.html b/browser/base/content/assistant/embedding-worker.html new file mode 100644 index 0000000000000..6bd54b59bb490 --- /dev/null +++ b/browser/base/content/assistant/embedding-worker.html @@ -0,0 +1,18 @@ + + + + + + Embedding Worker + + + + + + + + \ No newline at end of file diff --git a/browser/base/content/assistant/images/empty-state-bg.png b/browser/base/content/assistant/images/empty-state-bg.png new file mode 100644 index 0000000000000..4527fdcf5e5ce Binary files /dev/null and b/browser/base/content/assistant/images/empty-state-bg.png differ diff --git a/browser/base/content/assistant/kahana-interceptor.html b/browser/base/content/assistant/kahana-interceptor.html new file mode 100644 index 0000000000000..d3338b79b830a --- /dev/null +++ b/browser/base/content/assistant/kahana-interceptor.html @@ -0,0 +1,149 @@ + + + + + + Oasis Browser - Authentication Handler + + + +
    +
    +
    Processing authentication...
    +
    +
    + + + + diff --git a/browser/base/content/assistant/lambda/native-assist/index.mjs b/browser/base/content/assistant/lambda/native-assist/index.mjs new file mode 100644 index 0000000000000..0f811d08d2945 --- /dev/null +++ b/browser/base/content/assistant/lambda/native-assist/index.mjs @@ -0,0 +1,671 @@ +import { + SecretsManagerClient, + GetSecretValueCommand, +} from "@aws-sdk/client-secrets-manager"; +import { GoogleGenAI, Type } from "@google/genai"; +import jwt from "jsonwebtoken"; + +const REGION = process.env.AWS_REGION || "us-east-2"; +const GEMINI_SECRET_ID = process.env.GEMINI_SECRET_ID || "prod/Oasis/gemini"; +const SUPABASE_SECRET_ID = process.env.SUPABASE_SECRET_ID; +const MODEL = process.env.MODEL || "gemini-2.5-flash"; +const TEMP = Number(process.env.TEMP ?? 0.3); +const ENV_FALLBACK = process.env.GEMINI_API_KEY || ""; + +const sm = new SecretsManagerClient({ region: REGION }); +let cachedSecrets = {}; + +async function getSecret(secretId) { + if (cachedSecrets[secretId]) { + return cachedSecrets[secretId]; + } + if (!secretId) { + throw new Error("Secret ID is not configured."); + } + + const command = new GetSecretValueCommand({ + SecretId: secretId, + VersionStage: "AWSCURRENT", + }); + const response = await sm.send(command); + let secretString = response.SecretString; + if (!secretString && response.SecretBinary) { + secretString = Buffer.from(response.SecretBinary, "base64").toString("utf8"); + } + + cachedSecrets[secretId] = secretString; + return secretString; +} + +function safeParseJSON(s) { + try { + return JSON.parse(s); + } catch { + return null; + } +} + +function findKey(obj) { + const candidates = [ + "gemini_key", + "GEMINI_API_KEY", + "api_key", + "API_KEY", + "apiKey", + "key", + "token", + ]; + for (const k of candidates) { + const v = obj?.[k]; + if (typeof v === "string" && v.trim()) { + return v.trim(); + } + } + + const stack = [obj]; + while (stack.length) { + const cur = stack.pop(); + if (cur && typeof cur === "object") { + for (const v of Object.values(cur)) { + if (typeof v === "string" && v.trim().length >= 20) { + return v.trim(); + } + if (v && typeof v === "object") { + stack.push(v); + } + } + } + } + return ""; +} + +function extractKeyFromAny(raw) { + if (!raw) return ""; + if (typeof raw === "string") { + const s = raw.trim(); + if (!s) return ""; + if (s.startsWith("{")) { + const obj = safeParseJSON(s); + if (obj) return findKey(obj); + } + return s; + } + if (typeof raw === "object") { + return findKey(raw); + } + return ""; +} + +async function getGeminiClient() { + if (ENV_FALLBACK) { + return new GoogleGenAI({ apiKey: ENV_FALLBACK }); + } + + const rawSecret = await getSecret(GEMINI_SECRET_ID); + const key = extractKeyFromAny(rawSecret); + if (!key) { + throw new Error("Gemini key missing in secret"); + } + return new GoogleGenAI({ apiKey: key }); +} + +async function getSupabaseJwtSecret() { + const rawSecret = await getSecret(SUPABASE_SECRET_ID); + const secretObj = safeParseJSON(rawSecret); + if (secretObj && secretObj.SUPABASE_JWT_SECRET) { + return secretObj.SUPABASE_JWT_SECRET; + } + throw new Error("SUPABASE_JWT_SECRET not found in secret value."); +} + +function normalizeRole(role) { + return /^(human|user)$/i.test(String(role || "")) ? "user" : "model"; +} + +function toContents(messages = []) { + return messages.map((m) => ({ + role: normalizeRole(m?.role), + parts: [{ text: typeof m?.content === "string" ? m.content : String(m?.content ?? "") }], + })); +} + +function extractResponseText(response) { + if (!response) return ""; + if (typeof response.text === "string") { + return response.text; + } + if (typeof response.text === "function") { + return response.text(); + } + + const parts = response?.candidates?.[0]?.content?.parts || []; + const textPart = parts.find((p) => typeof p?.text === "string"); + return textPart?.text || ""; +} + +function extractFirstFunctionCall(response) { + if (!response) return null; + + if (Array.isArray(response.functionCalls) && response.functionCalls.length > 0) { + return response.functionCalls[0]; + } + + const parts = response?.candidates?.[0]?.content?.parts || []; + for (const part of parts) { + if (part?.functionCall) { + return part.functionCall; + } + } + return null; +} + +/** Max inner model↔tool rounds (invalid-route retries + optional refine). */ +function clampAssistInnerRounds(raw) { + const n = Number(raw); + if (!Number.isFinite(n)) { + return 1; + } + return Math.min(8, Math.max(1, Math.floor(n))); +} + +/** @typedef {{ input_tokens: number; output_tokens: number; total_tokens: number }} UsageTriple */ + +/** @param {unknown} response */ +function extractTokenTripleFromGenAiResponse(response) { + const u = response?.usageMetadata ?? response?.usage_metadata; + if (!u || typeof u !== "object") { + return { input_tokens: 0, output_tokens: 0, total_tokens: 0 }; + } + const input = Number(u.promptTokenCount ?? u.prompt_token_count ?? 0); + const output = Number(u.candidatesTokenCount ?? u.candidates_token_count ?? 0); + const totalRaw = Number(u.totalTokenCount ?? u.total_token_count ?? NaN); + const total = Number.isFinite(totalRaw) ? totalRaw : input + output; + return { + input_tokens: Number.isFinite(input) ? input : 0, + output_tokens: Number.isFinite(output) ? output : 0, + total_tokens: Number.isFinite(total) ? total : 0, + }; +} + +/** @param {UsageTriple} a @param {UsageTriple} b */ +function addUsageTriple(a, b) { + return { + input_tokens: a.input_tokens + b.input_tokens, + output_tokens: a.output_tokens + b.output_tokens, + total_tokens: a.total_tokens + b.total_tokens, + }; +} + +/** Gemini REST / client-style snake_case for subscription + UI. */ +function usageMetadataSnakeFromTriple(agg) { + return { + prompt_token_count: agg.input_tokens, + candidates_token_count: agg.output_tokens, + total_token_count: agg.total_tokens, + }; +} + +/** @param {Record} body @param {UsageTriple} agg */ +function withAssistUsageMetadata(body, agg) { + if ( + agg.input_tokens === 0 && + agg.output_tokens === 0 && + agg.total_tokens === 0 + ) { + return body; + } + return { ...body, usage_metadata: usageMetadataSnakeFromTriple(agg) }; +} + +function appendModelFunctionCallTurn(contents, functionCall) { + const fc = { + name: functionCall.name, + args: functionCall.args || {}, + }; + if (functionCall.id != null && functionCall.id !== "") { + fc.id = functionCall.id; + } + contents.push({ + role: "model", + parts: [{ functionCall: fc }], + }); +} + +function appendFunctionResponseTurn(contents, functionCall, resultPayload) { + const part = { + name: functionCall.name, + response: { result: resultPayload }, + }; + if (functionCall.id != null && functionCall.id !== "") { + part.id = functionCall.id; + } + contents.push({ + role: "user", + parts: [{ functionResponse: part }], + }); +} + +/** + * Claude-style routing loop: repeated generateContent until a final route, + * chat text, or max rounds. Tool "results" are synthetic (browser does not + * execute inside Lambda); invalid route_command gets an error functionResponse. + */ +async function runAssistRoutingLoop({ + ai, + messages, + routeOptions, + canChat, + enableFunctionCalling, + maxInnerRounds, + refineAfterRoute, + config, +}) { + const contents = toContents(messages); + let lastValidRoute = null; + let roundCount = 0; + /** @type {UsageTriple} */ + let usageAgg = { input_tokens: 0, output_tokens: 0, total_tokens: 0 }; + + for (let i = 0; i < maxInnerRounds; i++) { + const response = await ai.models.generateContent({ + model: MODEL, + config, + contents, + }); + usageAgg = addUsageTriple(usageAgg, extractTokenTripleFromGenAiResponse(response)); + roundCount += 1; + + if (enableFunctionCalling) { + const fc = extractFirstFunctionCall(response); + if (fc?.name === "route_command") { + const callArgs = safeJsonObject(fc.args); + const next = String(callArgs.next || "").trim(); + const args = safeJsonObject(callArgs.args); + + if (routeOptions.includes(next)) { + lastValidRoute = { next, args }; + const canRefineMore = refineAfterRoute && i + 1 < maxInnerRounds; + if (!canRefineMore) { + return cors( + 200, + withAssistUsageMetadata( + { + next, + args, + reason: "native-tool-call", + inner_rounds: roundCount, + }, + usageAgg + ) + ); + } + appendModelFunctionCallTurn(contents, fc); + appendFunctionResponseTurn(contents, fc, { + ok: true, + routedCommand: next, + message: + "Route accepted by host. Call route_command again only if correcting the choice; otherwise respond with the single word DONE.", + }); + continue; + } + + if (i + 1 < maxInnerRounds) { + appendModelFunctionCallTurn(contents, fc); + appendFunctionResponseTurn(contents, fc, { + ok: false, + error: "invalid_command", + validCommands: routeOptions, + }); + continue; + } + } + } + + const text = String(extractResponseText(response) || "").trim(); + + if (lastValidRoute) { + return cors( + 200, + withAssistUsageMetadata( + { + next: lastValidRoute.next, + args: lastValidRoute.args, + ...(text && text.toUpperCase() !== "DONE" ? { content: text } : {}), + reason: "multi-turn-route", + inner_rounds: roundCount, + }, + usageAgg + ) + ); + } + + if (canChat) { + return cors( + 200, + withAssistUsageMetadata( + { + next: "chat", + content: text, + reason: "no-tool-call", + inner_rounds: roundCount, + }, + usageAgg + ) + ); + } + + return cors( + 200, + withAssistUsageMetadata( + { + next: routeOptions[0], + args: {}, + reason: "no-tool-call-fallback", + inner_rounds: roundCount, + }, + usageAgg + ) + ); + } + + if (lastValidRoute) { + return cors( + 200, + withAssistUsageMetadata( + { + next: lastValidRoute.next, + args: lastValidRoute.args, + reason: "multi-turn-max-rounds", + inner_rounds: roundCount, + }, + usageAgg + ) + ); + } + + return cors( + 200, + withAssistUsageMetadata( + { + next: routeOptions[0], + args: {}, + reason: "no-tool-call-fallback", + inner_rounds: roundCount, + }, + usageAgg + ) + ); +} + +function safeJsonObject(value) { + if (!value || typeof value !== "object" || Array.isArray(value)) { + return {}; + } + return value; +} + +function sanitizeOptions(options) { + const out = []; + const seen = new Set(); + for (const opt of options || []) { + const next = String(opt || "").trim(); + if (!next || seen.has(next)) continue; + seen.add(next); + out.push(next); + } + return out; +} + +function normalizeToolName(name) { + const normalized = String(name || "").trim(); + if (!normalized) return ""; + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(normalized)) { + return ""; + } + return normalized; +} + +function sanitizeTools(tools, allowedOptions) { + const optionSet = new Set(allowedOptions); + const seen = new Set(); + const out = []; + + for (const tool of tools || []) { + const name = normalizeToolName(tool?.name); + if (!name || seen.has(name) || !optionSet.has(name)) { + continue; + } + seen.add(name); + const description = String(tool?.description || "").trim(); + out.push({ name, description }); + } + + return out; +} + +function cors(code, body) { + return { + statusCode: code, + headers: { + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Headers": "Content-Type, Authorization", + "Access-Control-Allow-Methods": "POST, OPTIONS", + "Content-Type": "application/json", + }, + body: typeof body === "string" ? body : JSON.stringify(body), + }; +} + +function buildAssistSystemPrompt({ system, routeOptions, tools, canChat }) { + const toolLines = (tools || []) + .map((tool) => { + const name = String(tool?.name || "").trim(); + if (!name) return ""; + const description = String(tool?.description || "").trim(); + return description ? `- ${name}: ${description}` : `- ${name}`; + }) + .filter(Boolean) + .join("\n"); + + if (routeOptions.length === 0) { + return [ + system || "", + "Respond with plain text only.", + "Do not emit JSON or function-call placeholders.", + ] + .filter(Boolean) + .join("\n"); + } + + const optionLine = `Valid command names: ${routeOptions.join(", ")}`; + const chatLine = canChat + ? "If no tool should be called, respond in plain text so the caller can route to chat." + : "Always choose one of the valid command names."; + + return [ + system || "", + "\nYou are a strict browser command router.", + optionLine, + toolLines ? `Available tools:\n${toolLines}` : "", + "If the latest user message is a browser action, call route_command with the best command and args.", + "If it is not a browser action or is unclear, do not call a function.", + chatLine, + "Do not invent command names.", + ] + .filter(Boolean) + .join("\n"); +} + +async function handleAssist(req) { + const { + system, + messages = [], + options = [], + tools = [], + max_inner_rounds: maxInnerRaw, + refine_after_route: refineRaw, + } = req || {}; + const validOptions = sanitizeOptions(options); + const canChat = validOptions.includes("chat"); + const routeOptions = validOptions.filter((opt) => opt !== "chat"); + const declaredTools = sanitizeTools(Array.isArray(tools) ? tools : [], routeOptions); + const enableFunctionCalling = routeOptions.length > 0 && declaredTools.length > 0; + + if (validOptions.length === 0) { + return cors(400, { error: "assist requires non-empty options" }); + } + + const maxInnerRounds = clampAssistInnerRounds( + maxInnerRaw ?? process.env.ASSIST_MAX_INNER_ROUNDS ?? 1 + ); + const refineAfterRoute = Boolean(refineRaw); + + const ai = await getGeminiClient(); + const systemInstruction = buildAssistSystemPrompt({ + system, + routeOptions, + tools: declaredTools, + canChat, + }); + + const config = { + systemInstruction, + temperature: TEMP, + }; + + if (enableFunctionCalling) { + config.tools = [ + { + functionDeclarations: [ + { + name: "route_command", + description: "Select one browser command and provide its JSON args.", + parameters: { + type: Type.OBJECT, + properties: { + next: { + type: Type.STRING, + enum: routeOptions, + description: "Command name selected from the valid options list.", + }, + args: { + type: Type.OBJECT, + description: "Arguments object for the selected command.", + }, + }, + required: ["next"], + }, + }, + ], + }, + ]; + config.toolConfig = { + functionCallingConfig: { + mode: "AUTO", + }, + }; + + return runAssistRoutingLoop({ + ai, + messages, + routeOptions, + canChat, + enableFunctionCalling, + maxInnerRounds, + refineAfterRoute, + config, + }); + } + + const response = await ai.models.generateContent({ + model: MODEL, + config, + contents: toContents(messages), + }); + + const usageAgg = extractTokenTripleFromGenAiResponse(response); + const content = String(extractResponseText(response) || "").trim(); + if (canChat) { + return cors( + 200, + withAssistUsageMetadata( + { + next: "chat", + content, + reason: "no-tool-call", + inner_rounds: 1, + }, + usageAgg + ) + ); + } + + return cors( + 200, + withAssistUsageMetadata( + { + next: routeOptions[0], + args: {}, + reason: "no-tool-call-fallback", + inner_rounds: 1, + }, + usageAgg + ) + ); +} + +function getMethod(event) { + return event?.requestContext?.http?.method || "POST"; +} + +function parseBody(event) { + const body = event?.body + ? event.isBase64Encoded + ? Buffer.from(event.body, "base64").toString() + : event.body + : "{}"; + return safeParseJSON(body) || {}; +} + +function authHeaderFromEvent(event) { + return event?.headers?.authorization || event?.headers?.Authorization; +} + +export const handler = async (event) => { + if (getMethod(event) === "OPTIONS") { + return cors(204, ""); + } + + try { + const authHeader = authHeaderFromEvent(event); + if (!authHeader || !authHeader.startsWith("Bearer ")) { + return cors(401, { + error: "Unauthorized: Missing or invalid Authorization header", + }); + } + + const token = authHeader.substring(7); + const supabaseSecret = await getSupabaseJwtSecret(); + jwt.verify(token, supabaseSecret); + + const req = parseBody(event); + const op = String(req?.op || "").toLowerCase(); + if (op === "assist") { + return handleAssist(req); + } + + return cors(404, { + error: "Not Found", + hint: "POST with {op:\"assist\"}", + }); + } catch (error) { + if (error?.name === "JsonWebTokenError" || error?.name === "TokenExpiredError") { + return cors(401, { error: `Unauthorized: ${error.message}` }); + } + console.error("Handler error:", error); + return cors(500, { + error: "Internal Server Error", + message: String(error?.message || error), + }); + } +}; diff --git a/browser/base/content/assistant/logos/logo.svg b/browser/base/content/assistant/logos/logo.svg new file mode 100644 index 0000000000000..a80b3ed9f7b09 --- /dev/null +++ b/browser/base/content/assistant/logos/logo.svg @@ -0,0 +1,3 @@ + + + diff --git a/browser/base/content/assistant/oauth-callback.html b/browser/base/content/assistant/oauth-callback.html new file mode 100644 index 0000000000000..ecd9ac6535d02 --- /dev/null +++ b/browser/base/content/assistant/oauth-callback.html @@ -0,0 +1,151 @@ + + + + + + Oasis Browser - Authentication + + + +
    +
    +
    Processing authentication...
    +
    +
    + + + + diff --git a/browser/base/content/assistant/oauth-handler.html b/browser/base/content/assistant/oauth-handler.html new file mode 100644 index 0000000000000..07f62ead5c2f7 --- /dev/null +++ b/browser/base/content/assistant/oauth-handler.html @@ -0,0 +1,164 @@ + + + + + + Oasis Browser - OAuth Handler + + + +
    +
    +
    Processing OAuth callback...
    +
    +
    +
    + + + + diff --git a/browser/base/content/assistant/package.json b/browser/base/content/assistant/package.json new file mode 100644 index 0000000000000..33705b13be50d --- /dev/null +++ b/browser/base/content/assistant/package.json @@ -0,0 +1,13 @@ +{ + "name": "oasis-assistant", + "private": true, + "scripts": { + "install:all": "cd ui-preact && npm install && cd ../build && npm install", + "build:ui": "cd ui-preact && npm run build", + "build:logic": "cd build && npm run build", + "build": "npm run build:ui && npm run build:logic", + "watch:ui": "cd ui-preact && npm run build -- --watch", + "watch:logic": "cd build && npm run build -- --watch", + "watch": "npm run watch:ui & npm run watch:logic & wait" + } +} diff --git a/browser/base/content/assistant/public-oauth-callback.html b/browser/base/content/assistant/public-oauth-callback.html new file mode 100644 index 0000000000000..f3d3f6945bf22 --- /dev/null +++ b/browser/base/content/assistant/public-oauth-callback.html @@ -0,0 +1,150 @@ + + + + + + Oasis OAuth Callback + + + +
    +

    OAuth successful

    +

    + Copy the code below, then return to Oasis Assistant to complete sign-in. +

    +
    +
    + + + + diff --git a/browser/base/content/assistant/shared/capabilitiesOverviewConstants.ts b/browser/base/content/assistant/shared/capabilitiesOverviewConstants.ts new file mode 100644 index 0000000000000..22cdcb0653b15 --- /dev/null +++ b/browser/base/content/assistant/shared/capabilitiesOverviewConstants.ts @@ -0,0 +1,12 @@ +export const CAPABILITIES_OVERVIEW_FIRST_LINE = "What Oasis can do in this build"; + +export const CAPABILITIES_BLOCK_DELIMITER = "\n<<>>\n"; + +export const OASIS_CAPABILITIES_FEATURES_URL = + "https://kahana.co/features/oasis-assistant"; + +export const OASIS_CAPABILITIES_LINK_LABEL = "Oasis assistant on Kahana"; + +export const OASIS_CAPABILITIES_FEEDBACK_URL = "https://tally.so/r/3jkNN6"; + +export const OASIS_CAPABILITIES_FEEDBACK_LINK_LABEL = "Send feedback"; diff --git a/browser/base/content/assistant/shared/contracts.ts b/browser/base/content/assistant/shared/contracts.ts new file mode 100644 index 0000000000000..d8282ceaded21 --- /dev/null +++ b/browser/base/content/assistant/shared/contracts.ts @@ -0,0 +1,79 @@ +export type AssistantInputType = "text" | "voice"; +export type InteractionCommandArgs = Record; + +export type ToolActionStatus = "pending" | "running" | "done" | "error"; +export type ToolBridgeUpdateStatus = "done" | "error"; + +export type AmbiguityTarget = "bookmark-folder" | "tab-group" | "tab"; + +export type PendingConfirmationPayload = { + command: string; + args: InteractionCommandArgs; + description: string; +}; + +export type PendingAmbiguityPayload = { + kind: "container_target" | "close_delete_target"; + name: string; + query?: string; + all?: boolean; + originalText: string; + choices?: AmbiguityTarget[]; + tabIndex?: number; + verb?: string; + description: string; +}; + +export type OasisRecordToolActionStart = ( + commandName: string, + messageId?: string, + label?: string +) => string | undefined; + +export type OasisRecordToolActionUpdate = ( + actionId: string, + status: ToolBridgeUpdateStatus +) => void; + +export type AssistantHistoryWireEntry = { + id?: string; + role?: string; + type?: string; + content?: string; + lc_kwargs?: { content?: string }; + constructor?: { name?: string }; +}; + +export type VoiceUiDelivery = "spoken" | "text_chat"; + +export type RunAssistantStream = ( + prompt: string, + onChunk: (chunk: string) => void, + inputType?: AssistantInputType, + messageId?: string, + voiceDelivery?: VoiceUiDelivery +) => Promise; + +export const OASIS_EVENT_AUTH_UPDATE = "oasis-auth-update" as const; +export const OASIS_EVENT_HISTORY_UPDATE = "oasis-history-update" as const; +export const OASIS_EVENT_CONFIRMATION_UPDATE = + "oasis-confirmation-update" as const; +export const OASIS_EVENT_BOOKMARK_FOLDERS_CHANGED = + "oasis-bookmark-folders-changed" as const; + +export type OasisEventName = + | typeof OASIS_EVENT_AUTH_UPDATE + | typeof OASIS_EVENT_HISTORY_UPDATE + | typeof OASIS_EVENT_CONFIRMATION_UPDATE + | typeof OASIS_EVENT_BOOKMARK_FOLDERS_CHANGED; + +export type BookmarkFoldersChangedDetail = { + folderNames?: string[]; +}; + +export type OasisEventDetailMap = { + [OASIS_EVENT_AUTH_UPDATE]: unknown; + [OASIS_EVENT_HISTORY_UPDATE]: undefined; + [OASIS_EVENT_CONFIRMATION_UPDATE]: PendingConfirmationPayload | null; + [OASIS_EVENT_BOOKMARK_FOLDERS_CHANGED]: BookmarkFoldersChangedDetail; +}; diff --git a/browser/base/content/assistant/ui-preact/README.md b/browser/base/content/assistant/ui-preact/README.md new file mode 100644 index 0000000000000..6c756931420f3 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/README.md @@ -0,0 +1,15 @@ +Preact prototype for Oasis assistant UI + +Build: + +```bash +cd browser/base/content/assistant/ui-preact +npm install +npm run build +``` + +This produces `../dist/assistant.ui.bundle.js` which should be included by the chrome so it runs in the privileged context (or load `assistant.bridge.js` before it). + +Notes: +- Keep `assistant.bridge.js` loaded in chrome scope to expose `window.assistantBridge`. +- The bundle must avoid `eval`/`new Function` to satisfy chrome/CSP. diff --git a/browser/base/content/assistant/ui-preact/node_modules/.bin/esbuild b/browser/base/content/assistant/ui-preact/node_modules/.bin/esbuild new file mode 120000 index 0000000000000..c83ac070798fc --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/.bin/esbuild @@ -0,0 +1 @@ +../esbuild/bin/esbuild \ No newline at end of file diff --git a/browser/base/content/assistant/ui-preact/node_modules/.bin/esbuild.cmd b/browser/base/content/assistant/ui-preact/node_modules/.bin/esbuild.cmd new file mode 100644 index 0000000000000..d36853926a42f --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/.bin/esbuild.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%\..\esbuild\bin\esbuild" %* diff --git a/browser/base/content/assistant/ui-preact/node_modules/.bin/esbuild.ps1 b/browser/base/content/assistant/ui-preact/node_modules/.bin/esbuild.ps1 new file mode 100644 index 0000000000000..81ffbf9c33b52 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/.bin/esbuild.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/../esbuild/bin/esbuild" $args + } else { + & "$basedir/node$exe" "$basedir/../esbuild/bin/esbuild" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../esbuild/bin/esbuild" $args + } else { + & "node$exe" "$basedir/../esbuild/bin/esbuild" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/browser/base/content/assistant/ui-preact/node_modules/.package-lock.json b/browser/base/content/assistant/ui-preact/node_modules/.package-lock.json new file mode 100644 index 0000000000000..4d1c9a0679cfe --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/.package-lock.json @@ -0,0 +1,540 @@ +{ + "name": "assistant-ui-preact", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@esbuild/aix-ppc64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.2.tgz", + "integrity": "sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.2.tgz", + "integrity": "sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==", + "cpu": [ + "arm" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.2.tgz", + "integrity": "sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==", + "cpu": [ + "arm64" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.2.tgz", + "integrity": "sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==", + "cpu": [ + "x64" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.2.tgz", + "integrity": "sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.2.tgz", + "integrity": "sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==", + "cpu": [ + "x64" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.2.tgz", + "integrity": "sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==", + "cpu": [ + "arm64" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.2.tgz", + "integrity": "sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==", + "cpu": [ + "x64" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.2.tgz", + "integrity": "sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==", + "cpu": [ + "arm" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.2.tgz", + "integrity": "sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==", + "cpu": [ + "arm64" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.2.tgz", + "integrity": "sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==", + "cpu": [ + "ia32" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.2.tgz", + "integrity": "sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==", + "cpu": [ + "loong64" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.2.tgz", + "integrity": "sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.2.tgz", + "integrity": "sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.2.tgz", + "integrity": "sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.2.tgz", + "integrity": "sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==", + "cpu": [ + "s390x" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.2.tgz", + "integrity": "sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==", + "cpu": [ + "x64" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.2.tgz", + "integrity": "sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==", + "cpu": [ + "arm64" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.2.tgz", + "integrity": "sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==", + "cpu": [ + "x64" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.2.tgz", + "integrity": "sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==", + "cpu": [ + "arm64" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.2.tgz", + "integrity": "sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==", + "cpu": [ + "x64" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.2.tgz", + "integrity": "sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==", + "cpu": [ + "arm64" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.2.tgz", + "integrity": "sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==", + "cpu": [ + "x64" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.2.tgz", + "integrity": "sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.2.tgz", + "integrity": "sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "ideallyInert": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.2.tgz", + "integrity": "sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/esbuild": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.2.tgz", + "integrity": "sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.2", + "@esbuild/android-arm": "0.27.2", + "@esbuild/android-arm64": "0.27.2", + "@esbuild/android-x64": "0.27.2", + "@esbuild/darwin-arm64": "0.27.2", + "@esbuild/darwin-x64": "0.27.2", + "@esbuild/freebsd-arm64": "0.27.2", + "@esbuild/freebsd-x64": "0.27.2", + "@esbuild/linux-arm": "0.27.2", + "@esbuild/linux-arm64": "0.27.2", + "@esbuild/linux-ia32": "0.27.2", + "@esbuild/linux-loong64": "0.27.2", + "@esbuild/linux-mips64el": "0.27.2", + "@esbuild/linux-ppc64": "0.27.2", + "@esbuild/linux-riscv64": "0.27.2", + "@esbuild/linux-s390x": "0.27.2", + "@esbuild/linux-x64": "0.27.2", + "@esbuild/netbsd-arm64": "0.27.2", + "@esbuild/netbsd-x64": "0.27.2", + "@esbuild/openbsd-arm64": "0.27.2", + "@esbuild/openbsd-x64": "0.27.2", + "@esbuild/openharmony-arm64": "0.27.2", + "@esbuild/sunos-x64": "0.27.2", + "@esbuild/win32-arm64": "0.27.2", + "@esbuild/win32-ia32": "0.27.2", + "@esbuild/win32-x64": "0.27.2" + } + }, + "node_modules/preact": { + "version": "10.28.2", + "resolved": "https://registry.npmjs.org/preact/-/preact-10.28.2.tgz", + "integrity": "sha512-lbteaWGzGHdlIuiJ0l2Jq454m6kcpI1zNje6d8MlGAFlYvP2GO4ibnat7P74Esfz4sPTdM6UxtTwh/d3pwM9JA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + } + } +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/@esbuild/win32-x64/README.md b/browser/base/content/assistant/ui-preact/node_modules/@esbuild/win32-x64/README.md new file mode 100644 index 0000000000000..a99ee7cf84e91 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/@esbuild/win32-x64/README.md @@ -0,0 +1,3 @@ +# esbuild + +This is the Windows 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details. diff --git a/browser/base/content/assistant/ui-preact/node_modules/@esbuild/win32-x64/esbuild.exe b/browser/base/content/assistant/ui-preact/node_modules/@esbuild/win32-x64/esbuild.exe new file mode 100644 index 0000000000000..c3a9089f12e65 Binary files /dev/null and b/browser/base/content/assistant/ui-preact/node_modules/@esbuild/win32-x64/esbuild.exe differ diff --git a/browser/base/content/assistant/ui-preact/node_modules/@esbuild/win32-x64/package.json b/browser/base/content/assistant/ui-preact/node_modules/@esbuild/win32-x64/package.json new file mode 100644 index 0000000000000..fe55f7adb0d22 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/@esbuild/win32-x64/package.json @@ -0,0 +1,20 @@ +{ + "name": "@esbuild/win32-x64", + "version": "0.27.2", + "description": "The Windows 64-bit binary for esbuild, a JavaScript bundler.", + "repository": { + "type": "git", + "url": "git+https://github.com/evanw/esbuild.git" + }, + "license": "MIT", + "preferUnplugged": true, + "engines": { + "node": ">=18" + }, + "os": [ + "win32" + ], + "cpu": [ + "x64" + ] +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/esbuild/LICENSE.md b/browser/base/content/assistant/ui-preact/node_modules/esbuild/LICENSE.md new file mode 100644 index 0000000000000..2027e8dcf3787 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/esbuild/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Evan Wallace + +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/browser/base/content/assistant/ui-preact/node_modules/esbuild/README.md b/browser/base/content/assistant/ui-preact/node_modules/esbuild/README.md new file mode 100644 index 0000000000000..93863d198004e --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/esbuild/README.md @@ -0,0 +1,3 @@ +# esbuild + +This is a JavaScript bundler and minifier. See https://github.com/evanw/esbuild and the [JavaScript API documentation](https://esbuild.github.io/api/) for details. diff --git a/browser/base/content/assistant/ui-preact/node_modules/esbuild/bin/esbuild b/browser/base/content/assistant/ui-preact/node_modules/esbuild/bin/esbuild new file mode 100755 index 0000000000000..8935f40754a9a Binary files /dev/null and b/browser/base/content/assistant/ui-preact/node_modules/esbuild/bin/esbuild differ diff --git a/browser/base/content/assistant/ui-preact/node_modules/esbuild/install.js b/browser/base/content/assistant/ui-preact/node_modules/esbuild/install.js new file mode 100644 index 0000000000000..1019e62435fd0 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/esbuild/install.js @@ -0,0 +1,289 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); + +// lib/npm/node-platform.ts +var fs = require("fs"); +var os = require("os"); +var path = require("path"); +var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH; +var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild"; +var knownWindowsPackages = { + "win32 arm64 LE": "@esbuild/win32-arm64", + "win32 ia32 LE": "@esbuild/win32-ia32", + "win32 x64 LE": "@esbuild/win32-x64" +}; +var knownUnixlikePackages = { + "aix ppc64 BE": "@esbuild/aix-ppc64", + "android arm64 LE": "@esbuild/android-arm64", + "darwin arm64 LE": "@esbuild/darwin-arm64", + "darwin x64 LE": "@esbuild/darwin-x64", + "freebsd arm64 LE": "@esbuild/freebsd-arm64", + "freebsd x64 LE": "@esbuild/freebsd-x64", + "linux arm LE": "@esbuild/linux-arm", + "linux arm64 LE": "@esbuild/linux-arm64", + "linux ia32 LE": "@esbuild/linux-ia32", + "linux mips64el LE": "@esbuild/linux-mips64el", + "linux ppc64 LE": "@esbuild/linux-ppc64", + "linux riscv64 LE": "@esbuild/linux-riscv64", + "linux s390x BE": "@esbuild/linux-s390x", + "linux x64 LE": "@esbuild/linux-x64", + "linux loong64 LE": "@esbuild/linux-loong64", + "netbsd arm64 LE": "@esbuild/netbsd-arm64", + "netbsd x64 LE": "@esbuild/netbsd-x64", + "openbsd arm64 LE": "@esbuild/openbsd-arm64", + "openbsd x64 LE": "@esbuild/openbsd-x64", + "sunos x64 LE": "@esbuild/sunos-x64" +}; +var knownWebAssemblyFallbackPackages = { + "android arm LE": "@esbuild/android-arm", + "android x64 LE": "@esbuild/android-x64", + "openharmony arm64 LE": "@esbuild/openharmony-arm64" +}; +function pkgAndSubpathForCurrentPlatform() { + let pkg; + let subpath; + let isWASM = false; + let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`; + if (platformKey in knownWindowsPackages) { + pkg = knownWindowsPackages[platformKey]; + subpath = "esbuild.exe"; + } else if (platformKey in knownUnixlikePackages) { + pkg = knownUnixlikePackages[platformKey]; + subpath = "bin/esbuild"; + } else if (platformKey in knownWebAssemblyFallbackPackages) { + pkg = knownWebAssemblyFallbackPackages[platformKey]; + subpath = "bin/esbuild"; + isWASM = true; + } else { + throw new Error(`Unsupported platform: ${platformKey}`); + } + return { pkg, subpath, isWASM }; +} +function downloadedBinPath(pkg, subpath) { + const esbuildLibDir = path.dirname(require.resolve("esbuild")); + return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`); +} + +// lib/npm/node-install.ts +var fs2 = require("fs"); +var os2 = require("os"); +var path2 = require("path"); +var zlib = require("zlib"); +var https = require("https"); +var child_process = require("child_process"); +var versionFromPackageJSON = require(path2.join(__dirname, "package.json")).version; +var toPath = path2.join(__dirname, "bin", "esbuild"); +var isToPathJS = true; +function validateBinaryVersion(...command) { + command.push("--version"); + let stdout; + try { + stdout = child_process.execFileSync(command.shift(), command, { + // Without this, this install script strangely crashes with the error + // "EACCES: permission denied, write" but only on Ubuntu Linux when node is + // installed from the Snap Store. This is not a problem when you download + // the official version of node. The problem appears to be that stderr + // (i.e. file descriptor 2) isn't writable? + // + // More info: + // - https://snapcraft.io/ (what the Snap Store is) + // - https://nodejs.org/dist/ (download the official version of node) + // - https://github.com/evanw/esbuild/issues/1711#issuecomment-1027554035 + // + stdio: "pipe" + }).toString().trim(); + } catch (err) { + if (os2.platform() === "darwin" && /_SecTrustEvaluateWithError/.test(err + "")) { + let os3 = "this version of macOS"; + try { + os3 = "macOS " + child_process.execFileSync("sw_vers", ["-productVersion"]).toString().trim(); + } catch { + } + throw new Error(`The "esbuild" package cannot be installed because ${os3} is too outdated. + +The Go compiler (which esbuild relies on) no longer supports ${os3}, +which means the "esbuild" binary executable can't be run. You can either: + + * Update your version of macOS to one that the Go compiler supports + * Use the "esbuild-wasm" package instead of the "esbuild" package + * Build esbuild yourself using an older version of the Go compiler +`); + } + throw err; + } + if (stdout !== versionFromPackageJSON) { + throw new Error(`Expected ${JSON.stringify(versionFromPackageJSON)} but got ${JSON.stringify(stdout)}`); + } +} +function isYarn() { + const { npm_config_user_agent } = process.env; + if (npm_config_user_agent) { + return /\byarn\//.test(npm_config_user_agent); + } + return false; +} +function fetch(url) { + return new Promise((resolve, reject) => { + https.get(url, (res) => { + if ((res.statusCode === 301 || res.statusCode === 302) && res.headers.location) + return fetch(res.headers.location).then(resolve, reject); + if (res.statusCode !== 200) + return reject(new Error(`Server responded with ${res.statusCode}`)); + let chunks = []; + res.on("data", (chunk) => chunks.push(chunk)); + res.on("end", () => resolve(Buffer.concat(chunks))); + }).on("error", reject); + }); +} +function extractFileFromTarGzip(buffer, subpath) { + try { + buffer = zlib.unzipSync(buffer); + } catch (err) { + throw new Error(`Invalid gzip data in archive: ${err && err.message || err}`); + } + let str = (i, n) => String.fromCharCode(...buffer.subarray(i, i + n)).replace(/\0.*$/, ""); + let offset = 0; + subpath = `package/${subpath}`; + while (offset < buffer.length) { + let name = str(offset, 100); + let size = parseInt(str(offset + 124, 12), 8); + offset += 512; + if (!isNaN(size)) { + if (name === subpath) return buffer.subarray(offset, offset + size); + offset += size + 511 & ~511; + } + } + throw new Error(`Could not find ${JSON.stringify(subpath)} in archive`); +} +function installUsingNPM(pkg, subpath, binPath) { + const env = { ...process.env, npm_config_global: void 0 }; + const esbuildLibDir = path2.dirname(require.resolve("esbuild")); + const installDir = path2.join(esbuildLibDir, "npm-install"); + fs2.mkdirSync(installDir); + try { + fs2.writeFileSync(path2.join(installDir, "package.json"), "{}"); + child_process.execSync( + `npm install --loglevel=error --prefer-offline --no-audit --progress=false ${pkg}@${versionFromPackageJSON}`, + { cwd: installDir, stdio: "pipe", env } + ); + const installedBinPath = path2.join(installDir, "node_modules", pkg, subpath); + fs2.renameSync(installedBinPath, binPath); + } finally { + try { + removeRecursive(installDir); + } catch { + } + } +} +function removeRecursive(dir) { + for (const entry of fs2.readdirSync(dir)) { + const entryPath = path2.join(dir, entry); + let stats; + try { + stats = fs2.lstatSync(entryPath); + } catch { + continue; + } + if (stats.isDirectory()) removeRecursive(entryPath); + else fs2.unlinkSync(entryPath); + } + fs2.rmdirSync(dir); +} +function applyManualBinaryPathOverride(overridePath) { + const pathString = JSON.stringify(overridePath); + fs2.writeFileSync(toPath, `#!/usr/bin/env node +require('child_process').execFileSync(${pathString}, process.argv.slice(2), { stdio: 'inherit' }); +`); + const libMain = path2.join(__dirname, "lib", "main.js"); + const code = fs2.readFileSync(libMain, "utf8"); + fs2.writeFileSync(libMain, `var ESBUILD_BINARY_PATH = ${pathString}; +${code}`); +} +function maybeOptimizePackage(binPath) { + const { isWASM } = pkgAndSubpathForCurrentPlatform(); + if (os2.platform() !== "win32" && !isYarn() && !isWASM) { + const tempPath = path2.join(__dirname, "bin-esbuild"); + try { + fs2.linkSync(binPath, tempPath); + fs2.renameSync(tempPath, toPath); + isToPathJS = false; + fs2.unlinkSync(tempPath); + } catch { + } + } +} +async function downloadDirectlyFromNPM(pkg, subpath, binPath) { + const url = `https://registry.npmjs.org/${pkg}/-/${pkg.replace("@esbuild/", "")}-${versionFromPackageJSON}.tgz`; + console.error(`[esbuild] Trying to download ${JSON.stringify(url)}`); + try { + fs2.writeFileSync(binPath, extractFileFromTarGzip(await fetch(url), subpath)); + fs2.chmodSync(binPath, 493); + } catch (e) { + console.error(`[esbuild] Failed to download ${JSON.stringify(url)}: ${e && e.message || e}`); + throw e; + } +} +async function checkAndPreparePackage() { + if (isValidBinaryPath(ESBUILD_BINARY_PATH)) { + if (!fs2.existsSync(ESBUILD_BINARY_PATH)) { + console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`); + } else { + applyManualBinaryPathOverride(ESBUILD_BINARY_PATH); + return; + } + } + const { pkg, subpath } = pkgAndSubpathForCurrentPlatform(); + let binPath; + try { + binPath = require.resolve(`${pkg}/${subpath}`); + } catch (e) { + console.error(`[esbuild] Failed to find package "${pkg}" on the file system + +This can happen if you use the "--no-optional" flag. The "optionalDependencies" +package.json feature is used by esbuild to install the correct binary executable +for your current platform. This install script will now attempt to work around +this. If that fails, you need to remove the "--no-optional" flag to use esbuild. +`); + binPath = downloadedBinPath(pkg, subpath); + try { + console.error(`[esbuild] Trying to install package "${pkg}" using npm`); + installUsingNPM(pkg, subpath, binPath); + } catch (e2) { + console.error(`[esbuild] Failed to install package "${pkg}" using npm: ${e2 && e2.message || e2}`); + try { + await downloadDirectlyFromNPM(pkg, subpath, binPath); + } catch (e3) { + throw new Error(`Failed to install package "${pkg}"`); + } + } + } + maybeOptimizePackage(binPath); +} +checkAndPreparePackage().then(() => { + if (isToPathJS) { + validateBinaryVersion(process.execPath, toPath); + } else { + validateBinaryVersion(toPath); + } +}); diff --git a/browser/base/content/assistant/ui-preact/node_modules/esbuild/lib/main.d.ts b/browser/base/content/assistant/ui-preact/node_modules/esbuild/lib/main.d.ts new file mode 100644 index 0000000000000..9e69c39f58b92 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/esbuild/lib/main.d.ts @@ -0,0 +1,716 @@ +export type Platform = 'browser' | 'node' | 'neutral' +export type Format = 'iife' | 'cjs' | 'esm' +export type Loader = 'base64' | 'binary' | 'copy' | 'css' | 'dataurl' | 'default' | 'empty' | 'file' | 'js' | 'json' | 'jsx' | 'local-css' | 'text' | 'ts' | 'tsx' +export type LogLevel = 'verbose' | 'debug' | 'info' | 'warning' | 'error' | 'silent' +export type Charset = 'ascii' | 'utf8' +export type Drop = 'console' | 'debugger' +export type AbsPaths = 'code' | 'log' | 'metafile' + +interface CommonOptions { + /** Documentation: https://esbuild.github.io/api/#sourcemap */ + sourcemap?: boolean | 'linked' | 'inline' | 'external' | 'both' + /** Documentation: https://esbuild.github.io/api/#legal-comments */ + legalComments?: 'none' | 'inline' | 'eof' | 'linked' | 'external' + /** Documentation: https://esbuild.github.io/api/#source-root */ + sourceRoot?: string + /** Documentation: https://esbuild.github.io/api/#sources-content */ + sourcesContent?: boolean + + /** Documentation: https://esbuild.github.io/api/#format */ + format?: Format + /** Documentation: https://esbuild.github.io/api/#global-name */ + globalName?: string + /** Documentation: https://esbuild.github.io/api/#target */ + target?: string | string[] + /** Documentation: https://esbuild.github.io/api/#supported */ + supported?: Record + /** Documentation: https://esbuild.github.io/api/#platform */ + platform?: Platform + + /** Documentation: https://esbuild.github.io/api/#mangle-props */ + mangleProps?: RegExp + /** Documentation: https://esbuild.github.io/api/#mangle-props */ + reserveProps?: RegExp + /** Documentation: https://esbuild.github.io/api/#mangle-props */ + mangleQuoted?: boolean + /** Documentation: https://esbuild.github.io/api/#mangle-props */ + mangleCache?: Record + /** Documentation: https://esbuild.github.io/api/#drop */ + drop?: Drop[] + /** Documentation: https://esbuild.github.io/api/#drop-labels */ + dropLabels?: string[] + /** Documentation: https://esbuild.github.io/api/#minify */ + minify?: boolean + /** Documentation: https://esbuild.github.io/api/#minify */ + minifyWhitespace?: boolean + /** Documentation: https://esbuild.github.io/api/#minify */ + minifyIdentifiers?: boolean + /** Documentation: https://esbuild.github.io/api/#minify */ + minifySyntax?: boolean + /** Documentation: https://esbuild.github.io/api/#line-limit */ + lineLimit?: number + /** Documentation: https://esbuild.github.io/api/#charset */ + charset?: Charset + /** Documentation: https://esbuild.github.io/api/#tree-shaking */ + treeShaking?: boolean + /** Documentation: https://esbuild.github.io/api/#ignore-annotations */ + ignoreAnnotations?: boolean + + /** Documentation: https://esbuild.github.io/api/#jsx */ + jsx?: 'transform' | 'preserve' | 'automatic' + /** Documentation: https://esbuild.github.io/api/#jsx-factory */ + jsxFactory?: string + /** Documentation: https://esbuild.github.io/api/#jsx-fragment */ + jsxFragment?: string + /** Documentation: https://esbuild.github.io/api/#jsx-import-source */ + jsxImportSource?: string + /** Documentation: https://esbuild.github.io/api/#jsx-development */ + jsxDev?: boolean + /** Documentation: https://esbuild.github.io/api/#jsx-side-effects */ + jsxSideEffects?: boolean + + /** Documentation: https://esbuild.github.io/api/#define */ + define?: { [key: string]: string } + /** Documentation: https://esbuild.github.io/api/#pure */ + pure?: string[] + /** Documentation: https://esbuild.github.io/api/#keep-names */ + keepNames?: boolean + + /** Documentation: https://esbuild.github.io/api/#abs-paths */ + absPaths?: AbsPaths[] + /** Documentation: https://esbuild.github.io/api/#color */ + color?: boolean + /** Documentation: https://esbuild.github.io/api/#log-level */ + logLevel?: LogLevel + /** Documentation: https://esbuild.github.io/api/#log-limit */ + logLimit?: number + /** Documentation: https://esbuild.github.io/api/#log-override */ + logOverride?: Record + + /** Documentation: https://esbuild.github.io/api/#tsconfig-raw */ + tsconfigRaw?: string | TsconfigRaw +} + +export interface TsconfigRaw { + compilerOptions?: { + alwaysStrict?: boolean + baseUrl?: string + experimentalDecorators?: boolean + importsNotUsedAsValues?: 'remove' | 'preserve' | 'error' + jsx?: 'preserve' | 'react-native' | 'react' | 'react-jsx' | 'react-jsxdev' + jsxFactory?: string + jsxFragmentFactory?: string + jsxImportSource?: string + paths?: Record + preserveValueImports?: boolean + strict?: boolean + target?: string + useDefineForClassFields?: boolean + verbatimModuleSyntax?: boolean + } +} + +export interface BuildOptions extends CommonOptions { + /** Documentation: https://esbuild.github.io/api/#bundle */ + bundle?: boolean + /** Documentation: https://esbuild.github.io/api/#splitting */ + splitting?: boolean + /** Documentation: https://esbuild.github.io/api/#preserve-symlinks */ + preserveSymlinks?: boolean + /** Documentation: https://esbuild.github.io/api/#outfile */ + outfile?: string + /** Documentation: https://esbuild.github.io/api/#metafile */ + metafile?: boolean + /** Documentation: https://esbuild.github.io/api/#outdir */ + outdir?: string + /** Documentation: https://esbuild.github.io/api/#outbase */ + outbase?: string + /** Documentation: https://esbuild.github.io/api/#external */ + external?: string[] + /** Documentation: https://esbuild.github.io/api/#packages */ + packages?: 'bundle' | 'external' + /** Documentation: https://esbuild.github.io/api/#alias */ + alias?: Record + /** Documentation: https://esbuild.github.io/api/#loader */ + loader?: { [ext: string]: Loader } + /** Documentation: https://esbuild.github.io/api/#resolve-extensions */ + resolveExtensions?: string[] + /** Documentation: https://esbuild.github.io/api/#main-fields */ + mainFields?: string[] + /** Documentation: https://esbuild.github.io/api/#conditions */ + conditions?: string[] + /** Documentation: https://esbuild.github.io/api/#write */ + write?: boolean + /** Documentation: https://esbuild.github.io/api/#allow-overwrite */ + allowOverwrite?: boolean + /** Documentation: https://esbuild.github.io/api/#tsconfig */ + tsconfig?: string + /** Documentation: https://esbuild.github.io/api/#out-extension */ + outExtension?: { [ext: string]: string } + /** Documentation: https://esbuild.github.io/api/#public-path */ + publicPath?: string + /** Documentation: https://esbuild.github.io/api/#entry-names */ + entryNames?: string + /** Documentation: https://esbuild.github.io/api/#chunk-names */ + chunkNames?: string + /** Documentation: https://esbuild.github.io/api/#asset-names */ + assetNames?: string + /** Documentation: https://esbuild.github.io/api/#inject */ + inject?: string[] + /** Documentation: https://esbuild.github.io/api/#banner */ + banner?: { [type: string]: string } + /** Documentation: https://esbuild.github.io/api/#footer */ + footer?: { [type: string]: string } + /** Documentation: https://esbuild.github.io/api/#entry-points */ + entryPoints?: (string | { in: string, out: string })[] | Record + /** Documentation: https://esbuild.github.io/api/#stdin */ + stdin?: StdinOptions + /** Documentation: https://esbuild.github.io/plugins/ */ + plugins?: Plugin[] + /** Documentation: https://esbuild.github.io/api/#working-directory */ + absWorkingDir?: string + /** Documentation: https://esbuild.github.io/api/#node-paths */ + nodePaths?: string[]; // The "NODE_PATH" variable from Node.js +} + +export interface StdinOptions { + contents: string | Uint8Array + resolveDir?: string + sourcefile?: string + loader?: Loader +} + +export interface Message { + id: string + pluginName: string + text: string + location: Location | null + notes: Note[] + + /** + * Optional user-specified data that is passed through unmodified. You can + * use this to stash the original error, for example. + */ + detail: any +} + +export interface Note { + text: string + location: Location | null +} + +export interface Location { + file: string + namespace: string + /** 1-based */ + line: number + /** 0-based, in bytes */ + column: number + /** in bytes */ + length: number + lineText: string + suggestion: string +} + +export interface OutputFile { + path: string + contents: Uint8Array + hash: string + /** "contents" as text (changes automatically with "contents") */ + readonly text: string +} + +export interface BuildResult { + errors: Message[] + warnings: Message[] + /** Only when "write: false" */ + outputFiles: OutputFile[] | (ProvidedOptions['write'] extends false ? never : undefined) + /** Only when "metafile: true" */ + metafile: Metafile | (ProvidedOptions['metafile'] extends true ? never : undefined) + /** Only when "mangleCache" is present */ + mangleCache: Record | (ProvidedOptions['mangleCache'] extends Object ? never : undefined) +} + +export interface BuildFailure extends Error { + errors: Message[] + warnings: Message[] +} + +/** Documentation: https://esbuild.github.io/api/#serve-arguments */ +export interface ServeOptions { + port?: number + host?: string + servedir?: string + keyfile?: string + certfile?: string + fallback?: string + cors?: CORSOptions + onRequest?: (args: ServeOnRequestArgs) => void +} + +/** Documentation: https://esbuild.github.io/api/#cors */ +export interface CORSOptions { + origin?: string | string[] +} + +export interface ServeOnRequestArgs { + remoteAddress: string + method: string + path: string + status: number + /** The time to generate the response, not to send it */ + timeInMS: number +} + +/** Documentation: https://esbuild.github.io/api/#serve-return-values */ +export interface ServeResult { + port: number + hosts: string[] +} + +export interface TransformOptions extends CommonOptions { + /** Documentation: https://esbuild.github.io/api/#sourcefile */ + sourcefile?: string + /** Documentation: https://esbuild.github.io/api/#loader */ + loader?: Loader + /** Documentation: https://esbuild.github.io/api/#banner */ + banner?: string + /** Documentation: https://esbuild.github.io/api/#footer */ + footer?: string +} + +export interface TransformResult { + code: string + map: string + warnings: Message[] + /** Only when "mangleCache" is present */ + mangleCache: Record | (ProvidedOptions['mangleCache'] extends Object ? never : undefined) + /** Only when "legalComments" is "external" */ + legalComments: string | (ProvidedOptions['legalComments'] extends 'external' ? never : undefined) +} + +export interface TransformFailure extends Error { + errors: Message[] + warnings: Message[] +} + +export interface Plugin { + name: string + setup: (build: PluginBuild) => (void | Promise) +} + +export interface PluginBuild { + /** Documentation: https://esbuild.github.io/plugins/#build-options */ + initialOptions: BuildOptions + + /** Documentation: https://esbuild.github.io/plugins/#resolve */ + resolve(path: string, options?: ResolveOptions): Promise + + /** Documentation: https://esbuild.github.io/plugins/#on-start */ + onStart(callback: () => + (OnStartResult | null | void | Promise)): void + + /** Documentation: https://esbuild.github.io/plugins/#on-end */ + onEnd(callback: (result: BuildResult) => + (OnEndResult | null | void | Promise)): void + + /** Documentation: https://esbuild.github.io/plugins/#on-resolve */ + onResolve(options: OnResolveOptions, callback: (args: OnResolveArgs) => + (OnResolveResult | null | undefined | Promise)): void + + /** Documentation: https://esbuild.github.io/plugins/#on-load */ + onLoad(options: OnLoadOptions, callback: (args: OnLoadArgs) => + (OnLoadResult | null | undefined | Promise)): void + + /** Documentation: https://esbuild.github.io/plugins/#on-dispose */ + onDispose(callback: () => void): void + + // This is a full copy of the esbuild library in case you need it + esbuild: { + context: typeof context, + build: typeof build, + buildSync: typeof buildSync, + transform: typeof transform, + transformSync: typeof transformSync, + formatMessages: typeof formatMessages, + formatMessagesSync: typeof formatMessagesSync, + analyzeMetafile: typeof analyzeMetafile, + analyzeMetafileSync: typeof analyzeMetafileSync, + initialize: typeof initialize, + version: typeof version, + } +} + +/** Documentation: https://esbuild.github.io/plugins/#resolve-options */ +export interface ResolveOptions { + pluginName?: string + importer?: string + namespace?: string + resolveDir?: string + kind?: ImportKind + pluginData?: any + with?: Record +} + +/** Documentation: https://esbuild.github.io/plugins/#resolve-results */ +export interface ResolveResult { + errors: Message[] + warnings: Message[] + + path: string + external: boolean + sideEffects: boolean + namespace: string + suffix: string + pluginData: any +} + +export interface OnStartResult { + errors?: PartialMessage[] + warnings?: PartialMessage[] +} + +export interface OnEndResult { + errors?: PartialMessage[] + warnings?: PartialMessage[] +} + +/** Documentation: https://esbuild.github.io/plugins/#on-resolve-options */ +export interface OnResolveOptions { + filter: RegExp + namespace?: string +} + +/** Documentation: https://esbuild.github.io/plugins/#on-resolve-arguments */ +export interface OnResolveArgs { + path: string + importer: string + namespace: string + resolveDir: string + kind: ImportKind + pluginData: any + with: Record +} + +export type ImportKind = + | 'entry-point' + + // JS + | 'import-statement' + | 'require-call' + | 'dynamic-import' + | 'require-resolve' + + // CSS + | 'import-rule' + | 'composes-from' + | 'url-token' + +/** Documentation: https://esbuild.github.io/plugins/#on-resolve-results */ +export interface OnResolveResult { + pluginName?: string + + errors?: PartialMessage[] + warnings?: PartialMessage[] + + path?: string + external?: boolean + sideEffects?: boolean + namespace?: string + suffix?: string + pluginData?: any + + watchFiles?: string[] + watchDirs?: string[] +} + +/** Documentation: https://esbuild.github.io/plugins/#on-load-options */ +export interface OnLoadOptions { + filter: RegExp + namespace?: string +} + +/** Documentation: https://esbuild.github.io/plugins/#on-load-arguments */ +export interface OnLoadArgs { + path: string + namespace: string + suffix: string + pluginData: any + with: Record +} + +/** Documentation: https://esbuild.github.io/plugins/#on-load-results */ +export interface OnLoadResult { + pluginName?: string + + errors?: PartialMessage[] + warnings?: PartialMessage[] + + contents?: string | Uint8Array + resolveDir?: string + loader?: Loader + pluginData?: any + + watchFiles?: string[] + watchDirs?: string[] +} + +export interface PartialMessage { + id?: string + pluginName?: string + text?: string + location?: Partial | null + notes?: PartialNote[] + detail?: any +} + +export interface PartialNote { + text?: string + location?: Partial | null +} + +/** Documentation: https://esbuild.github.io/api/#metafile */ +export interface Metafile { + inputs: { + [path: string]: { + bytes: number + imports: { + path: string + kind: ImportKind + external?: boolean + original?: string + with?: Record + }[] + format?: 'cjs' | 'esm' + with?: Record + } + } + outputs: { + [path: string]: { + bytes: number + inputs: { + [path: string]: { + bytesInOutput: number + } + } + imports: { + path: string + kind: ImportKind | 'file-loader' + external?: boolean + }[] + exports: string[] + entryPoint?: string + cssBundle?: string + } + } +} + +export interface FormatMessagesOptions { + kind: 'error' | 'warning' + color?: boolean + terminalWidth?: number +} + +export interface AnalyzeMetafileOptions { + color?: boolean + verbose?: boolean +} + +/** Documentation: https://esbuild.github.io/api/#watch-arguments */ +export interface WatchOptions { + delay?: number // In milliseconds +} + +export interface BuildContext { + /** Documentation: https://esbuild.github.io/api/#rebuild */ + rebuild(): Promise> + + /** Documentation: https://esbuild.github.io/api/#watch */ + watch(options?: WatchOptions): Promise + + /** Documentation: https://esbuild.github.io/api/#serve */ + serve(options?: ServeOptions): Promise + + cancel(): Promise + dispose(): Promise +} + +// This is a TypeScript type-level function which replaces any keys in "In" +// that aren't in "Out" with "never". We use this to reject properties with +// typos in object literals. See: https://stackoverflow.com/questions/49580725 +type SameShape = In & { [Key in Exclude]: never } + +/** + * This function invokes the "esbuild" command-line tool for you. It returns a + * promise that either resolves with a "BuildResult" object or rejects with a + * "BuildFailure" object. + * + * - Works in node: yes + * - Works in browser: yes + * + * Documentation: https://esbuild.github.io/api/#build + */ +export declare function build(options: SameShape): Promise> + +/** + * This is the advanced long-running form of "build" that supports additional + * features such as watch mode and a local development server. + * + * - Works in node: yes + * - Works in browser: no + * + * Documentation: https://esbuild.github.io/api/#build + */ +export declare function context(options: SameShape): Promise> + +/** + * This function transforms a single JavaScript file. It can be used to minify + * JavaScript, convert TypeScript/JSX to JavaScript, or convert newer JavaScript + * to older JavaScript. It returns a promise that is either resolved with a + * "TransformResult" object or rejected with a "TransformFailure" object. + * + * - Works in node: yes + * - Works in browser: yes + * + * Documentation: https://esbuild.github.io/api/#transform + */ +export declare function transform(input: string | Uint8Array, options?: SameShape): Promise> + +/** + * Converts log messages to formatted message strings suitable for printing in + * the terminal. This allows you to reuse the built-in behavior of esbuild's + * log message formatter. This is a batch-oriented API for efficiency. + * + * - Works in node: yes + * - Works in browser: yes + */ +export declare function formatMessages(messages: PartialMessage[], options: FormatMessagesOptions): Promise + +/** + * Pretty-prints an analysis of the metafile JSON to a string. This is just for + * convenience to be able to match esbuild's pretty-printing exactly. If you want + * to customize it, you can just inspect the data in the metafile yourself. + * + * - Works in node: yes + * - Works in browser: yes + * + * Documentation: https://esbuild.github.io/api/#analyze + */ +export declare function analyzeMetafile(metafile: Metafile | string, options?: AnalyzeMetafileOptions): Promise + +/** + * A synchronous version of "build". + * + * - Works in node: yes + * - Works in browser: no + * + * Documentation: https://esbuild.github.io/api/#build + */ +export declare function buildSync(options: SameShape): BuildResult + +/** + * A synchronous version of "transform". + * + * - Works in node: yes + * - Works in browser: no + * + * Documentation: https://esbuild.github.io/api/#transform + */ +export declare function transformSync(input: string | Uint8Array, options?: SameShape): TransformResult + +/** + * A synchronous version of "formatMessages". + * + * - Works in node: yes + * - Works in browser: no + */ +export declare function formatMessagesSync(messages: PartialMessage[], options: FormatMessagesOptions): string[] + +/** + * A synchronous version of "analyzeMetafile". + * + * - Works in node: yes + * - Works in browser: no + * + * Documentation: https://esbuild.github.io/api/#analyze + */ +export declare function analyzeMetafileSync(metafile: Metafile | string, options?: AnalyzeMetafileOptions): string + +/** + * This configures the browser-based version of esbuild. It is necessary to + * call this first and wait for the returned promise to be resolved before + * making other API calls when using esbuild in the browser. + * + * - Works in node: yes + * - Works in browser: yes ("options" is required) + * + * Documentation: https://esbuild.github.io/api/#browser + */ +export declare function initialize(options: InitializeOptions): Promise + +export interface InitializeOptions { + /** + * The URL of the "esbuild.wasm" file. This must be provided when running + * esbuild in the browser. + */ + wasmURL?: string | URL + + /** + * The result of calling "new WebAssembly.Module(buffer)" where "buffer" + * is a typed array or ArrayBuffer containing the binary code of the + * "esbuild.wasm" file. + * + * You can use this as an alternative to "wasmURL" for environments where it's + * not possible to download the WebAssembly module. + */ + wasmModule?: WebAssembly.Module + + /** + * By default esbuild runs the WebAssembly-based browser API in a web worker + * to avoid blocking the UI thread. This can be disabled by setting "worker" + * to false. + */ + worker?: boolean +} + +export let version: string + +// Call this function to terminate esbuild's child process. The child process +// is not terminated and re-created after each API call because it's more +// efficient to keep it around when there are multiple API calls. +// +// In node this happens automatically before the parent node process exits. So +// you only need to call this if you know you will not make any more esbuild +// API calls and you want to clean up resources. +// +// Unlike node, Deno lacks the necessary APIs to clean up child processes +// automatically. You must manually call stop() in Deno when you're done +// using esbuild or Deno will continue running forever. +// +// Another reason you might want to call this is if you are using esbuild from +// within a Deno test. Deno fails tests that create a child process without +// killing it before the test ends, so you have to call this function (and +// await the returned promise) in every Deno test that uses esbuild. +export declare function stop(): Promise + +// Note: These declarations exist to avoid type errors when you omit "dom" from +// "lib" in your "tsconfig.json" file. TypeScript confusingly declares the +// global "WebAssembly" type in "lib.dom.d.ts" even though it has nothing to do +// with the browser DOM and is present in many non-browser JavaScript runtimes +// (e.g. node and deno). Declaring it here allows esbuild's API to be used in +// these scenarios. +// +// There's an open issue about getting this problem corrected (although these +// declarations will need to remain even if this is fixed for backward +// compatibility with older TypeScript versions): +// +// https://github.com/microsoft/TypeScript-DOM-lib-generator/issues/826 +// +declare global { + namespace WebAssembly { + interface Module { + } + } + interface URL { + } +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/esbuild/lib/main.js b/browser/base/content/assistant/ui-preact/node_modules/esbuild/lib/main.js new file mode 100644 index 0000000000000..65bacc8dda444 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/esbuild/lib/main.js @@ -0,0 +1,2242 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// lib/npm/node.ts +var node_exports = {}; +__export(node_exports, { + analyzeMetafile: () => analyzeMetafile, + analyzeMetafileSync: () => analyzeMetafileSync, + build: () => build, + buildSync: () => buildSync, + context: () => context, + default: () => node_default, + formatMessages: () => formatMessages, + formatMessagesSync: () => formatMessagesSync, + initialize: () => initialize, + stop: () => stop, + transform: () => transform, + transformSync: () => transformSync, + version: () => version +}); +module.exports = __toCommonJS(node_exports); + +// lib/shared/stdio_protocol.ts +function encodePacket(packet) { + let visit = (value) => { + if (value === null) { + bb.write8(0); + } else if (typeof value === "boolean") { + bb.write8(1); + bb.write8(+value); + } else if (typeof value === "number") { + bb.write8(2); + bb.write32(value | 0); + } else if (typeof value === "string") { + bb.write8(3); + bb.write(encodeUTF8(value)); + } else if (value instanceof Uint8Array) { + bb.write8(4); + bb.write(value); + } else if (value instanceof Array) { + bb.write8(5); + bb.write32(value.length); + for (let item of value) { + visit(item); + } + } else { + let keys = Object.keys(value); + bb.write8(6); + bb.write32(keys.length); + for (let key of keys) { + bb.write(encodeUTF8(key)); + visit(value[key]); + } + } + }; + let bb = new ByteBuffer(); + bb.write32(0); + bb.write32(packet.id << 1 | +!packet.isRequest); + visit(packet.value); + writeUInt32LE(bb.buf, bb.len - 4, 0); + return bb.buf.subarray(0, bb.len); +} +function decodePacket(bytes) { + let visit = () => { + switch (bb.read8()) { + case 0: + return null; + case 1: + return !!bb.read8(); + case 2: + return bb.read32(); + case 3: + return decodeUTF8(bb.read()); + case 4: + return bb.read(); + case 5: { + let count = bb.read32(); + let value2 = []; + for (let i = 0; i < count; i++) { + value2.push(visit()); + } + return value2; + } + case 6: { + let count = bb.read32(); + let value2 = {}; + for (let i = 0; i < count; i++) { + value2[decodeUTF8(bb.read())] = visit(); + } + return value2; + } + default: + throw new Error("Invalid packet"); + } + }; + let bb = new ByteBuffer(bytes); + let id = bb.read32(); + let isRequest = (id & 1) === 0; + id >>>= 1; + let value = visit(); + if (bb.ptr !== bytes.length) { + throw new Error("Invalid packet"); + } + return { id, isRequest, value }; +} +var ByteBuffer = class { + constructor(buf = new Uint8Array(1024)) { + this.buf = buf; + this.len = 0; + this.ptr = 0; + } + _write(delta) { + if (this.len + delta > this.buf.length) { + let clone = new Uint8Array((this.len + delta) * 2); + clone.set(this.buf); + this.buf = clone; + } + this.len += delta; + return this.len - delta; + } + write8(value) { + let offset = this._write(1); + this.buf[offset] = value; + } + write32(value) { + let offset = this._write(4); + writeUInt32LE(this.buf, value, offset); + } + write(bytes) { + let offset = this._write(4 + bytes.length); + writeUInt32LE(this.buf, bytes.length, offset); + this.buf.set(bytes, offset + 4); + } + _read(delta) { + if (this.ptr + delta > this.buf.length) { + throw new Error("Invalid packet"); + } + this.ptr += delta; + return this.ptr - delta; + } + read8() { + return this.buf[this._read(1)]; + } + read32() { + return readUInt32LE(this.buf, this._read(4)); + } + read() { + let length = this.read32(); + let bytes = new Uint8Array(length); + let ptr = this._read(bytes.length); + bytes.set(this.buf.subarray(ptr, ptr + length)); + return bytes; + } +}; +var encodeUTF8; +var decodeUTF8; +var encodeInvariant; +if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") { + let encoder = new TextEncoder(); + let decoder = new TextDecoder(); + encodeUTF8 = (text) => encoder.encode(text); + decodeUTF8 = (bytes) => decoder.decode(bytes); + encodeInvariant = 'new TextEncoder().encode("")'; +} else if (typeof Buffer !== "undefined") { + encodeUTF8 = (text) => Buffer.from(text); + decodeUTF8 = (bytes) => { + let { buffer, byteOffset, byteLength } = bytes; + return Buffer.from(buffer, byteOffset, byteLength).toString(); + }; + encodeInvariant = 'Buffer.from("")'; +} else { + throw new Error("No UTF-8 codec found"); +} +if (!(encodeUTF8("") instanceof Uint8Array)) + throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false + +This indicates that your JavaScript environment is broken. You cannot use +esbuild in this environment because esbuild relies on this invariant. This +is not a problem with esbuild. You need to fix your environment instead. +`); +function readUInt32LE(buffer, offset) { + return buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24; +} +function writeUInt32LE(buffer, value, offset) { + buffer[offset++] = value; + buffer[offset++] = value >> 8; + buffer[offset++] = value >> 16; + buffer[offset++] = value >> 24; +} + +// lib/shared/common.ts +var quote = JSON.stringify; +var buildLogLevelDefault = "warning"; +var transformLogLevelDefault = "silent"; +function validateAndJoinStringArray(values, what) { + const toJoin = []; + for (const value of values) { + validateStringValue(value, what); + if (value.indexOf(",") >= 0) throw new Error(`Invalid ${what}: ${value}`); + toJoin.push(value); + } + return toJoin.join(","); +} +var canBeAnything = () => null; +var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean"; +var mustBeString = (value) => typeof value === "string" ? null : "a string"; +var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object"; +var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer"; +var mustBeValidPortNumber = (value) => typeof value === "number" && value === (value | 0) && value >= 0 && value <= 65535 ? null : "a valid port number"; +var mustBeFunction = (value) => typeof value === "function" ? null : "a function"; +var mustBeArray = (value) => Array.isArray(value) ? null : "an array"; +var mustBeArrayOfStrings = (value) => Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "an array of strings"; +var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object"; +var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object"; +var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module"; +var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null"; +var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean"; +var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object"; +var mustBeStringOrArrayOfStrings = (value) => typeof value === "string" || Array.isArray(value) && value.every((x) => typeof x === "string") ? null : "a string or an array of strings"; +var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array"; +var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL"; +function getFlag(object, keys, key, mustBeFn) { + let value = object[key]; + keys[key + ""] = true; + if (value === void 0) return void 0; + let mustBe = mustBeFn(value); + if (mustBe !== null) throw new Error(`${quote(key)} must be ${mustBe}`); + return value; +} +function checkForInvalidFlags(object, keys, where) { + for (let key in object) { + if (!(key in keys)) { + throw new Error(`Invalid option ${where}: ${quote(key)}`); + } + } +} +function validateInitializeOptions(options) { + let keys = /* @__PURE__ */ Object.create(null); + let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL); + let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule); + let worker = getFlag(options, keys, "worker", mustBeBoolean); + checkForInvalidFlags(options, keys, "in initialize() call"); + return { + wasmURL, + wasmModule, + worker + }; +} +function validateMangleCache(mangleCache) { + let validated; + if (mangleCache !== void 0) { + validated = /* @__PURE__ */ Object.create(null); + for (let key in mangleCache) { + let value = mangleCache[key]; + if (typeof value === "string" || value === false) { + validated[key] = value; + } else { + throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`); + } + } + } + return validated; +} +function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) { + let color = getFlag(options, keys, "color", mustBeBoolean); + let logLevel = getFlag(options, keys, "logLevel", mustBeString); + let logLimit = getFlag(options, keys, "logLimit", mustBeInteger); + if (color !== void 0) flags.push(`--color=${color}`); + else if (isTTY2) flags.push(`--color=true`); + flags.push(`--log-level=${logLevel || logLevelDefault}`); + flags.push(`--log-limit=${logLimit || 0}`); +} +function validateStringValue(value, what, key) { + if (typeof value !== "string") { + throw new Error(`Expected value for ${what}${key !== void 0 ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`); + } + return value; +} +function pushCommonFlags(flags, options, keys) { + let legalComments = getFlag(options, keys, "legalComments", mustBeString); + let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString); + let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean); + let target = getFlag(options, keys, "target", mustBeStringOrArrayOfStrings); + let format = getFlag(options, keys, "format", mustBeString); + let globalName = getFlag(options, keys, "globalName", mustBeString); + let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp); + let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp); + let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean); + let minify = getFlag(options, keys, "minify", mustBeBoolean); + let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean); + let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean); + let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean); + let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger); + let drop = getFlag(options, keys, "drop", mustBeArrayOfStrings); + let dropLabels = getFlag(options, keys, "dropLabels", mustBeArrayOfStrings); + let charset = getFlag(options, keys, "charset", mustBeString); + let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean); + let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean); + let jsx = getFlag(options, keys, "jsx", mustBeString); + let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString); + let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString); + let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString); + let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean); + let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean); + let define = getFlag(options, keys, "define", mustBeObject); + let logOverride = getFlag(options, keys, "logOverride", mustBeObject); + let supported = getFlag(options, keys, "supported", mustBeObject); + let pure = getFlag(options, keys, "pure", mustBeArrayOfStrings); + let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean); + let platform = getFlag(options, keys, "platform", mustBeString); + let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject); + let absPaths = getFlag(options, keys, "absPaths", mustBeArrayOfStrings); + if (legalComments) flags.push(`--legal-comments=${legalComments}`); + if (sourceRoot !== void 0) flags.push(`--source-root=${sourceRoot}`); + if (sourcesContent !== void 0) flags.push(`--sources-content=${sourcesContent}`); + if (target) flags.push(`--target=${validateAndJoinStringArray(Array.isArray(target) ? target : [target], "target")}`); + if (format) flags.push(`--format=${format}`); + if (globalName) flags.push(`--global-name=${globalName}`); + if (platform) flags.push(`--platform=${platform}`); + if (tsconfigRaw) flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`); + if (minify) flags.push("--minify"); + if (minifySyntax) flags.push("--minify-syntax"); + if (minifyWhitespace) flags.push("--minify-whitespace"); + if (minifyIdentifiers) flags.push("--minify-identifiers"); + if (lineLimit) flags.push(`--line-limit=${lineLimit}`); + if (charset) flags.push(`--charset=${charset}`); + if (treeShaking !== void 0) flags.push(`--tree-shaking=${treeShaking}`); + if (ignoreAnnotations) flags.push(`--ignore-annotations`); + if (drop) for (let what of drop) flags.push(`--drop:${validateStringValue(what, "drop")}`); + if (dropLabels) flags.push(`--drop-labels=${validateAndJoinStringArray(dropLabels, "drop label")}`); + if (absPaths) flags.push(`--abs-paths=${validateAndJoinStringArray(absPaths, "abs paths")}`); + if (mangleProps) flags.push(`--mangle-props=${jsRegExpToGoRegExp(mangleProps)}`); + if (reserveProps) flags.push(`--reserve-props=${jsRegExpToGoRegExp(reserveProps)}`); + if (mangleQuoted !== void 0) flags.push(`--mangle-quoted=${mangleQuoted}`); + if (jsx) flags.push(`--jsx=${jsx}`); + if (jsxFactory) flags.push(`--jsx-factory=${jsxFactory}`); + if (jsxFragment) flags.push(`--jsx-fragment=${jsxFragment}`); + if (jsxImportSource) flags.push(`--jsx-import-source=${jsxImportSource}`); + if (jsxDev) flags.push(`--jsx-dev`); + if (jsxSideEffects) flags.push(`--jsx-side-effects`); + if (define) { + for (let key in define) { + if (key.indexOf("=") >= 0) throw new Error(`Invalid define: ${key}`); + flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`); + } + } + if (logOverride) { + for (let key in logOverride) { + if (key.indexOf("=") >= 0) throw new Error(`Invalid log override: ${key}`); + flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`); + } + } + if (supported) { + for (let key in supported) { + if (key.indexOf("=") >= 0) throw new Error(`Invalid supported: ${key}`); + const value = supported[key]; + if (typeof value !== "boolean") throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`); + flags.push(`--supported:${key}=${value}`); + } + } + if (pure) for (let fn of pure) flags.push(`--pure:${validateStringValue(fn, "pure")}`); + if (keepNames) flags.push(`--keep-names`); +} +function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) { + var _a2; + let flags = []; + let entries = []; + let keys = /* @__PURE__ */ Object.create(null); + let stdinContents = null; + let stdinResolveDir = null; + pushLogFlags(flags, options, keys, isTTY2, logLevelDefault); + pushCommonFlags(flags, options, keys); + let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean); + let bundle = getFlag(options, keys, "bundle", mustBeBoolean); + let splitting = getFlag(options, keys, "splitting", mustBeBoolean); + let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean); + let metafile = getFlag(options, keys, "metafile", mustBeBoolean); + let outfile = getFlag(options, keys, "outfile", mustBeString); + let outdir = getFlag(options, keys, "outdir", mustBeString); + let outbase = getFlag(options, keys, "outbase", mustBeString); + let tsconfig = getFlag(options, keys, "tsconfig", mustBeString); + let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArrayOfStrings); + let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArrayOfStrings); + let mainFields = getFlag(options, keys, "mainFields", mustBeArrayOfStrings); + let conditions = getFlag(options, keys, "conditions", mustBeArrayOfStrings); + let external = getFlag(options, keys, "external", mustBeArrayOfStrings); + let packages = getFlag(options, keys, "packages", mustBeString); + let alias = getFlag(options, keys, "alias", mustBeObject); + let loader = getFlag(options, keys, "loader", mustBeObject); + let outExtension = getFlag(options, keys, "outExtension", mustBeObject); + let publicPath = getFlag(options, keys, "publicPath", mustBeString); + let entryNames = getFlag(options, keys, "entryNames", mustBeString); + let chunkNames = getFlag(options, keys, "chunkNames", mustBeString); + let assetNames = getFlag(options, keys, "assetNames", mustBeString); + let inject = getFlag(options, keys, "inject", mustBeArrayOfStrings); + let banner = getFlag(options, keys, "banner", mustBeObject); + let footer = getFlag(options, keys, "footer", mustBeObject); + let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints); + let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString); + let stdin = getFlag(options, keys, "stdin", mustBeObject); + let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault; + let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean); + let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject); + keys.plugins = true; + checkForInvalidFlags(options, keys, `in ${callName}() call`); + if (sourcemap) flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`); + if (bundle) flags.push("--bundle"); + if (allowOverwrite) flags.push("--allow-overwrite"); + if (splitting) flags.push("--splitting"); + if (preserveSymlinks) flags.push("--preserve-symlinks"); + if (metafile) flags.push(`--metafile`); + if (outfile) flags.push(`--outfile=${outfile}`); + if (outdir) flags.push(`--outdir=${outdir}`); + if (outbase) flags.push(`--outbase=${outbase}`); + if (tsconfig) flags.push(`--tsconfig=${tsconfig}`); + if (packages) flags.push(`--packages=${packages}`); + if (resolveExtensions) flags.push(`--resolve-extensions=${validateAndJoinStringArray(resolveExtensions, "resolve extension")}`); + if (publicPath) flags.push(`--public-path=${publicPath}`); + if (entryNames) flags.push(`--entry-names=${entryNames}`); + if (chunkNames) flags.push(`--chunk-names=${chunkNames}`); + if (assetNames) flags.push(`--asset-names=${assetNames}`); + if (mainFields) flags.push(`--main-fields=${validateAndJoinStringArray(mainFields, "main field")}`); + if (conditions) flags.push(`--conditions=${validateAndJoinStringArray(conditions, "condition")}`); + if (external) for (let name of external) flags.push(`--external:${validateStringValue(name, "external")}`); + if (alias) { + for (let old in alias) { + if (old.indexOf("=") >= 0) throw new Error(`Invalid package name in alias: ${old}`); + flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`); + } + } + if (banner) { + for (let type in banner) { + if (type.indexOf("=") >= 0) throw new Error(`Invalid banner file type: ${type}`); + flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`); + } + } + if (footer) { + for (let type in footer) { + if (type.indexOf("=") >= 0) throw new Error(`Invalid footer file type: ${type}`); + flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`); + } + } + if (inject) for (let path3 of inject) flags.push(`--inject:${validateStringValue(path3, "inject")}`); + if (loader) { + for (let ext in loader) { + if (ext.indexOf("=") >= 0) throw new Error(`Invalid loader extension: ${ext}`); + flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`); + } + } + if (outExtension) { + for (let ext in outExtension) { + if (ext.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext}`); + flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`); + } + } + if (entryPoints) { + if (Array.isArray(entryPoints)) { + for (let i = 0, n = entryPoints.length; i < n; i++) { + let entryPoint = entryPoints[i]; + if (typeof entryPoint === "object" && entryPoint !== null) { + let entryPointKeys = /* @__PURE__ */ Object.create(null); + let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString); + let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString); + checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i); + if (input === void 0) throw new Error('Missing property "in" for entry point at index ' + i); + if (output === void 0) throw new Error('Missing property "out" for entry point at index ' + i); + entries.push([output, input]); + } else { + entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]); + } + } + } else { + for (let key in entryPoints) { + entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]); + } + } + } + if (stdin) { + let stdinKeys = /* @__PURE__ */ Object.create(null); + let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array); + let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString); + let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString); + let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString); + checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object'); + if (sourcefile) flags.push(`--sourcefile=${sourcefile}`); + if (loader2) flags.push(`--loader=${loader2}`); + if (resolveDir) stdinResolveDir = resolveDir; + if (typeof contents === "string") stdinContents = encodeUTF8(contents); + else if (contents instanceof Uint8Array) stdinContents = contents; + } + let nodePaths = []; + if (nodePathsInput) { + for (let value of nodePathsInput) { + value += ""; + nodePaths.push(value); + } + } + return { + entries, + flags, + write, + stdinContents, + stdinResolveDir, + absWorkingDir, + nodePaths, + mangleCache: validateMangleCache(mangleCache) + }; +} +function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) { + let flags = []; + let keys = /* @__PURE__ */ Object.create(null); + pushLogFlags(flags, options, keys, isTTY2, logLevelDefault); + pushCommonFlags(flags, options, keys); + let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean); + let sourcefile = getFlag(options, keys, "sourcefile", mustBeString); + let loader = getFlag(options, keys, "loader", mustBeString); + let banner = getFlag(options, keys, "banner", mustBeString); + let footer = getFlag(options, keys, "footer", mustBeString); + let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject); + checkForInvalidFlags(options, keys, `in ${callName}() call`); + if (sourcemap) flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`); + if (sourcefile) flags.push(`--sourcefile=${sourcefile}`); + if (loader) flags.push(`--loader=${loader}`); + if (banner) flags.push(`--banner=${banner}`); + if (footer) flags.push(`--footer=${footer}`); + return { + flags, + mangleCache: validateMangleCache(mangleCache) + }; +} +function createChannel(streamIn) { + const requestCallbacksByKey = {}; + const closeData = { didClose: false, reason: "" }; + let responseCallbacks = {}; + let nextRequestID = 0; + let nextBuildKey = 0; + let stdout = new Uint8Array(16 * 1024); + let stdoutUsed = 0; + let readFromStdout = (chunk) => { + let limit = stdoutUsed + chunk.length; + if (limit > stdout.length) { + let swap = new Uint8Array(limit * 2); + swap.set(stdout); + stdout = swap; + } + stdout.set(chunk, stdoutUsed); + stdoutUsed += chunk.length; + let offset = 0; + while (offset + 4 <= stdoutUsed) { + let length = readUInt32LE(stdout, offset); + if (offset + 4 + length > stdoutUsed) { + break; + } + offset += 4; + handleIncomingPacket(stdout.subarray(offset, offset + length)); + offset += length; + } + if (offset > 0) { + stdout.copyWithin(0, offset, stdoutUsed); + stdoutUsed -= offset; + } + }; + let afterClose = (error) => { + closeData.didClose = true; + if (error) closeData.reason = ": " + (error.message || error); + const text = "The service was stopped" + closeData.reason; + for (let id in responseCallbacks) { + responseCallbacks[id](text, null); + } + responseCallbacks = {}; + }; + let sendRequest = (refs, value, callback) => { + if (closeData.didClose) return callback("The service is no longer running" + closeData.reason, null); + let id = nextRequestID++; + responseCallbacks[id] = (error, response) => { + try { + callback(error, response); + } finally { + if (refs) refs.unref(); + } + }; + if (refs) refs.ref(); + streamIn.writeToStdin(encodePacket({ id, isRequest: true, value })); + }; + let sendResponse = (id, value) => { + if (closeData.didClose) throw new Error("The service is no longer running" + closeData.reason); + streamIn.writeToStdin(encodePacket({ id, isRequest: false, value })); + }; + let handleRequest = async (id, request) => { + try { + if (request.command === "ping") { + sendResponse(id, {}); + return; + } + if (typeof request.key === "number") { + const requestCallbacks = requestCallbacksByKey[request.key]; + if (!requestCallbacks) { + return; + } + const callback = requestCallbacks[request.command]; + if (callback) { + await callback(id, request); + return; + } + } + throw new Error(`Invalid command: ` + request.command); + } catch (e) { + const errors = [extractErrorMessageV8(e, streamIn, null, void 0, "")]; + try { + sendResponse(id, { errors }); + } catch { + } + } + }; + let isFirstPacket = true; + let handleIncomingPacket = (bytes) => { + if (isFirstPacket) { + isFirstPacket = false; + let binaryVersion = String.fromCharCode(...bytes); + if (binaryVersion !== "0.27.2") { + throw new Error(`Cannot start service: Host version "${"0.27.2"}" does not match binary version ${quote(binaryVersion)}`); + } + return; + } + let packet = decodePacket(bytes); + if (packet.isRequest) { + handleRequest(packet.id, packet.value); + } else { + let callback = responseCallbacks[packet.id]; + delete responseCallbacks[packet.id]; + if (packet.value.error) callback(packet.value.error, {}); + else callback(null, packet.value); + } + }; + let buildOrContext = ({ callName, refs, options, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => { + let refCount = 0; + const buildKey = nextBuildKey++; + const requestCallbacks = {}; + const buildRefs = { + ref() { + if (++refCount === 1) { + if (refs) refs.ref(); + } + }, + unref() { + if (--refCount === 0) { + delete requestCallbacksByKey[buildKey]; + if (refs) refs.unref(); + } + } + }; + requestCallbacksByKey[buildKey] = requestCallbacks; + buildRefs.ref(); + buildOrContextImpl( + callName, + buildKey, + sendRequest, + sendResponse, + buildRefs, + streamIn, + requestCallbacks, + options, + isTTY2, + defaultWD2, + (err, res) => { + try { + callback(err, res); + } finally { + buildRefs.unref(); + } + } + ); + }; + let transform2 = ({ callName, refs, input, options, isTTY: isTTY2, fs: fs3, callback }) => { + const details = createObjectStash(); + let start = (inputPath) => { + try { + if (typeof input !== "string" && !(input instanceof Uint8Array)) + throw new Error('The input to "transform" must be a string or a Uint8Array'); + let { + flags, + mangleCache + } = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault); + let request = { + command: "transform", + flags, + inputFS: inputPath !== null, + input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input + }; + if (mangleCache) request.mangleCache = mangleCache; + sendRequest(refs, request, (error, response) => { + if (error) return callback(new Error(error), null); + let errors = replaceDetailsInMessages(response.errors, details); + let warnings = replaceDetailsInMessages(response.warnings, details); + let outstanding = 1; + let next = () => { + if (--outstanding === 0) { + let result = { + warnings, + code: response.code, + map: response.map, + mangleCache: void 0, + legalComments: void 0 + }; + if ("legalComments" in response) result.legalComments = response == null ? void 0 : response.legalComments; + if (response.mangleCache) result.mangleCache = response == null ? void 0 : response.mangleCache; + callback(null, result); + } + }; + if (errors.length > 0) return callback(failureErrorWithLog("Transform failed", errors, warnings), null); + if (response.codeFS) { + outstanding++; + fs3.readFile(response.code, (err, contents) => { + if (err !== null) { + callback(err, null); + } else { + response.code = contents; + next(); + } + }); + } + if (response.mapFS) { + outstanding++; + fs3.readFile(response.map, (err, contents) => { + if (err !== null) { + callback(err, null); + } else { + response.map = contents; + next(); + } + }); + } + next(); + }); + } catch (e) { + let flags = []; + try { + pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault); + } catch { + } + const error = extractErrorMessageV8(e, streamIn, details, void 0, ""); + sendRequest(refs, { command: "error", flags, error }, () => { + error.detail = details.load(error.detail); + callback(failureErrorWithLog("Transform failed", [error], []), null); + }); + } + }; + if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) { + let next = start; + start = () => fs3.writeFile(input, next); + } + start(null); + }; + let formatMessages2 = ({ callName, refs, messages, options, callback }) => { + if (!options) throw new Error(`Missing second argument in ${callName}() call`); + let keys = {}; + let kind = getFlag(options, keys, "kind", mustBeString); + let color = getFlag(options, keys, "color", mustBeBoolean); + let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger); + checkForInvalidFlags(options, keys, `in ${callName}() call`); + if (kind === void 0) throw new Error(`Missing "kind" in ${callName}() call`); + if (kind !== "error" && kind !== "warning") throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`); + let request = { + command: "format-msgs", + messages: sanitizeMessages(messages, "messages", null, "", terminalWidth), + isWarning: kind === "warning" + }; + if (color !== void 0) request.color = color; + if (terminalWidth !== void 0) request.terminalWidth = terminalWidth; + sendRequest(refs, request, (error, response) => { + if (error) return callback(new Error(error), null); + callback(null, response.messages); + }); + }; + let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => { + if (options === void 0) options = {}; + let keys = {}; + let color = getFlag(options, keys, "color", mustBeBoolean); + let verbose = getFlag(options, keys, "verbose", mustBeBoolean); + checkForInvalidFlags(options, keys, `in ${callName}() call`); + let request = { + command: "analyze-metafile", + metafile + }; + if (color !== void 0) request.color = color; + if (verbose !== void 0) request.verbose = verbose; + sendRequest(refs, request, (error, response) => { + if (error) return callback(new Error(error), null); + callback(null, response.result); + }); + }; + return { + readFromStdout, + afterClose, + service: { + buildOrContext, + transform: transform2, + formatMessages: formatMessages2, + analyzeMetafile: analyzeMetafile2 + } + }; +} +function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, callback) { + const details = createObjectStash(); + const isContext = callName === "context"; + const handleError = (e, pluginName) => { + const flags = []; + try { + pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault); + } catch { + } + const message = extractErrorMessageV8(e, streamIn, details, void 0, pluginName); + sendRequest(refs, { command: "error", flags, error: message }, () => { + message.detail = details.load(message.detail); + callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null); + }); + }; + let plugins; + if (typeof options === "object") { + const value = options.plugins; + if (value !== void 0) { + if (!Array.isArray(value)) return handleError(new Error(`"plugins" must be an array`), ""); + plugins = value; + } + } + if (plugins && plugins.length > 0) { + if (streamIn.isSync) return handleError(new Error("Cannot use plugins in synchronous API calls"), ""); + handlePlugins( + buildKey, + sendRequest, + sendResponse, + refs, + streamIn, + requestCallbacks, + options, + plugins, + details + ).then( + (result) => { + if (!result.ok) return handleError(result.error, result.pluginName); + try { + buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks); + } catch (e) { + handleError(e, ""); + } + }, + (e) => handleError(e, "") + ); + return; + } + try { + buildOrContextContinue(null, (result, done) => done([], []), () => { + }); + } catch (e) { + handleError(e, ""); + } + function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) { + const writeDefault = streamIn.hasFS; + const { + entries, + flags, + write, + stdinContents, + stdinResolveDir, + absWorkingDir, + nodePaths, + mangleCache + } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault); + if (write && !streamIn.hasFS) throw new Error(`The "write" option is unavailable in this environment`); + const request = { + command: "build", + key: buildKey, + entries, + flags, + write, + stdinContents, + stdinResolveDir, + absWorkingDir: absWorkingDir || defaultWD2, + nodePaths, + context: isContext + }; + if (requestPlugins) request.plugins = requestPlugins; + if (mangleCache) request.mangleCache = mangleCache; + const buildResponseToResult = (response, callback2) => { + const result = { + errors: replaceDetailsInMessages(response.errors, details), + warnings: replaceDetailsInMessages(response.warnings, details), + outputFiles: void 0, + metafile: void 0, + mangleCache: void 0 + }; + const originalErrors = result.errors.slice(); + const originalWarnings = result.warnings.slice(); + if (response.outputFiles) result.outputFiles = response.outputFiles.map(convertOutputFiles); + if (response.metafile) result.metafile = JSON.parse(response.metafile); + if (response.mangleCache) result.mangleCache = response.mangleCache; + if (response.writeToStdout !== void 0) console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, "")); + runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => { + if (originalErrors.length > 0 || onEndErrors.length > 0) { + const error = failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings)); + return callback2(error, null, onEndErrors, onEndWarnings); + } + callback2(null, result, onEndErrors, onEndWarnings); + }); + }; + let latestResultPromise; + let provideLatestResult; + if (isContext) + requestCallbacks["on-end"] = (id, request2) => new Promise((resolve) => { + buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => { + const response = { + errors: onEndErrors, + warnings: onEndWarnings + }; + if (provideLatestResult) provideLatestResult(err, result); + latestResultPromise = void 0; + provideLatestResult = void 0; + sendResponse(id, response); + resolve(); + }); + }); + sendRequest(refs, request, (error, response) => { + if (error) return callback(new Error(error), null); + if (!isContext) { + return buildResponseToResult(response, (err, res) => { + scheduleOnDisposeCallbacks(); + return callback(err, res); + }); + } + if (response.errors.length > 0) { + return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null); + } + let didDispose = false; + const result = { + rebuild: () => { + if (!latestResultPromise) latestResultPromise = new Promise((resolve, reject) => { + let settlePromise; + provideLatestResult = (err, result2) => { + if (!settlePromise) settlePromise = () => err ? reject(err) : resolve(result2); + }; + const triggerAnotherBuild = () => { + const request2 = { + command: "rebuild", + key: buildKey + }; + sendRequest(refs, request2, (error2, response2) => { + if (error2) { + reject(new Error(error2)); + } else if (settlePromise) { + settlePromise(); + } else { + triggerAnotherBuild(); + } + }); + }; + triggerAnotherBuild(); + }); + return latestResultPromise; + }, + watch: (options2 = {}) => new Promise((resolve, reject) => { + if (!streamIn.hasFS) throw new Error(`Cannot use the "watch" API in this environment`); + const keys = {}; + const delay = getFlag(options2, keys, "delay", mustBeInteger); + checkForInvalidFlags(options2, keys, `in watch() call`); + const request2 = { + command: "watch", + key: buildKey + }; + if (delay) request2.delay = delay; + sendRequest(refs, request2, (error2) => { + if (error2) reject(new Error(error2)); + else resolve(void 0); + }); + }), + serve: (options2 = {}) => new Promise((resolve, reject) => { + if (!streamIn.hasFS) throw new Error(`Cannot use the "serve" API in this environment`); + const keys = {}; + const port = getFlag(options2, keys, "port", mustBeValidPortNumber); + const host = getFlag(options2, keys, "host", mustBeString); + const servedir = getFlag(options2, keys, "servedir", mustBeString); + const keyfile = getFlag(options2, keys, "keyfile", mustBeString); + const certfile = getFlag(options2, keys, "certfile", mustBeString); + const fallback = getFlag(options2, keys, "fallback", mustBeString); + const cors = getFlag(options2, keys, "cors", mustBeObject); + const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction); + checkForInvalidFlags(options2, keys, `in serve() call`); + const request2 = { + command: "serve", + key: buildKey, + onRequest: !!onRequest + }; + if (port !== void 0) request2.port = port; + if (host !== void 0) request2.host = host; + if (servedir !== void 0) request2.servedir = servedir; + if (keyfile !== void 0) request2.keyfile = keyfile; + if (certfile !== void 0) request2.certfile = certfile; + if (fallback !== void 0) request2.fallback = fallback; + if (cors) { + const corsKeys = {}; + const origin = getFlag(cors, corsKeys, "origin", mustBeStringOrArrayOfStrings); + checkForInvalidFlags(cors, corsKeys, `on "cors" object`); + if (Array.isArray(origin)) request2.corsOrigin = origin; + else if (origin !== void 0) request2.corsOrigin = [origin]; + } + sendRequest(refs, request2, (error2, response2) => { + if (error2) return reject(new Error(error2)); + if (onRequest) { + requestCallbacks["serve-request"] = (id, request3) => { + onRequest(request3.args); + sendResponse(id, {}); + }; + } + resolve(response2); + }); + }), + cancel: () => new Promise((resolve) => { + if (didDispose) return resolve(); + const request2 = { + command: "cancel", + key: buildKey + }; + sendRequest(refs, request2, () => { + resolve(); + }); + }), + dispose: () => new Promise((resolve) => { + if (didDispose) return resolve(); + didDispose = true; + const request2 = { + command: "dispose", + key: buildKey + }; + sendRequest(refs, request2, () => { + resolve(); + scheduleOnDisposeCallbacks(); + refs.unref(); + }); + }) + }; + refs.ref(); + callback(null, result); + }); + } +} +var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => { + let onStartCallbacks = []; + let onEndCallbacks = []; + let onResolveCallbacks = {}; + let onLoadCallbacks = {}; + let onDisposeCallbacks = []; + let nextCallbackID = 0; + let i = 0; + let requestPlugins = []; + let isSetupDone = false; + plugins = [...plugins]; + for (let item of plugins) { + let keys = {}; + if (typeof item !== "object") throw new Error(`Plugin at index ${i} must be an object`); + const name = getFlag(item, keys, "name", mustBeString); + if (typeof name !== "string" || name === "") throw new Error(`Plugin at index ${i} is missing a name`); + try { + let setup = getFlag(item, keys, "setup", mustBeFunction); + if (typeof setup !== "function") throw new Error(`Plugin is missing a setup function`); + checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`); + let plugin = { + name, + onStart: false, + onEnd: false, + onResolve: [], + onLoad: [] + }; + i++; + let resolve = (path3, options = {}) => { + if (!isSetupDone) throw new Error('Cannot call "resolve" before plugin setup has completed'); + if (typeof path3 !== "string") throw new Error(`The path to resolve must be a string`); + let keys2 = /* @__PURE__ */ Object.create(null); + let pluginName = getFlag(options, keys2, "pluginName", mustBeString); + let importer = getFlag(options, keys2, "importer", mustBeString); + let namespace = getFlag(options, keys2, "namespace", mustBeString); + let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString); + let kind = getFlag(options, keys2, "kind", mustBeString); + let pluginData = getFlag(options, keys2, "pluginData", canBeAnything); + let importAttributes = getFlag(options, keys2, "with", mustBeObject); + checkForInvalidFlags(options, keys2, "in resolve() call"); + return new Promise((resolve2, reject) => { + const request = { + command: "resolve", + path: path3, + key: buildKey, + pluginName: name + }; + if (pluginName != null) request.pluginName = pluginName; + if (importer != null) request.importer = importer; + if (namespace != null) request.namespace = namespace; + if (resolveDir != null) request.resolveDir = resolveDir; + if (kind != null) request.kind = kind; + else throw new Error(`Must specify "kind" when calling "resolve"`); + if (pluginData != null) request.pluginData = details.store(pluginData); + if (importAttributes != null) request.with = sanitizeStringMap(importAttributes, "with"); + sendRequest(refs, request, (error, response) => { + if (error !== null) reject(new Error(error)); + else resolve2({ + errors: replaceDetailsInMessages(response.errors, details), + warnings: replaceDetailsInMessages(response.warnings, details), + path: response.path, + external: response.external, + sideEffects: response.sideEffects, + namespace: response.namespace, + suffix: response.suffix, + pluginData: details.load(response.pluginData) + }); + }); + }); + }; + let promise = setup({ + initialOptions, + resolve, + onStart(callback) { + let registeredText = `This error came from the "onStart" callback registered here:`; + let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onStart"); + onStartCallbacks.push({ name, callback, note: registeredNote }); + plugin.onStart = true; + }, + onEnd(callback) { + let registeredText = `This error came from the "onEnd" callback registered here:`; + let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onEnd"); + onEndCallbacks.push({ name, callback, note: registeredNote }); + plugin.onEnd = true; + }, + onResolve(options, callback) { + let registeredText = `This error came from the "onResolve" callback registered here:`; + let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve"); + let keys2 = {}; + let filter = getFlag(options, keys2, "filter", mustBeRegExp); + let namespace = getFlag(options, keys2, "namespace", mustBeString); + checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`); + if (filter == null) throw new Error(`onResolve() call is missing a filter`); + let id = nextCallbackID++; + onResolveCallbacks[id] = { name, callback, note: registeredNote }; + plugin.onResolve.push({ id, filter: jsRegExpToGoRegExp(filter), namespace: namespace || "" }); + }, + onLoad(options, callback) { + let registeredText = `This error came from the "onLoad" callback registered here:`; + let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad"); + let keys2 = {}; + let filter = getFlag(options, keys2, "filter", mustBeRegExp); + let namespace = getFlag(options, keys2, "namespace", mustBeString); + checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`); + if (filter == null) throw new Error(`onLoad() call is missing a filter`); + let id = nextCallbackID++; + onLoadCallbacks[id] = { name, callback, note: registeredNote }; + plugin.onLoad.push({ id, filter: jsRegExpToGoRegExp(filter), namespace: namespace || "" }); + }, + onDispose(callback) { + onDisposeCallbacks.push(callback); + }, + esbuild: streamIn.esbuild + }); + if (promise) await promise; + requestPlugins.push(plugin); + } catch (e) { + return { ok: false, error: e, pluginName: name }; + } + } + requestCallbacks["on-start"] = async (id, request) => { + details.clear(); + let response = { errors: [], warnings: [] }; + await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => { + try { + let result = await callback(); + if (result != null) { + if (typeof result !== "object") throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`); + let keys = {}; + let errors = getFlag(result, keys, "errors", mustBeArray); + let warnings = getFlag(result, keys, "warnings", mustBeArray); + checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`); + if (errors != null) response.errors.push(...sanitizeMessages(errors, "errors", details, name, void 0)); + if (warnings != null) response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, void 0)); + } + } catch (e) { + response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name)); + } + })); + sendResponse(id, response); + }; + requestCallbacks["on-resolve"] = async (id, request) => { + let response = {}, name = "", callback, note; + for (let id2 of request.ids) { + try { + ({ name, callback, note } = onResolveCallbacks[id2]); + let result = await callback({ + path: request.path, + importer: request.importer, + namespace: request.namespace, + resolveDir: request.resolveDir, + kind: request.kind, + pluginData: details.load(request.pluginData), + with: request.with + }); + if (result != null) { + if (typeof result !== "object") throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`); + let keys = {}; + let pluginName = getFlag(result, keys, "pluginName", mustBeString); + let path3 = getFlag(result, keys, "path", mustBeString); + let namespace = getFlag(result, keys, "namespace", mustBeString); + let suffix = getFlag(result, keys, "suffix", mustBeString); + let external = getFlag(result, keys, "external", mustBeBoolean); + let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean); + let pluginData = getFlag(result, keys, "pluginData", canBeAnything); + let errors = getFlag(result, keys, "errors", mustBeArray); + let warnings = getFlag(result, keys, "warnings", mustBeArray); + let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings); + let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings); + checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`); + response.id = id2; + if (pluginName != null) response.pluginName = pluginName; + if (path3 != null) response.path = path3; + if (namespace != null) response.namespace = namespace; + if (suffix != null) response.suffix = suffix; + if (external != null) response.external = external; + if (sideEffects != null) response.sideEffects = sideEffects; + if (pluginData != null) response.pluginData = details.store(pluginData); + if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0); + if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0); + if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles"); + if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs"); + break; + } + } catch (e) { + response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] }; + break; + } + } + sendResponse(id, response); + }; + requestCallbacks["on-load"] = async (id, request) => { + let response = {}, name = "", callback, note; + for (let id2 of request.ids) { + try { + ({ name, callback, note } = onLoadCallbacks[id2]); + let result = await callback({ + path: request.path, + namespace: request.namespace, + suffix: request.suffix, + pluginData: details.load(request.pluginData), + with: request.with + }); + if (result != null) { + if (typeof result !== "object") throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`); + let keys = {}; + let pluginName = getFlag(result, keys, "pluginName", mustBeString); + let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array); + let resolveDir = getFlag(result, keys, "resolveDir", mustBeString); + let pluginData = getFlag(result, keys, "pluginData", canBeAnything); + let loader = getFlag(result, keys, "loader", mustBeString); + let errors = getFlag(result, keys, "errors", mustBeArray); + let warnings = getFlag(result, keys, "warnings", mustBeArray); + let watchFiles = getFlag(result, keys, "watchFiles", mustBeArrayOfStrings); + let watchDirs = getFlag(result, keys, "watchDirs", mustBeArrayOfStrings); + checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`); + response.id = id2; + if (pluginName != null) response.pluginName = pluginName; + if (contents instanceof Uint8Array) response.contents = contents; + else if (contents != null) response.contents = encodeUTF8(contents); + if (resolveDir != null) response.resolveDir = resolveDir; + if (pluginData != null) response.pluginData = details.store(pluginData); + if (loader != null) response.loader = loader; + if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0); + if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0); + if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles"); + if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs"); + break; + } + } catch (e) { + response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] }; + break; + } + } + sendResponse(id, response); + }; + let runOnEndCallbacks = (result, done) => done([], []); + if (onEndCallbacks.length > 0) { + runOnEndCallbacks = (result, done) => { + (async () => { + const onEndErrors = []; + const onEndWarnings = []; + for (const { name, callback, note } of onEndCallbacks) { + let newErrors; + let newWarnings; + try { + const value = await callback(result); + if (value != null) { + if (typeof value !== "object") throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`); + let keys = {}; + let errors = getFlag(value, keys, "errors", mustBeArray); + let warnings = getFlag(value, keys, "warnings", mustBeArray); + checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`); + if (errors != null) newErrors = sanitizeMessages(errors, "errors", details, name, void 0); + if (warnings != null) newWarnings = sanitizeMessages(warnings, "warnings", details, name, void 0); + } + } catch (e) { + newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)]; + } + if (newErrors) { + onEndErrors.push(...newErrors); + try { + result.errors.push(...newErrors); + } catch { + } + } + if (newWarnings) { + onEndWarnings.push(...newWarnings); + try { + result.warnings.push(...newWarnings); + } catch { + } + } + } + done(onEndErrors, onEndWarnings); + })(); + }; + } + let scheduleOnDisposeCallbacks = () => { + for (const cb of onDisposeCallbacks) { + setTimeout(() => cb(), 0); + } + }; + isSetupDone = true; + return { + ok: true, + requestPlugins, + runOnEndCallbacks, + scheduleOnDisposeCallbacks + }; +}; +function createObjectStash() { + const map = /* @__PURE__ */ new Map(); + let nextID = 0; + return { + clear() { + map.clear(); + }, + load(id) { + return map.get(id); + }, + store(value) { + if (value === void 0) return -1; + const id = nextID++; + map.set(id, value); + return id; + } + }; +} +function extractCallerV8(e, streamIn, ident) { + let note; + let tried = false; + return () => { + if (tried) return note; + tried = true; + try { + let lines = (e.stack + "").split("\n"); + lines.splice(1, 1); + let location = parseStackLinesV8(streamIn, lines, ident); + if (location) { + note = { text: e.message, location }; + return note; + } + } catch { + } + }; +} +function extractErrorMessageV8(e, streamIn, stash, note, pluginName) { + let text = "Internal error"; + let location = null; + try { + text = (e && e.message || e) + ""; + } catch { + } + try { + location = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), ""); + } catch { + } + return { id: "", pluginName, text, location, notes: note ? [note] : [], detail: stash ? stash.store(e) : -1 }; +} +function parseStackLinesV8(streamIn, lines, ident) { + let at = " at "; + if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) { + for (let i = 1; i < lines.length; i++) { + let line = lines[i]; + if (!line.startsWith(at)) continue; + line = line.slice(at.length); + while (true) { + let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line); + if (match) { + line = match[1]; + continue; + } + match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line); + if (match) { + line = match[1]; + continue; + } + match = /^(\S+):(\d+):(\d+)$/.exec(line); + if (match) { + let contents; + try { + contents = streamIn.readFileSync(match[1], "utf8"); + } catch { + break; + } + let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || ""; + let column = +match[3] - 1; + let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0; + return { + file: match[1], + namespace: "file", + line: +match[2], + column: encodeUTF8(lineText.slice(0, column)).length, + length: encodeUTF8(lineText.slice(column, column + length)).length, + lineText: lineText + "\n" + lines.slice(1).join("\n"), + suggestion: "" + }; + } + break; + } + } + } + return null; +} +function failureErrorWithLog(text, errors, warnings) { + let limit = 5; + text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e, i) => { + if (i === limit) return "\n..."; + if (!e.location) return ` +error: ${e.text}`; + let { file, line, column } = e.location; + let pluginText = e.pluginName ? `[plugin: ${e.pluginName}] ` : ""; + return ` +${file}:${line}:${column}: ERROR: ${pluginText}${e.text}`; + }).join(""); + let error = new Error(text); + for (const [key, value] of [["errors", errors], ["warnings", warnings]]) { + Object.defineProperty(error, key, { + configurable: true, + enumerable: true, + get: () => value, + set: (value2) => Object.defineProperty(error, key, { + configurable: true, + enumerable: true, + value: value2 + }) + }); + } + return error; +} +function replaceDetailsInMessages(messages, stash) { + for (const message of messages) { + message.detail = stash.load(message.detail); + } + return messages; +} +function sanitizeLocation(location, where, terminalWidth) { + if (location == null) return null; + let keys = {}; + let file = getFlag(location, keys, "file", mustBeString); + let namespace = getFlag(location, keys, "namespace", mustBeString); + let line = getFlag(location, keys, "line", mustBeInteger); + let column = getFlag(location, keys, "column", mustBeInteger); + let length = getFlag(location, keys, "length", mustBeInteger); + let lineText = getFlag(location, keys, "lineText", mustBeString); + let suggestion = getFlag(location, keys, "suggestion", mustBeString); + checkForInvalidFlags(location, keys, where); + if (lineText) { + const relevantASCII = lineText.slice( + 0, + (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80) + ); + if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) { + lineText = relevantASCII; + } + } + return { + file: file || "", + namespace: namespace || "", + line: line || 0, + column: column || 0, + length: length || 0, + lineText: lineText || "", + suggestion: suggestion || "" + }; +} +function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) { + let messagesClone = []; + let index = 0; + for (const message of messages) { + let keys = {}; + let id = getFlag(message, keys, "id", mustBeString); + let pluginName = getFlag(message, keys, "pluginName", mustBeString); + let text = getFlag(message, keys, "text", mustBeString); + let location = getFlag(message, keys, "location", mustBeObjectOrNull); + let notes = getFlag(message, keys, "notes", mustBeArray); + let detail = getFlag(message, keys, "detail", canBeAnything); + let where = `in element ${index} of "${property}"`; + checkForInvalidFlags(message, keys, where); + let notesClone = []; + if (notes) { + for (const note of notes) { + let noteKeys = {}; + let noteText = getFlag(note, noteKeys, "text", mustBeString); + let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull); + checkForInvalidFlags(note, noteKeys, where); + notesClone.push({ + text: noteText || "", + location: sanitizeLocation(noteLocation, where, terminalWidth) + }); + } + } + messagesClone.push({ + id: id || "", + pluginName: pluginName || fallbackPluginName, + text: text || "", + location: sanitizeLocation(location, where, terminalWidth), + notes: notesClone, + detail: stash ? stash.store(detail) : -1 + }); + index++; + } + return messagesClone; +} +function sanitizeStringArray(values, property) { + const result = []; + for (const value of values) { + if (typeof value !== "string") throw new Error(`${quote(property)} must be an array of strings`); + result.push(value); + } + return result; +} +function sanitizeStringMap(map, property) { + const result = /* @__PURE__ */ Object.create(null); + for (const key in map) { + const value = map[key]; + if (typeof value !== "string") throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`); + result[key] = value; + } + return result; +} +function convertOutputFiles({ path: path3, contents, hash }) { + let text = null; + return { + path: path3, + contents, + hash, + get text() { + const binary = this.contents; + if (text === null || binary !== contents) { + contents = binary; + text = decodeUTF8(binary); + } + return text; + } + }; +} +function jsRegExpToGoRegExp(regexp) { + let result = regexp.source; + if (regexp.flags) result = `(?${regexp.flags})${result}`; + return result; +} + +// lib/npm/node-platform.ts +var fs = require("fs"); +var os = require("os"); +var path = require("path"); +var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH; +var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild"; +var packageDarwin_arm64 = "@esbuild/darwin-arm64"; +var packageDarwin_x64 = "@esbuild/darwin-x64"; +var knownWindowsPackages = { + "win32 arm64 LE": "@esbuild/win32-arm64", + "win32 ia32 LE": "@esbuild/win32-ia32", + "win32 x64 LE": "@esbuild/win32-x64" +}; +var knownUnixlikePackages = { + "aix ppc64 BE": "@esbuild/aix-ppc64", + "android arm64 LE": "@esbuild/android-arm64", + "darwin arm64 LE": "@esbuild/darwin-arm64", + "darwin x64 LE": "@esbuild/darwin-x64", + "freebsd arm64 LE": "@esbuild/freebsd-arm64", + "freebsd x64 LE": "@esbuild/freebsd-x64", + "linux arm LE": "@esbuild/linux-arm", + "linux arm64 LE": "@esbuild/linux-arm64", + "linux ia32 LE": "@esbuild/linux-ia32", + "linux mips64el LE": "@esbuild/linux-mips64el", + "linux ppc64 LE": "@esbuild/linux-ppc64", + "linux riscv64 LE": "@esbuild/linux-riscv64", + "linux s390x BE": "@esbuild/linux-s390x", + "linux x64 LE": "@esbuild/linux-x64", + "linux loong64 LE": "@esbuild/linux-loong64", + "netbsd arm64 LE": "@esbuild/netbsd-arm64", + "netbsd x64 LE": "@esbuild/netbsd-x64", + "openbsd arm64 LE": "@esbuild/openbsd-arm64", + "openbsd x64 LE": "@esbuild/openbsd-x64", + "sunos x64 LE": "@esbuild/sunos-x64" +}; +var knownWebAssemblyFallbackPackages = { + "android arm LE": "@esbuild/android-arm", + "android x64 LE": "@esbuild/android-x64", + "openharmony arm64 LE": "@esbuild/openharmony-arm64" +}; +function pkgAndSubpathForCurrentPlatform() { + let pkg; + let subpath; + let isWASM = false; + let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`; + if (platformKey in knownWindowsPackages) { + pkg = knownWindowsPackages[platformKey]; + subpath = "esbuild.exe"; + } else if (platformKey in knownUnixlikePackages) { + pkg = knownUnixlikePackages[platformKey]; + subpath = "bin/esbuild"; + } else if (platformKey in knownWebAssemblyFallbackPackages) { + pkg = knownWebAssemblyFallbackPackages[platformKey]; + subpath = "bin/esbuild"; + isWASM = true; + } else { + throw new Error(`Unsupported platform: ${platformKey}`); + } + return { pkg, subpath, isWASM }; +} +function pkgForSomeOtherPlatform() { + const libMainJS = require.resolve("esbuild"); + const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS))); + if (path.basename(nodeModulesDirectory) === "node_modules") { + for (const unixKey in knownUnixlikePackages) { + try { + const pkg = knownUnixlikePackages[unixKey]; + if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg; + } catch { + } + } + for (const windowsKey in knownWindowsPackages) { + try { + const pkg = knownWindowsPackages[windowsKey]; + if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg; + } catch { + } + } + } + return null; +} +function downloadedBinPath(pkg, subpath) { + const esbuildLibDir = path.dirname(require.resolve("esbuild")); + return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`); +} +function generateBinPath() { + if (isValidBinaryPath(ESBUILD_BINARY_PATH)) { + if (!fs.existsSync(ESBUILD_BINARY_PATH)) { + console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`); + } else { + return { binPath: ESBUILD_BINARY_PATH, isWASM: false }; + } + } + const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform(); + let binPath; + try { + binPath = require.resolve(`${pkg}/${subpath}`); + } catch (e) { + binPath = downloadedBinPath(pkg, subpath); + if (!fs.existsSync(binPath)) { + try { + require.resolve(pkg); + } catch { + const otherPkg = pkgForSomeOtherPlatform(); + if (otherPkg) { + let suggestions = ` +Specifically the "${otherPkg}" package is present but this platform +needs the "${pkg}" package instead. People often get into this +situation by installing esbuild on Windows or macOS and copying "node_modules" +into a Docker image that runs Linux, or by copying "node_modules" between +Windows and WSL environments. + +If you are installing with npm, you can try not copying the "node_modules" +directory when you copy the files over, and running "npm ci" or "npm install" +on the destination platform after the copy. Or you could consider using yarn +instead of npm which has built-in support for installing a package on multiple +platforms simultaneously. + +If you are installing with yarn, you can try listing both this platform and the +other platform in your ".yarnrc.yml" file using the "supportedArchitectures" +feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures +Keep in mind that this means multiple copies of esbuild will be present. +`; + if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) { + suggestions = ` +Specifically the "${otherPkg}" package is present but this platform +needs the "${pkg}" package instead. People often get into this +situation by installing esbuild with npm running inside of Rosetta 2 and then +trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta +2 is Apple's on-the-fly x86_64-to-arm64 translation service). + +If you are installing with npm, you can try ensuring that both npm and node are +not running under Rosetta 2 and then reinstalling esbuild. This likely involves +changing how you installed npm and/or node. For example, installing node with +the universal installer here should work: https://nodejs.org/en/download/. Or +you could consider using yarn instead of npm which has built-in support for +installing a package on multiple platforms simultaneously. + +If you are installing with yarn, you can try listing both "arm64" and "x64" +in your ".yarnrc.yml" file using the "supportedArchitectures" feature: +https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures +Keep in mind that this means multiple copies of esbuild will be present. +`; + } + throw new Error(` +You installed esbuild for another platform than the one you're currently using. +This won't work because esbuild is written with native code and needs to +install a platform-specific binary executable. +${suggestions} +Another alternative is to use the "esbuild-wasm" package instead, which works +the same way on all platforms. But it comes with a heavy performance cost and +can sometimes be 10x slower than the "esbuild" package, so you may also not +want to do that. +`); + } + throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild. + +If you are installing esbuild with npm, make sure that you don't specify the +"--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature +of "package.json" is used by esbuild to install the correct binary executable +for your current platform.`); + } + throw e; + } + } + if (/\.zip\//.test(binPath)) { + let pnpapi; + try { + pnpapi = require("pnpapi"); + } catch (e) { + } + if (pnpapi) { + const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation; + const binTargetPath = path.join( + root, + "node_modules", + ".cache", + "esbuild", + `pnpapi-${pkg.replace("/", "-")}-${"0.27.2"}-${path.basename(subpath)}` + ); + if (!fs.existsSync(binTargetPath)) { + fs.mkdirSync(path.dirname(binTargetPath), { recursive: true }); + fs.copyFileSync(binPath, binTargetPath); + fs.chmodSync(binTargetPath, 493); + } + return { binPath: binTargetPath, isWASM }; + } + } + return { binPath, isWASM }; +} + +// lib/npm/node.ts +var child_process = require("child_process"); +var crypto = require("crypto"); +var path2 = require("path"); +var fs2 = require("fs"); +var os2 = require("os"); +var tty = require("tty"); +var worker_threads; +if (process.env.ESBUILD_WORKER_THREADS !== "0") { + try { + worker_threads = require("worker_threads"); + } catch { + } + let [major, minor] = process.versions.node.split("."); + if ( + // { + if ((!ESBUILD_BINARY_PATH || false) && (path2.basename(__filename) !== "main.js" || path2.basename(__dirname) !== "lib")) { + throw new Error( + `The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle. + +More information: The file containing the code for esbuild's JavaScript API (${__filename}) does not appear to be inside the esbuild package on the file system, which usually means that the esbuild package was bundled into another file. This is problematic because the API needs to run a binary executable inside the esbuild package which is located using a relative path from the API code to the executable. If the esbuild package is bundled, the relative path will be incorrect and the executable won't be found.` + ); + } + if (false) { + return ["node", [path2.join(__dirname, "..", "bin", "esbuild")]]; + } else { + const { binPath, isWASM } = generateBinPath(); + if (isWASM) { + return ["node", [binPath]]; + } else { + return [binPath, []]; + } + } +}; +var isTTY = () => tty.isatty(2); +var fsSync = { + readFile(tempFile, callback) { + try { + let contents = fs2.readFileSync(tempFile, "utf8"); + try { + fs2.unlinkSync(tempFile); + } catch { + } + callback(null, contents); + } catch (err) { + callback(err, null); + } + }, + writeFile(contents, callback) { + try { + let tempFile = randomFileName(); + fs2.writeFileSync(tempFile, contents); + callback(tempFile); + } catch { + callback(null); + } + } +}; +var fsAsync = { + readFile(tempFile, callback) { + try { + fs2.readFile(tempFile, "utf8", (err, contents) => { + try { + fs2.unlink(tempFile, () => callback(err, contents)); + } catch { + callback(err, contents); + } + }); + } catch (err) { + callback(err, null); + } + }, + writeFile(contents, callback) { + try { + let tempFile = randomFileName(); + fs2.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile)); + } catch { + callback(null); + } + } +}; +var version = "0.27.2"; +var build = (options) => ensureServiceIsRunning().build(options); +var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions); +var transform = (input, options) => ensureServiceIsRunning().transform(input, options); +var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options); +var analyzeMetafile = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options); +var buildSync = (options) => { + if (worker_threads && !isInternalWorkerThread) { + if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads); + return workerThreadService.buildSync(options); + } + let result; + runServiceSync((service) => service.buildOrContext({ + callName: "buildSync", + refs: null, + options, + isTTY: isTTY(), + defaultWD, + callback: (err, res) => { + if (err) throw err; + result = res; + } + })); + return result; +}; +var transformSync = (input, options) => { + if (worker_threads && !isInternalWorkerThread) { + if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads); + return workerThreadService.transformSync(input, options); + } + let result; + runServiceSync((service) => service.transform({ + callName: "transformSync", + refs: null, + input, + options: options || {}, + isTTY: isTTY(), + fs: fsSync, + callback: (err, res) => { + if (err) throw err; + result = res; + } + })); + return result; +}; +var formatMessagesSync = (messages, options) => { + if (worker_threads && !isInternalWorkerThread) { + if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads); + return workerThreadService.formatMessagesSync(messages, options); + } + let result; + runServiceSync((service) => service.formatMessages({ + callName: "formatMessagesSync", + refs: null, + messages, + options, + callback: (err, res) => { + if (err) throw err; + result = res; + } + })); + return result; +}; +var analyzeMetafileSync = (metafile, options) => { + if (worker_threads && !isInternalWorkerThread) { + if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads); + return workerThreadService.analyzeMetafileSync(metafile, options); + } + let result; + runServiceSync((service) => service.analyzeMetafile({ + callName: "analyzeMetafileSync", + refs: null, + metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile), + options, + callback: (err, res) => { + if (err) throw err; + result = res; + } + })); + return result; +}; +var stop = () => { + if (stopService) stopService(); + if (workerThreadService) workerThreadService.stop(); + return Promise.resolve(); +}; +var initializeWasCalled = false; +var initialize = (options) => { + options = validateInitializeOptions(options || {}); + if (options.wasmURL) throw new Error(`The "wasmURL" option only works in the browser`); + if (options.wasmModule) throw new Error(`The "wasmModule" option only works in the browser`); + if (options.worker) throw new Error(`The "worker" option only works in the browser`); + if (initializeWasCalled) throw new Error('Cannot call "initialize" more than once'); + ensureServiceIsRunning(); + initializeWasCalled = true; + return Promise.resolve(); +}; +var defaultWD = process.cwd(); +var longLivedService; +var stopService; +var ensureServiceIsRunning = () => { + if (longLivedService) return longLivedService; + let [command, args] = esbuildCommandAndArgs(); + let child = child_process.spawn(command, args.concat(`--service=${"0.27.2"}`, "--ping"), { + windowsHide: true, + stdio: ["pipe", "pipe", "inherit"], + cwd: defaultWD + }); + let { readFromStdout, afterClose, service } = createChannel({ + writeToStdin(bytes) { + child.stdin.write(bytes, (err) => { + if (err) afterClose(err); + }); + }, + readFileSync: fs2.readFileSync, + isSync: false, + hasFS: true, + esbuild: node_exports + }); + child.stdin.on("error", afterClose); + child.on("error", afterClose); + const stdin = child.stdin; + const stdout = child.stdout; + stdout.on("data", readFromStdout); + stdout.on("end", afterClose); + stopService = () => { + stdin.destroy(); + stdout.destroy(); + child.kill(); + initializeWasCalled = false; + longLivedService = void 0; + stopService = void 0; + }; + let refCount = 0; + child.unref(); + if (stdin.unref) { + stdin.unref(); + } + if (stdout.unref) { + stdout.unref(); + } + const refs = { + ref() { + if (++refCount === 1) child.ref(); + }, + unref() { + if (--refCount === 0) child.unref(); + } + }; + longLivedService = { + build: (options) => new Promise((resolve, reject) => { + service.buildOrContext({ + callName: "build", + refs, + options, + isTTY: isTTY(), + defaultWD, + callback: (err, res) => err ? reject(err) : resolve(res) + }); + }), + context: (options) => new Promise((resolve, reject) => service.buildOrContext({ + callName: "context", + refs, + options, + isTTY: isTTY(), + defaultWD, + callback: (err, res) => err ? reject(err) : resolve(res) + })), + transform: (input, options) => new Promise((resolve, reject) => service.transform({ + callName: "transform", + refs, + input, + options: options || {}, + isTTY: isTTY(), + fs: fsAsync, + callback: (err, res) => err ? reject(err) : resolve(res) + })), + formatMessages: (messages, options) => new Promise((resolve, reject) => service.formatMessages({ + callName: "formatMessages", + refs, + messages, + options, + callback: (err, res) => err ? reject(err) : resolve(res) + })), + analyzeMetafile: (metafile, options) => new Promise((resolve, reject) => service.analyzeMetafile({ + callName: "analyzeMetafile", + refs, + metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile), + options, + callback: (err, res) => err ? reject(err) : resolve(res) + })) + }; + return longLivedService; +}; +var runServiceSync = (callback) => { + let [command, args] = esbuildCommandAndArgs(); + let stdin = new Uint8Array(); + let { readFromStdout, afterClose, service } = createChannel({ + writeToStdin(bytes) { + if (stdin.length !== 0) throw new Error("Must run at most one command"); + stdin = bytes; + }, + isSync: true, + hasFS: true, + esbuild: node_exports + }); + callback(service); + let stdout = child_process.execFileSync(command, args.concat(`--service=${"0.27.2"}`), { + cwd: defaultWD, + windowsHide: true, + input: stdin, + // We don't know how large the output could be. If it's too large, the + // command will fail with ENOBUFS. Reserve 16mb for now since that feels + // like it should be enough. Also allow overriding this with an environment + // variable. + maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024 + }); + readFromStdout(stdout); + afterClose(null); +}; +var randomFileName = () => { + return path2.join(os2.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`); +}; +var workerThreadService = null; +var startWorkerThreadService = (worker_threads2) => { + let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel(); + let worker = new worker_threads2.Worker(__filename, { + workerData: { workerPort, defaultWD, esbuildVersion: "0.27.2" }, + transferList: [workerPort], + // From node's documentation: https://nodejs.org/api/worker_threads.html + // + // Take care when launching worker threads from preload scripts (scripts loaded + // and run using the `-r` command line flag). Unless the `execArgv` option is + // explicitly set, new Worker threads automatically inherit the command line flags + // from the running process and will preload the same preload scripts as the main + // thread. If the preload script unconditionally launches a worker thread, every + // thread spawned will spawn another until the application crashes. + // + execArgv: [] + }); + let nextID = 0; + let fakeBuildError = (text) => { + let error = new Error(`Build failed with 1 error: +error: ${text}`); + let errors = [{ id: "", pluginName: "", text, location: null, notes: [], detail: void 0 }]; + error.errors = errors; + error.warnings = []; + return error; + }; + let validateBuildSyncOptions = (options) => { + if (!options) return; + let plugins = options.plugins; + if (plugins && plugins.length > 0) throw fakeBuildError(`Cannot use plugins in synchronous API calls`); + }; + let applyProperties = (object, properties) => { + for (let key in properties) { + object[key] = properties[key]; + } + }; + let runCallSync = (command, args) => { + let id = nextID++; + let sharedBuffer = new SharedArrayBuffer(8); + let sharedBufferView = new Int32Array(sharedBuffer); + let msg = { sharedBuffer, id, command, args }; + worker.postMessage(msg); + let status = Atomics.wait(sharedBufferView, 0, 0); + if (status !== "ok" && status !== "not-equal") throw new Error("Internal error: Atomics.wait() failed: " + status); + let { message: { id: id2, resolve, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort); + if (id !== id2) throw new Error(`Internal error: Expected id ${id} but got id ${id2}`); + if (reject) { + applyProperties(reject, properties); + throw reject; + } + return resolve; + }; + worker.unref(); + return { + buildSync(options) { + validateBuildSyncOptions(options); + return runCallSync("build", [options]); + }, + transformSync(input, options) { + return runCallSync("transform", [input, options]); + }, + formatMessagesSync(messages, options) { + return runCallSync("formatMessages", [messages, options]); + }, + analyzeMetafileSync(metafile, options) { + return runCallSync("analyzeMetafile", [metafile, options]); + }, + stop() { + worker.terminate(); + workerThreadService = null; + } + }; +}; +var startSyncServiceWorker = () => { + let workerPort = worker_threads.workerData.workerPort; + let parentPort = worker_threads.parentPort; + let extractProperties = (object) => { + let properties = {}; + if (object && typeof object === "object") { + for (let key in object) { + properties[key] = object[key]; + } + } + return properties; + }; + try { + let service = ensureServiceIsRunning(); + defaultWD = worker_threads.workerData.defaultWD; + parentPort.on("message", (msg) => { + (async () => { + let { sharedBuffer, id, command, args } = msg; + let sharedBufferView = new Int32Array(sharedBuffer); + try { + switch (command) { + case "build": + workerPort.postMessage({ id, resolve: await service.build(args[0]) }); + break; + case "transform": + workerPort.postMessage({ id, resolve: await service.transform(args[0], args[1]) }); + break; + case "formatMessages": + workerPort.postMessage({ id, resolve: await service.formatMessages(args[0], args[1]) }); + break; + case "analyzeMetafile": + workerPort.postMessage({ id, resolve: await service.analyzeMetafile(args[0], args[1]) }); + break; + default: + throw new Error(`Invalid command: ${command}`); + } + } catch (reject) { + workerPort.postMessage({ id, reject, properties: extractProperties(reject) }); + } + Atomics.add(sharedBufferView, 0, 1); + Atomics.notify(sharedBufferView, 0, Infinity); + })(); + }); + } catch (reject) { + parentPort.on("message", (msg) => { + let { sharedBuffer, id } = msg; + let sharedBufferView = new Int32Array(sharedBuffer); + workerPort.postMessage({ id, reject, properties: extractProperties(reject) }); + Atomics.add(sharedBufferView, 0, 1); + Atomics.notify(sharedBufferView, 0, Infinity); + }); + } +}; +if (isInternalWorkerThread) { + startSyncServiceWorker(); +} +var node_default = node_exports; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + analyzeMetafile, + analyzeMetafileSync, + build, + buildSync, + context, + formatMessages, + formatMessagesSync, + initialize, + stop, + transform, + transformSync, + version +}); diff --git a/browser/base/content/assistant/ui-preact/node_modules/esbuild/package.json b/browser/base/content/assistant/ui-preact/node_modules/esbuild/package.json new file mode 100644 index 0000000000000..dec92c2fbe2ae --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/esbuild/package.json @@ -0,0 +1,49 @@ +{ + "name": "esbuild", + "version": "0.27.2", + "description": "An extremely fast JavaScript and CSS bundler and minifier.", + "repository": { + "type": "git", + "url": "git+https://github.com/evanw/esbuild.git" + }, + "scripts": { + "postinstall": "node install.js" + }, + "main": "lib/main.js", + "types": "lib/main.d.ts", + "engines": { + "node": ">=18" + }, + "bin": { + "esbuild": "bin/esbuild" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.2", + "@esbuild/android-arm": "0.27.2", + "@esbuild/android-arm64": "0.27.2", + "@esbuild/android-x64": "0.27.2", + "@esbuild/darwin-arm64": "0.27.2", + "@esbuild/darwin-x64": "0.27.2", + "@esbuild/freebsd-arm64": "0.27.2", + "@esbuild/freebsd-x64": "0.27.2", + "@esbuild/linux-arm": "0.27.2", + "@esbuild/linux-arm64": "0.27.2", + "@esbuild/linux-ia32": "0.27.2", + "@esbuild/linux-loong64": "0.27.2", + "@esbuild/linux-mips64el": "0.27.2", + "@esbuild/linux-ppc64": "0.27.2", + "@esbuild/linux-riscv64": "0.27.2", + "@esbuild/linux-s390x": "0.27.2", + "@esbuild/linux-x64": "0.27.2", + "@esbuild/netbsd-arm64": "0.27.2", + "@esbuild/netbsd-x64": "0.27.2", + "@esbuild/openbsd-arm64": "0.27.2", + "@esbuild/openbsd-x64": "0.27.2", + "@esbuild/openharmony-arm64": "0.27.2", + "@esbuild/sunos-x64": "0.27.2", + "@esbuild/win32-arm64": "0.27.2", + "@esbuild/win32-ia32": "0.27.2", + "@esbuild/win32-x64": "0.27.2" + }, + "license": "MIT" +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/LICENSE b/browser/base/content/assistant/ui-preact/node_modules/preact/LICENSE new file mode 100644 index 0000000000000..da5389a93cbaa --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015-present Jason Miller + +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/browser/base/content/assistant/ui-preact/node_modules/preact/README.md b/browser/base/content/assistant/ui-preact/node_modules/preact/README.md new file mode 100644 index 0000000000000..65e9e0ddc8300 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/README.md @@ -0,0 +1,185 @@ +

    + + +![Preact](https://raw.githubusercontent.com/preactjs/preact/8b0bcc927995c188eca83cba30fbc83491cc0b2f/logo.svg?sanitize=true 'Preact') + + +

    +

    Fast 3kB alternative to React with the same modern API.

    + +**All the power of Virtual DOM components, without the overhead:** + +- Familiar React API & patterns: ES6 Class, hooks, and Functional Components +- Extensive React compatibility via a simple [preact/compat] alias +- Everything you need: JSX, VDOM, [DevTools], HMR, SSR. +- Highly optimized diff algorithm and seamless hydration from Server Side Rendering +- Supports all modern browsers and IE11 +- Transparent asynchronous rendering with a pluggable scheduler + +### 💁 More information at the [Preact Website ➞](https://preactjs.com) + + + + + + + +
    + +[![npm](https://img.shields.io/npm/v/preact.svg)](https://www.npmjs.com/package/preact) +[![Preact Slack Community](https://img.shields.io/badge/Slack%20Community-preact.slack.com-blue)](https://chat.preactjs.com) +[![OpenCollective Backers](https://opencollective.com/preact/backers/badge.svg)](#backers) +[![OpenCollective Sponsors](https://opencollective.com/preact/sponsors/badge.svg)](#sponsors) + +[![coveralls](https://img.shields.io/coveralls/preactjs/preact/main.svg)](https://coveralls.io/github/preactjs/preact) +[![gzip size](https://img.badgesize.io/https://unpkg.com/preact/dist/preact.min.js?compression=gzip&label=gzip)](https://unpkg.com/preact/dist/preact.min.js) +[![brotli size](https://img.badgesize.io/https://unpkg.com/preact/dist/preact.min.js?compression=brotli&label=brotli)](https://unpkg.com/preact/dist/preact.min.js) + +
    + +You can find some awesome libraries in the [awesome-preact list](https://github.com/preactjs/awesome-preact) :sunglasses: + +--- + +## Getting Started + +> 💁 _**Note:** You [don't need ES2015 to use Preact](https://github.com/developit/preact-in-es3)... but give it a try!_ + +#### Tutorial: Building UI with Preact + +With Preact, you create user interfaces by assembling trees of components and elements. Components are functions or classes that return a description of what their tree should output. These descriptions are typically written in [JSX](https://facebook.github.io/jsx/) (shown underneath), or [HTM](https://github.com/developit/htm) which leverages standard JavaScript Tagged Templates. Both syntaxes can express trees of elements with "props" (similar to HTML attributes) and children. + +To get started using Preact, first look at the render() function. This function accepts a tree description and creates the structure described. Next, it appends this structure to a parent DOM element provided as the second argument. Future calls to render() will reuse the existing tree and update it in-place in the DOM. Internally, render() will calculate the difference from previous outputted structures in an attempt to perform as few DOM operations as possible. + +```js +import { h, render } from 'preact'; +// Tells babel to use h for JSX. It's better to configure this globally. +// See https://babeljs.io/docs/en/babel-plugin-transform-react-jsx#usage +// In tsconfig you can specify this with the jsxFactory +/** @jsx h */ + +// create our tree and append it to document.body: +render( +
    +

    Hello

    +
    , + document.body +); + +// update the tree in-place: +render( +
    +

    Hello World!

    +
    , + document.body +); +// ^ this second invocation of render(...) will use a single DOM call to update the text of the

    +``` + +Hooray! render() has taken our structure and output a User Interface! This approach demonstrates a simple case, but would be difficult to use as an application grows in complexity. Each change would be forced to calculate the difference between the current and updated structure for the entire application. Components can help here – by dividing the User Interface into nested Components each can calculate their difference from their mounted point. Here's an example: + +```js +import { render, h } from 'preact'; +import { useState } from 'preact/hooks'; + +/** @jsx h */ + +const App = () => { + const [input, setInput] = useState(''); + + return ( +
    +

    Do you agree to the statement: "Preact is awesome"?

    + setInput(e.target.value)} /> +
    + ); +}; + +render(, document.body); +``` + +--- + +## 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/preact#sponsor)] + + + + + + + + + + + + + + + + + + +             + + + + + + + + + + + + + + + +## Backers + +Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/preact#backer)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +--- + +## License + +MIT + +[![Preact](https://i.imgur.com/YqCHvEW.gif)](https://preactjs.com) + +[preact/compat]: https://github.com/preactjs/preact/tree/main/compat +[hyperscript]: https://github.com/dominictarr/hyperscript +[DevTools]: https://github.com/preactjs/preact-devtools diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/compat/client.d.ts b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/client.d.ts new file mode 100644 index 0000000000000..e1beab907115d --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/client.d.ts @@ -0,0 +1,13 @@ +// Intentionally not using a relative path to take advantage of +// the TS version resolution mechanism +import * as preact from 'preact'; + +export function createRoot(container: preact.ContainerNode): { + render(children: preact.ComponentChild): void; + unmount(): void; +}; + +export function hydrateRoot( + container: preact.ContainerNode, + children: preact.ComponentChild +): ReturnType; diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/compat/client.js b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/client.js new file mode 100644 index 0000000000000..bc48c21bf2772 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/client.js @@ -0,0 +1,21 @@ +const { render, hydrate, unmountComponentAtNode } = require('preact/compat'); + +function createRoot(container) { + return { + // eslint-disable-next-line + render: function (children) { + render(children, container); + }, + // eslint-disable-next-line + unmount: function () { + unmountComponentAtNode(container); + } + }; +} + +exports.createRoot = createRoot; + +exports.hydrateRoot = function (container, children) { + hydrate(children, container); + return createRoot(container); +}; diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/compat/client.mjs b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/client.mjs new file mode 100644 index 0000000000000..f9d1814e18af4 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/client.mjs @@ -0,0 +1,24 @@ +import { render, hydrate, unmountComponentAtNode } from 'preact/compat'; + +export function createRoot(container) { + return { + // eslint-disable-next-line + render: function (children) { + render(children, container); + }, + // eslint-disable-next-line + unmount: function () { + unmountComponentAtNode(container); + } + }; +} + +export function hydrateRoot(container, children) { + hydrate(children, container); + return createRoot(container); +} + +export default { + createRoot, + hydrateRoot +}; diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/compat/dist/compat.js b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/dist/compat.js new file mode 100644 index 0000000000000..f84edb1f94684 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/dist/compat.js @@ -0,0 +1,2 @@ +var n=require("preact"),t=require("preact/hooks");function e(n,t){for(var e in t)n[e]=t[e];return n}function r(n,t){for(var e in n)if("__source"!==e&&!(e in t))return!0;for(var r in t)if("__source"!==r&&n[r]!==t[r])return!0;return!1}function u(n,e){var r=e(),u=t.useState({t:{__:r,u:e}}),i=u[0].t,l=u[1];return t.useLayoutEffect(function(){i.__=r,i.u=e,o(i)&&l({t:i})},[n,r,e]),t.useEffect(function(){return o(i)&&l({t:i}),n(function(){o(i)&&l({t:i})})},[n]),r}function o(n){var t,e,r=n.u,u=n.__;try{var o=r();return!((t=u)===(e=o)&&(0!==t||1/t==1/e)||t!=t&&e!=e)}catch(n){return!0}}function i(n){n()}function l(n){return n}function c(){return[!1,i]}var f=t.useLayoutEffect;function a(n,t){this.props=n,this.context=t}function s(t,e){function u(n){var t=this.props.ref,u=t==n.ref;return!u&&t&&(t.call?t(null):t.current=null),e?!e(this.props,n)||!u:r(this.props,n)}function o(e){return this.shouldComponentUpdate=u,n.createElement(t,e)}return o.displayName="Memo("+(t.displayName||t.name)+")",o.prototype.isReactComponent=!0,o.__f=!0,o.type=t,o}(a.prototype=new n.Component).isPureReactComponent=!0,a.prototype.shouldComponentUpdate=function(n,t){return r(this.props,n)||r(this.state,t)};var p=n.options.__b;n.options.__b=function(n){n.type&&n.type.__f&&n.ref&&(n.props.ref=n.ref,n.ref=null),p&&p(n)};var h="undefined"!=typeof Symbol&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function v(n){function t(t){var r=e({},t);return delete r.ref,n(r,t.ref||null)}return t.$$typeof=h,t.render=n,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(n.displayName||n.name)+")",t}var d=function(t,e){return null==t?null:n.toChildArray(n.toChildArray(t).map(e))},m={map:d,forEach:d,count:function(t){return t?n.toChildArray(t).length:0},only:function(t){var e=n.toChildArray(t);if(1!==e.length)throw"Children.only";return e[0]},toArray:n.toChildArray},x=n.options.__e;n.options.__e=function(n,t,e,r){if(n.then)for(var u,o=t;o=o.__;)if((u=o.__c)&&u.__c)return null==t.__e&&(t.__e=e.__e,t.__k=e.__k),u.__c(n,t);x(n,t,e,r)};var b=n.options.unmount;function _(n,t,r){return n&&(n.__c&&n.__c.__H&&(n.__c.__H.__.forEach(function(n){"function"==typeof n.__c&&n.__c()}),n.__c.__H=null),null!=(n=e({},n)).__c&&(n.__c.__P===r&&(n.__c.__P=t),n.__c.__e=!0,n.__c=null),n.__k=n.__k&&n.__k.map(function(n){return _(n,t,r)})),n}function y(n,t,e){return n&&e&&(n.__v=null,n.__k=n.__k&&n.__k.map(function(n){return y(n,t,e)}),n.__c&&n.__c.__P===t&&(n.__e&&e.appendChild(n.__e),n.__c.__e=!0,n.__c.__P=e)),n}function g(){this.__u=0,this.o=null,this.__b=null}function S(n){var t=n.__.__c;return t&&t.__a&&t.__a(n)}function E(t){var e,r,u,o=null;function i(i){if(e||(e=t()).then(function(n){n&&(o=n.default||n),u=!0},function(n){r=n,u=!0}),r)throw r;if(!u)throw e;return o?n.createElement(o,i):null}return i.displayName="Lazy",i.__f=!0,i}function C(){this.i=null,this.l=null}n.options.unmount=function(n){var t=n.__c;t&&t.__R&&t.__R(),t&&32&n.__u&&(n.type=null),b&&b(n)},(g.prototype=new n.Component).__c=function(n,t){var e=t.__c,r=this;null==r.o&&(r.o=[]),r.o.push(e);var u=S(r.__v),o=!1,i=function(){o||(o=!0,e.__R=null,u?u(l):l())};e.__R=i;var l=function(){if(!--r.__u){if(r.state.__a){var n=r.state.__a;r.__v.__k[0]=y(n,n.__c.__P,n.__c.__O)}var t;for(r.setState({__a:r.__b=null});t=r.o.pop();)t.forceUpdate()}};r.__u++||32&t.__u||r.setState({__a:r.__b=r.__v.__k[0]}),n.then(i,i)},g.prototype.componentWillUnmount=function(){this.o=[]},g.prototype.render=function(t,e){if(this.__b){if(this.__v.__k){var r=document.createElement("div"),u=this.__v.__k[0].__c;this.__v.__k[0]=_(this.__b,r,u.__O=u.__P)}this.__b=null}var o=e.__a&&n.createElement(n.Fragment,null,t.fallback);return o&&(o.__u&=-33),[n.createElement(n.Fragment,null,e.__a?null:t.children),o]};var O=function(n,t,e){if(++e[1]===e[0]&&n.l.delete(t),n.props.revealOrder&&("t"!==n.props.revealOrder[0]||!n.l.size))for(e=n.i;e;){for(;e.length>3;)e.pop()();if(e[1]>>1,1),e.p.removeChild(n)}}}n.render(n.createElement(R,{context:e.context},t.__v),e.h)}function j(t,e){var r=n.createElement(w,{__v:t,p:e});return r.containerInfo=e,r}(C.prototype=new n.Component).__a=function(n){var t=this,e=S(t.__v),r=t.l.get(n);return r[0]++,function(u){var o=function(){t.props.revealOrder?(r.push(u),O(t,n,r)):u()};e?e(o):o()}},C.prototype.render=function(t){this.i=null,this.l=new Map;var e=n.toChildArray(t.children);t.revealOrder&&"b"===t.revealOrder[0]&&e.reverse();for(var r=e.length;r--;)this.l.set(e[r],this.i=[1,0,this.i]);return t.children},C.prototype.componentDidUpdate=C.prototype.componentDidMount=function(){var n=this;this.l.forEach(function(t,e){O(n,e,t)})};var k="undefined"!=typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103,I=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,N=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,M=/[A-Z0-9]/g,T="undefined"!=typeof document,A=function(n){return("undefined"!=typeof Symbol&&"symbol"==typeof Symbol()?/fil|che|rad/:/fil|che|ra/).test(n)};function D(t,e,r){return null==e.__k&&(e.textContent=""),n.render(t,e),"function"==typeof r&&r(),t?t.__c:null}function L(t,e,r){return n.hydrate(t,e),"function"==typeof r&&r(),t?t.__c:null}n.Component.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(n.Component.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(n){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:n})}})});var F=n.options.event;function U(){}function V(){return this.cancelBubble}function W(){return this.defaultPrevented}n.options.event=function(n){return F&&(n=F(n)),n.persist=U,n.isPropagationStopped=V,n.isDefaultPrevented=W,n.nativeEvent=n};var P,z={enumerable:!1,configurable:!0,get:function(){return this.class}},B=n.options.vnode;n.options.vnode=function(t){"string"==typeof t.type&&function(t){var e=t.props,r=t.type,u={},o=-1===r.indexOf("-");for(var i in e){var l=e[i];if(!("value"===i&&"defaultValue"in e&&null==l||T&&"children"===i&&"noscript"===r||"class"===i||"className"===i)){var c=i.toLowerCase();"defaultValue"===i&&"value"in e&&null==e.value?i="value":"download"===i&&!0===l?l="":"translate"===c&&"no"===l?l=!1:"o"===c[0]&&"n"===c[1]?"ondoubleclick"===c?i="ondblclick":"onchange"!==c||"input"!==r&&"textarea"!==r||A(e.type)?"onfocus"===c?i="onfocusin":"onblur"===c?i="onfocusout":N.test(i)&&(i=c):c=i="oninput":o&&I.test(i)?i=i.replace(M,"-$&").toLowerCase():null===l&&(l=void 0),"oninput"===c&&u[i=c]&&(i="oninputCapture"),u[i]=l}}"select"==r&&u.multiple&&Array.isArray(u.value)&&(u.value=n.toChildArray(e.children).forEach(function(n){n.props.selected=-1!=u.value.indexOf(n.props.value)})),"select"==r&&null!=u.defaultValue&&(u.value=n.toChildArray(e.children).forEach(function(n){n.props.selected=u.multiple?-1!=u.defaultValue.indexOf(n.props.value):u.defaultValue==n.props.value})),e.class&&!e.className?(u.class=e.class,Object.defineProperty(u,"className",z)):(e.className&&!e.class||e.class&&e.className)&&(u.class=u.className=e.className),t.props=u}(t),t.$$typeof=k,B&&B(t)};var H=n.options.__r;n.options.__r=function(n){H&&H(n),P=n.__c};var q=n.options.diffed;n.options.diffed=function(n){q&&q(n);var t=n.props,e=n.__e;null!=e&&"textarea"===n.type&&"value"in t&&t.value!==e.value&&(e.value=null==t.value?"":t.value),P=null};var Z={ReactCurrentDispatcher:{current:{readContext:function(n){return P.__n[n.__c].props.value},useCallback:t.useCallback,useContext:t.useContext,useDebugValue:t.useDebugValue,useDeferredValue:l,useEffect:t.useEffect,useId:t.useId,useImperativeHandle:t.useImperativeHandle,useInsertionEffect:f,useLayoutEffect:t.useLayoutEffect,useMemo:t.useMemo,useReducer:t.useReducer,useRef:t.useRef,useState:t.useState,useSyncExternalStore:u,useTransition:c}}};function Y(t){return n.createElement.bind(null,t)}function $(n){return!!n&&n.$$typeof===k}function G(t){return $(t)&&t.type===n.Fragment}function J(n){return!!n&&!!n.displayName&&("string"==typeof n.displayName||n.displayName instanceof String)&&n.displayName.startsWith("Memo(")}function K(t){return $(t)?n.cloneElement.apply(null,arguments):t}function Q(t){return!!t.__k&&(n.render(null,t),!0)}function X(n){return n&&(n.base||1===n.nodeType&&n)||null}var nn=function(n,t){return n(t)},tn=function(n,t){return n(t)},en=n.Fragment,rn=$,un={useState:t.useState,useId:t.useId,useReducer:t.useReducer,useEffect:t.useEffect,useLayoutEffect:t.useLayoutEffect,useInsertionEffect:f,useTransition:c,useDeferredValue:l,useSyncExternalStore:u,startTransition:i,useRef:t.useRef,useImperativeHandle:t.useImperativeHandle,useMemo:t.useMemo,useCallback:t.useCallback,useContext:t.useContext,useDebugValue:t.useDebugValue,version:"18.3.1",Children:m,render:D,hydrate:L,unmountComponentAtNode:Q,createPortal:j,createElement:n.createElement,createContext:n.createContext,createFactory:Y,cloneElement:K,createRef:n.createRef,Fragment:n.Fragment,isValidElement:$,isElement:rn,isFragment:G,isMemo:J,findDOMNode:X,Component:n.Component,PureComponent:a,memo:s,forwardRef:v,flushSync:tn,unstable_batchedUpdates:nn,StrictMode:en,Suspense:g,SuspenseList:C,lazy:E,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Z};Object.defineProperty(exports,"Component",{enumerable:!0,get:function(){return n.Component}}),Object.defineProperty(exports,"Fragment",{enumerable:!0,get:function(){return n.Fragment}}),Object.defineProperty(exports,"createContext",{enumerable:!0,get:function(){return n.createContext}}),Object.defineProperty(exports,"createElement",{enumerable:!0,get:function(){return n.createElement}}),Object.defineProperty(exports,"createRef",{enumerable:!0,get:function(){return n.createRef}}),exports.Children=m,exports.PureComponent=a,exports.StrictMode=en,exports.Suspense=g,exports.SuspenseList=C,exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Z,exports.cloneElement=K,exports.createFactory=Y,exports.createPortal=j,exports.default=un,exports.findDOMNode=X,exports.flushSync=tn,exports.forwardRef=v,exports.hydrate=L,exports.isElement=rn,exports.isFragment=G,exports.isMemo=J,exports.isValidElement=$,exports.lazy=E,exports.memo=s,exports.render=D,exports.startTransition=i,exports.unmountComponentAtNode=Q,exports.unstable_batchedUpdates=nn,exports.useDeferredValue=l,exports.useInsertionEffect=f,exports.useSyncExternalStore=u,exports.useTransition=c,exports.version="18.3.1",Object.keys(t).forEach(function(n){"default"===n||exports.hasOwnProperty(n)||Object.defineProperty(exports,n,{enumerable:!0,get:function(){return t[n]}})}); +//# sourceMappingURL=compat.js.map diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/compat/dist/compat.js.map b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/dist/compat.js.map new file mode 100644 index 0000000000000..3275ece3591ea --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/dist/compat.js.map @@ -0,0 +1 @@ +{"version":3,"file":"compat.js","sources":["../src/util.js","../src/hooks.js","../src/PureComponent.js","../src/memo.js","../src/forwardRef.js","../src/Children.js","../src/suspense.js","../src/suspense-list.js","../../src/constants.js","../src/portals.js","../src/render.js","../src/index.js"],"sourcesContent":["/**\n * Assign properties from `props` to `obj`\n * @template O, P The obj and props types\n * @param {O} obj The object to copy properties to\n * @param {P} props The object to copy properties from\n * @returns {O & P}\n */\nexport function assign(obj, props) {\n\tfor (let i in props) obj[i] = props[i];\n\treturn /** @type {O & P} */ (obj);\n}\n\n/**\n * Check if two objects have a different shape\n * @param {object} a\n * @param {object} b\n * @returns {boolean}\n */\nexport function shallowDiffers(a, b) {\n\tfor (let i in a) if (i !== '__source' && !(i in b)) return true;\n\tfor (let i in b) if (i !== '__source' && a[i] !== b[i]) return true;\n\treturn false;\n}\n\n/**\n * Check if two values are the same value\n * @param {*} x\n * @param {*} y\n * @returns {boolean}\n */\nexport function is(x, y) {\n\treturn (x === y && (x !== 0 || 1 / x === 1 / y)) || (x !== x && y !== y);\n}\n","import { useState, useLayoutEffect, useEffect } from 'preact/hooks';\nimport { is } from './util';\n\n/**\n * This is taken from https://github.com/facebook/react/blob/main/packages/use-sync-external-store/src/useSyncExternalStoreShimClient.js#L84\n * on a high level this cuts out the warnings, ... and attempts a smaller implementation\n * @typedef {{ _value: any; _getSnapshot: () => any }} Store\n */\nexport function useSyncExternalStore(subscribe, getSnapshot) {\n\tconst value = getSnapshot();\n\n\t/**\n\t * @typedef {{ _instance: Store }} StoreRef\n\t * @type {[StoreRef, (store: StoreRef) => void]}\n\t */\n\tconst [{ _instance }, forceUpdate] = useState({\n\t\t_instance: { _value: value, _getSnapshot: getSnapshot }\n\t});\n\n\tuseLayoutEffect(() => {\n\t\t_instance._value = value;\n\t\t_instance._getSnapshot = getSnapshot;\n\n\t\tif (didSnapshotChange(_instance)) {\n\t\t\tforceUpdate({ _instance });\n\t\t}\n\t}, [subscribe, value, getSnapshot]);\n\n\tuseEffect(() => {\n\t\tif (didSnapshotChange(_instance)) {\n\t\t\tforceUpdate({ _instance });\n\t\t}\n\n\t\treturn subscribe(() => {\n\t\t\tif (didSnapshotChange(_instance)) {\n\t\t\t\tforceUpdate({ _instance });\n\t\t\t}\n\t\t});\n\t}, [subscribe]);\n\n\treturn value;\n}\n\n/** @type {(inst: Store) => boolean} */\nfunction didSnapshotChange(inst) {\n\tconst latestGetSnapshot = inst._getSnapshot;\n\tconst prevValue = inst._value;\n\ttry {\n\t\tconst nextValue = latestGetSnapshot();\n\t\treturn !is(prevValue, nextValue);\n\t} catch (error) {\n\t\treturn true;\n\t}\n}\n\nexport function startTransition(cb) {\n\tcb();\n}\n\nexport function useDeferredValue(val) {\n\treturn val;\n}\n\nexport function useTransition() {\n\treturn [false, startTransition];\n}\n\n// TODO: in theory this should be done after a VNode is diffed as we want to insert\n// styles/... before it attaches\nexport const useInsertionEffect = useLayoutEffect;\n","import { Component } from 'preact';\nimport { shallowDiffers } from './util';\n\n/**\n * Component class with a predefined `shouldComponentUpdate` implementation\n */\nexport function PureComponent(p, c) {\n\tthis.props = p;\n\tthis.context = c;\n}\nPureComponent.prototype = new Component();\n// Some third-party libraries check if this property is present\nPureComponent.prototype.isPureReactComponent = true;\nPureComponent.prototype.shouldComponentUpdate = function (props, state) {\n\treturn shallowDiffers(this.props, props) || shallowDiffers(this.state, state);\n};\n","import { createElement } from 'preact';\nimport { shallowDiffers } from './util';\n\n/**\n * Memoize a component, so that it only updates when the props actually have\n * changed. This was previously known as `React.pure`.\n * @param {import('./internal').FunctionComponent} c functional component\n * @param {(prev: object, next: object) => boolean} [comparer] Custom equality function\n * @returns {import('./internal').FunctionComponent}\n */\nexport function memo(c, comparer) {\n\tfunction shouldUpdate(nextProps) {\n\t\tlet ref = this.props.ref;\n\t\tlet updateRef = ref == nextProps.ref;\n\t\tif (!updateRef && ref) {\n\t\t\tref.call ? ref(null) : (ref.current = null);\n\t\t}\n\n\t\tif (!comparer) {\n\t\t\treturn shallowDiffers(this.props, nextProps);\n\t\t}\n\n\t\treturn !comparer(this.props, nextProps) || !updateRef;\n\t}\n\n\tfunction Memoed(props) {\n\t\tthis.shouldComponentUpdate = shouldUpdate;\n\t\treturn createElement(c, props);\n\t}\n\tMemoed.displayName = 'Memo(' + (c.displayName || c.name) + ')';\n\tMemoed.prototype.isReactComponent = true;\n\tMemoed._forwarded = true;\n\tMemoed.type = c;\n\treturn Memoed;\n}\n","import { options } from 'preact';\nimport { assign } from './util';\n\nlet oldDiffHook = options._diff;\noptions._diff = vnode => {\n\tif (vnode.type && vnode.type._forwarded && vnode.ref) {\n\t\tvnode.props.ref = vnode.ref;\n\t\tvnode.ref = null;\n\t}\n\tif (oldDiffHook) oldDiffHook(vnode);\n};\n\nexport const REACT_FORWARD_SYMBOL =\n\t(typeof Symbol != 'undefined' &&\n\t\tSymbol.for &&\n\t\tSymbol.for('react.forward_ref')) ||\n\t0xf47;\n\n/**\n * Pass ref down to a child. This is mainly used in libraries with HOCs that\n * wrap components. Using `forwardRef` there is an easy way to get a reference\n * of the wrapped component instead of one of the wrapper itself.\n * @param {import('./index').ForwardFn} fn\n * @returns {import('./internal').FunctionComponent}\n */\nexport function forwardRef(fn) {\n\tfunction Forwarded(props) {\n\t\tlet clone = assign({}, props);\n\t\tdelete clone.ref;\n\t\treturn fn(clone, props.ref || null);\n\t}\n\n\t// mobx-react checks for this being present\n\tForwarded.$$typeof = REACT_FORWARD_SYMBOL;\n\t// mobx-react heavily relies on implementation details.\n\t// It expects an object here with a `render` property,\n\t// and prototype.render will fail. Without this\n\t// mobx-react throws.\n\tForwarded.render = fn;\n\n\tForwarded.prototype.isReactComponent = Forwarded._forwarded = true;\n\tForwarded.displayName = 'ForwardRef(' + (fn.displayName || fn.name) + ')';\n\treturn Forwarded;\n}\n","import { toChildArray } from 'preact';\n\nconst mapFn = (children, fn) => {\n\tif (children == null) return null;\n\treturn toChildArray(toChildArray(children).map(fn));\n};\n\n// This API is completely unnecessary for Preact, so it's basically passthrough.\nexport const Children = {\n\tmap: mapFn,\n\tforEach: mapFn,\n\tcount(children) {\n\t\treturn children ? toChildArray(children).length : 0;\n\t},\n\tonly(children) {\n\t\tconst normalized = toChildArray(children);\n\t\tif (normalized.length !== 1) throw 'Children.only';\n\t\treturn normalized[0];\n\t},\n\ttoArray: toChildArray\n};\n","import { Component, createElement, options, Fragment } from 'preact';\nimport { MODE_HYDRATE } from '../../src/constants';\nimport { assign } from './util';\n\nconst oldCatchError = options._catchError;\noptions._catchError = function (error, newVNode, oldVNode, errorInfo) {\n\tif (error.then) {\n\t\t/** @type {import('./internal').Component} */\n\t\tlet component;\n\t\tlet vnode = newVNode;\n\n\t\tfor (; (vnode = vnode._parent); ) {\n\t\t\tif ((component = vnode._component) && component._childDidSuspend) {\n\t\t\t\tif (newVNode._dom == null) {\n\t\t\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t\t\t\tnewVNode._children = oldVNode._children;\n\t\t\t\t}\n\t\t\t\t// Don't call oldCatchError if we found a Suspense\n\t\t\t\treturn component._childDidSuspend(error, newVNode);\n\t\t\t}\n\t\t}\n\t}\n\toldCatchError(error, newVNode, oldVNode, errorInfo);\n};\n\nconst oldUnmount = options.unmount;\noptions.unmount = function (vnode) {\n\t/** @type {import('./internal').Component} */\n\tconst component = vnode._component;\n\tif (component && component._onResolve) {\n\t\tcomponent._onResolve();\n\t}\n\n\t// if the component is still hydrating\n\t// most likely it is because the component is suspended\n\t// we set the vnode.type as `null` so that it is not a typeof function\n\t// so the unmount will remove the vnode._dom\n\tif (component && vnode._flags & MODE_HYDRATE) {\n\t\tvnode.type = null;\n\t}\n\n\tif (oldUnmount) oldUnmount(vnode);\n};\n\nfunction detachedClone(vnode, detachedParent, parentDom) {\n\tif (vnode) {\n\t\tif (vnode._component && vnode._component.__hooks) {\n\t\t\tvnode._component.__hooks._list.forEach(effect => {\n\t\t\t\tif (typeof effect._cleanup == 'function') effect._cleanup();\n\t\t\t});\n\n\t\t\tvnode._component.__hooks = null;\n\t\t}\n\n\t\tvnode = assign({}, vnode);\n\t\tif (vnode._component != null) {\n\t\t\tif (vnode._component._parentDom === parentDom) {\n\t\t\t\tvnode._component._parentDom = detachedParent;\n\t\t\t}\n\n\t\t\tvnode._component._force = true;\n\n\t\t\tvnode._component = null;\n\t\t}\n\n\t\tvnode._children =\n\t\t\tvnode._children &&\n\t\t\tvnode._children.map(child =>\n\t\t\t\tdetachedClone(child, detachedParent, parentDom)\n\t\t\t);\n\t}\n\n\treturn vnode;\n}\n\nfunction removeOriginal(vnode, detachedParent, originalParent) {\n\tif (vnode && originalParent) {\n\t\tvnode._original = null;\n\t\tvnode._children =\n\t\t\tvnode._children &&\n\t\t\tvnode._children.map(child =>\n\t\t\t\tremoveOriginal(child, detachedParent, originalParent)\n\t\t\t);\n\n\t\tif (vnode._component) {\n\t\t\tif (vnode._component._parentDom === detachedParent) {\n\t\t\t\tif (vnode._dom) {\n\t\t\t\t\toriginalParent.appendChild(vnode._dom);\n\t\t\t\t}\n\t\t\t\tvnode._component._force = true;\n\t\t\t\tvnode._component._parentDom = originalParent;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn vnode;\n}\n\n// having custom inheritance instead of a class here saves a lot of bytes\nexport function Suspense() {\n\t// we do not call super here to golf some bytes...\n\tthis._pendingSuspensionCount = 0;\n\tthis._suspenders = null;\n\tthis._detachOnNextRender = null;\n}\n\n// Things we do here to save some bytes but are not proper JS inheritance:\n// - call `new Component()` as the prototype\n// - do not set `Suspense.prototype.constructor` to `Suspense`\nSuspense.prototype = new Component();\n\n/**\n * @this {import('./internal').SuspenseComponent}\n * @param {Promise} promise The thrown promise\n * @param {import('./internal').VNode} suspendingVNode The suspending component\n */\nSuspense.prototype._childDidSuspend = function (promise, suspendingVNode) {\n\tconst suspendingComponent = suspendingVNode._component;\n\n\t/** @type {import('./internal').SuspenseComponent} */\n\tconst c = this;\n\n\tif (c._suspenders == null) {\n\t\tc._suspenders = [];\n\t}\n\tc._suspenders.push(suspendingComponent);\n\n\tconst resolve = suspended(c._vnode);\n\n\tlet resolved = false;\n\tconst onResolved = () => {\n\t\tif (resolved) return;\n\n\t\tresolved = true;\n\t\tsuspendingComponent._onResolve = null;\n\n\t\tif (resolve) {\n\t\t\tresolve(onSuspensionComplete);\n\t\t} else {\n\t\t\tonSuspensionComplete();\n\t\t}\n\t};\n\n\tsuspendingComponent._onResolve = onResolved;\n\n\tconst onSuspensionComplete = () => {\n\t\tif (!--c._pendingSuspensionCount) {\n\t\t\t// If the suspension was during hydration we don't need to restore the\n\t\t\t// suspended children into the _children array\n\t\t\tif (c.state._suspended) {\n\t\t\t\tconst suspendedVNode = c.state._suspended;\n\t\t\t\tc._vnode._children[0] = removeOriginal(\n\t\t\t\t\tsuspendedVNode,\n\t\t\t\t\tsuspendedVNode._component._parentDom,\n\t\t\t\t\tsuspendedVNode._component._originalParentDom\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tc.setState({ _suspended: (c._detachOnNextRender = null) });\n\n\t\t\tlet suspended;\n\t\t\twhile ((suspended = c._suspenders.pop())) {\n\t\t\t\tsuspended.forceUpdate();\n\t\t\t}\n\t\t}\n\t};\n\n\t/**\n\t * We do not set `suspended: true` during hydration because we want the actual markup\n\t * to remain on screen and hydrate it when the suspense actually gets resolved.\n\t * While in non-hydration cases the usual fallback -> component flow would occour.\n\t */\n\tif (\n\t\t!c._pendingSuspensionCount++ &&\n\t\t!(suspendingVNode._flags & MODE_HYDRATE)\n\t) {\n\t\tc.setState({ _suspended: (c._detachOnNextRender = c._vnode._children[0]) });\n\t}\n\tpromise.then(onResolved, onResolved);\n};\n\nSuspense.prototype.componentWillUnmount = function () {\n\tthis._suspenders = [];\n};\n\n/**\n * @this {import('./internal').SuspenseComponent}\n * @param {import('./internal').SuspenseComponent[\"props\"]} props\n * @param {import('./internal').SuspenseState} state\n */\nSuspense.prototype.render = function (props, state) {\n\tif (this._detachOnNextRender) {\n\t\t// When the Suspense's _vnode was created by a call to createVNode\n\t\t// (i.e. due to a setState further up in the tree)\n\t\t// it's _children prop is null, in this case we \"forget\" about the parked vnodes to detach\n\t\tif (this._vnode._children) {\n\t\t\tconst detachedParent = document.createElement('div');\n\t\t\tconst detachedComponent = this._vnode._children[0]._component;\n\t\t\tthis._vnode._children[0] = detachedClone(\n\t\t\t\tthis._detachOnNextRender,\n\t\t\t\tdetachedParent,\n\t\t\t\t(detachedComponent._originalParentDom = detachedComponent._parentDom)\n\t\t\t);\n\t\t}\n\n\t\tthis._detachOnNextRender = null;\n\t}\n\n\t// Wrap fallback tree in a VNode that prevents itself from being marked as aborting mid-hydration:\n\t/** @type {import('./internal').VNode} */\n\tconst fallback =\n\t\tstate._suspended && createElement(Fragment, null, props.fallback);\n\tif (fallback) fallback._flags &= ~MODE_HYDRATE;\n\n\treturn [\n\t\tcreateElement(Fragment, null, state._suspended ? null : props.children),\n\t\tfallback\n\t];\n};\n\n/**\n * Checks and calls the parent component's _suspended method, passing in the\n * suspended vnode. This is a way for a parent (e.g. SuspenseList) to get notified\n * that one of its children/descendants suspended.\n *\n * The parent MAY return a callback. The callback will get called when the\n * suspension resolves, notifying the parent of the fact.\n * Moreover, the callback gets function `unsuspend` as a parameter. The resolved\n * child descendant will not actually get unsuspended until `unsuspend` gets called.\n * This is a way for the parent to delay unsuspending.\n *\n * If the parent does not return a callback then the resolved vnode\n * gets unsuspended immediately when it resolves.\n *\n * @param {import('./internal').VNode} vnode\n * @returns {((unsuspend: () => void) => void)?}\n */\nexport function suspended(vnode) {\n\t/** @type {import('./internal').Component} */\n\tlet component = vnode._parent._component;\n\treturn component && component._suspended && component._suspended(vnode);\n}\n\nexport function lazy(loader) {\n\tlet prom;\n\tlet component = null;\n\tlet error;\n\tlet resolved;\n\n\tfunction Lazy(props) {\n\t\tif (!prom) {\n\t\t\tprom = loader();\n\t\t\tprom.then(\n\t\t\t\texports => {\n\t\t\t\t\tif (exports) {\n\t\t\t\t\t\tcomponent = exports.default || exports;\n\t\t\t\t\t}\n\t\t\t\t\tresolved = true;\n\t\t\t\t},\n\t\t\t\te => {\n\t\t\t\t\terror = e;\n\t\t\t\t\tresolved = true;\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\n\t\tif (error) {\n\t\t\tthrow error;\n\t\t}\n\n\t\tif (!resolved) {\n\t\t\tthrow prom;\n\t\t}\n\n\t\treturn component ? createElement(component, props) : null;\n\t}\n\n\tLazy.displayName = 'Lazy';\n\tLazy._forwarded = true;\n\treturn Lazy;\n}\n","import { Component, toChildArray } from 'preact';\nimport { suspended } from './suspense.js';\n\n// Indexes to linked list nodes (nodes are stored as arrays to save bytes).\nconst SUSPENDED_COUNT = 0;\nconst RESOLVED_COUNT = 1;\nconst NEXT_NODE = 2;\n\n// Having custom inheritance instead of a class here saves a lot of bytes.\nexport function SuspenseList() {\n\tthis._next = null;\n\tthis._map = null;\n}\n\n// Mark one of child's earlier suspensions as resolved.\n// Some pending callbacks may become callable due to this\n// (e.g. the last suspended descendant gets resolved when\n// revealOrder === 'together'). Process those callbacks as well.\nconst resolve = (list, child, node) => {\n\tif (++node[RESOLVED_COUNT] === node[SUSPENDED_COUNT]) {\n\t\t// The number a child (or any of its descendants) has been suspended\n\t\t// matches the number of times it's been resolved. Therefore we\n\t\t// mark the child as completely resolved by deleting it from ._map.\n\t\t// This is used to figure out when *all* children have been completely\n\t\t// resolved when revealOrder is 'together'.\n\t\tlist._map.delete(child);\n\t}\n\n\t// If revealOrder is falsy then we can do an early exit, as the\n\t// callbacks won't get queued in the node anyway.\n\t// If revealOrder is 'together' then also do an early exit\n\t// if all suspended descendants have not yet been resolved.\n\tif (\n\t\t!list.props.revealOrder ||\n\t\t(list.props.revealOrder[0] === 't' && list._map.size)\n\t) {\n\t\treturn;\n\t}\n\n\t// Walk the currently suspended children in order, calling their\n\t// stored callbacks on the way. Stop if we encounter a child that\n\t// has not been completely resolved yet.\n\tnode = list._next;\n\twhile (node) {\n\t\twhile (node.length > 3) {\n\t\t\tnode.pop()();\n\t\t}\n\t\tif (node[RESOLVED_COUNT] < node[SUSPENDED_COUNT]) {\n\t\t\tbreak;\n\t\t}\n\t\tlist._next = node = node[NEXT_NODE];\n\t}\n};\n\n// Things we do here to save some bytes but are not proper JS inheritance:\n// - call `new Component()` as the prototype\n// - do not set `Suspense.prototype.constructor` to `Suspense`\nSuspenseList.prototype = new Component();\n\nSuspenseList.prototype._suspended = function (child) {\n\tconst list = this;\n\tconst delegated = suspended(list._vnode);\n\n\tlet node = list._map.get(child);\n\tnode[SUSPENDED_COUNT]++;\n\n\treturn unsuspend => {\n\t\tconst wrappedUnsuspend = () => {\n\t\t\tif (!list.props.revealOrder) {\n\t\t\t\t// Special case the undefined (falsy) revealOrder, as there\n\t\t\t\t// is no need to coordinate a specific order or unsuspends.\n\t\t\t\tunsuspend();\n\t\t\t} else {\n\t\t\t\tnode.push(unsuspend);\n\t\t\t\tresolve(list, child, node);\n\t\t\t}\n\t\t};\n\t\tif (delegated) {\n\t\t\tdelegated(wrappedUnsuspend);\n\t\t} else {\n\t\t\twrappedUnsuspend();\n\t\t}\n\t};\n};\n\nSuspenseList.prototype.render = function (props) {\n\tthis._next = null;\n\tthis._map = new Map();\n\n\tconst children = toChildArray(props.children);\n\tif (props.revealOrder && props.revealOrder[0] === 'b') {\n\t\t// If order === 'backwards' (or, well, anything starting with a 'b')\n\t\t// then flip the child list around so that the last child will be\n\t\t// the first in the linked list.\n\t\tchildren.reverse();\n\t}\n\t// Build the linked list. Iterate through the children in reverse order\n\t// so that `_next` points to the first linked list node to be resolved.\n\tfor (let i = children.length; i--; ) {\n\t\t// Create a new linked list node as an array of form:\n\t\t// \t[suspended_count, resolved_count, next_node]\n\t\t// where suspended_count and resolved_count are numeric counters for\n\t\t// keeping track how many times a node has been suspended and resolved.\n\t\t//\n\t\t// Note that suspended_count starts from 1 instead of 0, so we can block\n\t\t// processing callbacks until componentDidMount has been called. In a sense\n\t\t// node is suspended at least until componentDidMount gets called!\n\t\t//\n\t\t// Pending callbacks are added to the end of the node:\n\t\t// \t[suspended_count, resolved_count, next_node, callback_0, callback_1, ...]\n\t\tthis._map.set(children[i], (this._next = [1, 0, this._next]));\n\t}\n\treturn props.children;\n};\n\nSuspenseList.prototype.componentDidUpdate =\n\tSuspenseList.prototype.componentDidMount = function () {\n\t\t// Iterate through all children after mounting for two reasons:\n\t\t// 1. As each node[SUSPENDED_COUNT] starts from 1, this iteration increases\n\t\t// each node[RELEASED_COUNT] by 1, therefore balancing the counters.\n\t\t// The nodes can now be completely consumed from the linked list.\n\t\t// 2. Handle nodes that might have gotten resolved between render and\n\t\t// componentDidMount.\n\t\tthis._map.forEach((node, child) => {\n\t\t\tresolve(this, child, node);\n\t\t});\n\t};\n","/** Normal hydration that attaches to a DOM tree but does not diff it. */\nexport const MODE_HYDRATE = 1 << 5;\n/** Signifies this VNode suspended on the previous render */\nexport const MODE_SUSPENDED = 1 << 7;\n/** Indicates that this node needs to be inserted while patching children */\nexport const INSERT_VNODE = 1 << 2;\n/** Indicates a VNode has been matched with another VNode in the diff */\nexport const MATCHED = 1 << 1;\n\n/** Reset all mode flags */\nexport const RESET_MODE = ~(MODE_HYDRATE | MODE_SUSPENDED);\n\nexport const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\nexport const XHTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\nexport const MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n\nexport const NULL = null;\nexport const UNDEFINED = undefined;\nexport const EMPTY_OBJ = /** @type {any} */ ({});\nexport const EMPTY_ARR = [];\nexport const IS_NON_DIMENSIONAL =\n\t/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;\n","import { createElement, render } from 'preact';\n\n/**\n * @param {import('../../src/index').RenderableProps<{ context: any }>} props\n */\nfunction ContextProvider(props) {\n\tthis.getChildContext = () => props.context;\n\treturn props.children;\n}\n\n/**\n * Portal component\n * @this {import('./internal').Component}\n * @param {object | null | undefined} props\n *\n * TODO: use createRoot() instead of fake root\n */\nfunction Portal(props) {\n\tconst _this = this;\n\tlet container = props._container;\n\n\t_this.componentWillUnmount = function () {\n\t\trender(null, _this._temp);\n\t\t_this._temp = null;\n\t\t_this._container = null;\n\t};\n\n\t// When we change container we should clear our old container and\n\t// indicate a new mount.\n\tif (_this._container && _this._container !== container) {\n\t\t_this.componentWillUnmount();\n\t}\n\n\tif (!_this._temp) {\n\t\t// Ensure the element has a mask for useId invocations\n\t\tlet root = _this._vnode;\n\t\twhile (root !== null && !root._mask && root._parent !== null) {\n\t\t\troot = root._parent;\n\t\t}\n\n\t\t_this._container = container;\n\n\t\t// Create a fake DOM parent node that manages a subset of `container`'s children:\n\t\t_this._temp = {\n\t\t\tnodeType: 1,\n\t\t\tparentNode: container,\n\t\t\tchildNodes: [],\n\t\t\t_children: { _mask: root._mask },\n\t\t\tcontains: () => true,\n\t\t\tinsertBefore(child, before) {\n\t\t\t\tthis.childNodes.push(child);\n\t\t\t\t_this._container.insertBefore(child, before);\n\t\t\t},\n\t\t\tremoveChild(child) {\n\t\t\t\tthis.childNodes.splice(this.childNodes.indexOf(child) >>> 1, 1);\n\t\t\t\t_this._container.removeChild(child);\n\t\t\t}\n\t\t};\n\t}\n\n\t// Render our wrapping element into temp.\n\trender(\n\t\tcreateElement(ContextProvider, { context: _this.context }, props._vnode),\n\t\t_this._temp\n\t);\n}\n\n/**\n * Create a `Portal` to continue rendering the vnode tree at a different DOM node\n * @param {import('./internal').VNode} vnode The vnode to render\n * @param {import('./internal').PreactElement} container The DOM node to continue rendering in to.\n */\nexport function createPortal(vnode, container) {\n\tconst el = createElement(Portal, { _vnode: vnode, _container: container });\n\tel.containerInfo = container;\n\treturn el;\n}\n","import {\n\trender as preactRender,\n\thydrate as preactHydrate,\n\toptions,\n\ttoChildArray,\n\tComponent\n} from 'preact';\nimport {\n\tuseCallback,\n\tuseContext,\n\tuseDebugValue,\n\tuseEffect,\n\tuseId,\n\tuseImperativeHandle,\n\tuseLayoutEffect,\n\tuseMemo,\n\tuseReducer,\n\tuseRef,\n\tuseState\n} from 'preact/hooks';\nimport {\n\tuseDeferredValue,\n\tuseInsertionEffect,\n\tuseSyncExternalStore,\n\tuseTransition\n} from './index';\n\nexport const REACT_ELEMENT_TYPE =\n\t(typeof Symbol != 'undefined' && Symbol.for && Symbol.for('react.element')) ||\n\t0xeac7;\n\nconst CAMEL_PROPS =\n\t/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/;\nconst ON_ANI = /^on(Ani|Tra|Tou|BeforeInp|Compo)/;\nconst CAMEL_REPLACE = /[A-Z0-9]/g;\nconst IS_DOM = typeof document !== 'undefined';\n\n// Input types for which onchange should not be converted to oninput.\n// type=\"file|checkbox|radio\", plus \"range\" in IE11.\n// (IE11 doesn't support Symbol, which we use here to turn `rad` into `ra` which matches \"range\")\nconst onChangeInputType = type =>\n\t(typeof Symbol != 'undefined' && typeof Symbol() == 'symbol'\n\t\t? /fil|che|rad/\n\t\t: /fil|che|ra/\n\t).test(type);\n\n// Some libraries like `react-virtualized` explicitly check for this.\nComponent.prototype.isReactComponent = {};\n\n// `UNSAFE_*` lifecycle hooks\n// Preact only ever invokes the unprefixed methods.\n// Here we provide a base \"fallback\" implementation that calls any defined UNSAFE_ prefixed method.\n// - If a component defines its own `componentDidMount()` (including via defineProperty), use that.\n// - If a component defines `UNSAFE_componentDidMount()`, `componentDidMount` is the alias getter/setter.\n// - If anything assigns to an `UNSAFE_*` property, the assignment is forwarded to the unprefixed property.\n// See https://github.com/preactjs/preact/issues/1941\n[\n\t'componentWillMount',\n\t'componentWillReceiveProps',\n\t'componentWillUpdate'\n].forEach(key => {\n\tObject.defineProperty(Component.prototype, key, {\n\t\tconfigurable: true,\n\t\tget() {\n\t\t\treturn this['UNSAFE_' + key];\n\t\t},\n\t\tset(v) {\n\t\t\tObject.defineProperty(this, key, {\n\t\t\t\tconfigurable: true,\n\t\t\t\twritable: true,\n\t\t\t\tvalue: v\n\t\t\t});\n\t\t}\n\t});\n});\n\n/**\n * Proxy render() since React returns a Component reference.\n * @param {import('./internal').VNode} vnode VNode tree to render\n * @param {import('./internal').PreactElement} parent DOM node to render vnode tree into\n * @param {() => void} [callback] Optional callback that will be called after rendering\n * @returns {import('./internal').Component | null} The root component reference or null\n */\nexport function render(vnode, parent, callback) {\n\t// React destroys any existing DOM nodes, see #1727\n\t// ...but only on the first render, see #1828\n\tif (parent._children == null) {\n\t\tparent.textContent = '';\n\t}\n\n\tpreactRender(vnode, parent);\n\tif (typeof callback == 'function') callback();\n\n\treturn vnode ? vnode._component : null;\n}\n\nexport function hydrate(vnode, parent, callback) {\n\tpreactHydrate(vnode, parent);\n\tif (typeof callback == 'function') callback();\n\n\treturn vnode ? vnode._component : null;\n}\n\nlet oldEventHook = options.event;\noptions.event = e => {\n\tif (oldEventHook) e = oldEventHook(e);\n\n\te.persist = empty;\n\te.isPropagationStopped = isPropagationStopped;\n\te.isDefaultPrevented = isDefaultPrevented;\n\treturn (e.nativeEvent = e);\n};\n\nfunction empty() {}\n\nfunction isPropagationStopped() {\n\treturn this.cancelBubble;\n}\n\nfunction isDefaultPrevented() {\n\treturn this.defaultPrevented;\n}\n\nconst classNameDescriptorNonEnumberable = {\n\tenumerable: false,\n\tconfigurable: true,\n\tget() {\n\t\treturn this.class;\n\t}\n};\n\nfunction handleDomVNode(vnode) {\n\tlet props = vnode.props,\n\t\ttype = vnode.type,\n\t\tnormalizedProps = {};\n\n\tlet isNonDashedType = type.indexOf('-') === -1;\n\tfor (let i in props) {\n\t\tlet value = props[i];\n\n\t\tif (\n\t\t\t(i === 'value' && 'defaultValue' in props && value == null) ||\n\t\t\t// Emulate React's behavior of not rendering the contents of noscript tags on the client.\n\t\t\t(IS_DOM && i === 'children' && type === 'noscript') ||\n\t\t\ti === 'class' ||\n\t\t\ti === 'className'\n\t\t) {\n\t\t\t// Skip applying value if it is null/undefined and we already set\n\t\t\t// a default value\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet lowerCased = i.toLowerCase();\n\t\tif (i === 'defaultValue' && 'value' in props && props.value == null) {\n\t\t\t// `defaultValue` is treated as a fallback `value` when a value prop is present but null/undefined.\n\t\t\t// `defaultValue` for Elements with no value prop is the same as the DOM defaultValue property.\n\t\t\ti = 'value';\n\t\t} else if (i === 'download' && value === true) {\n\t\t\t// Calling `setAttribute` with a truthy value will lead to it being\n\t\t\t// passed as a stringified value, e.g. `download=\"true\"`. React\n\t\t\t// converts it to an empty string instead, otherwise the attribute\n\t\t\t// value will be used as the file name and the file will be called\n\t\t\t// \"true\" upon downloading it.\n\t\t\tvalue = '';\n\t\t} else if (lowerCased === 'translate' && value === 'no') {\n\t\t\tvalue = false;\n\t\t} else if (lowerCased[0] === 'o' && lowerCased[1] === 'n') {\n\t\t\tif (lowerCased === 'ondoubleclick') {\n\t\t\t\ti = 'ondblclick';\n\t\t\t} else if (\n\t\t\t\tlowerCased === 'onchange' &&\n\t\t\t\t(type === 'input' || type === 'textarea') &&\n\t\t\t\t!onChangeInputType(props.type)\n\t\t\t) {\n\t\t\t\tlowerCased = i = 'oninput';\n\t\t\t} else if (lowerCased === 'onfocus') {\n\t\t\t\ti = 'onfocusin';\n\t\t\t} else if (lowerCased === 'onblur') {\n\t\t\t\ti = 'onfocusout';\n\t\t\t} else if (ON_ANI.test(i)) {\n\t\t\t\ti = lowerCased;\n\t\t\t}\n\t\t} else if (isNonDashedType && CAMEL_PROPS.test(i)) {\n\t\t\ti = i.replace(CAMEL_REPLACE, '-$&').toLowerCase();\n\t\t} else if (value === null) {\n\t\t\tvalue = undefined;\n\t\t}\n\n\t\t// Add support for onInput and onChange, see #3561\n\t\t// if we have an oninput prop already change it to oninputCapture\n\t\tif (lowerCased === 'oninput') {\n\t\t\ti = lowerCased;\n\t\t\tif (normalizedProps[i]) {\n\t\t\t\ti = 'oninputCapture';\n\t\t\t}\n\t\t}\n\n\t\tnormalizedProps[i] = value;\n\t}\n\n\t// Add support for array select values: \n\tif (\n\t\ttype == 'select' &&\n\t\tnormalizedProps.multiple &&\n\t\tArray.isArray(normalizedProps.value)\n\t) {\n\t\t// forEach() always returns undefined, which we abuse here to unset the value prop.\n\t\tnormalizedProps.value = toChildArray(props.children).forEach(child => {\n\t\t\tchild.props.selected =\n\t\t\t\tnormalizedProps.value.indexOf(child.props.value) != -1;\n\t\t});\n\t}\n\n\t// Adding support for defaultValue in select tag\n\tif (type == 'select' && normalizedProps.defaultValue != null) {\n\t\tnormalizedProps.value = toChildArray(props.children).forEach(child => {\n\t\t\tif (normalizedProps.multiple) {\n\t\t\t\tchild.props.selected =\n\t\t\t\t\tnormalizedProps.defaultValue.indexOf(child.props.value) != -1;\n\t\t\t} else {\n\t\t\t\tchild.props.selected =\n\t\t\t\t\tnormalizedProps.defaultValue == child.props.value;\n\t\t\t}\n\t\t});\n\t}\n\n\tif (props.class && !props.className) {\n\t\tnormalizedProps.class = props.class;\n\t\tObject.defineProperty(\n\t\t\tnormalizedProps,\n\t\t\t'className',\n\t\t\tclassNameDescriptorNonEnumberable\n\t\t);\n\t} else if (props.className && !props.class) {\n\t\tnormalizedProps.class = normalizedProps.className = props.className;\n\t} else if (props.class && props.className) {\n\t\tnormalizedProps.class = normalizedProps.className = props.className;\n\t}\n\n\tvnode.props = normalizedProps;\n}\n\nlet oldVNodeHook = options.vnode;\noptions.vnode = vnode => {\n\t// only normalize props on Element nodes\n\tif (typeof vnode.type === 'string') {\n\t\thandleDomVNode(vnode);\n\t}\n\n\tvnode.$$typeof = REACT_ELEMENT_TYPE;\n\n\tif (oldVNodeHook) oldVNodeHook(vnode);\n};\n\n// Only needed for react-relay\nlet currentComponent;\nconst oldBeforeRender = options._render;\noptions._render = function (vnode) {\n\tif (oldBeforeRender) {\n\t\toldBeforeRender(vnode);\n\t}\n\tcurrentComponent = vnode._component;\n};\n\nconst oldDiffed = options.diffed;\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions.diffed = function (vnode) {\n\tif (oldDiffed) {\n\t\toldDiffed(vnode);\n\t}\n\n\tconst props = vnode.props;\n\tconst dom = vnode._dom;\n\n\tif (\n\t\tdom != null &&\n\t\tvnode.type === 'textarea' &&\n\t\t'value' in props &&\n\t\tprops.value !== dom.value\n\t) {\n\t\tdom.value = props.value == null ? '' : props.value;\n\t}\n\n\tcurrentComponent = null;\n};\n\n// This is a very very private internal function for React it\n// is used to sort-of do runtime dependency injection.\nexport const __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = {\n\tReactCurrentDispatcher: {\n\t\tcurrent: {\n\t\t\treadContext(context) {\n\t\t\t\treturn currentComponent._globalContext[context._id].props.value;\n\t\t\t},\n\t\t\tuseCallback,\n\t\t\tuseContext,\n\t\t\tuseDebugValue,\n\t\t\tuseDeferredValue,\n\t\t\tuseEffect,\n\t\t\tuseId,\n\t\t\tuseImperativeHandle,\n\t\t\tuseInsertionEffect,\n\t\t\tuseLayoutEffect,\n\t\t\tuseMemo,\n\t\t\t// useMutableSource, // experimental-only and replaced by uSES, likely not worth supporting\n\t\t\tuseReducer,\n\t\t\tuseRef,\n\t\t\tuseState,\n\t\t\tuseSyncExternalStore,\n\t\t\tuseTransition\n\t\t}\n\t}\n};\n","import {\n\tcreateElement,\n\trender as preactRender,\n\tcloneElement as preactCloneElement,\n\tcreateRef,\n\tComponent,\n\tcreateContext,\n\tFragment\n} from 'preact';\nimport {\n\tuseState,\n\tuseId,\n\tuseReducer,\n\tuseEffect,\n\tuseLayoutEffect,\n\tuseRef,\n\tuseImperativeHandle,\n\tuseMemo,\n\tuseCallback,\n\tuseContext,\n\tuseDebugValue\n} from 'preact/hooks';\nimport {\n\tuseInsertionEffect,\n\tstartTransition,\n\tuseDeferredValue,\n\tuseSyncExternalStore,\n\tuseTransition\n} from './hooks';\nimport { PureComponent } from './PureComponent';\nimport { memo } from './memo';\nimport { forwardRef } from './forwardRef';\nimport { Children } from './Children';\nimport { Suspense, lazy } from './suspense';\nimport { SuspenseList } from './suspense-list';\nimport { createPortal } from './portals';\nimport {\n\thydrate,\n\trender,\n\tREACT_ELEMENT_TYPE,\n\t__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED\n} from './render';\n\nconst version = '18.3.1'; // trick libraries to think we are react\n\n/**\n * Legacy version of createElement.\n * @param {import('./internal').VNode[\"type\"]} type The node name or Component constructor\n */\nfunction createFactory(type) {\n\treturn createElement.bind(null, type);\n}\n\n/**\n * Check if the passed element is a valid (p)react node.\n * @param {*} element The element to check\n * @returns {boolean}\n */\nfunction isValidElement(element) {\n\treturn !!element && element.$$typeof === REACT_ELEMENT_TYPE;\n}\n\n/**\n * Check if the passed element is a Fragment node.\n * @param {*} element The element to check\n * @returns {boolean}\n */\nfunction isFragment(element) {\n\treturn isValidElement(element) && element.type === Fragment;\n}\n\n/**\n * Check if the passed element is a Memo node.\n * @param {*} element The element to check\n * @returns {boolean}\n */\nfunction isMemo(element) {\n\treturn (\n\t\t!!element &&\n\t\t!!element.displayName &&\n\t\t(typeof element.displayName === 'string' ||\n\t\t\telement.displayName instanceof String) &&\n\t\telement.displayName.startsWith('Memo(')\n\t);\n}\n\n/**\n * Wrap `cloneElement` to abort if the passed element is not a valid element and apply\n * all vnode normalizations.\n * @param {import('./internal').VNode} element The vnode to clone\n * @param {object} props Props to add when cloning\n * @param {Array} rest Optional component children\n */\nfunction cloneElement(element) {\n\tif (!isValidElement(element)) return element;\n\treturn preactCloneElement.apply(null, arguments);\n}\n\n/**\n * Remove a component tree from the DOM, including state and event handlers.\n * @param {import('./internal').PreactElement} container\n * @returns {boolean}\n */\nfunction unmountComponentAtNode(container) {\n\tif (container._children) {\n\t\tpreactRender(null, container);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n/**\n * Get the matching DOM node for a component\n * @param {import('./internal').Component} component\n * @returns {import('./internal').PreactElement | null}\n */\nfunction findDOMNode(component) {\n\treturn (\n\t\t(component &&\n\t\t\t(component.base || (component.nodeType === 1 && component))) ||\n\t\tnull\n\t);\n}\n\n/**\n * Deprecated way to control batched rendering inside the reconciler, but we\n * already schedule in batches inside our rendering code\n * @template Arg\n * @param {(arg: Arg) => void} callback function that triggers the updated\n * @param {Arg} [arg] Optional argument that can be passed to the callback\n */\n// eslint-disable-next-line camelcase\nconst unstable_batchedUpdates = (callback, arg) => callback(arg);\n\n/**\n * In React, `flushSync` flushes the entire tree and forces a rerender. It's\n * implmented here as a no-op.\n * @template Arg\n * @template Result\n * @param {(arg: Arg) => Result} callback function that runs before the flush\n * @param {Arg} [arg] Optional argument that can be passed to the callback\n * @returns\n */\nconst flushSync = (callback, arg) => callback(arg);\n\n/**\n * Strict Mode is not implemented in Preact, so we provide a stand-in for it\n * that just renders its children without imposing any restrictions.\n */\nconst StrictMode = Fragment;\n\n// compat to react-is\nexport const isElement = isValidElement;\n\nexport * from 'preact/hooks';\nexport {\n\tversion,\n\tChildren,\n\trender,\n\thydrate,\n\tunmountComponentAtNode,\n\tcreatePortal,\n\tcreateElement,\n\tcreateContext,\n\tcreateFactory,\n\tcloneElement,\n\tcreateRef,\n\tFragment,\n\tisValidElement,\n\tisFragment,\n\tisMemo,\n\tfindDOMNode,\n\tComponent,\n\tPureComponent,\n\tmemo,\n\tforwardRef,\n\tflushSync,\n\tuseInsertionEffect,\n\tstartTransition,\n\tuseDeferredValue,\n\tuseSyncExternalStore,\n\tuseTransition,\n\t// eslint-disable-next-line camelcase\n\tunstable_batchedUpdates,\n\tStrictMode,\n\tSuspense,\n\tSuspenseList,\n\tlazy,\n\t__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED\n};\n\n// React copies the named exports to the default one.\nexport default {\n\tuseState,\n\tuseId,\n\tuseReducer,\n\tuseEffect,\n\tuseLayoutEffect,\n\tuseInsertionEffect,\n\tuseTransition,\n\tuseDeferredValue,\n\tuseSyncExternalStore,\n\tstartTransition,\n\tuseRef,\n\tuseImperativeHandle,\n\tuseMemo,\n\tuseCallback,\n\tuseContext,\n\tuseDebugValue,\n\tversion,\n\tChildren,\n\trender,\n\thydrate,\n\tunmountComponentAtNode,\n\tcreatePortal,\n\tcreateElement,\n\tcreateContext,\n\tcreateFactory,\n\tcloneElement,\n\tcreateRef,\n\tFragment,\n\tisValidElement,\n\tisElement,\n\tisFragment,\n\tisMemo,\n\tfindDOMNode,\n\tComponent,\n\tPureComponent,\n\tmemo,\n\tforwardRef,\n\tflushSync,\n\tunstable_batchedUpdates,\n\tStrictMode,\n\tSuspense,\n\tSuspenseList,\n\tlazy,\n\t__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED\n};\n"],"names":["assign","obj","props","i","shallowDiffers","a","b","useSyncExternalStore","subscribe","getSnapshot","value","_useState","useState","_instance","__","_getSnapshot","forceUpdate","useLayoutEffect","didSnapshotChange","useEffect","inst","x","y","latestGetSnapshot","prevValue","nextValue","error","startTransition","cb","useDeferredValue","val","useTransition","useInsertionEffect","PureComponent","p","c","this","context","memo","comparer","shouldUpdate","nextProps","ref","updateRef","call","current","Memoed","shouldComponentUpdate","createElement","displayName","name","prototype","isReactComponent","__f","type","Component","isPureReactComponent","state","oldDiffHook","options","__b","vnode","REACT_FORWARD_SYMBOL","Symbol","for","forwardRef","fn","Forwarded","clone","$$typeof","render","mapFn","children","toChildArray","map","Children","forEach","count","length","only","normalized","toArray","oldCatchError","__e","newVNode","oldVNode","errorInfo","then","component","__c","__k","oldUnmount","unmount","detachedClone","detachedParent","parentDom","__H","effect","__P","child","removeOriginal","originalParent","__v","appendChild","Suspense","__u","_suspenders","suspended","__a","lazy","loader","prom","resolved","Lazy","exports","default","e","SuspenseList","_next","_map","__R","promise","suspendingVNode","suspendingComponent","push","resolve","onResolved","onSuspensionComplete","suspendedVNode","__O","setState","pop","componentWillUnmount","document","detachedComponent","fallback","Fragment","list","node","delete","revealOrder","size","ContextProvider","getChildContext","Portal","_this","container","_container","_temp","root","__m","nodeType","parentNode","childNodes","contains","insertBefore","before","removeChild","splice","indexOf","createPortal","el","containerInfo","delegated","get","unsuspend","wrappedUnsuspend","Map","reverse","set","componentDidUpdate","componentDidMount","REACT_ELEMENT_TYPE","CAMEL_PROPS","ON_ANI","CAMEL_REPLACE","IS_DOM","onChangeInputType","test","parent","callback","textContent","preactRender","hydrate","preactHydrate","key","Object","defineProperty","configurable","v","writable","oldEventHook","event","empty","isPropagationStopped","cancelBubble","isDefaultPrevented","defaultPrevented","persist","nativeEvent","currentComponent","classNameDescriptorNonEnumberable","enumerable","class","oldVNodeHook","normalizedProps","isNonDashedType","lowerCased","toLowerCase","replace","undefined","multiple","Array","isArray","selected","defaultValue","className","handleDomVNode","oldBeforeRender","__r","oldDiffed","diffed","dom","__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED","ReactCurrentDispatcher","readContext","__n","useCallback","useContext","useDebugValue","useId","useImperativeHandle","useMemo","useReducer","useRef","version","createFactory","bind","isValidElement","element","isFragment","isMemo","String","startsWith","cloneElement","preactCloneElement","apply","arguments","unmountComponentAtNode","findDOMNode","base","unstable_batchedUpdates","arg","flushSync","StrictMode","isElement","index","createContext","createRef"],"mappings":"oeAOgB,SAAAA,EAAOC,EAAKC,GAC3B,IAAK,IAAIC,KAAKD,EAAOD,EAAIE,GAAKD,EAAMC,GACpC,OAA6BF,CAC9B,CAQO,SAASG,EAAeC,EAAGC,GACjC,IAAK,IAAIH,KAAKE,EAAG,GAAU,aAANF,KAAsBA,KAAKG,GAAI,OAAW,EAC/D,IAAK,IAAIH,KAAKG,EAAG,GAAU,aAANH,GAAoBE,EAAEF,KAAOG,EAAEH,GAAI,OAAW,EACnE,OAAO,CACR,CCdgB,SAAAI,EAAqBC,EAAWC,GAC/C,IAAMC,EAAQD,IAMdE,EAAqCC,EAAS,CAC7CC,EAAW,CAAEC,GAAQJ,EAAOK,EAAcN,KADlCI,EAASF,EAATE,GAAAA,EAAaG,EAAWL,EAIjCM,GAqBA,OArBAA,EAAgB,WACfJ,EAASC,GAAUJ,EACnBG,EAAUE,EAAeN,EAErBS,EAAkBL,IACrBG,EAAY,CAAEH,EAAAA,GAEhB,EAAG,CAACL,EAAWE,EAAOD,IAEtBU,EAAU,WAKT,OAJID,EAAkBL,IACrBG,EAAY,CAAEH,EAAAA,IAGRL,EAAU,WACZU,EAAkBL,IACrBG,EAAY,CAAEH,EAAAA,GAEhB,EACD,EAAG,CAACL,IAEGE,CACR,CAGA,SAASQ,EAAkBE,GAC1B,IDfkBC,EAAGC,ECefC,EAAoBH,EAAKL,EACzBS,EAAYJ,EAAIN,GACtB,IACC,IAAMW,EAAYF,IAClB,SDnBiBF,ECmBNG,MDnBSF,ECmBEG,KDlBG,IAANJ,GAAW,EAAIA,GAAM,EAAIC,IAAQD,GAAMA,GAAKC,GAAMA,ECqBtE,CAFE,MAAOI,GACR,OACD,CAAA,CACD,CAEgB,SAAAC,EAAgBC,GAC/BA,GACD,CAEgB,SAAAC,EAAiBC,GAChC,OAAOA,CACR,CAEgB,SAAAC,IACf,MAAO,EAAC,EAAOJ,EAChB,CAIa,IAAAK,EAAqBf,WC/DlBgB,EAAcC,EAAGC,GAChCC,KAAKlC,MAAQgC,EACbE,KAAKC,QAAUF,CAChB,UCCgBG,EAAKH,EAAGI,GACvB,SAASC,EAAaC,GACrB,IAAIC,EAAMN,KAAKlC,MAAMwC,IACjBC,EAAYD,GAAOD,EAAUC,IAKjC,OAJKC,GAAaD,IACjBA,EAAIE,KAAOF,EAAI,MAASA,EAAIG,QAAU,MAGlCN,GAIGA,EAASH,KAAKlC,MAAOuC,KAAeE,EAHpCvC,EAAegC,KAAKlC,MAAOuC,EAIpC,CAEA,SAASK,EAAO5C,GAEf,OADAkC,KAAKW,sBAAwBP,EACtBQ,EAAcb,EAAGjC,EACzB,CAKA,OAJA4C,EAAOG,YAAc,SAAWd,EAAEc,aAAed,EAAEe,MAAQ,IAC3DJ,EAAOK,UAAUC,kBAAmB,EACpCN,EAAMO,KAAc,EACpBP,EAAOQ,KAAOnB,EACPW,CACR,EDxBAb,EAAckB,UAAY,IAAII,GAENC,sBAAuB,EAC/CvB,EAAckB,UAAUJ,sBAAwB,SAAU7C,EAAOuD,GAChE,OAAOrD,EAAegC,KAAKlC,MAAOA,IAAUE,EAAegC,KAAKqB,MAAOA,EACxE,EEZA,IAAIC,EAAcC,EAAOC,IACzBD,EAAOC,IAAS,SAAAC,GACXA,EAAMP,MAAQO,EAAMP,KAAID,KAAeQ,EAAMnB,MAChDmB,EAAM3D,MAAMwC,IAAMmB,EAAMnB,IACxBmB,EAAMnB,IAAM,MAETgB,GAAaA,EAAYG,EAC9B,EAEO,IAAMC,EACM,oBAAVC,QACPA,OAAOC,KACPD,OAAOC,IAAI,sBACZ,cASeC,EAAWC,GAC1B,SAASC,EAAUjE,GAClB,IAAIkE,EAAQpE,EAAO,CAAE,EAAEE,GAEvB,cADOkE,EAAM1B,IACNwB,EAAGE,EAAOlE,EAAMwC,KAAO,KAC/B,CAYA,OATAyB,EAAUE,SAAWP,EAKrBK,EAAUG,OAASJ,EAEnBC,EAAUhB,UAAUC,iBAAmBe,EAASd,KAAc,EAC9Dc,EAAUlB,YAAc,eAAiBiB,EAAGjB,aAAeiB,EAAGhB,MAAQ,IAC/DiB,CACR,CCzCA,IAAMI,EAAQ,SAACC,EAAUN,GACxB,OAAgB,MAAZM,EAA6B,KAC1BC,EAAaA,EAAaD,GAAUE,IAAIR,GAChD,EAGaS,EAAW,CACvBD,IAAKH,EACLK,QAASL,EACTM,MAAK,SAACL,GACL,OAAOA,EAAWC,EAAaD,GAAUM,OAAS,CACnD,EACAC,KAAI,SAACP,GACJ,IAAMQ,EAAaP,EAAaD,GAChC,GAA0B,IAAtBQ,EAAWF,OAAc,KAAM,gBACnC,OAAOE,EAAW,EACnB,EACAC,QAASR,GCfJS,EAAgBvB,EAAOwB,IAC7BxB,EAAOwB,IAAe,SAAUzD,EAAO0D,EAAUC,EAAUC,GAC1D,GAAI5D,EAAM6D,KAKT,IAHA,IAAIC,EACA3B,EAAQuB,EAEJvB,EAAQA,EAAK/C,IACpB,IAAK0E,EAAY3B,EAAK4B,MAAgBD,EAASC,IAM9C,OALqB,MAAjBL,EAAQD,MACXC,EAAQD,IAAQE,EAAQF,IACxBC,EAAQM,IAAaL,EAAQK,KAGvBF,EAASC,IAAkB/D,EAAO0D,GAI5CF,EAAcxD,EAAO0D,EAAUC,EAAUC,EAC1C,EAEA,IAAMK,EAAahC,EAAQiC,QAmB3B,SAASC,EAAchC,EAAOiC,EAAgBC,GA4B7C,OA3BIlC,IACCA,EAAK4B,KAAe5B,EAAK4B,IAAAO,MAC5BnC,EAAK4B,IAAAO,IAAAlF,GAA0B8D,QAAQ,SAAAqB,GACR,mBAAnBA,EAAMR,KAAyBQ,EAAMR,KACjD,GAEA5B,EAAK4B,IAAAO,IAAsB,MAIJ,OADxBnC,EAAQ7D,EAAO,CAAE,EAAE6D,IACV4B,MACJ5B,EAAK4B,IAAAS,MAA2BH,IACnClC,EAAK4B,IAAAS,IAAyBJ,GAG/BjC,EAAK4B,IAAAN,KAAqB,EAE1BtB,EAAK4B,IAAc,MAGpB5B,EAAK6B,IACJ7B,EAAK6B,KACL7B,EAAK6B,IAAWhB,IAAI,SAAAyB,GACnB,OAAAN,EAAcM,EAAOL,EAAgBC,EAAU,IAI3ClC,CACR,CAEA,SAASuC,EAAevC,EAAOiC,EAAgBO,GAoB9C,OAnBIxC,GAASwC,IACZxC,EAAKyC,IAAa,KAClBzC,EAAK6B,IACJ7B,EAAK6B,KACL7B,EAAK6B,IAAWhB,IAAI,SAAAyB,GACnB,OAAAC,EAAeD,EAAOL,EAAgBO,EAAe,GAGnDxC,EAAK4B,KACJ5B,EAAK4B,IAAAS,MAA2BJ,IAC/BjC,EAAKsB,KACRkB,EAAeE,YAAY1C,EAAKsB,KAEjCtB,EAAK4B,IAAAN,KAAqB,EAC1BtB,EAAK4B,IAAAS,IAAyBG,IAK1BxC,CACR,CAGO,SAAS2C,IAEfpE,KAAIqE,IAA2B,EAC/BrE,KAAKsE,EAAc,KACnBtE,KAAIwB,IAAuB,IAC5B,CAqIgB,SAAA+C,EAAU9C,GAEzB,IAAI2B,EAAY3B,EAAK/C,GAAA2E,IACrB,OAAOD,GAAaA,EAASoB,KAAepB,EAASoB,IAAY/C,EAClE,CAEgB,SAAAgD,EAAKC,GACpB,IAAIC,EAEArF,EACAsF,EAFAxB,EAAY,KAIhB,SAASyB,EAAK/G,GAiBb,GAhBK6G,IACJA,EAAOD,KACFvB,KACJ,SAAA2B,GACKA,IACH1B,EAAY0B,EAAQC,SAAWD,GAEhCF,GAAW,CACZ,EACA,SAAAI,GACC1F,EAAQ0F,EACRJ,GAAW,CACZ,GAIEtF,EACH,MAAMA,EAGP,IAAKsF,EACJ,MAAMD,EAGP,OAAOvB,EAAYxC,EAAcwC,EAAWtF,GAAS,IACtD,CAIA,OAFA+G,EAAKhE,YAAc,OACnBgE,EAAI5D,KAAc,EACX4D,CACR,UC/QgBI,IACfjF,KAAKkF,EAAQ,KACblF,KAAKmF,EAAO,IACb,CDcA5D,EAAQiC,QAAU,SAAU/B,GAE3B,IAAM2B,EAAY3B,EAAK4B,IACnBD,GAAaA,EAASgC,KACzBhC,EAASgC,MAONhC,GEpCuB,GFoCV3B,EAAK4C,MACrB5C,EAAMP,KAAO,MAGVqC,GAAYA,EAAW9B,EAC5B,GAmEA2C,EAASrD,UAAY,IAAII,GAOPkC,IAAoB,SAAUgC,EAASC,GACxD,IAAMC,EAAsBD,EAAejC,IAGrCtD,EAAIC,KAEW,MAAjBD,EAAEuE,IACLvE,EAAEuE,EAAc,IAEjBvE,EAAEuE,EAAYkB,KAAKD,GAEnB,IAAME,EAAUlB,EAAUxE,EAACmE,KAEvBU,GAAW,EACTc,EAAa,WACdd,IAEJA,GAAW,EACXW,EAAmBH,IAAc,KAE7BK,EACHA,EAAQE,GAERA,IAEF,EAEAJ,EAAmBH,IAAcM,EAEjC,IAAMC,EAAuB,WAC5B,MAAO5F,EAACsE,IAA0B,CAGjC,GAAItE,EAAEsB,MAAKmD,IAAa,CACvB,IAAMoB,EAAiB7F,EAAEsB,MAAKmD,IAC9BzE,EAACmE,IAAAZ,IAAkB,GAAKU,EACvB4B,EACAA,EAAcvC,IAAAS,IACd8B,EAAcvC,IAAAwC,IAEhB,CAIA,IAAItB,EACJ,IAHAxE,EAAE+F,SAAS,CAAEtB,IAAazE,EAACyB,IAAuB,OAG1C+C,EAAYxE,EAAEuE,EAAYyB,OACjCxB,EAAU3F,aAEZ,CACD,EAQEmB,EAACsE,OE5KwB,GF6KxBiB,EAAejB,KAEjBtE,EAAE+F,SAAS,CAAEtB,IAAazE,EAACyB,IAAuBzB,EAACmE,IAAAZ,IAAkB,KAEtE+B,EAAQlC,KAAKuC,EAAYA,EAC1B,EAEAtB,EAASrD,UAAUiF,qBAAuB,WACzChG,KAAKsE,EAAc,EACpB,EAOAF,EAASrD,UAAUmB,OAAS,SAAUpE,EAAOuD,GAC5C,GAAIrB,KAAIwB,IAAsB,CAI7B,GAAIxB,KAAIkE,IAAAZ,IAAmB,CAC1B,IAAMI,EAAiBuC,SAASrF,cAAc,OACxCsF,EAAoBlG,KAAIkE,IAAAZ,IAAkB,GAAED,IAClDrD,KAAIkE,IAAAZ,IAAkB,GAAKG,EAC1BzD,KAAIwB,IACJkC,EACCwC,EAAiBL,IAAsBK,EAAiBpC,IAE3D,CAEA9D,KAAIwB,IAAuB,IAC5B,CAIA,IAAM2E,EACL9E,EAAKmD,KAAe5D,EAAcwF,EAAU,KAAMtI,EAAMqI,UAGzD,OAFIA,IAAUA,EAAQ9B,MAAW,IAE1B,CACNzD,EAAcwF,EAAU,KAAM/E,EAAKmD,IAAc,KAAO1G,EAAMsE,UAC9D+D,EAEF,ECxMA,IAAMV,EAAU,SAACY,EAAMtC,EAAOuC,GAc7B,KAbMA,EAdgB,KAcSA,EAfR,IAqBtBD,EAAKlB,EAAKoB,OAAOxC,GAQhBsC,EAAKvI,MAAM0I,cACmB,MAA9BH,EAAKvI,MAAM0I,YAAY,KAAcH,EAAKlB,EAAKsB,MASjD,IADAH,EAAOD,EAAKnB,EACLoB,GAAM,CACZ,KAAOA,EAAK5D,OAAS,GACpB4D,EAAKP,KAALO,GAED,GAAIA,EA1CiB,GA0CMA,EA3CL,GA4CrB,MAEDD,EAAKnB,EAAQoB,EAAOA,EA5CJ,EA6CjB,CACD,EE/CA,SAASI,EAAgB5I,GAExB,OADAkC,KAAK2G,gBAAkB,WAAM,OAAA7I,EAAMmC,OAAO,EACnCnC,EAAMsE,QACd,CASA,SAASwE,EAAO9I,GACf,IAAM+I,EAAQ7G,KACV8G,EAAYhJ,EAAMiJ,EActB,GAZAF,EAAMb,qBAAuB,WAC5B9D,EAAO,KAAM2E,EAAMG,GACnBH,EAAMG,EAAQ,KACdH,EAAME,EAAa,IACpB,EAIIF,EAAME,GAAcF,EAAME,IAAeD,GAC5CD,EAAMb,wBAGFa,EAAMG,EAAO,CAGjB,IADA,IAAIC,EAAOJ,EAAK3C,IACA,OAAT+C,IAAkBA,EAAIC,KAA2B,OAAjBD,EAAIvI,IAC1CuI,EAAOA,EAAIvI,GAGZmI,EAAME,EAAaD,EAGnBD,EAAMG,EAAQ,CACbG,SAAU,EACVC,WAAYN,EACZO,WAAY,GACZ/D,IAAW,CAAE4D,IAAOD,EAAIC,KACxBI,SAAU,WAAF,QAAY,EACpBC,aAAA,SAAaxD,EAAOyD,GACnBxH,KAAKqH,WAAW7B,KAAKzB,GACrB8C,EAAME,EAAWQ,aAAaxD,EAAOyD,EACtC,EACAC,qBAAY1D,GACX/D,KAAKqH,WAAWK,OAAO1H,KAAKqH,WAAWM,QAAQ5D,KAAW,EAAG,GAC7D8C,EAAME,EAAWU,YAAY1D,EAC9B,EAEF,CAGA7B,EACCtB,EAAc8F,EAAiB,CAAEzG,QAAS4G,EAAM5G,SAAWnC,EAAKoG,KAChE2C,EAAMG,EAER,CAOO,SAASY,EAAanG,EAAOqF,GACnC,IAAMe,EAAKjH,EAAcgG,EAAQ,CAAE1C,IAAQzC,EAAOsF,EAAYD,IAE9D,OADAe,EAAGC,cAAgBhB,EACZe,CACR,EFnBA5C,EAAalE,UAAY,IAAII,GAEPqD,IAAc,SAAUT,GAC7C,IAAMsC,EAAOrG,KACP+H,EAAYxD,EAAU8B,EAAInC,KAE5BoC,EAAOD,EAAKlB,EAAK6C,IAAIjE,GAGzB,OAFAuC,EA5DuB,KA8DhB,SAAA2B,GACN,IAAMC,EAAmB,WACnB7B,EAAKvI,MAAM0I,aAKfF,EAAKd,KAAKyC,GACVxC,EAAQY,EAAMtC,EAAOuC,IAHrB2B,GAKF,EACIF,EACHA,EAAUG,GAEVA,GAEF,CACD,EAEAjD,EAAalE,UAAUmB,OAAS,SAAUpE,GACzCkC,KAAKkF,EAAQ,KACblF,KAAKmF,EAAO,IAAIgD,IAEhB,IAAM/F,EAAWC,EAAavE,EAAMsE,UAChCtE,EAAM0I,aAAwC,MAAzB1I,EAAM0I,YAAY,IAI1CpE,EAASgG,UAIV,IAAK,IAAIrK,EAAIqE,EAASM,OAAQ3E,KAY7BiC,KAAKmF,EAAKkD,IAAIjG,EAASrE,GAAKiC,KAAKkF,EAAQ,CAAC,EAAG,EAAGlF,KAAKkF,IAEtD,OAAOpH,EAAMsE,QACd,EAEA6C,EAAalE,UAAUuH,mBACtBrD,EAAalE,UAAUwH,kBAAoB,eAAY1B,EAAA7G,KAOtDA,KAAKmF,EAAK3C,QAAQ,SAAC8D,EAAMvC,GACxB0B,EAAQoB,EAAM9C,EAAOuC,EACtB,EACD,EGnGY,IAAAkC,EACM,oBAAV7G,QAAyBA,OAAOC,KAAOD,OAAOC,IAAI,kBAC1D,MAEK6G,EACL,8RACKC,EAAS,mCACTC,EAAgB,YAChBC,EAA6B,oBAAb3C,SAKhB4C,EAAoB,SAAA3H,GACzB,OAAkB,oBAAVS,QAA4C,iBAAZA,SACrC,cACA,cACDmH,KAAK5H,EAAK,EAuCG,SAAAgB,GAAOT,EAAOsH,EAAQC,GAUrC,OAPwB,MAApBD,EAAMzF,MACTyF,EAAOE,YAAc,IAGtBC,EAAazH,EAAOsH,GACG,mBAAZC,GAAwBA,IAE5BvH,EAAQA,EAAK4B,IAAc,IACnC,CAEgB,SAAA8F,GAAQ1H,EAAOsH,EAAQC,GAItC,OAHAI,EAAc3H,EAAOsH,GACE,mBAAZC,GAAwBA,IAE5BvH,EAAQA,EAAK4B,IAAc,IACnC,CAtDAlC,EAAUJ,UAAUC,iBAAmB,CAAA,EASvC,CACC,qBACA,4BACA,uBACCwB,QAAQ,SAAA6G,GACTC,OAAOC,eAAepI,EAAUJ,UAAWsI,EAAK,CAC/CG,cAAc,EACdxB,IAAG,WACF,OAAOhI,KAAK,UAAYqJ,EACzB,EACAhB,IAAG,SAACoB,GACHH,OAAOC,eAAevJ,KAAMqJ,EAAK,CAChCG,cAAc,EACdE,UAAU,EACVpL,MAAOmL,GAET,GAEF,GA6BA,IAAIE,GAAepI,EAAQqI,MAU3B,SAASC,KAAQ,CAEjB,SAASC,KACR,OAAW9J,KAAC+J,YACb,CAEA,SAASC,KACR,OAAOhK,KAAKiK,gBACb,CAjBA1I,EAAQqI,MAAQ,SAAA5E,GAMf,OALI2E,KAAc3E,EAAI2E,GAAa3E,IAEnCA,EAAEkF,QAAUL,GACZ7E,EAAE8E,qBAAuBA,GACzB9E,EAAEgF,mBAAqBA,GACfhF,EAAEmF,YAAcnF,CACzB,EAYA,IAoIIoF,GApIEC,GAAoC,CACzCC,YAAY,EACZd,cAAc,EACdxB,eACC,OAAWhI,KAACuK,KACb,GAkHGC,GAAejJ,EAAQE,MAC3BF,EAAQE,MAAQ,SAAAA,GAEW,iBAAfA,EAAMP,MAlHlB,SAAwBO,GACvB,IAAI3D,EAAQ2D,EAAM3D,MACjBoD,EAAOO,EAAMP,KACbuJ,EAAkB,CAAE,EAEjBC,GAAyC,IAAvBxJ,EAAKyG,QAAQ,KACnC,IAAK,IAAI5J,KAAKD,EAAO,CACpB,IAAIQ,EAAQR,EAAMC,GAElB,KACQ,UAANA,GAAiB,iBAAkBD,GAAkB,MAATQ,GAE5CsK,GAAgB,aAAN7K,GAA6B,aAATmD,GACzB,UAANnD,GACM,cAANA,GALD,CAYA,IAAI4M,EAAa5M,EAAE6M,cACT,iBAAN7M,GAAwB,UAAWD,GAAwB,MAAfA,EAAMQ,MAGrDP,EAAI,QACY,aAANA,IAA8B,IAAVO,EAM9BA,EAAQ,GACiB,cAAfqM,GAAwC,OAAVrM,EACxCA,GAAQ,EACoB,MAAlBqM,EAAW,IAAgC,MAAlBA,EAAW,GAC3B,kBAAfA,EACH5M,EAAI,aAEW,aAAf4M,GACU,UAATzJ,GAA6B,aAATA,GACpB2H,EAAkB/K,EAAMoD,MAGA,YAAfyJ,EACV5M,EAAI,YACqB,WAAf4M,EACV5M,EAAI,aACM2K,EAAOI,KAAK/K,KACtBA,EAAI4M,GANJA,EAAa5M,EAAI,UAQR2M,GAAmBjC,EAAYK,KAAK/K,GAC9CA,EAAIA,EAAE8M,QAAQlC,EAAe,OAAOiC,cAChB,OAAVtM,IACVA,OAAQwM,GAKU,YAAfH,GAECF,EADJ1M,EAAI4M,KAEH5M,EAAI,kBAIN0M,EAAgB1M,GAAKO,CA/CrB,CAgDD,CAIS,UAAR4C,GACAuJ,EAAgBM,UAChBC,MAAMC,QAAQR,EAAgBnM,SAG9BmM,EAAgBnM,MAAQ+D,EAAavE,EAAMsE,UAAUI,QAAQ,SAAAuB,GAC5DA,EAAMjG,MAAMoN,UAC0C,GAArDT,EAAgBnM,MAAMqJ,QAAQ5D,EAAMjG,MAAMQ,MAC5C,IAIW,UAAR4C,GAAoD,MAAhCuJ,EAAgBU,eACvCV,EAAgBnM,MAAQ+D,EAAavE,EAAMsE,UAAUI,QAAQ,SAAAuB,GAE3DA,EAAMjG,MAAMoN,SADTT,EAAgBM,UAE0C,GAA5DN,EAAgBU,aAAaxD,QAAQ5D,EAAMjG,MAAMQ,OAGjDmM,EAAgBU,cAAgBpH,EAAMjG,MAAMQ,KAE/C,IAGGR,EAAMyM,QAAUzM,EAAMsN,WACzBX,EAAgBF,MAAQzM,EAAMyM,MAC9BjB,OAAOC,eACNkB,EACA,YACAJ,MAESvM,EAAMsN,YAActN,EAAMyM,OAE1BzM,EAAMyM,OAASzM,EAAMsN,aAD/BX,EAAgBF,MAAQE,EAAgBW,UAAYtN,EAAMsN,WAK3D3J,EAAM3D,MAAQ2M,CACf,CAMEY,CAAe5J,GAGhBA,EAAMQ,SAAWuG,EAEbgC,IAAcA,GAAa/I,EAChC,EAIA,IAAM6J,GAAkB/J,EAAOgK,IAC/BhK,EAAOgK,IAAW,SAAU9J,GACvB6J,IACHA,GAAgB7J,GAEjB2I,GAAmB3I,EAAK4B,GACzB,EAEA,IAAMmI,GAAYjK,EAAQkK,OAE1BlK,EAAQkK,OAAS,SAAUhK,GACtB+J,IACHA,GAAU/J,GAGX,IAAM3D,EAAQ2D,EAAM3D,MACd4N,EAAMjK,EAAKsB,IAGT,MAAP2I,GACe,aAAfjK,EAAMP,MACN,UAAWpD,GACXA,EAAMQ,QAAUoN,EAAIpN,QAEpBoN,EAAIpN,MAAuB,MAAfR,EAAMQ,MAAgB,GAAKR,EAAMQ,OAG9C8L,GAAmB,IACpB,EAIa,IAAAuB,GAAqD,CACjEC,uBAAwB,CACvBnL,QAAS,CACRoL,qBAAY5L,GACX,OAAOmK,GAAgB0B,IAAgB7L,EAAOoD,KAAMvF,MAAMQ,KAC3D,EACAyN,YAAAA,EACAC,WAAAA,EACAC,cAAAA,EACAxM,iBAAAA,EACAV,UAAAA,EACAmN,MAAAA,EACAC,oBAAAA,EACAvM,mBAAAA,EACAf,gBAAAA,EACAuN,QAAAA,EAEAC,WAAAA,EACAC,OAAAA,EACA9N,SAAAA,EACAL,qBAAAA,EACAwB,cAAAA,KC1QG4M,GAAU,SAMhB,SAASC,GAActL,GACtB,OAAON,EAAc6L,KAAK,KAAMvL,EACjC,CAOA,SAASwL,GAAeC,GACvB,QAASA,GAAWA,EAAQ1K,WAAauG,CAC1C,CAOA,SAASoE,GAAWD,GACnB,OAAOD,GAAeC,IAAYA,EAAQzL,OAASkF,CACpD,CAOA,SAASyG,GAAOF,GACf,QACGA,KACAA,EAAQ9L,cACsB,iBAAxB8L,EAAQ9L,aACf8L,EAAQ9L,uBAAuBiM,SAChCH,EAAQ9L,YAAYkM,WAAW,QAEjC,CASA,SAASC,GAAaL,GACrB,OAAKD,GAAeC,GACbM,EAAmBC,MAAM,KAAMC,WADDR,CAEtC,CAOA,SAASS,GAAuBtG,GAC/B,QAAIA,EAASxD,MACZ4F,EAAa,KAAMpC,MAIrB,CAOA,SAASuG,GAAYjK,GACpB,OACEA,IACCA,EAAUkK,MAAgC,IAAvBlK,EAAU+D,UAAkB/D,IACjD,IAEF,CAUM,IAAAmK,GAA0B,SAACvE,EAAUwE,GAAQ,OAAAxE,EAASwE,EAAI,EAW1DC,GAAY,SAACzE,EAAUwE,UAAQxE,EAASwE,EAAI,EAM5CE,GAAatH,EAGNuH,GAAYjB,GAwCzBkB,GAAe,CACdpP,SAAAA,EACA0N,MAAAA,EACAG,WAAAA,EACAtN,UAAAA,EACAF,gBAAAA,EACAe,mBAAAA,EACAD,cAAAA,EACAF,iBAAAA,EACAtB,qBAAAA,EACAoB,gBAAAA,EACA+M,OAAAA,EACAH,oBAAAA,EACAC,QAAAA,EACAL,YAAAA,EACAC,WAAAA,EACAC,cAAAA,EACAM,QAtKe,SAuKfhK,SAAAA,EACAL,OAAAA,GACAiH,QAAAA,GACAiE,uBAAAA,GACAxF,aAAAA,EACAhH,cAAAA,EACAiN,cAAAA,EACArB,cAAAA,GACAQ,aAAAA,GACAc,UAAAA,EACA1H,SAAAA,EACAsG,eAAAA,GACAiB,UAAAA,GACAf,WAAAA,GACAC,OAAAA,GACAQ,YAAAA,GACAlM,UAAAA,EACAtB,cAAAA,EACAK,KAAAA,EACA2B,WAAAA,EACA4L,UAAAA,GACAF,wBAAAA,GACAG,WAAAA,GACAtJ,SAAAA,EACAa,aAAAA,EACAR,KAAAA,EACAkH,mDAAAA"} \ No newline at end of file diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/compat/dist/compat.umd.js b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/dist/compat.umd.js new file mode 100644 index 0000000000000..f3d4093a9c978 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/dist/compat.umd.js @@ -0,0 +1,2 @@ +!function(n,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("preact"),require("preact/hooks")):"function"==typeof define&&define.amd?define(["exports","preact","preact/hooks"],e):e((n||self).preactCompat={},n.preact,n.preactHooks)}(this,function(n,e,t){function r(n,e){for(var t in e)n[t]=e[t];return n}function u(n,e){for(var t in n)if("__source"!==t&&!(t in e))return!0;for(var r in e)if("__source"!==r&&n[r]!==e[r])return!0;return!1}function o(n,e){var r=e(),u=t.useState({t:{__:r,u:e}}),o=u[0].t,l=u[1];return t.useLayoutEffect(function(){o.__=r,o.u=e,i(o)&&l({t:o})},[n,r,e]),t.useEffect(function(){return i(o)&&l({t:o}),n(function(){i(o)&&l({t:o})})},[n]),r}function i(n){var e,t,r=n.u,u=n.__;try{var o=r();return!((e=u)===(t=o)&&(0!==e||1/e==1/t)||e!=e&&t!=t)}catch(n){return!0}}function l(n){n()}function c(n){return n}function f(){return[!1,l]}var a=t.useLayoutEffect;function s(n,e){this.props=n,this.context=e}function h(n,t){function r(n){var e=this.props.ref,r=e==n.ref;return!r&&e&&(e.call?e(null):e.current=null),t?!t(this.props,n)||!r:u(this.props,n)}function o(t){return this.shouldComponentUpdate=r,e.createElement(n,t)}return o.displayName="Memo("+(n.displayName||n.name)+")",o.prototype.isReactComponent=!0,o.__f=!0,o.type=n,o}(s.prototype=new e.Component).isPureReactComponent=!0,s.prototype.shouldComponentUpdate=function(n,e){return u(this.props,n)||u(this.state,e)};var d=e.options.__b;e.options.__b=function(n){n.type&&n.type.__f&&n.ref&&(n.props.ref=n.ref,n.ref=null),d&&d(n)};var v="undefined"!=typeof Symbol&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function m(n){function e(e){var t=r({},e);return delete t.ref,n(t,e.ref||null)}return e.$$typeof=v,e.render=n,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(n.displayName||n.name)+")",e}var p=function(n,t){return null==n?null:e.toChildArray(e.toChildArray(n).map(t))},b={map:p,forEach:p,count:function(n){return n?e.toChildArray(n).length:0},only:function(n){var t=e.toChildArray(n);if(1!==t.length)throw"Children.only";return t[0]},toArray:e.toChildArray},y=e.options.__e;e.options.__e=function(n,e,t,r){if(n.then)for(var u,o=e;o=o.__;)if((u=o.__c)&&u.__c)return null==e.__e&&(e.__e=t.__e,e.__k=t.__k),u.__c(n,e);y(n,e,t,r)};var _=e.options.unmount;function g(n,e,t){return n&&(n.__c&&n.__c.__H&&(n.__c.__H.__.forEach(function(n){"function"==typeof n.__c&&n.__c()}),n.__c.__H=null),null!=(n=r({},n)).__c&&(n.__c.__P===t&&(n.__c.__P=e),n.__c.__e=!0,n.__c=null),n.__k=n.__k&&n.__k.map(function(n){return g(n,e,t)})),n}function S(n,e,t){return n&&t&&(n.__v=null,n.__k=n.__k&&n.__k.map(function(n){return S(n,e,t)}),n.__c&&n.__c.__P===e&&(n.__e&&t.appendChild(n.__e),n.__c.__e=!0,n.__c.__P=t)),n}function E(){this.__u=0,this.o=null,this.__b=null}function C(n){var e=n.__.__c;return e&&e.__a&&e.__a(n)}function x(n){var t,r,u,o=null;function i(i){if(t||(t=n()).then(function(n){n&&(o=n.default||n),u=!0},function(n){r=n,u=!0}),r)throw r;if(!u)throw t;return o?e.createElement(o,i):null}return i.displayName="Lazy",i.__f=!0,i}function O(){this.i=null,this.l=null}e.options.unmount=function(n){var e=n.__c;e&&e.__R&&e.__R(),e&&32&n.__u&&(n.type=null),_&&_(n)},(E.prototype=new e.Component).__c=function(n,e){var t=e.__c,r=this;null==r.o&&(r.o=[]),r.o.push(t);var u=C(r.__v),o=!1,i=function(){o||(o=!0,t.__R=null,u?u(l):l())};t.__R=i;var l=function(){if(!--r.__u){if(r.state.__a){var n=r.state.__a;r.__v.__k[0]=S(n,n.__c.__P,n.__c.__O)}var e;for(r.setState({__a:r.__b=null});e=r.o.pop();)e.forceUpdate()}};r.__u++||32&e.__u||r.setState({__a:r.__b=r.__v.__k[0]}),n.then(i,i)},E.prototype.componentWillUnmount=function(){this.o=[]},E.prototype.render=function(n,t){if(this.__b){if(this.__v.__k){var r=document.createElement("div"),u=this.__v.__k[0].__c;this.__v.__k[0]=g(this.__b,r,u.__O=u.__P)}this.__b=null}var o=t.__a&&e.createElement(e.Fragment,null,n.fallback);return o&&(o.__u&=-33),[e.createElement(e.Fragment,null,t.__a?null:n.children),o]};var R=function(n,e,t){if(++t[1]===t[0]&&n.l.delete(e),n.props.revealOrder&&("t"!==n.props.revealOrder[0]||!n.l.size))for(t=n.i;t;){for(;t.length>3;)t.pop()();if(t[1]>>1,1),t.h.removeChild(n)}}}e.render(e.createElement(w,{context:t.context},n.__v),t.v)}function k(n,t){var r=e.createElement(j,{__v:n,h:t});return r.containerInfo=t,r}(O.prototype=new e.Component).__a=function(n){var e=this,t=C(e.__v),r=e.l.get(n);return r[0]++,function(u){var o=function(){e.props.revealOrder?(r.push(u),R(e,n,r)):u()};t?t(o):o()}},O.prototype.render=function(n){this.i=null,this.l=new Map;var t=e.toChildArray(n.children);n.revealOrder&&"b"===n.revealOrder[0]&&t.reverse();for(var r=t.length;r--;)this.l.set(t[r],this.i=[1,0,this.i]);return n.children},O.prototype.componentDidUpdate=O.prototype.componentDidMount=function(){var n=this;this.l.forEach(function(e,t){R(n,t,e)})};var T="undefined"!=typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103,I=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,N=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,M=/[A-Z0-9]/g,A="undefined"!=typeof document,D=function(n){return("undefined"!=typeof Symbol&&"symbol"==typeof Symbol()?/fil|che|rad/:/fil|che|ra/).test(n)};function L(n,t,r){return null==t.__k&&(t.textContent=""),e.render(n,t),"function"==typeof r&&r(),n?n.__c:null}function F(n,t,r){return e.hydrate(n,t),"function"==typeof r&&r(),n?n.__c:null}e.Component.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(n){Object.defineProperty(e.Component.prototype,n,{configurable:!0,get:function(){return this["UNSAFE_"+n]},set:function(e){Object.defineProperty(this,n,{configurable:!0,writable:!0,value:e})}})});var U=e.options.event;function V(){}function W(){return this.cancelBubble}function P(){return this.defaultPrevented}e.options.event=function(n){return U&&(n=U(n)),n.persist=V,n.isPropagationStopped=W,n.isDefaultPrevented=P,n.nativeEvent=n};var z,B={enumerable:!1,configurable:!0,get:function(){return this.class}},H=e.options.vnode;e.options.vnode=function(n){"string"==typeof n.type&&function(n){var t=n.props,r=n.type,u={},o=-1===r.indexOf("-");for(var i in t){var l=t[i];if(!("value"===i&&"defaultValue"in t&&null==l||A&&"children"===i&&"noscript"===r||"class"===i||"className"===i)){var c=i.toLowerCase();"defaultValue"===i&&"value"in t&&null==t.value?i="value":"download"===i&&!0===l?l="":"translate"===c&&"no"===l?l=!1:"o"===c[0]&&"n"===c[1]?"ondoubleclick"===c?i="ondblclick":"onchange"!==c||"input"!==r&&"textarea"!==r||D(t.type)?"onfocus"===c?i="onfocusin":"onblur"===c?i="onfocusout":N.test(i)&&(i=c):c=i="oninput":o&&I.test(i)?i=i.replace(M,"-$&").toLowerCase():null===l&&(l=void 0),"oninput"===c&&u[i=c]&&(i="oninputCapture"),u[i]=l}}"select"==r&&u.multiple&&Array.isArray(u.value)&&(u.value=e.toChildArray(t.children).forEach(function(n){n.props.selected=-1!=u.value.indexOf(n.props.value)})),"select"==r&&null!=u.defaultValue&&(u.value=e.toChildArray(t.children).forEach(function(n){n.props.selected=u.multiple?-1!=u.defaultValue.indexOf(n.props.value):u.defaultValue==n.props.value})),t.class&&!t.className?(u.class=t.class,Object.defineProperty(u,"className",B)):(t.className&&!t.class||t.class&&t.className)&&(u.class=u.className=t.className),n.props=u}(n),n.$$typeof=T,H&&H(n)};var q=e.options.__r;e.options.__r=function(n){q&&q(n),z=n.__c};var Z=e.options.diffed;e.options.diffed=function(n){Z&&Z(n);var e=n.props,t=n.__e;null!=t&&"textarea"===n.type&&"value"in e&&e.value!==t.value&&(t.value=null==e.value?"":e.value),z=null};var Y={ReactCurrentDispatcher:{current:{readContext:function(n){return z.__n[n.__c].props.value},useCallback:t.useCallback,useContext:t.useContext,useDebugValue:t.useDebugValue,useDeferredValue:c,useEffect:t.useEffect,useId:t.useId,useImperativeHandle:t.useImperativeHandle,useInsertionEffect:a,useLayoutEffect:t.useLayoutEffect,useMemo:t.useMemo,useReducer:t.useReducer,useRef:t.useRef,useState:t.useState,useSyncExternalStore:o,useTransition:f}}},$="18.3.1";function G(n){return e.createElement.bind(null,n)}function J(n){return!!n&&n.$$typeof===T}function K(n){return J(n)&&n.type===e.Fragment}function Q(n){return!!n&&!!n.displayName&&("string"==typeof n.displayName||n.displayName instanceof String)&&n.displayName.startsWith("Memo(")}function X(n){return J(n)?e.cloneElement.apply(null,arguments):n}function nn(n){return!!n.__k&&(e.render(null,n),!0)}function en(n){return n&&(n.base||1===n.nodeType&&n)||null}var tn=function(n,e){return n(e)},rn=function(n,e){return n(e)},un=e.Fragment,on=J,ln={useState:t.useState,useId:t.useId,useReducer:t.useReducer,useEffect:t.useEffect,useLayoutEffect:t.useLayoutEffect,useInsertionEffect:a,useTransition:f,useDeferredValue:c,useSyncExternalStore:o,startTransition:l,useRef:t.useRef,useImperativeHandle:t.useImperativeHandle,useMemo:t.useMemo,useCallback:t.useCallback,useContext:t.useContext,useDebugValue:t.useDebugValue,version:$,Children:b,render:L,hydrate:F,unmountComponentAtNode:nn,createPortal:k,createElement:e.createElement,createContext:e.createContext,createFactory:G,cloneElement:X,createRef:e.createRef,Fragment:e.Fragment,isValidElement:J,isElement:on,isFragment:K,isMemo:Q,findDOMNode:en,Component:e.Component,PureComponent:s,memo:h,forwardRef:m,flushSync:rn,unstable_batchedUpdates:tn,StrictMode:un,Suspense:E,SuspenseList:O,lazy:x,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Y};Object.defineProperty(n,"Component",{enumerable:!0,get:function(){return e.Component}}),Object.defineProperty(n,"Fragment",{enumerable:!0,get:function(){return e.Fragment}}),Object.defineProperty(n,"createContext",{enumerable:!0,get:function(){return e.createContext}}),Object.defineProperty(n,"createElement",{enumerable:!0,get:function(){return e.createElement}}),Object.defineProperty(n,"createRef",{enumerable:!0,get:function(){return e.createRef}}),n.Children=b,n.PureComponent=s,n.StrictMode=un,n.Suspense=E,n.SuspenseList=O,n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Y,n.cloneElement=X,n.createFactory=G,n.createPortal=k,n.default=ln,n.findDOMNode=en,n.flushSync=rn,n.forwardRef=m,n.hydrate=F,n.isElement=on,n.isFragment=K,n.isMemo=Q,n.isValidElement=J,n.lazy=x,n.memo=h,n.render=L,n.startTransition=l,n.unmountComponentAtNode=nn,n.unstable_batchedUpdates=tn,n.useDeferredValue=c,n.useInsertionEffect=a,n.useSyncExternalStore=o,n.useTransition=f,n.version=$,Object.keys(t).forEach(function(e){"default"===e||n.hasOwnProperty(e)||Object.defineProperty(n,e,{enumerable:!0,get:function(){return t[e]}})})}); +//# sourceMappingURL=compat.umd.js.map diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/compat/dist/compat.umd.js.map b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/dist/compat.umd.js.map new file mode 100644 index 0000000000000..543e302be1701 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/dist/compat.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"compat.umd.js","sources":["../src/util.js","../src/hooks.js","../src/PureComponent.js","../src/memo.js","../src/forwardRef.js","../src/Children.js","../src/suspense.js","../src/suspense-list.js","../../src/constants.js","../src/portals.js","../src/render.js","../src/index.js"],"sourcesContent":["/**\n * Assign properties from `props` to `obj`\n * @template O, P The obj and props types\n * @param {O} obj The object to copy properties to\n * @param {P} props The object to copy properties from\n * @returns {O & P}\n */\nexport function assign(obj, props) {\n\tfor (let i in props) obj[i] = props[i];\n\treturn /** @type {O & P} */ (obj);\n}\n\n/**\n * Check if two objects have a different shape\n * @param {object} a\n * @param {object} b\n * @returns {boolean}\n */\nexport function shallowDiffers(a, b) {\n\tfor (let i in a) if (i !== '__source' && !(i in b)) return true;\n\tfor (let i in b) if (i !== '__source' && a[i] !== b[i]) return true;\n\treturn false;\n}\n\n/**\n * Check if two values are the same value\n * @param {*} x\n * @param {*} y\n * @returns {boolean}\n */\nexport function is(x, y) {\n\treturn (x === y && (x !== 0 || 1 / x === 1 / y)) || (x !== x && y !== y);\n}\n","import { useState, useLayoutEffect, useEffect } from 'preact/hooks';\nimport { is } from './util';\n\n/**\n * This is taken from https://github.com/facebook/react/blob/main/packages/use-sync-external-store/src/useSyncExternalStoreShimClient.js#L84\n * on a high level this cuts out the warnings, ... and attempts a smaller implementation\n * @typedef {{ _value: any; _getSnapshot: () => any }} Store\n */\nexport function useSyncExternalStore(subscribe, getSnapshot) {\n\tconst value = getSnapshot();\n\n\t/**\n\t * @typedef {{ _instance: Store }} StoreRef\n\t * @type {[StoreRef, (store: StoreRef) => void]}\n\t */\n\tconst [{ _instance }, forceUpdate] = useState({\n\t\t_instance: { _value: value, _getSnapshot: getSnapshot }\n\t});\n\n\tuseLayoutEffect(() => {\n\t\t_instance._value = value;\n\t\t_instance._getSnapshot = getSnapshot;\n\n\t\tif (didSnapshotChange(_instance)) {\n\t\t\tforceUpdate({ _instance });\n\t\t}\n\t}, [subscribe, value, getSnapshot]);\n\n\tuseEffect(() => {\n\t\tif (didSnapshotChange(_instance)) {\n\t\t\tforceUpdate({ _instance });\n\t\t}\n\n\t\treturn subscribe(() => {\n\t\t\tif (didSnapshotChange(_instance)) {\n\t\t\t\tforceUpdate({ _instance });\n\t\t\t}\n\t\t});\n\t}, [subscribe]);\n\n\treturn value;\n}\n\n/** @type {(inst: Store) => boolean} */\nfunction didSnapshotChange(inst) {\n\tconst latestGetSnapshot = inst._getSnapshot;\n\tconst prevValue = inst._value;\n\ttry {\n\t\tconst nextValue = latestGetSnapshot();\n\t\treturn !is(prevValue, nextValue);\n\t} catch (error) {\n\t\treturn true;\n\t}\n}\n\nexport function startTransition(cb) {\n\tcb();\n}\n\nexport function useDeferredValue(val) {\n\treturn val;\n}\n\nexport function useTransition() {\n\treturn [false, startTransition];\n}\n\n// TODO: in theory this should be done after a VNode is diffed as we want to insert\n// styles/... before it attaches\nexport const useInsertionEffect = useLayoutEffect;\n","import { Component } from 'preact';\nimport { shallowDiffers } from './util';\n\n/**\n * Component class with a predefined `shouldComponentUpdate` implementation\n */\nexport function PureComponent(p, c) {\n\tthis.props = p;\n\tthis.context = c;\n}\nPureComponent.prototype = new Component();\n// Some third-party libraries check if this property is present\nPureComponent.prototype.isPureReactComponent = true;\nPureComponent.prototype.shouldComponentUpdate = function (props, state) {\n\treturn shallowDiffers(this.props, props) || shallowDiffers(this.state, state);\n};\n","import { createElement } from 'preact';\nimport { shallowDiffers } from './util';\n\n/**\n * Memoize a component, so that it only updates when the props actually have\n * changed. This was previously known as `React.pure`.\n * @param {import('./internal').FunctionComponent} c functional component\n * @param {(prev: object, next: object) => boolean} [comparer] Custom equality function\n * @returns {import('./internal').FunctionComponent}\n */\nexport function memo(c, comparer) {\n\tfunction shouldUpdate(nextProps) {\n\t\tlet ref = this.props.ref;\n\t\tlet updateRef = ref == nextProps.ref;\n\t\tif (!updateRef && ref) {\n\t\t\tref.call ? ref(null) : (ref.current = null);\n\t\t}\n\n\t\tif (!comparer) {\n\t\t\treturn shallowDiffers(this.props, nextProps);\n\t\t}\n\n\t\treturn !comparer(this.props, nextProps) || !updateRef;\n\t}\n\n\tfunction Memoed(props) {\n\t\tthis.shouldComponentUpdate = shouldUpdate;\n\t\treturn createElement(c, props);\n\t}\n\tMemoed.displayName = 'Memo(' + (c.displayName || c.name) + ')';\n\tMemoed.prototype.isReactComponent = true;\n\tMemoed._forwarded = true;\n\tMemoed.type = c;\n\treturn Memoed;\n}\n","import { options } from 'preact';\nimport { assign } from './util';\n\nlet oldDiffHook = options._diff;\noptions._diff = vnode => {\n\tif (vnode.type && vnode.type._forwarded && vnode.ref) {\n\t\tvnode.props.ref = vnode.ref;\n\t\tvnode.ref = null;\n\t}\n\tif (oldDiffHook) oldDiffHook(vnode);\n};\n\nexport const REACT_FORWARD_SYMBOL =\n\t(typeof Symbol != 'undefined' &&\n\t\tSymbol.for &&\n\t\tSymbol.for('react.forward_ref')) ||\n\t0xf47;\n\n/**\n * Pass ref down to a child. This is mainly used in libraries with HOCs that\n * wrap components. Using `forwardRef` there is an easy way to get a reference\n * of the wrapped component instead of one of the wrapper itself.\n * @param {import('./index').ForwardFn} fn\n * @returns {import('./internal').FunctionComponent}\n */\nexport function forwardRef(fn) {\n\tfunction Forwarded(props) {\n\t\tlet clone = assign({}, props);\n\t\tdelete clone.ref;\n\t\treturn fn(clone, props.ref || null);\n\t}\n\n\t// mobx-react checks for this being present\n\tForwarded.$$typeof = REACT_FORWARD_SYMBOL;\n\t// mobx-react heavily relies on implementation details.\n\t// It expects an object here with a `render` property,\n\t// and prototype.render will fail. Without this\n\t// mobx-react throws.\n\tForwarded.render = fn;\n\n\tForwarded.prototype.isReactComponent = Forwarded._forwarded = true;\n\tForwarded.displayName = 'ForwardRef(' + (fn.displayName || fn.name) + ')';\n\treturn Forwarded;\n}\n","import { toChildArray } from 'preact';\n\nconst mapFn = (children, fn) => {\n\tif (children == null) return null;\n\treturn toChildArray(toChildArray(children).map(fn));\n};\n\n// This API is completely unnecessary for Preact, so it's basically passthrough.\nexport const Children = {\n\tmap: mapFn,\n\tforEach: mapFn,\n\tcount(children) {\n\t\treturn children ? toChildArray(children).length : 0;\n\t},\n\tonly(children) {\n\t\tconst normalized = toChildArray(children);\n\t\tif (normalized.length !== 1) throw 'Children.only';\n\t\treturn normalized[0];\n\t},\n\ttoArray: toChildArray\n};\n","import { Component, createElement, options, Fragment } from 'preact';\nimport { MODE_HYDRATE } from '../../src/constants';\nimport { assign } from './util';\n\nconst oldCatchError = options._catchError;\noptions._catchError = function (error, newVNode, oldVNode, errorInfo) {\n\tif (error.then) {\n\t\t/** @type {import('./internal').Component} */\n\t\tlet component;\n\t\tlet vnode = newVNode;\n\n\t\tfor (; (vnode = vnode._parent); ) {\n\t\t\tif ((component = vnode._component) && component._childDidSuspend) {\n\t\t\t\tif (newVNode._dom == null) {\n\t\t\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t\t\t\tnewVNode._children = oldVNode._children;\n\t\t\t\t}\n\t\t\t\t// Don't call oldCatchError if we found a Suspense\n\t\t\t\treturn component._childDidSuspend(error, newVNode);\n\t\t\t}\n\t\t}\n\t}\n\toldCatchError(error, newVNode, oldVNode, errorInfo);\n};\n\nconst oldUnmount = options.unmount;\noptions.unmount = function (vnode) {\n\t/** @type {import('./internal').Component} */\n\tconst component = vnode._component;\n\tif (component && component._onResolve) {\n\t\tcomponent._onResolve();\n\t}\n\n\t// if the component is still hydrating\n\t// most likely it is because the component is suspended\n\t// we set the vnode.type as `null` so that it is not a typeof function\n\t// so the unmount will remove the vnode._dom\n\tif (component && vnode._flags & MODE_HYDRATE) {\n\t\tvnode.type = null;\n\t}\n\n\tif (oldUnmount) oldUnmount(vnode);\n};\n\nfunction detachedClone(vnode, detachedParent, parentDom) {\n\tif (vnode) {\n\t\tif (vnode._component && vnode._component.__hooks) {\n\t\t\tvnode._component.__hooks._list.forEach(effect => {\n\t\t\t\tif (typeof effect._cleanup == 'function') effect._cleanup();\n\t\t\t});\n\n\t\t\tvnode._component.__hooks = null;\n\t\t}\n\n\t\tvnode = assign({}, vnode);\n\t\tif (vnode._component != null) {\n\t\t\tif (vnode._component._parentDom === parentDom) {\n\t\t\t\tvnode._component._parentDom = detachedParent;\n\t\t\t}\n\n\t\t\tvnode._component._force = true;\n\n\t\t\tvnode._component = null;\n\t\t}\n\n\t\tvnode._children =\n\t\t\tvnode._children &&\n\t\t\tvnode._children.map(child =>\n\t\t\t\tdetachedClone(child, detachedParent, parentDom)\n\t\t\t);\n\t}\n\n\treturn vnode;\n}\n\nfunction removeOriginal(vnode, detachedParent, originalParent) {\n\tif (vnode && originalParent) {\n\t\tvnode._original = null;\n\t\tvnode._children =\n\t\t\tvnode._children &&\n\t\t\tvnode._children.map(child =>\n\t\t\t\tremoveOriginal(child, detachedParent, originalParent)\n\t\t\t);\n\n\t\tif (vnode._component) {\n\t\t\tif (vnode._component._parentDom === detachedParent) {\n\t\t\t\tif (vnode._dom) {\n\t\t\t\t\toriginalParent.appendChild(vnode._dom);\n\t\t\t\t}\n\t\t\t\tvnode._component._force = true;\n\t\t\t\tvnode._component._parentDom = originalParent;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn vnode;\n}\n\n// having custom inheritance instead of a class here saves a lot of bytes\nexport function Suspense() {\n\t// we do not call super here to golf some bytes...\n\tthis._pendingSuspensionCount = 0;\n\tthis._suspenders = null;\n\tthis._detachOnNextRender = null;\n}\n\n// Things we do here to save some bytes but are not proper JS inheritance:\n// - call `new Component()` as the prototype\n// - do not set `Suspense.prototype.constructor` to `Suspense`\nSuspense.prototype = new Component();\n\n/**\n * @this {import('./internal').SuspenseComponent}\n * @param {Promise} promise The thrown promise\n * @param {import('./internal').VNode} suspendingVNode The suspending component\n */\nSuspense.prototype._childDidSuspend = function (promise, suspendingVNode) {\n\tconst suspendingComponent = suspendingVNode._component;\n\n\t/** @type {import('./internal').SuspenseComponent} */\n\tconst c = this;\n\n\tif (c._suspenders == null) {\n\t\tc._suspenders = [];\n\t}\n\tc._suspenders.push(suspendingComponent);\n\n\tconst resolve = suspended(c._vnode);\n\n\tlet resolved = false;\n\tconst onResolved = () => {\n\t\tif (resolved) return;\n\n\t\tresolved = true;\n\t\tsuspendingComponent._onResolve = null;\n\n\t\tif (resolve) {\n\t\t\tresolve(onSuspensionComplete);\n\t\t} else {\n\t\t\tonSuspensionComplete();\n\t\t}\n\t};\n\n\tsuspendingComponent._onResolve = onResolved;\n\n\tconst onSuspensionComplete = () => {\n\t\tif (!--c._pendingSuspensionCount) {\n\t\t\t// If the suspension was during hydration we don't need to restore the\n\t\t\t// suspended children into the _children array\n\t\t\tif (c.state._suspended) {\n\t\t\t\tconst suspendedVNode = c.state._suspended;\n\t\t\t\tc._vnode._children[0] = removeOriginal(\n\t\t\t\t\tsuspendedVNode,\n\t\t\t\t\tsuspendedVNode._component._parentDom,\n\t\t\t\t\tsuspendedVNode._component._originalParentDom\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tc.setState({ _suspended: (c._detachOnNextRender = null) });\n\n\t\t\tlet suspended;\n\t\t\twhile ((suspended = c._suspenders.pop())) {\n\t\t\t\tsuspended.forceUpdate();\n\t\t\t}\n\t\t}\n\t};\n\n\t/**\n\t * We do not set `suspended: true` during hydration because we want the actual markup\n\t * to remain on screen and hydrate it when the suspense actually gets resolved.\n\t * While in non-hydration cases the usual fallback -> component flow would occour.\n\t */\n\tif (\n\t\t!c._pendingSuspensionCount++ &&\n\t\t!(suspendingVNode._flags & MODE_HYDRATE)\n\t) {\n\t\tc.setState({ _suspended: (c._detachOnNextRender = c._vnode._children[0]) });\n\t}\n\tpromise.then(onResolved, onResolved);\n};\n\nSuspense.prototype.componentWillUnmount = function () {\n\tthis._suspenders = [];\n};\n\n/**\n * @this {import('./internal').SuspenseComponent}\n * @param {import('./internal').SuspenseComponent[\"props\"]} props\n * @param {import('./internal').SuspenseState} state\n */\nSuspense.prototype.render = function (props, state) {\n\tif (this._detachOnNextRender) {\n\t\t// When the Suspense's _vnode was created by a call to createVNode\n\t\t// (i.e. due to a setState further up in the tree)\n\t\t// it's _children prop is null, in this case we \"forget\" about the parked vnodes to detach\n\t\tif (this._vnode._children) {\n\t\t\tconst detachedParent = document.createElement('div');\n\t\t\tconst detachedComponent = this._vnode._children[0]._component;\n\t\t\tthis._vnode._children[0] = detachedClone(\n\t\t\t\tthis._detachOnNextRender,\n\t\t\t\tdetachedParent,\n\t\t\t\t(detachedComponent._originalParentDom = detachedComponent._parentDom)\n\t\t\t);\n\t\t}\n\n\t\tthis._detachOnNextRender = null;\n\t}\n\n\t// Wrap fallback tree in a VNode that prevents itself from being marked as aborting mid-hydration:\n\t/** @type {import('./internal').VNode} */\n\tconst fallback =\n\t\tstate._suspended && createElement(Fragment, null, props.fallback);\n\tif (fallback) fallback._flags &= ~MODE_HYDRATE;\n\n\treturn [\n\t\tcreateElement(Fragment, null, state._suspended ? null : props.children),\n\t\tfallback\n\t];\n};\n\n/**\n * Checks and calls the parent component's _suspended method, passing in the\n * suspended vnode. This is a way for a parent (e.g. SuspenseList) to get notified\n * that one of its children/descendants suspended.\n *\n * The parent MAY return a callback. The callback will get called when the\n * suspension resolves, notifying the parent of the fact.\n * Moreover, the callback gets function `unsuspend` as a parameter. The resolved\n * child descendant will not actually get unsuspended until `unsuspend` gets called.\n * This is a way for the parent to delay unsuspending.\n *\n * If the parent does not return a callback then the resolved vnode\n * gets unsuspended immediately when it resolves.\n *\n * @param {import('./internal').VNode} vnode\n * @returns {((unsuspend: () => void) => void)?}\n */\nexport function suspended(vnode) {\n\t/** @type {import('./internal').Component} */\n\tlet component = vnode._parent._component;\n\treturn component && component._suspended && component._suspended(vnode);\n}\n\nexport function lazy(loader) {\n\tlet prom;\n\tlet component = null;\n\tlet error;\n\tlet resolved;\n\n\tfunction Lazy(props) {\n\t\tif (!prom) {\n\t\t\tprom = loader();\n\t\t\tprom.then(\n\t\t\t\texports => {\n\t\t\t\t\tif (exports) {\n\t\t\t\t\t\tcomponent = exports.default || exports;\n\t\t\t\t\t}\n\t\t\t\t\tresolved = true;\n\t\t\t\t},\n\t\t\t\te => {\n\t\t\t\t\terror = e;\n\t\t\t\t\tresolved = true;\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\n\t\tif (error) {\n\t\t\tthrow error;\n\t\t}\n\n\t\tif (!resolved) {\n\t\t\tthrow prom;\n\t\t}\n\n\t\treturn component ? createElement(component, props) : null;\n\t}\n\n\tLazy.displayName = 'Lazy';\n\tLazy._forwarded = true;\n\treturn Lazy;\n}\n","import { Component, toChildArray } from 'preact';\nimport { suspended } from './suspense.js';\n\n// Indexes to linked list nodes (nodes are stored as arrays to save bytes).\nconst SUSPENDED_COUNT = 0;\nconst RESOLVED_COUNT = 1;\nconst NEXT_NODE = 2;\n\n// Having custom inheritance instead of a class here saves a lot of bytes.\nexport function SuspenseList() {\n\tthis._next = null;\n\tthis._map = null;\n}\n\n// Mark one of child's earlier suspensions as resolved.\n// Some pending callbacks may become callable due to this\n// (e.g. the last suspended descendant gets resolved when\n// revealOrder === 'together'). Process those callbacks as well.\nconst resolve = (list, child, node) => {\n\tif (++node[RESOLVED_COUNT] === node[SUSPENDED_COUNT]) {\n\t\t// The number a child (or any of its descendants) has been suspended\n\t\t// matches the number of times it's been resolved. Therefore we\n\t\t// mark the child as completely resolved by deleting it from ._map.\n\t\t// This is used to figure out when *all* children have been completely\n\t\t// resolved when revealOrder is 'together'.\n\t\tlist._map.delete(child);\n\t}\n\n\t// If revealOrder is falsy then we can do an early exit, as the\n\t// callbacks won't get queued in the node anyway.\n\t// If revealOrder is 'together' then also do an early exit\n\t// if all suspended descendants have not yet been resolved.\n\tif (\n\t\t!list.props.revealOrder ||\n\t\t(list.props.revealOrder[0] === 't' && list._map.size)\n\t) {\n\t\treturn;\n\t}\n\n\t// Walk the currently suspended children in order, calling their\n\t// stored callbacks on the way. Stop if we encounter a child that\n\t// has not been completely resolved yet.\n\tnode = list._next;\n\twhile (node) {\n\t\twhile (node.length > 3) {\n\t\t\tnode.pop()();\n\t\t}\n\t\tif (node[RESOLVED_COUNT] < node[SUSPENDED_COUNT]) {\n\t\t\tbreak;\n\t\t}\n\t\tlist._next = node = node[NEXT_NODE];\n\t}\n};\n\n// Things we do here to save some bytes but are not proper JS inheritance:\n// - call `new Component()` as the prototype\n// - do not set `Suspense.prototype.constructor` to `Suspense`\nSuspenseList.prototype = new Component();\n\nSuspenseList.prototype._suspended = function (child) {\n\tconst list = this;\n\tconst delegated = suspended(list._vnode);\n\n\tlet node = list._map.get(child);\n\tnode[SUSPENDED_COUNT]++;\n\n\treturn unsuspend => {\n\t\tconst wrappedUnsuspend = () => {\n\t\t\tif (!list.props.revealOrder) {\n\t\t\t\t// Special case the undefined (falsy) revealOrder, as there\n\t\t\t\t// is no need to coordinate a specific order or unsuspends.\n\t\t\t\tunsuspend();\n\t\t\t} else {\n\t\t\t\tnode.push(unsuspend);\n\t\t\t\tresolve(list, child, node);\n\t\t\t}\n\t\t};\n\t\tif (delegated) {\n\t\t\tdelegated(wrappedUnsuspend);\n\t\t} else {\n\t\t\twrappedUnsuspend();\n\t\t}\n\t};\n};\n\nSuspenseList.prototype.render = function (props) {\n\tthis._next = null;\n\tthis._map = new Map();\n\n\tconst children = toChildArray(props.children);\n\tif (props.revealOrder && props.revealOrder[0] === 'b') {\n\t\t// If order === 'backwards' (or, well, anything starting with a 'b')\n\t\t// then flip the child list around so that the last child will be\n\t\t// the first in the linked list.\n\t\tchildren.reverse();\n\t}\n\t// Build the linked list. Iterate through the children in reverse order\n\t// so that `_next` points to the first linked list node to be resolved.\n\tfor (let i = children.length; i--; ) {\n\t\t// Create a new linked list node as an array of form:\n\t\t// \t[suspended_count, resolved_count, next_node]\n\t\t// where suspended_count and resolved_count are numeric counters for\n\t\t// keeping track how many times a node has been suspended and resolved.\n\t\t//\n\t\t// Note that suspended_count starts from 1 instead of 0, so we can block\n\t\t// processing callbacks until componentDidMount has been called. In a sense\n\t\t// node is suspended at least until componentDidMount gets called!\n\t\t//\n\t\t// Pending callbacks are added to the end of the node:\n\t\t// \t[suspended_count, resolved_count, next_node, callback_0, callback_1, ...]\n\t\tthis._map.set(children[i], (this._next = [1, 0, this._next]));\n\t}\n\treturn props.children;\n};\n\nSuspenseList.prototype.componentDidUpdate =\n\tSuspenseList.prototype.componentDidMount = function () {\n\t\t// Iterate through all children after mounting for two reasons:\n\t\t// 1. As each node[SUSPENDED_COUNT] starts from 1, this iteration increases\n\t\t// each node[RELEASED_COUNT] by 1, therefore balancing the counters.\n\t\t// The nodes can now be completely consumed from the linked list.\n\t\t// 2. Handle nodes that might have gotten resolved between render and\n\t\t// componentDidMount.\n\t\tthis._map.forEach((node, child) => {\n\t\t\tresolve(this, child, node);\n\t\t});\n\t};\n","/** Normal hydration that attaches to a DOM tree but does not diff it. */\nexport const MODE_HYDRATE = 1 << 5;\n/** Signifies this VNode suspended on the previous render */\nexport const MODE_SUSPENDED = 1 << 7;\n/** Indicates that this node needs to be inserted while patching children */\nexport const INSERT_VNODE = 1 << 2;\n/** Indicates a VNode has been matched with another VNode in the diff */\nexport const MATCHED = 1 << 1;\n\n/** Reset all mode flags */\nexport const RESET_MODE = ~(MODE_HYDRATE | MODE_SUSPENDED);\n\nexport const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\nexport const XHTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\nexport const MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n\nexport const NULL = null;\nexport const UNDEFINED = undefined;\nexport const EMPTY_OBJ = /** @type {any} */ ({});\nexport const EMPTY_ARR = [];\nexport const IS_NON_DIMENSIONAL =\n\t/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;\n","import { createElement, render } from 'preact';\n\n/**\n * @param {import('../../src/index').RenderableProps<{ context: any }>} props\n */\nfunction ContextProvider(props) {\n\tthis.getChildContext = () => props.context;\n\treturn props.children;\n}\n\n/**\n * Portal component\n * @this {import('./internal').Component}\n * @param {object | null | undefined} props\n *\n * TODO: use createRoot() instead of fake root\n */\nfunction Portal(props) {\n\tconst _this = this;\n\tlet container = props._container;\n\n\t_this.componentWillUnmount = function () {\n\t\trender(null, _this._temp);\n\t\t_this._temp = null;\n\t\t_this._container = null;\n\t};\n\n\t// When we change container we should clear our old container and\n\t// indicate a new mount.\n\tif (_this._container && _this._container !== container) {\n\t\t_this.componentWillUnmount();\n\t}\n\n\tif (!_this._temp) {\n\t\t// Ensure the element has a mask for useId invocations\n\t\tlet root = _this._vnode;\n\t\twhile (root !== null && !root._mask && root._parent !== null) {\n\t\t\troot = root._parent;\n\t\t}\n\n\t\t_this._container = container;\n\n\t\t// Create a fake DOM parent node that manages a subset of `container`'s children:\n\t\t_this._temp = {\n\t\t\tnodeType: 1,\n\t\t\tparentNode: container,\n\t\t\tchildNodes: [],\n\t\t\t_children: { _mask: root._mask },\n\t\t\tcontains: () => true,\n\t\t\tinsertBefore(child, before) {\n\t\t\t\tthis.childNodes.push(child);\n\t\t\t\t_this._container.insertBefore(child, before);\n\t\t\t},\n\t\t\tremoveChild(child) {\n\t\t\t\tthis.childNodes.splice(this.childNodes.indexOf(child) >>> 1, 1);\n\t\t\t\t_this._container.removeChild(child);\n\t\t\t}\n\t\t};\n\t}\n\n\t// Render our wrapping element into temp.\n\trender(\n\t\tcreateElement(ContextProvider, { context: _this.context }, props._vnode),\n\t\t_this._temp\n\t);\n}\n\n/**\n * Create a `Portal` to continue rendering the vnode tree at a different DOM node\n * @param {import('./internal').VNode} vnode The vnode to render\n * @param {import('./internal').PreactElement} container The DOM node to continue rendering in to.\n */\nexport function createPortal(vnode, container) {\n\tconst el = createElement(Portal, { _vnode: vnode, _container: container });\n\tel.containerInfo = container;\n\treturn el;\n}\n","import {\n\trender as preactRender,\n\thydrate as preactHydrate,\n\toptions,\n\ttoChildArray,\n\tComponent\n} from 'preact';\nimport {\n\tuseCallback,\n\tuseContext,\n\tuseDebugValue,\n\tuseEffect,\n\tuseId,\n\tuseImperativeHandle,\n\tuseLayoutEffect,\n\tuseMemo,\n\tuseReducer,\n\tuseRef,\n\tuseState\n} from 'preact/hooks';\nimport {\n\tuseDeferredValue,\n\tuseInsertionEffect,\n\tuseSyncExternalStore,\n\tuseTransition\n} from './index';\n\nexport const REACT_ELEMENT_TYPE =\n\t(typeof Symbol != 'undefined' && Symbol.for && Symbol.for('react.element')) ||\n\t0xeac7;\n\nconst CAMEL_PROPS =\n\t/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/;\nconst ON_ANI = /^on(Ani|Tra|Tou|BeforeInp|Compo)/;\nconst CAMEL_REPLACE = /[A-Z0-9]/g;\nconst IS_DOM = typeof document !== 'undefined';\n\n// Input types for which onchange should not be converted to oninput.\n// type=\"file|checkbox|radio\", plus \"range\" in IE11.\n// (IE11 doesn't support Symbol, which we use here to turn `rad` into `ra` which matches \"range\")\nconst onChangeInputType = type =>\n\t(typeof Symbol != 'undefined' && typeof Symbol() == 'symbol'\n\t\t? /fil|che|rad/\n\t\t: /fil|che|ra/\n\t).test(type);\n\n// Some libraries like `react-virtualized` explicitly check for this.\nComponent.prototype.isReactComponent = {};\n\n// `UNSAFE_*` lifecycle hooks\n// Preact only ever invokes the unprefixed methods.\n// Here we provide a base \"fallback\" implementation that calls any defined UNSAFE_ prefixed method.\n// - If a component defines its own `componentDidMount()` (including via defineProperty), use that.\n// - If a component defines `UNSAFE_componentDidMount()`, `componentDidMount` is the alias getter/setter.\n// - If anything assigns to an `UNSAFE_*` property, the assignment is forwarded to the unprefixed property.\n// See https://github.com/preactjs/preact/issues/1941\n[\n\t'componentWillMount',\n\t'componentWillReceiveProps',\n\t'componentWillUpdate'\n].forEach(key => {\n\tObject.defineProperty(Component.prototype, key, {\n\t\tconfigurable: true,\n\t\tget() {\n\t\t\treturn this['UNSAFE_' + key];\n\t\t},\n\t\tset(v) {\n\t\t\tObject.defineProperty(this, key, {\n\t\t\t\tconfigurable: true,\n\t\t\t\twritable: true,\n\t\t\t\tvalue: v\n\t\t\t});\n\t\t}\n\t});\n});\n\n/**\n * Proxy render() since React returns a Component reference.\n * @param {import('./internal').VNode} vnode VNode tree to render\n * @param {import('./internal').PreactElement} parent DOM node to render vnode tree into\n * @param {() => void} [callback] Optional callback that will be called after rendering\n * @returns {import('./internal').Component | null} The root component reference or null\n */\nexport function render(vnode, parent, callback) {\n\t// React destroys any existing DOM nodes, see #1727\n\t// ...but only on the first render, see #1828\n\tif (parent._children == null) {\n\t\tparent.textContent = '';\n\t}\n\n\tpreactRender(vnode, parent);\n\tif (typeof callback == 'function') callback();\n\n\treturn vnode ? vnode._component : null;\n}\n\nexport function hydrate(vnode, parent, callback) {\n\tpreactHydrate(vnode, parent);\n\tif (typeof callback == 'function') callback();\n\n\treturn vnode ? vnode._component : null;\n}\n\nlet oldEventHook = options.event;\noptions.event = e => {\n\tif (oldEventHook) e = oldEventHook(e);\n\n\te.persist = empty;\n\te.isPropagationStopped = isPropagationStopped;\n\te.isDefaultPrevented = isDefaultPrevented;\n\treturn (e.nativeEvent = e);\n};\n\nfunction empty() {}\n\nfunction isPropagationStopped() {\n\treturn this.cancelBubble;\n}\n\nfunction isDefaultPrevented() {\n\treturn this.defaultPrevented;\n}\n\nconst classNameDescriptorNonEnumberable = {\n\tenumerable: false,\n\tconfigurable: true,\n\tget() {\n\t\treturn this.class;\n\t}\n};\n\nfunction handleDomVNode(vnode) {\n\tlet props = vnode.props,\n\t\ttype = vnode.type,\n\t\tnormalizedProps = {};\n\n\tlet isNonDashedType = type.indexOf('-') === -1;\n\tfor (let i in props) {\n\t\tlet value = props[i];\n\n\t\tif (\n\t\t\t(i === 'value' && 'defaultValue' in props && value == null) ||\n\t\t\t// Emulate React's behavior of not rendering the contents of noscript tags on the client.\n\t\t\t(IS_DOM && i === 'children' && type === 'noscript') ||\n\t\t\ti === 'class' ||\n\t\t\ti === 'className'\n\t\t) {\n\t\t\t// Skip applying value if it is null/undefined and we already set\n\t\t\t// a default value\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet lowerCased = i.toLowerCase();\n\t\tif (i === 'defaultValue' && 'value' in props && props.value == null) {\n\t\t\t// `defaultValue` is treated as a fallback `value` when a value prop is present but null/undefined.\n\t\t\t// `defaultValue` for Elements with no value prop is the same as the DOM defaultValue property.\n\t\t\ti = 'value';\n\t\t} else if (i === 'download' && value === true) {\n\t\t\t// Calling `setAttribute` with a truthy value will lead to it being\n\t\t\t// passed as a stringified value, e.g. `download=\"true\"`. React\n\t\t\t// converts it to an empty string instead, otherwise the attribute\n\t\t\t// value will be used as the file name and the file will be called\n\t\t\t// \"true\" upon downloading it.\n\t\t\tvalue = '';\n\t\t} else if (lowerCased === 'translate' && value === 'no') {\n\t\t\tvalue = false;\n\t\t} else if (lowerCased[0] === 'o' && lowerCased[1] === 'n') {\n\t\t\tif (lowerCased === 'ondoubleclick') {\n\t\t\t\ti = 'ondblclick';\n\t\t\t} else if (\n\t\t\t\tlowerCased === 'onchange' &&\n\t\t\t\t(type === 'input' || type === 'textarea') &&\n\t\t\t\t!onChangeInputType(props.type)\n\t\t\t) {\n\t\t\t\tlowerCased = i = 'oninput';\n\t\t\t} else if (lowerCased === 'onfocus') {\n\t\t\t\ti = 'onfocusin';\n\t\t\t} else if (lowerCased === 'onblur') {\n\t\t\t\ti = 'onfocusout';\n\t\t\t} else if (ON_ANI.test(i)) {\n\t\t\t\ti = lowerCased;\n\t\t\t}\n\t\t} else if (isNonDashedType && CAMEL_PROPS.test(i)) {\n\t\t\ti = i.replace(CAMEL_REPLACE, '-$&').toLowerCase();\n\t\t} else if (value === null) {\n\t\t\tvalue = undefined;\n\t\t}\n\n\t\t// Add support for onInput and onChange, see #3561\n\t\t// if we have an oninput prop already change it to oninputCapture\n\t\tif (lowerCased === 'oninput') {\n\t\t\ti = lowerCased;\n\t\t\tif (normalizedProps[i]) {\n\t\t\t\ti = 'oninputCapture';\n\t\t\t}\n\t\t}\n\n\t\tnormalizedProps[i] = value;\n\t}\n\n\t// Add support for array select values: + if ( + type == 'select' && + normalizedProps.multiple && + Array.isArray(normalizedProps.value) + ) { + // forEach() always returns undefined, which we abuse here to unset the value prop. + normalizedProps.value = toChildArray(props.children).forEach(child => { + child.props.selected = + normalizedProps.value.indexOf(child.props.value) != -1; + }); + } + + // Adding support for defaultValue in select tag + if (type == 'select' && normalizedProps.defaultValue != null) { + normalizedProps.value = toChildArray(props.children).forEach(child => { + if (normalizedProps.multiple) { + child.props.selected = + normalizedProps.defaultValue.indexOf(child.props.value) != -1; + } else { + child.props.selected = + normalizedProps.defaultValue == child.props.value; + } + }); + } + + if (props.class && !props.className) { + normalizedProps.class = props.class; + Object.defineProperty( + normalizedProps, + 'className', + classNameDescriptorNonEnumberable + ); + } else if (props.className && !props.class) { + normalizedProps.class = normalizedProps.className = props.className; + } else if (props.class && props.className) { + normalizedProps.class = normalizedProps.className = props.className; + } + + vnode.props = normalizedProps; +} + +let oldVNodeHook = options.vnode; +options.vnode = vnode => { + // only normalize props on Element nodes + if (typeof vnode.type === 'string') { + handleDomVNode(vnode); + } + + vnode.$$typeof = REACT_ELEMENT_TYPE; + + if (oldVNodeHook) oldVNodeHook(vnode); +}; + +// Only needed for react-relay +let currentComponent; +const oldBeforeRender = options._render; +options._render = function (vnode) { + if (oldBeforeRender) { + oldBeforeRender(vnode); + } + currentComponent = vnode._component; +}; + +const oldDiffed = options.diffed; +/** @type {(vnode: import('./internal').VNode) => void} */ +options.diffed = function (vnode) { + if (oldDiffed) { + oldDiffed(vnode); + } + + const props = vnode.props; + const dom = vnode._dom; + + if ( + dom != null && + vnode.type === 'textarea' && + 'value' in props && + props.value !== dom.value + ) { + dom.value = props.value == null ? '' : props.value; + } + + currentComponent = null; +}; + +// This is a very very private internal function for React it +// is used to sort-of do runtime dependency injection. +export const __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = { + ReactCurrentDispatcher: { + current: { + readContext(context) { + return currentComponent._globalContext[context._id].props.value; + }, + useCallback, + useContext, + useDebugValue, + useDeferredValue, + useEffect, + useId, + useImperativeHandle, + useInsertionEffect, + useLayoutEffect, + useMemo, + // useMutableSource, // experimental-only and replaced by uSES, likely not worth supporting + useReducer, + useRef, + useState, + useSyncExternalStore, + useTransition + } + } +}; diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/compat/src/suspense-list.d.ts b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/src/suspense-list.d.ts new file mode 100644 index 0000000000000..0a3be0adc90d5 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/src/suspense-list.d.ts @@ -0,0 +1,16 @@ +// Intentionally not using a relative path to take advantage of +// the TS version resolution mechanism +import { Component, ComponentChild, ComponentChildren } from 'preact'; + +// +// SuspenseList +// ----------------------------------- + +export interface SuspenseListProps { + children?: ComponentChildren; + revealOrder?: 'forwards' | 'backwards' | 'together'; +} + +export class SuspenseList extends Component { + render(): ComponentChild; +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/compat/src/suspense-list.js b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/src/suspense-list.js new file mode 100644 index 0000000000000..5e5d750a08952 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/src/suspense-list.js @@ -0,0 +1,127 @@ +import { Component, toChildArray } from 'preact'; +import { suspended } from './suspense.js'; + +// Indexes to linked list nodes (nodes are stored as arrays to save bytes). +const SUSPENDED_COUNT = 0; +const RESOLVED_COUNT = 1; +const NEXT_NODE = 2; + +// Having custom inheritance instead of a class here saves a lot of bytes. +export function SuspenseList() { + this._next = null; + this._map = null; +} + +// Mark one of child's earlier suspensions as resolved. +// Some pending callbacks may become callable due to this +// (e.g. the last suspended descendant gets resolved when +// revealOrder === 'together'). Process those callbacks as well. +const resolve = (list, child, node) => { + if (++node[RESOLVED_COUNT] === node[SUSPENDED_COUNT]) { + // The number a child (or any of its descendants) has been suspended + // matches the number of times it's been resolved. Therefore we + // mark the child as completely resolved by deleting it from ._map. + // This is used to figure out when *all* children have been completely + // resolved when revealOrder is 'together'. + list._map.delete(child); + } + + // If revealOrder is falsy then we can do an early exit, as the + // callbacks won't get queued in the node anyway. + // If revealOrder is 'together' then also do an early exit + // if all suspended descendants have not yet been resolved. + if ( + !list.props.revealOrder || + (list.props.revealOrder[0] === 't' && list._map.size) + ) { + return; + } + + // Walk the currently suspended children in order, calling their + // stored callbacks on the way. Stop if we encounter a child that + // has not been completely resolved yet. + node = list._next; + while (node) { + while (node.length > 3) { + node.pop()(); + } + if (node[RESOLVED_COUNT] < node[SUSPENDED_COUNT]) { + break; + } + list._next = node = node[NEXT_NODE]; + } +}; + +// Things we do here to save some bytes but are not proper JS inheritance: +// - call `new Component()` as the prototype +// - do not set `Suspense.prototype.constructor` to `Suspense` +SuspenseList.prototype = new Component(); + +SuspenseList.prototype._suspended = function (child) { + const list = this; + const delegated = suspended(list._vnode); + + let node = list._map.get(child); + node[SUSPENDED_COUNT]++; + + return unsuspend => { + const wrappedUnsuspend = () => { + if (!list.props.revealOrder) { + // Special case the undefined (falsy) revealOrder, as there + // is no need to coordinate a specific order or unsuspends. + unsuspend(); + } else { + node.push(unsuspend); + resolve(list, child, node); + } + }; + if (delegated) { + delegated(wrappedUnsuspend); + } else { + wrappedUnsuspend(); + } + }; +}; + +SuspenseList.prototype.render = function (props) { + this._next = null; + this._map = new Map(); + + const children = toChildArray(props.children); + if (props.revealOrder && props.revealOrder[0] === 'b') { + // If order === 'backwards' (or, well, anything starting with a 'b') + // then flip the child list around so that the last child will be + // the first in the linked list. + children.reverse(); + } + // Build the linked list. Iterate through the children in reverse order + // so that `_next` points to the first linked list node to be resolved. + for (let i = children.length; i--; ) { + // Create a new linked list node as an array of form: + // [suspended_count, resolved_count, next_node] + // where suspended_count and resolved_count are numeric counters for + // keeping track how many times a node has been suspended and resolved. + // + // Note that suspended_count starts from 1 instead of 0, so we can block + // processing callbacks until componentDidMount has been called. In a sense + // node is suspended at least until componentDidMount gets called! + // + // Pending callbacks are added to the end of the node: + // [suspended_count, resolved_count, next_node, callback_0, callback_1, ...] + this._map.set(children[i], (this._next = [1, 0, this._next])); + } + return props.children; +}; + +SuspenseList.prototype.componentDidUpdate = + SuspenseList.prototype.componentDidMount = function () { + // Iterate through all children after mounting for two reasons: + // 1. As each node[SUSPENDED_COUNT] starts from 1, this iteration increases + // each node[RELEASED_COUNT] by 1, therefore balancing the counters. + // The nodes can now be completely consumed from the linked list. + // 2. Handle nodes that might have gotten resolved between render and + // componentDidMount. + this._map.forEach((node, child) => { + resolve(this, child, node); + }); + }; diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/compat/src/suspense.d.ts b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/src/suspense.d.ts new file mode 100644 index 0000000000000..65c2a9372a22a --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/src/suspense.d.ts @@ -0,0 +1,19 @@ +// Intentionally not using a relative path to take advantage of +// the TS version resolution mechanism +import { Component, ComponentChild, ComponentChildren } from 'preact'; + +// +// Suspense/lazy +// ----------------------------------- +export function lazy( + loader: () => Promise<{ default: T } | T> +): T extends { default: infer U } ? U : T; + +export interface SuspenseProps { + children?: ComponentChildren; + fallback: ComponentChildren; +} + +export class Suspense extends Component { + render(): ComponentChild; +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/compat/src/suspense.js b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/src/suspense.js new file mode 100644 index 0000000000000..6d5333a3b7097 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/src/suspense.js @@ -0,0 +1,281 @@ +import { Component, createElement, options, Fragment } from 'preact'; +import { MODE_HYDRATE } from '../../src/constants'; +import { assign } from './util'; + +const oldCatchError = options._catchError; +options._catchError = function (error, newVNode, oldVNode, errorInfo) { + if (error.then) { + /** @type {import('./internal').Component} */ + let component; + let vnode = newVNode; + + for (; (vnode = vnode._parent); ) { + if ((component = vnode._component) && component._childDidSuspend) { + if (newVNode._dom == null) { + newVNode._dom = oldVNode._dom; + newVNode._children = oldVNode._children; + } + // Don't call oldCatchError if we found a Suspense + return component._childDidSuspend(error, newVNode); + } + } + } + oldCatchError(error, newVNode, oldVNode, errorInfo); +}; + +const oldUnmount = options.unmount; +options.unmount = function (vnode) { + /** @type {import('./internal').Component} */ + const component = vnode._component; + if (component && component._onResolve) { + component._onResolve(); + } + + // if the component is still hydrating + // most likely it is because the component is suspended + // we set the vnode.type as `null` so that it is not a typeof function + // so the unmount will remove the vnode._dom + if (component && vnode._flags & MODE_HYDRATE) { + vnode.type = null; + } + + if (oldUnmount) oldUnmount(vnode); +}; + +function detachedClone(vnode, detachedParent, parentDom) { + if (vnode) { + if (vnode._component && vnode._component.__hooks) { + vnode._component.__hooks._list.forEach(effect => { + if (typeof effect._cleanup == 'function') effect._cleanup(); + }); + + vnode._component.__hooks = null; + } + + vnode = assign({}, vnode); + if (vnode._component != null) { + if (vnode._component._parentDom === parentDom) { + vnode._component._parentDom = detachedParent; + } + + vnode._component._force = true; + + vnode._component = null; + } + + vnode._children = + vnode._children && + vnode._children.map(child => + detachedClone(child, detachedParent, parentDom) + ); + } + + return vnode; +} + +function removeOriginal(vnode, detachedParent, originalParent) { + if (vnode && originalParent) { + vnode._original = null; + vnode._children = + vnode._children && + vnode._children.map(child => + removeOriginal(child, detachedParent, originalParent) + ); + + if (vnode._component) { + if (vnode._component._parentDom === detachedParent) { + if (vnode._dom) { + originalParent.appendChild(vnode._dom); + } + vnode._component._force = true; + vnode._component._parentDom = originalParent; + } + } + } + + return vnode; +} + +// having custom inheritance instead of a class here saves a lot of bytes +export function Suspense() { + // we do not call super here to golf some bytes... + this._pendingSuspensionCount = 0; + this._suspenders = null; + this._detachOnNextRender = null; +} + +// Things we do here to save some bytes but are not proper JS inheritance: +// - call `new Component()` as the prototype +// - do not set `Suspense.prototype.constructor` to `Suspense` +Suspense.prototype = new Component(); + +/** + * @this {import('./internal').SuspenseComponent} + * @param {Promise} promise The thrown promise + * @param {import('./internal').VNode} suspendingVNode The suspending component + */ +Suspense.prototype._childDidSuspend = function (promise, suspendingVNode) { + const suspendingComponent = suspendingVNode._component; + + /** @type {import('./internal').SuspenseComponent} */ + const c = this; + + if (c._suspenders == null) { + c._suspenders = []; + } + c._suspenders.push(suspendingComponent); + + const resolve = suspended(c._vnode); + + let resolved = false; + const onResolved = () => { + if (resolved) return; + + resolved = true; + suspendingComponent._onResolve = null; + + if (resolve) { + resolve(onSuspensionComplete); + } else { + onSuspensionComplete(); + } + }; + + suspendingComponent._onResolve = onResolved; + + const onSuspensionComplete = () => { + if (!--c._pendingSuspensionCount) { + // If the suspension was during hydration we don't need to restore the + // suspended children into the _children array + if (c.state._suspended) { + const suspendedVNode = c.state._suspended; + c._vnode._children[0] = removeOriginal( + suspendedVNode, + suspendedVNode._component._parentDom, + suspendedVNode._component._originalParentDom + ); + } + + c.setState({ _suspended: (c._detachOnNextRender = null) }); + + let suspended; + while ((suspended = c._suspenders.pop())) { + suspended.forceUpdate(); + } + } + }; + + /** + * We do not set `suspended: true` during hydration because we want the actual markup + * to remain on screen and hydrate it when the suspense actually gets resolved. + * While in non-hydration cases the usual fallback -> component flow would occour. + */ + if ( + !c._pendingSuspensionCount++ && + !(suspendingVNode._flags & MODE_HYDRATE) + ) { + c.setState({ _suspended: (c._detachOnNextRender = c._vnode._children[0]) }); + } + promise.then(onResolved, onResolved); +}; + +Suspense.prototype.componentWillUnmount = function () { + this._suspenders = []; +}; + +/** + * @this {import('./internal').SuspenseComponent} + * @param {import('./internal').SuspenseComponent["props"]} props + * @param {import('./internal').SuspenseState} state + */ +Suspense.prototype.render = function (props, state) { + if (this._detachOnNextRender) { + // When the Suspense's _vnode was created by a call to createVNode + // (i.e. due to a setState further up in the tree) + // it's _children prop is null, in this case we "forget" about the parked vnodes to detach + if (this._vnode._children) { + const detachedParent = document.createElement('div'); + const detachedComponent = this._vnode._children[0]._component; + this._vnode._children[0] = detachedClone( + this._detachOnNextRender, + detachedParent, + (detachedComponent._originalParentDom = detachedComponent._parentDom) + ); + } + + this._detachOnNextRender = null; + } + + // Wrap fallback tree in a VNode that prevents itself from being marked as aborting mid-hydration: + /** @type {import('./internal').VNode} */ + const fallback = + state._suspended && createElement(Fragment, null, props.fallback); + if (fallback) fallback._flags &= ~MODE_HYDRATE; + + return [ + createElement(Fragment, null, state._suspended ? null : props.children), + fallback + ]; +}; + +/** + * Checks and calls the parent component's _suspended method, passing in the + * suspended vnode. This is a way for a parent (e.g. SuspenseList) to get notified + * that one of its children/descendants suspended. + * + * The parent MAY return a callback. The callback will get called when the + * suspension resolves, notifying the parent of the fact. + * Moreover, the callback gets function `unsuspend` as a parameter. The resolved + * child descendant will not actually get unsuspended until `unsuspend` gets called. + * This is a way for the parent to delay unsuspending. + * + * If the parent does not return a callback then the resolved vnode + * gets unsuspended immediately when it resolves. + * + * @param {import('./internal').VNode} vnode + * @returns {((unsuspend: () => void) => void)?} + */ +export function suspended(vnode) { + /** @type {import('./internal').Component} */ + let component = vnode._parent._component; + return component && component._suspended && component._suspended(vnode); +} + +export function lazy(loader) { + let prom; + let component = null; + let error; + let resolved; + + function Lazy(props) { + if (!prom) { + prom = loader(); + prom.then( + exports => { + if (exports) { + component = exports.default || exports; + } + resolved = true; + }, + e => { + error = e; + resolved = true; + } + ); + } + + if (error) { + throw error; + } + + if (!resolved) { + throw prom; + } + + return component ? createElement(component, props) : null; + } + + Lazy.displayName = 'Lazy'; + Lazy._forwarded = true; + return Lazy; +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/compat/src/util.js b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/src/util.js new file mode 100644 index 0000000000000..8ec376942b2ea --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/src/util.js @@ -0,0 +1,33 @@ +/** + * Assign properties from `props` to `obj` + * @template O, P The obj and props types + * @param {O} obj The object to copy properties to + * @param {P} props The object to copy properties from + * @returns {O & P} + */ +export function assign(obj, props) { + for (let i in props) obj[i] = props[i]; + return /** @type {O & P} */ (obj); +} + +/** + * Check if two objects have a different shape + * @param {object} a + * @param {object} b + * @returns {boolean} + */ +export function shallowDiffers(a, b) { + for (let i in a) if (i !== '__source' && !(i in b)) return true; + for (let i in b) if (i !== '__source' && a[i] !== b[i]) return true; + return false; +} + +/** + * Check if two values are the same value + * @param {*} x + * @param {*} y + * @returns {boolean} + */ +export function is(x, y) { + return (x === y && (x !== 0 || 1 / x === 1 / y)) || (x !== x && y !== y); +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/compat/test-utils.js b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/test-utils.js new file mode 100644 index 0000000000000..2dac062212445 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/test-utils.js @@ -0,0 +1 @@ +module.exports = require('preact/test-utils'); diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/compat/test-utils.mjs b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/test-utils.mjs new file mode 100644 index 0000000000000..16b6d0b2938dd --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/compat/test-utils.mjs @@ -0,0 +1 @@ +export * from 'preact/test-utils'; diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/debug/dist/debug.js b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/dist/debug.js new file mode 100644 index 0000000000000..125c3c4b0aa4a --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/dist/debug.js @@ -0,0 +1,2 @@ +var n=require("preact");require("preact/devtools");var e={};function t(e){return e.type===n.Fragment?"Fragment":"function"==typeof e.type?e.type.displayName||e.type.name:"string"==typeof e.type?e.type:"#text"}var o=[],r=[];function a(){return o.length>0?o[o.length-1]:null}var i=!0;function s(e){return"function"==typeof e.type&&e.type!=n.Fragment}function c(n){for(var e=[n],o=n;null!=o.__o;)e.push(o.__o),o=o.__o;return e.reduce(function(n,e){n+=" in "+t(e);var o=e.__source;return o?n+=" (at "+o.fileName+":"+o.lineNumber+")":i&&console.warn("Add @babel/plugin-transform-react-jsx-source to get a more detailed component stack. Note that you should not add it to production builds of your App for bundle size reasons."),i=!1,n+"\n"},"")}var l="function"==typeof WeakMap;function u(n){var e=[];return n.__k?(n.__k.forEach(function(n){n&&"function"==typeof n.type?e.push.apply(e,u(n)):n&&"string"==typeof n.type&&e.push(n.type)}),e):e}function f(n){return n?"function"==typeof n.type?null==n.__?null!=n.__e&&null!=n.__e.parentNode?n.__e.parentNode.localName:"":f(n.__):n.type:""}var d=n.Component.prototype.setState;function p(n){return"table"===n||"tfoot"===n||"tbody"===n||"thead"===n||"td"===n||"tr"===n||"th"===n}n.Component.prototype.setState=function(n,e){return null==this.__v&&null==this.state&&console.warn('Calling "this.setState" inside the constructor of a component is a no-op and might be a bug in your application. Instead, set "this.state = {}" directly.\n\n'+c(a())),d.call(this,n,e)};var h=/^(address|article|aside|blockquote|details|div|dl|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hgroup|hr|main|menu|nav|ol|p|pre|search|section|table|ul)$/,v=n.Component.prototype.forceUpdate;function y(n){var e=n.props,o=t(n),r="";for(var a in e)if(e.hasOwnProperty(a)&&"children"!==a){var i=e[a];"function"==typeof i&&(i="function "+(i.displayName||i.name)+"() {}"),i=Object(i)!==i||i.toString?i+"":Object.prototype.toString.call(i),r+=" "+a+"="+JSON.stringify(i)}var s=e.children;return"<"+o+r+(s&&s.length?">..":" />")}n.Component.prototype.forceUpdate=function(n){return null==this.__v?console.warn('Calling "this.forceUpdate" inside the constructor of a component is a no-op and might be a bug in your application.\n\n'+c(a())):null==this.__P&&console.warn('Can\'t call "this.forceUpdate" on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.\n\n'+c(this.__v)),v.call(this,n)},n.options.__m=function(n,e){var t=n.type,o=e.map(function(n){return n&&n.localName}).filter(Boolean);console.error('Expected a DOM node of type "'+t+'" but found "'+o.join(", ")+"\" as available DOM-node(s), this is caused by the SSR'd HTML containing different DOM-nodes compared to the hydrated one.\n\n"+c(n))},function(){!function(){var e=n.options.__b,t=n.options.diffed,a=n.options.__,i=n.options.vnode,c=n.options.__r;n.options.diffed=function(n){s(n)&&r.pop(),o.pop(),t&&t(n)},n.options.__b=function(n){s(n)&&o.push(n),e&&e(n)},n.options.__=function(n,e){r=[],a&&a(n,e)},n.options.vnode=function(n){n.__o=r.length>0?r[r.length-1]:null,i&&i(n)},n.options.__r=function(n){s(n)&&r.push(n),c&&c(n)}}();var a=!1,i=n.options.__b,d=n.options.diffed,v=n.options.vnode,m=n.options.__r,b=n.options.__e,w=n.options.__,g=n.options.__h,E=l?{useEffect:new WeakMap,useLayoutEffect:new WeakMap,lazyPropTypes:new WeakMap}:null,k=[];n.options.__e=function(n,e,o,r){if(e&&e.__c&&"function"==typeof n.then){var a=n;n=new Error("Missing Suspense. The throwing component was: "+t(e));for(var i=e;i;i=i.__)if(i.__c&&i.__c.__c){n=a;break}if(n instanceof Error)throw n}try{(r=r||{}).componentStack=c(e),b(n,e,o,r),"function"!=typeof n.then&&setTimeout(function(){throw n})}catch(n){throw n}},n.options.__=function(n,e){if(!e)throw new Error("Undefined parent passed to render(), this is the second argument.\nCheck if the element is available in the DOM/has the correct id.");var o;switch(e.nodeType){case 1:case 11:case 9:o=!0;break;default:o=!1}if(!o){var r=t(n);throw new Error("Expected a valid HTML node as a second argument to render.\tReceived "+e+" instead: render(<"+r+" />, "+e+");")}w&&w(n,e)},n.options.__b=function(n){var o=n.type;if(a=!0,void 0===o)throw new Error("Undefined component passed to createElement()\n\nYou likely forgot to export your component or might have mixed up default and named imports"+y(n)+"\n\n"+c(n));if(null!=o&&"object"==typeof o){if(void 0!==o.__k&&void 0!==o.__e)throw new Error("Invalid type passed to createElement(): "+o+"\n\nDid you accidentally pass a JSX literal as JSX twice?\n\n let My"+t(n)+" = "+y(o)+";\n let vnode = ;\n\nThis usually happens when you export a JSX literal and not the component.\n\n"+c(n));throw new Error("Invalid type passed to createElement(): "+(Array.isArray(o)?"array":o))}if(void 0!==n.ref&&"function"!=typeof n.ref&&"object"!=typeof n.ref&&!("$$typeof"in n))throw new Error('Component\'s "ref" property should be a function, or an object created by createRef(), but got ['+typeof n.ref+"] instead\n"+y(n)+"\n\n"+c(n));if("string"==typeof n.type)for(var r in n.props)if("o"===r[0]&&"n"===r[1]&&"function"!=typeof n.props[r]&&null!=n.props[r])throw new Error("Component's \""+r+'" property should be a function, but got ['+typeof n.props[r]+"] instead\n"+y(n)+"\n\n"+c(n));if("function"==typeof n.type&&n.type.propTypes){if("Lazy"===n.type.displayName&&E&&!E.lazyPropTypes.has(n.type)){var s="PropTypes are not supported on lazy(). Use propTypes on the wrapped component itself. ";try{var l=n.type();E.lazyPropTypes.set(n.type,!0),console.warn(s+"Component wrapped in lazy() is "+t(l))}catch(n){console.warn(s+"We will log the wrapped component's name once it is loaded.")}}var u=n.props;n.type.__f&&delete(u=function(n,e){for(var t in e)n[t]=e[t];return n}({},u)).ref,function(n,t,o,r,a){Object.keys(n).forEach(function(o){var i;try{i=n[o](t,o,r,"prop",null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(n){i=n}i&&!(i.message in e)&&(e[i.message]=!0,console.error("Failed prop type: "+i.message+(a&&"\n"+a()||"")))})}(n.type.propTypes,u,0,t(n),function(){return c(n)})}i&&i(n)};var T,_=0;n.options.__r=function(n){m&&m(n),a=!0;var e=n.__c;if(e===T?_++:_=1,_>=25)throw new Error("Too many re-renders. This is limited to prevent an infinite loop which may lock up your browser. The component causing this is: "+t(n));T=e},n.options.__h=function(n,e,t){if(!n||!a)throw new Error("Hook can only be invoked from render methods.");g&&g(n,e,t)};var O=function(n,e){return{get:function(){var t="get"+n+e;k&&k.indexOf(t)<0&&(k.push(t),console.warn("getting vnode."+n+" is deprecated, "+e))},set:function(){var t="set"+n+e;k&&k.indexOf(t)<0&&(k.push(t),console.warn("setting vnode."+n+" is not allowed, "+e))}}},I={nodeName:O("nodeName","use vnode.type"),attributes:O("attributes","use vnode.props"),children:O("children","use vnode.props.children")},x=Object.create({},I);n.options.vnode=function(n){var e=n.props;if(null!==n.type&&null!=e&&("__source"in e||"__self"in e)){var t=n.props={};for(var o in e){var r=e[o];"__source"===o?n.__source=r:"__self"===o?n.__self=r:t[o]=r}}n.__proto__=x,v&&v(n)},n.options.diffed=function(n){var e,o=n.type,r=n.__;if(n.__k&&n.__k.forEach(function(e){if("object"==typeof e&&e&&void 0===e.type){var t=Object.keys(e).join(",");throw new Error("Objects are not valid as a child. Encountered an object with the keys {"+t+"}.\n\n"+c(n))}}),n.__c===T&&(_=0),"string"==typeof o&&(p(o)||"p"===o||"a"===o||"button"===o)){var i=f(r);if(""!==i&&p(o))"table"===o&&"td"!==i&&p(i)?console.error("Improper nesting of table. Your should not have a table-node parent."+y(n)+"\n\n"+c(n)):"thead"!==o&&"tfoot"!==o&&"tbody"!==o||"table"===i?"tr"===o&&"thead"!==i&&"tfoot"!==i&&"tbody"!==i?console.error("Improper nesting of table. Your should have a parent."+y(n)+"\n\n"+c(n)):"td"===o&&"tr"!==i?console.error("Improper nesting of table. Your parent."+y(n)+"\n\n"+c(n)):"th"===o&&"tr"!==i&&console.error("Improper nesting of table. Your ."+y(n)+"\n\n"+c(n)):console.error("Improper nesting of table. Your should have a
    should have a
    should have a
    parent."+y(n)+"\n\n"+c(n));else if("p"===o){var s=u(n).filter(function(n){return h.test(n)});s.length&&console.error("Improper nesting of paragraph. Your

    should not have "+s.join(", ")+" as child-elements."+y(n)+"\n\n"+c(n))}else"a"!==o&&"button"!==o||-1!==u(n).indexOf(o)&&console.error("Improper nesting of interactive content. Your <"+o+"> should not have other "+("a"===o?"anchor":"button")+" tags as child-elements."+y(n)+"\n\n"+c(n))}if(a=!1,d&&d(n),null!=n.__k)for(var l=[],v=0;v {\n\t\tlet error;\n\t\ttry {\n\t\t\terror = typeSpecs[typeSpecName](\n\t\t\t\tvalues,\n\t\t\t\ttypeSpecName,\n\t\t\t\tcomponentName,\n\t\t\t\tlocation,\n\t\t\t\tnull,\n\t\t\t\tReactPropTypesSecret\n\t\t\t);\n\t\t} catch (e) {\n\t\t\terror = e;\n\t\t}\n\t\tif (error && !(error.message in loggedTypeFailures)) {\n\t\t\tloggedTypeFailures[error.message] = true;\n\t\t\tconsole.error(\n\t\t\t\t`Failed ${location} type: ${error.message}${\n\t\t\t\t\t(getStack && `\\n${getStack()}`) || ''\n\t\t\t\t}`\n\t\t\t);\n\t\t}\n\t});\n}\n","import { options, Fragment } from 'preact';\n\n/**\n * Get human readable name of the component/dom node\n * @param {import('./internal').VNode} vnode\n * @param {import('./internal').VNode} vnode\n * @returns {string}\n */\nexport function getDisplayName(vnode) {\n\tif (vnode.type === Fragment) {\n\t\treturn 'Fragment';\n\t} else if (typeof vnode.type == 'function') {\n\t\treturn vnode.type.displayName || vnode.type.name;\n\t} else if (typeof vnode.type == 'string') {\n\t\treturn vnode.type;\n\t}\n\n\treturn '#text';\n}\n\n/**\n * Used to keep track of the currently rendered `vnode` and print it\n * in debug messages.\n */\nlet renderStack = [];\n\n/**\n * Keep track of the current owners. An owner describes a component\n * which was responsible to render a specific `vnode`. This exclude\n * children that are passed via `props.children`, because they belong\n * to the parent owner.\n *\n * ```jsx\n * const Foo = props =>

    {props.children}
    // div's owner is Foo\n * const Bar = props => {\n * return (\n * // Foo's owner is Bar, span's owner is Bar\n * )\n * }\n * ```\n *\n * Note: A `vnode` may be hoisted to the root scope due to compiler\n * optimiztions. In these cases the `_owner` will be different.\n */\nlet ownerStack = [];\n\n/**\n * Get the currently rendered `vnode`\n * @returns {import('./internal').VNode | null}\n */\nexport function getCurrentVNode() {\n\treturn renderStack.length > 0 ? renderStack[renderStack.length - 1] : null;\n}\n\n/**\n * If the user doesn't have `@babel/plugin-transform-react-jsx-source`\n * somewhere in his tool chain we can't print the filename and source\n * location of a component. In that case we just omit that, but we'll\n * print a helpful message to the console, notifying the user of it.\n */\nlet showJsxSourcePluginWarning = true;\n\n/**\n * Check if a `vnode` is a possible owner.\n * @param {import('./internal').VNode} vnode\n */\nfunction isPossibleOwner(vnode) {\n\treturn typeof vnode.type == 'function' && vnode.type != Fragment;\n}\n\n/**\n * Return the component stack that was captured up to this point.\n * @param {import('./internal').VNode} vnode\n * @returns {string}\n */\nexport function getOwnerStack(vnode) {\n\tconst stack = [vnode];\n\tlet next = vnode;\n\twhile (next._owner != null) {\n\t\tstack.push(next._owner);\n\t\tnext = next._owner;\n\t}\n\n\treturn stack.reduce((acc, owner) => {\n\t\tacc += ` in ${getDisplayName(owner)}`;\n\n\t\tconst source = owner.__source;\n\t\tif (source) {\n\t\t\tacc += ` (at ${source.fileName}:${source.lineNumber})`;\n\t\t} else if (showJsxSourcePluginWarning) {\n\t\t\tconsole.warn(\n\t\t\t\t'Add @babel/plugin-transform-react-jsx-source to get a more detailed component stack. Note that you should not add it to production builds of your App for bundle size reasons.'\n\t\t\t);\n\t\t}\n\t\tshowJsxSourcePluginWarning = false;\n\n\t\treturn (acc += '\\n');\n\t}, '');\n}\n\n/**\n * Setup code to capture the component trace while rendering. Note that\n * we cannot simply traverse `vnode._parent` upwards, because we have some\n * debug messages for `this.setState` where the `vnode` is `undefined`.\n */\nexport function setupComponentStack() {\n\tlet oldDiff = options._diff;\n\tlet oldDiffed = options.diffed;\n\tlet oldRoot = options._root;\n\tlet oldVNode = options.vnode;\n\tlet oldRender = options._render;\n\n\toptions.diffed = vnode => {\n\t\tif (isPossibleOwner(vnode)) {\n\t\t\townerStack.pop();\n\t\t}\n\t\trenderStack.pop();\n\t\tif (oldDiffed) oldDiffed(vnode);\n\t};\n\n\toptions._diff = vnode => {\n\t\tif (isPossibleOwner(vnode)) {\n\t\t\trenderStack.push(vnode);\n\t\t}\n\t\tif (oldDiff) oldDiff(vnode);\n\t};\n\n\toptions._root = (vnode, parent) => {\n\t\townerStack = [];\n\t\tif (oldRoot) oldRoot(vnode, parent);\n\t};\n\n\toptions.vnode = vnode => {\n\t\tvnode._owner =\n\t\t\townerStack.length > 0 ? ownerStack[ownerStack.length - 1] : null;\n\t\tif (oldVNode) oldVNode(vnode);\n\t};\n\n\toptions._render = vnode => {\n\t\tif (isPossibleOwner(vnode)) {\n\t\t\townerStack.push(vnode);\n\t\t}\n\n\t\tif (oldRender) oldRender(vnode);\n\t};\n}\n","import { checkPropTypes } from './check-props';\nimport { options, Component } from 'preact';\nimport {\n\tELEMENT_NODE,\n\tDOCUMENT_NODE,\n\tDOCUMENT_FRAGMENT_NODE\n} from './constants';\nimport {\n\tgetOwnerStack,\n\tsetupComponentStack,\n\tgetCurrentVNode,\n\tgetDisplayName\n} from './component-stack';\nimport { assign, isNaN } from './util';\n\nconst isWeakMapSupported = typeof WeakMap == 'function';\n\n/**\n * @param {import('./internal').VNode} vnode\n * @returns {Array}\n */\nfunction getDomChildren(vnode) {\n\tlet domChildren = [];\n\n\tif (!vnode._children) return domChildren;\n\n\tvnode._children.forEach(child => {\n\t\tif (child && typeof child.type === 'function') {\n\t\t\tdomChildren.push.apply(domChildren, getDomChildren(child));\n\t\t} else if (child && typeof child.type === 'string') {\n\t\t\tdomChildren.push(child.type);\n\t\t}\n\t});\n\n\treturn domChildren;\n}\n\n/**\n * @param {import('./internal').VNode} parent\n * @returns {string}\n */\nfunction getClosestDomNodeParentName(parent) {\n\tif (!parent) return '';\n\tif (typeof parent.type == 'function') {\n\t\tif (parent._parent == null) {\n\t\t\tif (parent._dom != null && parent._dom.parentNode != null) {\n\t\t\t\treturn parent._dom.parentNode.localName;\n\t\t\t}\n\t\t\treturn '';\n\t\t}\n\t\treturn getClosestDomNodeParentName(parent._parent);\n\t}\n\treturn /** @type {string} */ (parent.type);\n}\n\nexport function initDebug() {\n\tsetupComponentStack();\n\n\tlet hooksAllowed = false;\n\n\t/* eslint-disable no-console */\n\tlet oldBeforeDiff = options._diff;\n\tlet oldDiffed = options.diffed;\n\tlet oldVnode = options.vnode;\n\tlet oldRender = options._render;\n\tlet oldCatchError = options._catchError;\n\tlet oldRoot = options._root;\n\tlet oldHook = options._hook;\n\tconst warnedComponents = !isWeakMapSupported\n\t\t? null\n\t\t: {\n\t\t\t\tuseEffect: new WeakMap(),\n\t\t\t\tuseLayoutEffect: new WeakMap(),\n\t\t\t\tlazyPropTypes: new WeakMap()\n\t\t\t};\n\tconst deprecations = [];\n\n\toptions._catchError = (error, vnode, oldVNode, errorInfo) => {\n\t\tlet component = vnode && vnode._component;\n\t\tif (component && typeof error.then == 'function') {\n\t\t\tconst promise = error;\n\t\t\terror = new Error(\n\t\t\t\t`Missing Suspense. The throwing component was: ${getDisplayName(vnode)}`\n\t\t\t);\n\n\t\t\tlet parent = vnode;\n\t\t\tfor (; parent; parent = parent._parent) {\n\t\t\t\tif (parent._component && parent._component._childDidSuspend) {\n\t\t\t\t\terror = promise;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// We haven't recovered and we know at this point that there is no\n\t\t\t// Suspense component higher up in the tree\n\t\t\tif (error instanceof Error) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\terrorInfo = errorInfo || {};\n\t\t\terrorInfo.componentStack = getOwnerStack(vnode);\n\t\t\toldCatchError(error, vnode, oldVNode, errorInfo);\n\n\t\t\t// when an error was handled by an ErrorBoundary we will nonetheless emit an error\n\t\t\t// event on the window object. This is to make up for react compatibility in dev mode\n\t\t\t// and thus make the Next.js dev overlay work.\n\t\t\tif (typeof error.then != 'function') {\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthrow error;\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tthrow e;\n\t\t}\n\t};\n\n\toptions._root = (vnode, parentNode) => {\n\t\tif (!parentNode) {\n\t\t\tthrow new Error(\n\t\t\t\t'Undefined parent passed to render(), this is the second argument.\\n' +\n\t\t\t\t\t'Check if the element is available in the DOM/has the correct id.'\n\t\t\t);\n\t\t}\n\n\t\tlet isValid;\n\t\tswitch (parentNode.nodeType) {\n\t\t\tcase ELEMENT_NODE:\n\t\t\tcase DOCUMENT_FRAGMENT_NODE:\n\t\t\tcase DOCUMENT_NODE:\n\t\t\t\tisValid = true;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tisValid = false;\n\t\t}\n\n\t\tif (!isValid) {\n\t\t\tlet componentName = getDisplayName(vnode);\n\t\t\tthrow new Error(\n\t\t\t\t`Expected a valid HTML node as a second argument to render.\tReceived ${parentNode} instead: render(<${componentName} />, ${parentNode});`\n\t\t\t);\n\t\t}\n\n\t\tif (oldRoot) oldRoot(vnode, parentNode);\n\t};\n\n\toptions._diff = vnode => {\n\t\tlet { type } = vnode;\n\n\t\thooksAllowed = true;\n\n\t\tif (type === undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t'Undefined component passed to createElement()\\n\\n' +\n\t\t\t\t\t'You likely forgot to export your component or might have mixed up default and named imports' +\n\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t);\n\t\t} else if (type != null && typeof type == 'object') {\n\t\t\tif (type._children !== undefined && type._dom !== undefined) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Invalid type passed to createElement(): ${type}\\n\\n` +\n\t\t\t\t\t\t'Did you accidentally pass a JSX literal as JSX twice?\\n\\n' +\n\t\t\t\t\t\t` let My${getDisplayName(vnode)} = ${serializeVNode(type)};\\n` +\n\t\t\t\t\t\t` let vnode = ;\\n\\n` +\n\t\t\t\t\t\t'This usually happens when you export a JSX literal and not the component.' +\n\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tthrow new Error(\n\t\t\t\t'Invalid type passed to createElement(): ' +\n\t\t\t\t\t(Array.isArray(type) ? 'array' : type)\n\t\t\t);\n\t\t}\n\n\t\tif (\n\t\t\tvnode.ref !== undefined &&\n\t\t\ttypeof vnode.ref != 'function' &&\n\t\t\ttypeof vnode.ref != 'object' &&\n\t\t\t!('$$typeof' in vnode) // allow string refs when preact-compat is installed\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`Component's \"ref\" property should be a function, or an object created ` +\n\t\t\t\t\t`by createRef(), but got [${typeof vnode.ref}] instead\\n` +\n\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t);\n\t\t}\n\n\t\tif (typeof vnode.type == 'string') {\n\t\t\tfor (const key in vnode.props) {\n\t\t\t\tif (\n\t\t\t\t\tkey[0] === 'o' &&\n\t\t\t\t\tkey[1] === 'n' &&\n\t\t\t\t\ttypeof vnode.props[key] != 'function' &&\n\t\t\t\t\tvnode.props[key] != null\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Component's \"${key}\" property should be a function, ` +\n\t\t\t\t\t\t\t`but got [${typeof vnode.props[key]}] instead\\n` +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check prop-types if available\n\t\tif (typeof vnode.type == 'function' && vnode.type.propTypes) {\n\t\t\tif (\n\t\t\t\tvnode.type.displayName === 'Lazy' &&\n\t\t\t\twarnedComponents &&\n\t\t\t\t!warnedComponents.lazyPropTypes.has(vnode.type)\n\t\t\t) {\n\t\t\t\tconst m =\n\t\t\t\t\t'PropTypes are not supported on lazy(). Use propTypes on the wrapped component itself. ';\n\t\t\t\ttry {\n\t\t\t\t\tconst lazyVNode = vnode.type();\n\t\t\t\t\twarnedComponents.lazyPropTypes.set(vnode.type, true);\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\tm + `Component wrapped in lazy() is ${getDisplayName(lazyVNode)}`\n\t\t\t\t\t);\n\t\t\t\t} catch (promise) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\tm + \"We will log the wrapped component's name once it is loaded.\"\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet values = vnode.props;\n\t\t\tif (vnode.type._forwarded) {\n\t\t\t\tvalues = assign({}, values);\n\t\t\t\tdelete values.ref;\n\t\t\t}\n\n\t\t\tcheckPropTypes(\n\t\t\t\tvnode.type.propTypes,\n\t\t\t\tvalues,\n\t\t\t\t'prop',\n\t\t\t\tgetDisplayName(vnode),\n\t\t\t\t() => getOwnerStack(vnode)\n\t\t\t);\n\t\t}\n\n\t\tif (oldBeforeDiff) oldBeforeDiff(vnode);\n\t};\n\n\tlet renderCount = 0;\n\tlet currentComponent;\n\toptions._render = vnode => {\n\t\tif (oldRender) {\n\t\t\toldRender(vnode);\n\t\t}\n\t\thooksAllowed = true;\n\n\t\tconst nextComponent = vnode._component;\n\t\tif (nextComponent === currentComponent) {\n\t\t\trenderCount++;\n\t\t} else {\n\t\t\trenderCount = 1;\n\t\t}\n\n\t\tif (renderCount >= 25) {\n\t\t\tthrow new Error(\n\t\t\t\t`Too many re-renders. This is limited to prevent an infinite loop ` +\n\t\t\t\t\t`which may lock up your browser. The component causing this is: ${getDisplayName(\n\t\t\t\t\t\tvnode\n\t\t\t\t\t)}`\n\t\t\t);\n\t\t}\n\n\t\tcurrentComponent = nextComponent;\n\t};\n\n\toptions._hook = (comp, index, type) => {\n\t\tif (!comp || !hooksAllowed) {\n\t\t\tthrow new Error('Hook can only be invoked from render methods.');\n\t\t}\n\n\t\tif (oldHook) oldHook(comp, index, type);\n\t};\n\n\t// Ideally we'd want to print a warning once per component, but we\n\t// don't have access to the vnode that triggered it here. As a\n\t// compromise and to avoid flooding the console with warnings we\n\t// print each deprecation warning only once.\n\tconst warn = (property, message) => ({\n\t\tget() {\n\t\t\tconst key = 'get' + property + message;\n\t\t\tif (deprecations && deprecations.indexOf(key) < 0) {\n\t\t\t\tdeprecations.push(key);\n\t\t\t\tconsole.warn(`getting vnode.${property} is deprecated, ${message}`);\n\t\t\t}\n\t\t},\n\t\tset() {\n\t\t\tconst key = 'set' + property + message;\n\t\t\tif (deprecations && deprecations.indexOf(key) < 0) {\n\t\t\t\tdeprecations.push(key);\n\t\t\t\tconsole.warn(`setting vnode.${property} is not allowed, ${message}`);\n\t\t\t}\n\t\t}\n\t});\n\n\tconst deprecatedAttributes = {\n\t\tnodeName: warn('nodeName', 'use vnode.type'),\n\t\tattributes: warn('attributes', 'use vnode.props'),\n\t\tchildren: warn('children', 'use vnode.props.children')\n\t};\n\n\tconst deprecatedProto = Object.create({}, deprecatedAttributes);\n\n\toptions.vnode = vnode => {\n\t\tconst props = vnode.props;\n\t\tif (\n\t\t\tvnode.type !== null &&\n\t\t\tprops != null &&\n\t\t\t('__source' in props || '__self' in props)\n\t\t) {\n\t\t\tconst newProps = (vnode.props = {});\n\t\t\tfor (let i in props) {\n\t\t\t\tconst v = props[i];\n\t\t\t\tif (i === '__source') vnode.__source = v;\n\t\t\t\telse if (i === '__self') vnode.__self = v;\n\t\t\t\telse newProps[i] = v;\n\t\t\t}\n\t\t}\n\n\t\t// eslint-disable-next-line\n\t\tvnode.__proto__ = deprecatedProto;\n\t\tif (oldVnode) oldVnode(vnode);\n\t};\n\n\toptions.diffed = vnode => {\n\t\tconst { type, _parent: parent } = vnode;\n\t\t// Check if the user passed plain objects as children. Note that we cannot\n\t\t// move this check into `options.vnode` because components can receive\n\t\t// children in any shape they want (e.g.\n\t\t// `{{ foo: 123, bar: \"abc\" }}`).\n\t\t// Putting this check in `options.diffed` ensures that\n\t\t// `vnode._children` is set and that we only validate the children\n\t\t// that were actually rendered.\n\t\tif (vnode._children) {\n\t\t\tvnode._children.forEach(child => {\n\t\t\t\tif (typeof child === 'object' && child && child.type === undefined) {\n\t\t\t\t\tconst keys = Object.keys(child).join(',');\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Objects are not valid as a child. Encountered an object with the keys {${keys}}.` +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tif (vnode._component === currentComponent) {\n\t\t\trenderCount = 0;\n\t\t}\n\n\t\tif (\n\t\t\ttypeof type === 'string' &&\n\t\t\t(isTableElement(type) ||\n\t\t\t\ttype === 'p' ||\n\t\t\t\ttype === 'a' ||\n\t\t\t\ttype === 'button')\n\t\t) {\n\t\t\t// Avoid false positives when Preact only partially rendered the\n\t\t\t// HTML tree. Whilst we attempt to include the outer DOM in our\n\t\t\t// validation, this wouldn't work on the server for\n\t\t\t// `preact-render-to-string`. There we'd otherwise flood the terminal\n\t\t\t// with false positives, which we'd like to avoid.\n\t\t\tlet domParentName = getClosestDomNodeParentName(parent);\n\t\t\tif (domParentName !== '' && isTableElement(type)) {\n\t\t\t\tif (\n\t\t\t\t\ttype === 'table' &&\n\t\t\t\t\t// Tables can be nested inside each other if it's inside a cell.\n\t\t\t\t\t// See https://developer.mozilla.org/en-US/docs/Learn/HTML/Tables/Advanced#nesting_tables\n\t\t\t\t\tdomParentName !== 'td' &&\n\t\t\t\t\tisTableElement(domParentName)\n\t\t\t\t) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t'Improper nesting of table. Your
    should not have a table-node parent.' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t} else if (\n\t\t\t\t\t(type === 'thead' || type === 'tfoot' || type === 'tbody') &&\n\t\t\t\t\tdomParentName !== 'table'\n\t\t\t\t) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t'Improper nesting of table. Your should have a
    parent.' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t} else if (\n\t\t\t\t\ttype === 'tr' &&\n\t\t\t\t\tdomParentName !== 'thead' &&\n\t\t\t\t\tdomParentName !== 'tfoot' &&\n\t\t\t\t\tdomParentName !== 'tbody'\n\t\t\t\t) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t'Improper nesting of table. Your should have a parent.' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t} else if (type === 'td' && domParentName !== 'tr') {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t'Improper nesting of table. Your parent.' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t} else if (type === 'th' && domParentName !== 'tr') {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t'Improper nesting of table. Your .' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} else if (type === 'p') {\n\t\t\t\tlet illegalDomChildrenTypes = getDomChildren(vnode).filter(childType =>\n\t\t\t\t\tILLEGAL_PARAGRAPH_CHILD_ELEMENTS.test(childType)\n\t\t\t\t);\n\t\t\t\tif (illegalDomChildrenTypes.length) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t'Improper nesting of paragraph. Your

    should not have ' +\n\t\t\t\t\t\t\tillegalDomChildrenTypes.join(', ') +\n\t\t\t\t\t\t\t' as child-elements.' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} else if (type === 'a' || type === 'button') {\n\t\t\t\tif (getDomChildren(vnode).indexOf(type) !== -1) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t`Improper nesting of interactive content. Your <${type}>` +\n\t\t\t\t\t\t\t` should not have other ${type === 'a' ? 'anchor' : 'button'}` +\n\t\t\t\t\t\t\t' tags as child-elements.' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\thooksAllowed = false;\n\n\t\tif (oldDiffed) oldDiffed(vnode);\n\n\t\tif (vnode._children != null) {\n\t\t\tconst keys = [];\n\t\t\tfor (let i = 0; i < vnode._children.length; i++) {\n\t\t\t\tconst child = vnode._children[i];\n\t\t\t\tif (!child || child.key == null) continue;\n\n\t\t\t\tconst key = child.key;\n\t\t\t\tif (keys.indexOf(key) !== -1) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t'Following component has two or more children with the ' +\n\t\t\t\t\t\t\t`same key attribute: \"${key}\". This may cause glitches and misbehavior ` +\n\t\t\t\t\t\t\t'in rendering process. Component: \\n\\n' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\n\t\t\t\t\t// Break early to not spam the console\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tkeys.push(key);\n\t\t\t}\n\t\t}\n\n\t\tif (vnode._component != null && vnode._component.__hooks != null) {\n\t\t\t// Validate that none of the hooks in this component contain arguments that are NaN.\n\t\t\t// This is a common mistake that can be hard to debug, so we want to catch it early.\n\t\t\tconst hooks = vnode._component.__hooks._list;\n\t\t\tif (hooks) {\n\t\t\t\tfor (let i = 0; i < hooks.length; i += 1) {\n\t\t\t\t\tconst hook = hooks[i];\n\t\t\t\t\tif (hook._args) {\n\t\t\t\t\t\tfor (let j = 0; j < hook._args.length; j++) {\n\t\t\t\t\t\t\tconst arg = hook._args[j];\n\t\t\t\t\t\t\tif (isNaN(arg)) {\n\t\t\t\t\t\t\t\tconst componentName = getDisplayName(vnode);\n\t\t\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t\t\t`Invalid argument passed to hook. Hooks should not be called with NaN in the dependency array. Hook index ${i} in component ${componentName} was called with NaN.`\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n}\n\nconst setState = Component.prototype.setState;\nComponent.prototype.setState = function (update, callback) {\n\tif (this._vnode == null) {\n\t\t// `this._vnode` will be `null` during componentWillMount. But it\n\t\t// is perfectly valid to call `setState` during cWM. So we\n\t\t// need an additional check to verify that we are dealing with a\n\t\t// call inside constructor.\n\t\tif (this.state == null) {\n\t\t\tconsole.warn(\n\t\t\t\t`Calling \"this.setState\" inside the constructor of a component is a ` +\n\t\t\t\t\t`no-op and might be a bug in your application. Instead, set ` +\n\t\t\t\t\t`\"this.state = {}\" directly.\\n\\n${getOwnerStack(getCurrentVNode())}`\n\t\t\t);\n\t\t}\n\t}\n\n\treturn setState.call(this, update, callback);\n};\n\nfunction isTableElement(type) {\n\treturn (\n\t\ttype === 'table' ||\n\t\ttype === 'tfoot' ||\n\t\ttype === 'tbody' ||\n\t\ttype === 'thead' ||\n\t\ttype === 'td' ||\n\t\ttype === 'tr' ||\n\t\ttype === 'th'\n\t);\n}\n\nconst ILLEGAL_PARAGRAPH_CHILD_ELEMENTS =\n\t/^(address|article|aside|blockquote|details|div|dl|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hgroup|hr|main|menu|nav|ol|p|pre|search|section|table|ul)$/;\n\nconst forceUpdate = Component.prototype.forceUpdate;\nComponent.prototype.forceUpdate = function (callback) {\n\tif (this._vnode == null) {\n\t\tconsole.warn(\n\t\t\t`Calling \"this.forceUpdate\" inside the constructor of a component is a ` +\n\t\t\t\t`no-op and might be a bug in your application.\\n\\n${getOwnerStack(\n\t\t\t\t\tgetCurrentVNode()\n\t\t\t\t)}`\n\t\t);\n\t} else if (this._parentDom == null) {\n\t\tconsole.warn(\n\t\t\t`Can't call \"this.forceUpdate\" on an unmounted component. This is a no-op, ` +\n\t\t\t\t`but it indicates a memory leak in your application. To fix, cancel all ` +\n\t\t\t\t`subscriptions and asynchronous tasks in the componentWillUnmount method.` +\n\t\t\t\t`\\n\\n${getOwnerStack(this._vnode)}`\n\t\t);\n\t}\n\treturn forceUpdate.call(this, callback);\n};\n\n/**\n * Serialize a vnode tree to a string\n * @param {import('./internal').VNode} vnode\n * @returns {string}\n */\nexport function serializeVNode(vnode) {\n\tlet { props } = vnode;\n\tlet name = getDisplayName(vnode);\n\n\tlet attrs = '';\n\tfor (let prop in props) {\n\t\tif (props.hasOwnProperty(prop) && prop !== 'children') {\n\t\t\tlet value = props[prop];\n\n\t\t\t// If it is an object but doesn't have toString(), use Object.toString\n\t\t\tif (typeof value == 'function') {\n\t\t\t\tvalue = `function ${value.displayName || value.name}() {}`;\n\t\t\t}\n\n\t\t\tvalue =\n\t\t\t\tObject(value) === value && !value.toString\n\t\t\t\t\t? Object.prototype.toString.call(value)\n\t\t\t\t\t: value + '';\n\n\t\t\tattrs += ` ${prop}=${JSON.stringify(value)}`;\n\t\t}\n\t}\n\n\tlet children = props.children;\n\treturn `<${name}${attrs}${\n\t\tchildren && children.length ? '>..' : ' />'\n\t}`;\n}\n\noptions._hydrationMismatch = (newVNode, excessDomChildren) => {\n\tconst { type } = newVNode;\n\tconst availableTypes = excessDomChildren\n\t\t.map(child => child && child.localName)\n\t\t.filter(Boolean);\n\tconsole.error(\n\t\t`Expected a DOM node of type \"${type}\" but found \"${availableTypes.join(', ')}\" as available DOM-node(s), this is caused by the SSR'd HTML containing different DOM-nodes compared to the hydrated one.\\n\\n${getOwnerStack(newVNode)}`\n\t);\n};\n","export const ELEMENT_NODE = 1;\nexport const DOCUMENT_NODE = 9;\nexport const DOCUMENT_FRAGMENT_NODE = 11;\n","/**\n * Assign properties from `props` to `obj`\n * @template O, P The obj and props types\n * @param {O} obj The object to copy properties to\n * @param {P} props The object to copy properties from\n * @returns {O & P}\n */\nexport function assign(obj, props) {\n\tfor (let i in props) obj[i] = props[i];\n\treturn /** @type {O & P} */ (obj);\n}\n\nexport function isNaN(value) {\n\treturn value !== value;\n}\n","import { initDebug } from './debug';\nimport 'preact/devtools';\n\ninitDebug();\n\nexport { resetPropWarnings } from './check-props';\n\nexport {\n\tgetCurrentVNode,\n\tgetDisplayName,\n\tgetOwnerStack\n} from './component-stack';\n"],"names":["loggedTypeFailures","getDisplayName","vnode","type","Fragment","displayName","name","renderStack","ownerStack","getCurrentVNode","length","showJsxSourcePluginWarning","isPossibleOwner","getOwnerStack","stack","next","__o","push","reduce","acc","owner","source","__source","fileName","lineNumber","console","warn","isWeakMapSupported","WeakMap","getDomChildren","domChildren","__k","forEach","child","apply","getClosestDomNodeParentName","parent","__","__e","parentNode","localName","setState","Component","prototype","isTableElement","update","callback","this","__v","state","call","ILLEGAL_PARAGRAPH_CHILD_ELEMENTS","forceUpdate","serializeVNode","props","attrs","prop","hasOwnProperty","value","Object","toString","JSON","stringify","children","__P","options","__m","newVNode","excessDomChildren","availableTypes","map","filter","Boolean","error","join","oldDiff","__b","oldDiffed","diffed","oldRoot","oldVNode","oldRender","__r","pop","setupComponentStack","hooksAllowed","oldBeforeDiff","oldVnode","oldCatchError","oldHook","__h","warnedComponents","useEffect","useLayoutEffect","lazyPropTypes","deprecations","errorInfo","__c","then","promise","Error","componentStack","setTimeout","e","isValid","nodeType","componentName","undefined","Array","isArray","ref","key","propTypes","has","m","lazyVNode","set","values","__f","obj","i","assign","typeSpecs","location","getStack","keys","typeSpecName","message","checkPropTypes","currentComponent","renderCount","nextComponent","comp","index","property","get","indexOf","deprecatedAttributes","nodeName","attributes","deprecatedProto","create","newProps","v","__self","__proto__","domParentName","illegalDomChildrenTypes","childType","test","__H","hooks","hook","j","initDebug"],"mappings":"mDAAA,IAEIA,EAAqB,CAAA,ECMlB,SAASC,EAAeC,GAC9B,OAAIA,EAAMC,OAASC,EAAAA,SACX,WACwB,mBAAdF,EAAMC,KAChBD,EAAMC,KAAKE,aAAeH,EAAMC,KAAKG,KACb,iBAAdJ,EAAMC,KAChBD,EAAMC,KAGP,OACR,CAMA,IAAII,EAAc,GAoBdC,EAAa,YAMDC,IACf,OAAOF,EAAYG,OAAS,EAAIH,EAAYA,EAAYG,OAAS,GAAK,IACvE,CAQA,IAAIC,GAA6B,EAMjC,SAASC,EAAgBV,GACxB,MAA4B,mBAAdA,EAAMC,MAAsBD,EAAMC,MAAQC,EAAAA,QACzD,CAOO,SAASS,EAAcX,GAG7B,IAFA,IAAMY,EAAQ,CAACZ,GACXa,EAAOb,EACW,MAAfa,EAAIC,KACVF,EAAMG,KAAKF,EAAIC,KACfD,EAAOA,EAAIC,IAGZ,OAAOF,EAAMI,OAAO,SAACC,EAAKC,GACzBD,GAAelB,QAAAA,EAAemB,GAE9B,IAAMC,EAASD,EAAME,SAUrB,OATID,EACHF,GAAeE,QAAAA,EAAOE,SAAYF,IAAAA,EAAOG,WAC1C,IAAWb,GACVc,QAAQC,KACP,kLAGFf,GAA6B,EAErBQ,EAAO,IAChB,EAAG,GACJ,CCnFA,IAAMQ,EAAuC,mBAAXC,QAMlC,SAASC,EAAe3B,GACvB,IAAI4B,EAAc,GAElB,OAAK5B,EAAK6B,KAEV7B,EAAK6B,IAAWC,QAAQ,SAAAC,GACnBA,GAA+B,mBAAfA,EAAM9B,KACzB2B,EAAYb,KAAKiB,MAAMJ,EAAaD,EAAeI,IACzCA,GAA+B,iBAAfA,EAAM9B,MAChC2B,EAAYb,KAAKgB,EAAM9B,KAEzB,GAEO2B,GAVsBA,CAW9B,CAMA,SAASK,EAA4BC,GACpC,OAAKA,EACqB,mBAAfA,EAAOjC,KACK,MAAlBiC,EAAMC,GACU,MAAfD,EAAME,KAA2C,MAA1BF,EAAME,IAAMC,WAC/BH,EAAME,IAAMC,WAAWC,UAExB,GAEDL,EAA4BC,EAAMC,IAEZD,EAAOjC,KAVjB,EAWrB,CA2bA,IAAMsC,EAAWC,EAASA,UAACC,UAAUF,SAmBrC,SAASG,EAAezC,GACvB,MACU,UAATA,GACS,UAATA,GACS,UAATA,GACS,UAATA,GACS,OAATA,GACS,OAATA,GACS,OAATA,CAEF,CA5BAuC,EAAAA,UAAUC,UAAUF,SAAW,SAAUI,EAAQC,GAehD,OAdmB,MAAfC,KAAIC,KAKW,MAAdD,KAAKE,OACRxB,QAAQC,KACP,gKAEmCb,EAAcJ,MAK7CgC,EAASS,KAAKH,KAAMF,EAAQC,EACpC,EAcA,IAAMK,EACL,+KAEKC,EAAcV,EAAAA,UAAUC,UAAUS,YAyBjC,SAASC,EAAenD,GAC9B,IAAMoD,EAAUpD,EAAVoD,MACFhD,EAAOL,EAAeC,GAEtBqD,EAAQ,GACZ,IAAK,IAAIC,KAAQF,EAChB,GAAIA,EAAMG,eAAeD,IAAkB,aAATA,EAAqB,CACtD,IAAIE,EAAQJ,EAAME,GAGE,mBAATE,IACVA,EAAK,aAAeA,EAAMrD,aAAeqD,EAAMpD,MAAI,SAGpDoD,EACCC,OAAOD,KAAWA,GAAUA,EAAME,SAE/BF,EAAQ,GADRC,OAAOhB,UAAUiB,SAASV,KAAKQ,GAGnCH,OAAaC,EAAI,IAAIK,KAAKC,UAAUJ,EACrC,CAGD,IAAIK,EAAWT,EAAMS,SACrB,MAAA,IAAWzD,EAAOiD,GACjBQ,GAAYA,EAASrD,OAAS,QAAUJ,EAAO,IAAM,MAEvD,CAnDAoC,EAASA,UAACC,UAAUS,YAAc,SAAUN,GAgB3C,OAfmB,MAAfC,KAAIC,IACPvB,QAAQC,KACP,0HACqDb,EACnDJ,MAG0B,MAAnBsC,KAAIiB,KACdvC,QAAQC,KACP,iOAGQb,EAAckC,KAAIC,MAGrBI,EAAYF,KAAKH,KAAMD,EAC/B,EAoCAmB,EAAOA,QAAAC,IAAsB,SAACC,EAAUC,GACvC,IAAQjE,EAASgE,EAAThE,KACFkE,EAAiBD,EACrBE,IAAI,SAAArC,GAAK,OAAIA,GAASA,EAAMO,SAAS,GACrC+B,OAAOC,SACT/C,QAAQgD,MACyBtE,gCAAAA,EAAoBkE,gBAAAA,EAAeK,KAAK,uIAAqI7D,EAAcsD,GAE7N,EAzhBO,YDkDA,WACN,IAAIQ,EAAUV,EAAAA,QAAOW,IACjBC,EAAYZ,EAAOA,QAACa,OACpBC,EAAUd,EAAOA,QAAA5B,GACjB2C,EAAWf,EAAOA,QAAC/D,MACnB+E,EAAYhB,EAAOA,QAAAiB,IAEvBjB,EAAAA,QAAQa,OAAS,SAAA5E,GACZU,EAAgBV,IACnBM,EAAW2E,MAEZ5E,EAAY4E,MACRN,GAAWA,EAAU3E,EAC1B,EAEA+D,EAAOA,QAAAW,IAAS,SAAA1E,GACXU,EAAgBV,IACnBK,EAAYU,KAAKf,GAEdyE,GAASA,EAAQzE,EACtB,EAEA+D,UAAO5B,GAAS,SAACnC,EAAOkC,GACvB5B,EAAa,GACTuE,GAASA,EAAQ7E,EAAOkC,EAC7B,EAEA6B,EAAAA,QAAQ/D,MAAQ,SAAAA,GACfA,EAAKc,IACJR,EAAWE,OAAS,EAAIF,EAAWA,EAAWE,OAAS,GAAK,KACzDsE,GAAUA,EAAS9E,EACxB,EAEA+D,EAAOA,QAAAiB,IAAW,SAAAhF,GACbU,EAAgBV,IACnBM,EAAWS,KAAKf,GAGb+E,GAAWA,EAAU/E,EAC1B,CACD,CCzFCkF,GAEA,IAAIC,GAAe,EAGfC,EAAgBrB,EAAAA,QAAOW,IACvBC,EAAYZ,EAAOA,QAACa,OACpBS,EAAWtB,EAAOA,QAAC/D,MACnB+E,EAAYhB,EAAOA,QAAAiB,IACnBM,EAAgBvB,EAAOA,QAAA3B,IACvByC,EAAUd,EAAOA,QAAA5B,GACjBoD,EAAUxB,EAAOA,QAAAyB,IACfC,EAAoBhE,EAEvB,CACAiE,UAAW,IAAIhE,QACfiE,gBAAiB,IAAIjE,QACrBkE,cAAe,IAAIlE,SAJnB,KAMGmE,EAAe,GAErB9B,EAAAA,QAAO3B,IAAe,SAACmC,EAAOvE,EAAO8E,EAAUgB,GAE9C,GADgB9F,GAASA,EAAK+F,KACQ,mBAAdxB,EAAMyB,KAAoB,CACjD,IAAMC,EAAU1B,EAChBA,EAAQ,IAAI2B,MAAK,iDACiCnG,EAAeC,IAIjE,IADA,IAAIkC,EAASlC,EACNkC,EAAQA,EAASA,EAAMC,GAC7B,GAAID,EAAM6D,KAAe7D,EAAM6D,IAAAA,IAA8B,CAC5DxB,EAAQ0B,EACR,KACD,CAKD,GAAI1B,aAAiB2B,MACpB,MAAM3B,CAER,CAEA,KACCuB,EAAYA,GAAa,IACfK,eAAiBxF,EAAcX,GACzCsF,EAAcf,EAAOvE,EAAO8E,EAAUgB,GAKb,mBAAdvB,EAAMyB,MAChBI,WAAW,WACV,MAAM7B,CACP,EAIF,CAFE,MAAO8B,GACR,MAAMA,CACP,CACD,EAEAtC,EAAOA,QAAA5B,GAAS,SAACnC,EAAOqC,GACvB,IAAKA,EACJ,UAAU6D,MACT,uIAKF,IAAII,EACJ,OAAQjE,EAAWkE,UAClB,KChIyB,EDiIzB,KC/HmC,GDgInC,KCjI0B,EDkIzBD,GAAU,EACV,MACD,QACCA,GAAU,EAGZ,IAAKA,EAAS,CACb,IAAIE,EAAgBzG,EAAeC,GACnC,MAAM,IAAIkG,8EAC8D7D,EAAU,qBAAqBmE,EAAa,QAAQnE,EAC5H,KACD,CAEIwC,GAASA,EAAQ7E,EAAOqC,EAC7B,EAEA0B,EAAOA,QAAAW,IAAS,SAAA1E,GACf,IAAMC,EAASD,EAATC,KAIN,GAFAkF,GAAe,OAEFsB,IAATxG,EACH,MAAU,IAAAiG,MACT,+IAEC/C,EAAenD,UACRW,EAAcX,IAEjB,GAAY,MAARC,GAA+B,iBAARA,EAAkB,CACnD,QAAuBwG,IAAnBxG,EAAI4B,UAA0C4E,IAAdxG,EAAImC,IACvC,MAAM,IAAI8D,MACT,2CAA2CjG,EAA3C,wEAEYF,EAAeC,GAAYmD,MAAAA,EAAelD,GAFtD,uBAGqBF,EAAeC,GAHpC,wFAKQW,EAAcX,IAIxB,MAAM,IAAIkG,MACT,4CACEQ,MAAMC,QAAQ1G,GAAQ,QAAUA,GAEpC,CAEA,QACewG,IAAdzG,EAAM4G,KACc,mBAAb5G,EAAM4G,KACO,iBAAb5G,EAAM4G,OACX,aAAc5G,GAEhB,MAAU,IAAAkG,MACT,0GACoClG,EAAM4G,IAAG,cAC5CzD,EAAenD,GACRW,OAAAA,EAAcX,IAIxB,GAAyB,iBAAdA,EAAMC,KAChB,IAAK,IAAM4G,KAAO7G,EAAMoD,MACvB,GACY,MAAXyD,EAAI,IACO,MAAXA,EAAI,IACuB,mBAApB7G,EAAMoD,MAAMyD,IACC,MAApB7G,EAAMoD,MAAMyD,GAEZ,MAAU,IAAAX,MACT,iBAAgBW,EAAhB,oDACoB7G,EAAMoD,MAAMyD,GAAiB,cAChD1D,EAAenD,GAAM,OACdW,EAAcX,IAO1B,GAAyB,mBAAdA,EAAMC,MAAsBD,EAAMC,KAAK6G,UAAW,CAC5D,GAC4B,SAA3B9G,EAAMC,KAAKE,aACXsF,IACCA,EAAiBG,cAAcmB,IAAI/G,EAAMC,MACzC,CACD,IAAM+G,EACL,yFACD,IACC,IAAMC,EAAYjH,EAAMC,OACxBwF,EAAiBG,cAAcsB,IAAIlH,EAAMC,MAAM,GAC/CsB,QAAQC,KACPwF,oCAAsCjH,EAAekH,GAMvD,CAJE,MAAOhB,GACR1E,QAAQC,KACPwF,EAAI,8DAEN,CACD,CAEA,IAAIG,EAASnH,EAAMoD,MACfpD,EAAMC,KAAImH,YACbD,WElOmBE,EAAKjE,GAC3B,IAAK,IAAIkE,KAAKlE,EAAOiE,EAAIC,GAAKlE,EAAMkE,GACpC,OAA6BD,CAC9B,CF+NaE,CAAO,CAAE,EAAEJ,IACNP,IFnNX,SACNY,EACAL,EACAM,EACAjB,EACAkB,GAEAjE,OAAOkE,KAAKH,GAAW1F,QAAQ,SAAA8F,GAC9B,IAAIrD,EACJ,IACCA,EAAQiD,EAAUI,GACjBT,EACAS,EACApB,EE4MA,OF1MA,KAtCyB,+CA2C3B,CAFE,MAAOH,GACR9B,EAAQ8B,CACT,CACI9B,KAAWA,EAAMsD,WAAW/H,KAC/BA,EAAmByE,EAAMsD,UAAW,EACpCtG,QAAQgD,2BACqBA,EAAMsD,SAChCH,GAAQ,KAASA,KAAiB,KAIvC,EACD,CEwLGI,CACC9H,EAAMC,KAAK6G,UACXK,EACA,EACApH,EAAeC,GACf,WAAM,OAAAW,EAAcX,EAAM,EAE5B,CAEIoF,GAAeA,EAAcpF,EAClC,EAEA,IACI+H,EADAC,EAAc,EAElBjE,EAAOA,QAAAiB,IAAW,SAAAhF,GACb+E,GACHA,EAAU/E,GAEXmF,GAAe,EAEf,IAAM8C,EAAgBjI,EAAK+F,IAO3B,GANIkC,IAAkBF,EACrBC,IAEAA,EAAc,EAGXA,GAAe,GAClB,MAAM,IAAI9B,MACT,mIACmEnG,EACjEC,IAKJ+H,EAAmBE,CACpB,EAEAlE,UAAOyB,IAAS,SAAC0C,EAAMC,EAAOlI,GAC7B,IAAKiI,IAAS/C,EACb,MAAU,IAAAe,MAAM,iDAGbX,GAASA,EAAQ2C,EAAMC,EAAOlI,EACnC,EAMA,IAAMuB,EAAO,SAAC4G,EAAUP,SAAa,CACpCQ,IAAA,WACC,IAAMxB,EAAM,MAAQuB,EAAWP,EAC3BhC,GAAgBA,EAAayC,QAAQzB,GAAO,IAC/ChB,EAAa9E,KAAK8F,GAClBtF,QAAQC,KAAsB4G,iBAAAA,qBAA2BP,GAE3D,EACAX,IAAG,WACF,IAAML,EAAM,MAAQuB,EAAWP,EAC3BhC,GAAgBA,EAAayC,QAAQzB,GAAO,IAC/ChB,EAAa9E,KAAK8F,GAClBtF,QAAQC,KAAI,iBAAkB4G,EAAQ,oBAAoBP,GAE5D,EACA,EAEKU,EAAuB,CAC5BC,SAAUhH,EAAK,WAAY,kBAC3BiH,WAAYjH,EAAK,aAAc,mBAC/BqC,SAAUrC,EAAK,WAAY,6BAGtBkH,EAAkBjF,OAAOkF,OAAO,CAAE,EAAEJ,GAE1CxE,EAAAA,QAAQ/D,MAAQ,SAAAA,GACf,IAAMoD,EAAQpD,EAAMoD,MACpB,GACgB,OAAfpD,EAAMC,MACG,MAATmD,IACC,aAAcA,GAAS,WAAYA,GACnC,CACD,IAAMwF,EAAY5I,EAAMoD,MAAQ,CAAA,EAChC,IAAK,IAAIkE,KAAKlE,EAAO,CACpB,IAAMyF,EAAIzF,EAAMkE,GACN,aAANA,EAAkBtH,EAAMoB,SAAWyH,EACxB,WAANvB,EAAgBtH,EAAM8I,OAASD,EACnCD,EAAStB,GAAKuB,CACpB,CACD,CAGA7I,EAAM+I,UAAYL,EACdrD,GAAUA,EAASrF,EACxB,EAEA+D,EAAAA,QAAQa,OAAS,SAAA5E,GAChB,IEnUoBwD,EFmUZvD,EAA0BD,EAA1BC,KAAeiC,EAAWlC,EAAKmC,GAwBvC,GAhBInC,EAAK6B,KACR7B,EAAK6B,IAAWC,QAAQ,SAAAC,GACvB,GAAqB,iBAAVA,GAAsBA,QAAwB0E,IAAf1E,EAAM9B,KAAoB,CACnE,IAAM0H,EAAOlE,OAAOkE,KAAK5F,GAAOyC,KAAK,KACrC,MAAM,IAAI0B,MACT,0EAA0EyB,EAA1E,SACQhH,EAAcX,GAExB,CACD,GAGGA,EAAK+F,MAAgBgC,IACxBC,EAAc,GAIE,iBAAT/H,IACNyC,EAAezC,IACN,MAATA,GACS,MAATA,GACS,WAATA,GACA,CAMD,IAAI+I,EAAgB/G,EAA4BC,GAChD,GAAsB,KAAlB8G,GAAwBtG,EAAezC,GAEhC,UAATA,GAGkB,OAAlB+I,GACAtG,EAAesG,GAEfzH,QAAQgD,MACP,+EACCpB,EAAenD,UACRW,EAAcX,IAGb,UAATC,GAA6B,UAATA,GAA6B,UAATA,GACvB,UAAlB+I,EAQS,OAAT/I,GACkB,UAAlB+I,GACkB,UAAlBA,GACkB,UAAlBA,EAEAzH,QAAQgD,MACP,iFACCpB,EAAenD,GAAM,OACdW,EAAcX,IAEJ,OAATC,GAAmC,OAAlB+I,EAC3BzH,QAAQgD,MACP,kEACCpB,EAAenD,GAAM,OACdW,EAAcX,IAEJ,OAATC,GAAmC,OAAlB+I,GAC3BzH,QAAQgD,MACP,2DACCpB,EAAenD,GACRW,OAAAA,EAAcX,IA1BvBuB,QAAQgD,MACP,oFACCpB,EAAenD,GAAM,OACdW,EAAcX,SA0BlB,GAAa,MAATC,EAAc,CACxB,IAAIgJ,EAA0BtH,EAAe3B,GAAOqE,OAAO,SAAA6E,GAC1D,OAAAjG,EAAiCkG,KAAKD,EAAU,GAE7CD,EAAwBzI,QAC3Be,QAAQgD,MACP,2DACC0E,EAAwBzE,KAAK,MAC7B,sBACArB,EAAenD,GACRW,OAAAA,EAAcX,GAGzB,KAAoB,MAATC,GAAyB,WAATA,IACmB,IAAzC0B,EAAe3B,GAAOsI,QAAQrI,IACjCsB,QAAQgD,MACP,kDAAkDtE,EAAlD,4BACoC,MAATA,EAAe,SAAW,UACpD,2BACAkD,EAAenD,GAAM,OACdW,EAAcX,GAI1B,CAMA,GAJAmF,GAAe,EAEXR,GAAWA,EAAU3E,GAEF,MAAnBA,EAAK6B,IAER,IADA,IAAM8F,EAAO,GACJL,EAAI,EAAGA,EAAItH,EAAK6B,IAAWrB,OAAQ8G,IAAK,CAChD,IAAMvF,EAAQ/B,EAAK6B,IAAWyF,GAC9B,GAAKvF,GAAsB,MAAbA,EAAM8E,IAApB,CAEA,IAAMA,EAAM9E,EAAM8E,IAClB,IAA2B,IAAvBc,EAAKW,QAAQzB,GAAa,CAC7BtF,QAAQgD,MACP,8EACyBsC,EADzB,mFAGC1D,EAAenD,GACRW,OAAAA,EAAcX,IAIvB,KACD,CAEA2H,EAAK5G,KAAK8F,GACX,CAGD,GAAwB,MAApB7G,EAAK+F,KAAmD,MAA5B/F,EAAK+F,IAAAqD,IAA6B,CAGjE,IAAMC,EAAQrJ,EAAK+F,IAAAqD,IAAAjH,GACnB,GAAIkH,EACH,IAAK,IAAI/B,EAAI,EAAGA,EAAI+B,EAAM7I,OAAQ8G,GAAK,EAAG,CACzC,IAAMgC,EAAOD,EAAM/B,GACnB,GAAIgC,EAAIF,IACP,IAAK,IAAIG,EAAI,EAAGA,EAAID,EAAIF,IAAO5I,OAAQ+I,IAEtC,IEtde/F,EFqdH8F,EAAIF,IAAOG,KEpdZ/F,EFqdK,CACf,IAAMgD,EAAgBzG,EAAeC,GACrCuB,QAAQC,KAAI,4GACiG8F,EAAC,iBAAiBd,EAC/H,wBACD,CAGH,CAEF,CACD,CACD,CG3eAgD,wGLIO,WACN1J,EAAqB,CAAA,CACtB"} \ No newline at end of file diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/debug/dist/debug.mjs b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/dist/debug.mjs new file mode 100644 index 0000000000000..8c3c2dfe8a75f --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/dist/debug.mjs @@ -0,0 +1,2 @@ +import{Fragment as n,options as e,Component as o}from"preact";import"preact/devtools";var t={};function r(){t={}}function a(e){return e.type===n?"Fragment":"function"==typeof e.type?e.type.displayName||e.type.name:"string"==typeof e.type?e.type:"#text"}var i=[],s=[];function c(){return i.length>0?i[i.length-1]:null}var l=!0;function u(e){return"function"==typeof e.type&&e.type!=n}function f(n){for(var e=[n],o=n;null!=o.__o;)e.push(o.__o),o=o.__o;return e.reduce(function(n,e){n+=" in "+a(e);var o=e.__source;return o?n+=" (at "+o.fileName+":"+o.lineNumber+")":l&&console.warn("Add @babel/plugin-transform-react-jsx-source to get a more detailed component stack. Note that you should not add it to production builds of your App for bundle size reasons."),l=!1,n+"\n"},"")}var d="function"==typeof WeakMap;function p(n){var e=[];return n.__k?(n.__k.forEach(function(n){n&&"function"==typeof n.type?e.push.apply(e,p(n)):n&&"string"==typeof n.type&&e.push(n.type)}),e):e}function h(n){return n?"function"==typeof n.type?null==n.__?null!=n.__e&&null!=n.__e.parentNode?n.__e.parentNode.localName:"":h(n.__):n.type:""}var v=o.prototype.setState;function y(n){return"table"===n||"tfoot"===n||"tbody"===n||"thead"===n||"td"===n||"tr"===n||"th"===n}o.prototype.setState=function(n,e){return null==this.__v&&null==this.state&&console.warn('Calling "this.setState" inside the constructor of a component is a no-op and might be a bug in your application. Instead, set "this.state = {}" directly.\n\n'+f(c())),v.call(this,n,e)};var m=/^(address|article|aside|blockquote|details|div|dl|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hgroup|hr|main|menu|nav|ol|p|pre|search|section|table|ul)$/,b=o.prototype.forceUpdate;function w(n){var e=n.props,o=a(n),t="";for(var r in e)if(e.hasOwnProperty(r)&&"children"!==r){var i=e[r];"function"==typeof i&&(i="function "+(i.displayName||i.name)+"() {}"),i=Object(i)!==i||i.toString?i+"":Object.prototype.toString.call(i),t+=" "+r+"="+JSON.stringify(i)}var s=e.children;return"<"+o+t+(s&&s.length?">..":" />")}o.prototype.forceUpdate=function(n){return null==this.__v?console.warn('Calling "this.forceUpdate" inside the constructor of a component is a no-op and might be a bug in your application.\n\n'+f(c())):null==this.__P&&console.warn('Can\'t call "this.forceUpdate" on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.\n\n'+f(this.__v)),b.call(this,n)},e.__m=function(n,e){var o=n.type,t=e.map(function(n){return n&&n.localName}).filter(Boolean);console.error('Expected a DOM node of type "'+o+'" but found "'+t.join(", ")+"\" as available DOM-node(s), this is caused by the SSR'd HTML containing different DOM-nodes compared to the hydrated one.\n\n"+f(n))},function(){!function(){var n=e.__b,o=e.diffed,t=e.__,r=e.vnode,a=e.__r;e.diffed=function(n){u(n)&&s.pop(),i.pop(),o&&o(n)},e.__b=function(e){u(e)&&i.push(e),n&&n(e)},e.__=function(n,e){s=[],t&&t(n,e)},e.vnode=function(n){n.__o=s.length>0?s[s.length-1]:null,r&&r(n)},e.__r=function(n){u(n)&&s.push(n),a&&a(n)}}();var n=!1,o=e.__b,r=e.diffed,c=e.vnode,l=e.__r,v=e.__e,b=e.__,g=e.__h,E=d?{useEffect:new WeakMap,useLayoutEffect:new WeakMap,lazyPropTypes:new WeakMap}:null,k=[];e.__e=function(n,e,o,t){if(e&&e.__c&&"function"==typeof n.then){var r=n;n=new Error("Missing Suspense. The throwing component was: "+a(e));for(var i=e;i;i=i.__)if(i.__c&&i.__c.__c){n=r;break}if(n instanceof Error)throw n}try{(t=t||{}).componentStack=f(e),v(n,e,o,t),"function"!=typeof n.then&&setTimeout(function(){throw n})}catch(n){throw n}},e.__=function(n,e){if(!e)throw new Error("Undefined parent passed to render(), this is the second argument.\nCheck if the element is available in the DOM/has the correct id.");var o;switch(e.nodeType){case 1:case 11:case 9:o=!0;break;default:o=!1}if(!o){var t=a(n);throw new Error("Expected a valid HTML node as a second argument to render.\tReceived "+e+" instead: render(<"+t+" />, "+e+");")}b&&b(n,e)},e.__b=function(e){var r=e.type;if(n=!0,void 0===r)throw new Error("Undefined component passed to createElement()\n\nYou likely forgot to export your component or might have mixed up default and named imports"+w(e)+"\n\n"+f(e));if(null!=r&&"object"==typeof r){if(void 0!==r.__k&&void 0!==r.__e)throw new Error("Invalid type passed to createElement(): "+r+"\n\nDid you accidentally pass a JSX literal as JSX twice?\n\n let My"+a(e)+" = "+w(r)+";\n let vnode = ;\n\nThis usually happens when you export a JSX literal and not the component.\n\n"+f(e));throw new Error("Invalid type passed to createElement(): "+(Array.isArray(r)?"array":r))}if(void 0!==e.ref&&"function"!=typeof e.ref&&"object"!=typeof e.ref&&!("$$typeof"in e))throw new Error('Component\'s "ref" property should be a function, or an object created by createRef(), but got ['+typeof e.ref+"] instead\n"+w(e)+"\n\n"+f(e));if("string"==typeof e.type)for(var i in e.props)if("o"===i[0]&&"n"===i[1]&&"function"!=typeof e.props[i]&&null!=e.props[i])throw new Error("Component's \""+i+'" property should be a function, but got ['+typeof e.props[i]+"] instead\n"+w(e)+"\n\n"+f(e));if("function"==typeof e.type&&e.type.propTypes){if("Lazy"===e.type.displayName&&E&&!E.lazyPropTypes.has(e.type)){var s="PropTypes are not supported on lazy(). Use propTypes on the wrapped component itself. ";try{var c=e.type();E.lazyPropTypes.set(e.type,!0),console.warn(s+"Component wrapped in lazy() is "+a(c))}catch(n){console.warn(s+"We will log the wrapped component's name once it is loaded.")}}var l=e.props;e.type.__f&&delete(l=function(n,e){for(var o in e)n[o]=e[o];return n}({},l)).ref,function(n,e,o,r,a){Object.keys(n).forEach(function(o){var i;try{i=n[o](e,o,r,"prop",null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(n){i=n}i&&!(i.message in t)&&(t[i.message]=!0,console.error("Failed prop type: "+i.message+(a&&"\n"+a()||"")))})}(e.type.propTypes,l,0,a(e),function(){return f(e)})}o&&o(e)};var T,_=0;e.__r=function(e){l&&l(e),n=!0;var o=e.__c;if(o===T?_++:_=1,_>=25)throw new Error("Too many re-renders. This is limited to prevent an infinite loop which may lock up your browser. The component causing this is: "+a(e));T=o},e.__h=function(e,o,t){if(!e||!n)throw new Error("Hook can only be invoked from render methods.");g&&g(e,o,t)};var O=function(n,e){return{get:function(){var o="get"+n+e;k&&k.indexOf(o)<0&&(k.push(o),console.warn("getting vnode."+n+" is deprecated, "+e))},set:function(){var o="set"+n+e;k&&k.indexOf(o)<0&&(k.push(o),console.warn("setting vnode."+n+" is not allowed, "+e))}}},I={nodeName:O("nodeName","use vnode.type"),attributes:O("attributes","use vnode.props"),children:O("children","use vnode.props.children")},M=Object.create({},I);e.vnode=function(n){var e=n.props;if(null!==n.type&&null!=e&&("__source"in e||"__self"in e)){var o=n.props={};for(var t in e){var r=e[t];"__source"===t?n.__source=r:"__self"===t?n.__self=r:o[t]=r}}n.__proto__=M,c&&c(n)},e.diffed=function(e){var o,t=e.type,i=e.__;if(e.__k&&e.__k.forEach(function(n){if("object"==typeof n&&n&&void 0===n.type){var o=Object.keys(n).join(",");throw new Error("Objects are not valid as a child. Encountered an object with the keys {"+o+"}.\n\n"+f(e))}}),e.__c===T&&(_=0),"string"==typeof t&&(y(t)||"p"===t||"a"===t||"button"===t)){var s=h(i);if(""!==s&&y(t))"table"===t&&"td"!==s&&y(s)?console.error("Improper nesting of table. Your

    should have a
    should have a
    should not have a table-node parent."+w(e)+"\n\n"+f(e)):"thead"!==t&&"tfoot"!==t&&"tbody"!==t||"table"===s?"tr"===t&&"thead"!==s&&"tfoot"!==s&&"tbody"!==s?console.error("Improper nesting of table. Your should have a parent."+w(e)+"\n\n"+f(e)):"td"===t&&"tr"!==s?console.error("Improper nesting of table. Your parent."+w(e)+"\n\n"+f(e)):"th"===t&&"tr"!==s&&console.error("Improper nesting of table. Your ."+w(e)+"\n\n"+f(e)):console.error("Improper nesting of table. Your should have a
    should have a
    should have a
    parent."+w(e)+"\n\n"+f(e));else if("p"===t){var c=p(e).filter(function(n){return m.test(n)});c.length&&console.error("Improper nesting of paragraph. Your

    should not have "+c.join(", ")+" as child-elements."+w(e)+"\n\n"+f(e))}else"a"!==t&&"button"!==t||-1!==p(e).indexOf(t)&&console.error("Improper nesting of interactive content. Your <"+t+"> should not have other "+("a"===t?"anchor":"button")+" tags as child-elements."+w(e)+"\n\n"+f(e))}if(n=!1,r&&r(e),null!=e.__k)for(var l=[],u=0;u0?i[i.length-1]:null}var l=!0;function u(e){return"function"==typeof e.type&&e.type!=n}function f(n){for(var e=[n],o=n;null!=o.__o;)e.push(o.__o),o=o.__o;return e.reduce(function(n,e){n+=" in "+a(e);var o=e.__source;return o?n+=" (at "+o.fileName+":"+o.lineNumber+")":l&&console.warn("Add @babel/plugin-transform-react-jsx-source to get a more detailed component stack. Note that you should not add it to production builds of your App for bundle size reasons."),l=!1,n+"\n"},"")}var d="function"==typeof WeakMap;function p(n){var e=[];return n.__k?(n.__k.forEach(function(n){n&&"function"==typeof n.type?e.push.apply(e,p(n)):n&&"string"==typeof n.type&&e.push(n.type)}),e):e}function h(n){return n?"function"==typeof n.type?null==n.__?null!=n.__e&&null!=n.__e.parentNode?n.__e.parentNode.localName:"":h(n.__):n.type:""}var v=o.prototype.setState;function y(n){return"table"===n||"tfoot"===n||"tbody"===n||"thead"===n||"td"===n||"tr"===n||"th"===n}o.prototype.setState=function(n,e){return null==this.__v&&null==this.state&&console.warn('Calling "this.setState" inside the constructor of a component is a no-op and might be a bug in your application. Instead, set "this.state = {}" directly.\n\n'+f(c())),v.call(this,n,e)};var m=/^(address|article|aside|blockquote|details|div|dl|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hgroup|hr|main|menu|nav|ol|p|pre|search|section|table|ul)$/,b=o.prototype.forceUpdate;function w(n){var e=n.props,o=a(n),t="";for(var r in e)if(e.hasOwnProperty(r)&&"children"!==r){var i=e[r];"function"==typeof i&&(i="function "+(i.displayName||i.name)+"() {}"),i=Object(i)!==i||i.toString?i+"":Object.prototype.toString.call(i),t+=" "+r+"="+JSON.stringify(i)}var s=e.children;return"<"+o+t+(s&&s.length?">..":" />")}o.prototype.forceUpdate=function(n){return null==this.__v?console.warn('Calling "this.forceUpdate" inside the constructor of a component is a no-op and might be a bug in your application.\n\n'+f(c())):null==this.__P&&console.warn('Can\'t call "this.forceUpdate" on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.\n\n'+f(this.__v)),b.call(this,n)},e.__m=function(n,e){var o=n.type,t=e.map(function(n){return n&&n.localName}).filter(Boolean);console.error('Expected a DOM node of type "'+o+'" but found "'+t.join(", ")+"\" as available DOM-node(s), this is caused by the SSR'd HTML containing different DOM-nodes compared to the hydrated one.\n\n"+f(n))},function(){!function(){var n=e.__b,o=e.diffed,t=e.__,r=e.vnode,a=e.__r;e.diffed=function(n){u(n)&&s.pop(),i.pop(),o&&o(n)},e.__b=function(e){u(e)&&i.push(e),n&&n(e)},e.__=function(n,e){s=[],t&&t(n,e)},e.vnode=function(n){n.__o=s.length>0?s[s.length-1]:null,r&&r(n)},e.__r=function(n){u(n)&&s.push(n),a&&a(n)}}();var n=!1,o=e.__b,r=e.diffed,c=e.vnode,l=e.__r,v=e.__e,b=e.__,g=e.__h,E=d?{useEffect:new WeakMap,useLayoutEffect:new WeakMap,lazyPropTypes:new WeakMap}:null,k=[];e.__e=function(n,e,o,t){if(e&&e.__c&&"function"==typeof n.then){var r=n;n=new Error("Missing Suspense. The throwing component was: "+a(e));for(var i=e;i;i=i.__)if(i.__c&&i.__c.__c){n=r;break}if(n instanceof Error)throw n}try{(t=t||{}).componentStack=f(e),v(n,e,o,t),"function"!=typeof n.then&&setTimeout(function(){throw n})}catch(n){throw n}},e.__=function(n,e){if(!e)throw new Error("Undefined parent passed to render(), this is the second argument.\nCheck if the element is available in the DOM/has the correct id.");var o;switch(e.nodeType){case 1:case 11:case 9:o=!0;break;default:o=!1}if(!o){var t=a(n);throw new Error("Expected a valid HTML node as a second argument to render.\tReceived "+e+" instead: render(<"+t+" />, "+e+");")}b&&b(n,e)},e.__b=function(e){var r=e.type;if(n=!0,void 0===r)throw new Error("Undefined component passed to createElement()\n\nYou likely forgot to export your component or might have mixed up default and named imports"+w(e)+"\n\n"+f(e));if(null!=r&&"object"==typeof r){if(void 0!==r.__k&&void 0!==r.__e)throw new Error("Invalid type passed to createElement(): "+r+"\n\nDid you accidentally pass a JSX literal as JSX twice?\n\n let My"+a(e)+" = "+w(r)+";\n let vnode = ;\n\nThis usually happens when you export a JSX literal and not the component.\n\n"+f(e));throw new Error("Invalid type passed to createElement(): "+(Array.isArray(r)?"array":r))}if(void 0!==e.ref&&"function"!=typeof e.ref&&"object"!=typeof e.ref&&!("$$typeof"in e))throw new Error('Component\'s "ref" property should be a function, or an object created by createRef(), but got ['+typeof e.ref+"] instead\n"+w(e)+"\n\n"+f(e));if("string"==typeof e.type)for(var i in e.props)if("o"===i[0]&&"n"===i[1]&&"function"!=typeof e.props[i]&&null!=e.props[i])throw new Error("Component's \""+i+'" property should be a function, but got ['+typeof e.props[i]+"] instead\n"+w(e)+"\n\n"+f(e));if("function"==typeof e.type&&e.type.propTypes){if("Lazy"===e.type.displayName&&E&&!E.lazyPropTypes.has(e.type)){var s="PropTypes are not supported on lazy(). Use propTypes on the wrapped component itself. ";try{var c=e.type();E.lazyPropTypes.set(e.type,!0),console.warn(s+"Component wrapped in lazy() is "+a(c))}catch(n){console.warn(s+"We will log the wrapped component's name once it is loaded.")}}var l=e.props;e.type.__f&&delete(l=function(n,e){for(var o in e)n[o]=e[o];return n}({},l)).ref,function(n,e,o,r,a){Object.keys(n).forEach(function(o){var i;try{i=n[o](e,o,r,"prop",null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(n){i=n}i&&!(i.message in t)&&(t[i.message]=!0,console.error("Failed prop type: "+i.message+(a&&"\n"+a()||"")))})}(e.type.propTypes,l,0,a(e),function(){return f(e)})}o&&o(e)};var T,_=0;e.__r=function(e){l&&l(e),n=!0;var o=e.__c;if(o===T?_++:_=1,_>=25)throw new Error("Too many re-renders. This is limited to prevent an infinite loop which may lock up your browser. The component causing this is: "+a(e));T=o},e.__h=function(e,o,t){if(!e||!n)throw new Error("Hook can only be invoked from render methods.");g&&g(e,o,t)};var O=function(n,e){return{get:function(){var o="get"+n+e;k&&k.indexOf(o)<0&&(k.push(o),console.warn("getting vnode."+n+" is deprecated, "+e))},set:function(){var o="set"+n+e;k&&k.indexOf(o)<0&&(k.push(o),console.warn("setting vnode."+n+" is not allowed, "+e))}}},I={nodeName:O("nodeName","use vnode.type"),attributes:O("attributes","use vnode.props"),children:O("children","use vnode.props.children")},M=Object.create({},I);e.vnode=function(n){var e=n.props;if(null!==n.type&&null!=e&&("__source"in e||"__self"in e)){var o=n.props={};for(var t in e){var r=e[t];"__source"===t?n.__source=r:"__self"===t?n.__self=r:o[t]=r}}n.__proto__=M,c&&c(n)},e.diffed=function(e){var o,t=e.type,i=e.__;if(e.__k&&e.__k.forEach(function(n){if("object"==typeof n&&n&&void 0===n.type){var o=Object.keys(n).join(",");throw new Error("Objects are not valid as a child. Encountered an object with the keys {"+o+"}.\n\n"+f(e))}}),e.__c===T&&(_=0),"string"==typeof t&&(y(t)||"p"===t||"a"===t||"button"===t)){var s=h(i);if(""!==s&&y(t))"table"===t&&"td"!==s&&y(s)?console.error("Improper nesting of table. Your

    should not have a table-node parent."+w(e)+"\n\n"+f(e)):"thead"!==t&&"tfoot"!==t&&"tbody"!==t||"table"===s?"tr"===t&&"thead"!==s&&"tfoot"!==s&&"tbody"!==s?console.error("Improper nesting of table. Your should have a parent."+w(e)+"\n\n"+f(e)):"td"===t&&"tr"!==s?console.error("Improper nesting of table. Your parent."+w(e)+"\n\n"+f(e)):"th"===t&&"tr"!==s&&console.error("Improper nesting of table. Your ."+w(e)+"\n\n"+f(e)):console.error("Improper nesting of table. Your should have a
    should have a
    should have a
    parent."+w(e)+"\n\n"+f(e));else if("p"===t){var c=p(e).filter(function(n){return m.test(n)});c.length&&console.error("Improper nesting of paragraph. Your

    should not have "+c.join(", ")+" as child-elements."+w(e)+"\n\n"+f(e))}else"a"!==t&&"button"!==t||-1!==p(e).indexOf(t)&&console.error("Improper nesting of interactive content. Your <"+t+"> should not have other "+("a"===t?"anchor":"button")+" tags as child-elements."+w(e)+"\n\n"+f(e))}if(n=!1,r&&r(e),null!=e.__k)for(var l=[],u=0;u {\n\t\tlet error;\n\t\ttry {\n\t\t\terror = typeSpecs[typeSpecName](\n\t\t\t\tvalues,\n\t\t\t\ttypeSpecName,\n\t\t\t\tcomponentName,\n\t\t\t\tlocation,\n\t\t\t\tnull,\n\t\t\t\tReactPropTypesSecret\n\t\t\t);\n\t\t} catch (e) {\n\t\t\terror = e;\n\t\t}\n\t\tif (error && !(error.message in loggedTypeFailures)) {\n\t\t\tloggedTypeFailures[error.message] = true;\n\t\t\tconsole.error(\n\t\t\t\t`Failed ${location} type: ${error.message}${\n\t\t\t\t\t(getStack && `\\n${getStack()}`) || ''\n\t\t\t\t}`\n\t\t\t);\n\t\t}\n\t});\n}\n","import { options, Fragment } from 'preact';\n\n/**\n * Get human readable name of the component/dom node\n * @param {import('./internal').VNode} vnode\n * @param {import('./internal').VNode} vnode\n * @returns {string}\n */\nexport function getDisplayName(vnode) {\n\tif (vnode.type === Fragment) {\n\t\treturn 'Fragment';\n\t} else if (typeof vnode.type == 'function') {\n\t\treturn vnode.type.displayName || vnode.type.name;\n\t} else if (typeof vnode.type == 'string') {\n\t\treturn vnode.type;\n\t}\n\n\treturn '#text';\n}\n\n/**\n * Used to keep track of the currently rendered `vnode` and print it\n * in debug messages.\n */\nlet renderStack = [];\n\n/**\n * Keep track of the current owners. An owner describes a component\n * which was responsible to render a specific `vnode`. This exclude\n * children that are passed via `props.children`, because they belong\n * to the parent owner.\n *\n * ```jsx\n * const Foo = props =>

    {props.children}
    // div's owner is Foo\n * const Bar = props => {\n * return (\n * // Foo's owner is Bar, span's owner is Bar\n * )\n * }\n * ```\n *\n * Note: A `vnode` may be hoisted to the root scope due to compiler\n * optimiztions. In these cases the `_owner` will be different.\n */\nlet ownerStack = [];\n\n/**\n * Get the currently rendered `vnode`\n * @returns {import('./internal').VNode | null}\n */\nexport function getCurrentVNode() {\n\treturn renderStack.length > 0 ? renderStack[renderStack.length - 1] : null;\n}\n\n/**\n * If the user doesn't have `@babel/plugin-transform-react-jsx-source`\n * somewhere in his tool chain we can't print the filename and source\n * location of a component. In that case we just omit that, but we'll\n * print a helpful message to the console, notifying the user of it.\n */\nlet showJsxSourcePluginWarning = true;\n\n/**\n * Check if a `vnode` is a possible owner.\n * @param {import('./internal').VNode} vnode\n */\nfunction isPossibleOwner(vnode) {\n\treturn typeof vnode.type == 'function' && vnode.type != Fragment;\n}\n\n/**\n * Return the component stack that was captured up to this point.\n * @param {import('./internal').VNode} vnode\n * @returns {string}\n */\nexport function getOwnerStack(vnode) {\n\tconst stack = [vnode];\n\tlet next = vnode;\n\twhile (next._owner != null) {\n\t\tstack.push(next._owner);\n\t\tnext = next._owner;\n\t}\n\n\treturn stack.reduce((acc, owner) => {\n\t\tacc += ` in ${getDisplayName(owner)}`;\n\n\t\tconst source = owner.__source;\n\t\tif (source) {\n\t\t\tacc += ` (at ${source.fileName}:${source.lineNumber})`;\n\t\t} else if (showJsxSourcePluginWarning) {\n\t\t\tconsole.warn(\n\t\t\t\t'Add @babel/plugin-transform-react-jsx-source to get a more detailed component stack. Note that you should not add it to production builds of your App for bundle size reasons.'\n\t\t\t);\n\t\t}\n\t\tshowJsxSourcePluginWarning = false;\n\n\t\treturn (acc += '\\n');\n\t}, '');\n}\n\n/**\n * Setup code to capture the component trace while rendering. Note that\n * we cannot simply traverse `vnode._parent` upwards, because we have some\n * debug messages for `this.setState` where the `vnode` is `undefined`.\n */\nexport function setupComponentStack() {\n\tlet oldDiff = options._diff;\n\tlet oldDiffed = options.diffed;\n\tlet oldRoot = options._root;\n\tlet oldVNode = options.vnode;\n\tlet oldRender = options._render;\n\n\toptions.diffed = vnode => {\n\t\tif (isPossibleOwner(vnode)) {\n\t\t\townerStack.pop();\n\t\t}\n\t\trenderStack.pop();\n\t\tif (oldDiffed) oldDiffed(vnode);\n\t};\n\n\toptions._diff = vnode => {\n\t\tif (isPossibleOwner(vnode)) {\n\t\t\trenderStack.push(vnode);\n\t\t}\n\t\tif (oldDiff) oldDiff(vnode);\n\t};\n\n\toptions._root = (vnode, parent) => {\n\t\townerStack = [];\n\t\tif (oldRoot) oldRoot(vnode, parent);\n\t};\n\n\toptions.vnode = vnode => {\n\t\tvnode._owner =\n\t\t\townerStack.length > 0 ? ownerStack[ownerStack.length - 1] : null;\n\t\tif (oldVNode) oldVNode(vnode);\n\t};\n\n\toptions._render = vnode => {\n\t\tif (isPossibleOwner(vnode)) {\n\t\t\townerStack.push(vnode);\n\t\t}\n\n\t\tif (oldRender) oldRender(vnode);\n\t};\n}\n","import { checkPropTypes } from './check-props';\nimport { options, Component } from 'preact';\nimport {\n\tELEMENT_NODE,\n\tDOCUMENT_NODE,\n\tDOCUMENT_FRAGMENT_NODE\n} from './constants';\nimport {\n\tgetOwnerStack,\n\tsetupComponentStack,\n\tgetCurrentVNode,\n\tgetDisplayName\n} from './component-stack';\nimport { assign, isNaN } from './util';\n\nconst isWeakMapSupported = typeof WeakMap == 'function';\n\n/**\n * @param {import('./internal').VNode} vnode\n * @returns {Array}\n */\nfunction getDomChildren(vnode) {\n\tlet domChildren = [];\n\n\tif (!vnode._children) return domChildren;\n\n\tvnode._children.forEach(child => {\n\t\tif (child && typeof child.type === 'function') {\n\t\t\tdomChildren.push.apply(domChildren, getDomChildren(child));\n\t\t} else if (child && typeof child.type === 'string') {\n\t\t\tdomChildren.push(child.type);\n\t\t}\n\t});\n\n\treturn domChildren;\n}\n\n/**\n * @param {import('./internal').VNode} parent\n * @returns {string}\n */\nfunction getClosestDomNodeParentName(parent) {\n\tif (!parent) return '';\n\tif (typeof parent.type == 'function') {\n\t\tif (parent._parent == null) {\n\t\t\tif (parent._dom != null && parent._dom.parentNode != null) {\n\t\t\t\treturn parent._dom.parentNode.localName;\n\t\t\t}\n\t\t\treturn '';\n\t\t}\n\t\treturn getClosestDomNodeParentName(parent._parent);\n\t}\n\treturn /** @type {string} */ (parent.type);\n}\n\nexport function initDebug() {\n\tsetupComponentStack();\n\n\tlet hooksAllowed = false;\n\n\t/* eslint-disable no-console */\n\tlet oldBeforeDiff = options._diff;\n\tlet oldDiffed = options.diffed;\n\tlet oldVnode = options.vnode;\n\tlet oldRender = options._render;\n\tlet oldCatchError = options._catchError;\n\tlet oldRoot = options._root;\n\tlet oldHook = options._hook;\n\tconst warnedComponents = !isWeakMapSupported\n\t\t? null\n\t\t: {\n\t\t\t\tuseEffect: new WeakMap(),\n\t\t\t\tuseLayoutEffect: new WeakMap(),\n\t\t\t\tlazyPropTypes: new WeakMap()\n\t\t\t};\n\tconst deprecations = [];\n\n\toptions._catchError = (error, vnode, oldVNode, errorInfo) => {\n\t\tlet component = vnode && vnode._component;\n\t\tif (component && typeof error.then == 'function') {\n\t\t\tconst promise = error;\n\t\t\terror = new Error(\n\t\t\t\t`Missing Suspense. The throwing component was: ${getDisplayName(vnode)}`\n\t\t\t);\n\n\t\t\tlet parent = vnode;\n\t\t\tfor (; parent; parent = parent._parent) {\n\t\t\t\tif (parent._component && parent._component._childDidSuspend) {\n\t\t\t\t\terror = promise;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// We haven't recovered and we know at this point that there is no\n\t\t\t// Suspense component higher up in the tree\n\t\t\tif (error instanceof Error) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\terrorInfo = errorInfo || {};\n\t\t\terrorInfo.componentStack = getOwnerStack(vnode);\n\t\t\toldCatchError(error, vnode, oldVNode, errorInfo);\n\n\t\t\t// when an error was handled by an ErrorBoundary we will nonetheless emit an error\n\t\t\t// event on the window object. This is to make up for react compatibility in dev mode\n\t\t\t// and thus make the Next.js dev overlay work.\n\t\t\tif (typeof error.then != 'function') {\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthrow error;\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tthrow e;\n\t\t}\n\t};\n\n\toptions._root = (vnode, parentNode) => {\n\t\tif (!parentNode) {\n\t\t\tthrow new Error(\n\t\t\t\t'Undefined parent passed to render(), this is the second argument.\\n' +\n\t\t\t\t\t'Check if the element is available in the DOM/has the correct id.'\n\t\t\t);\n\t\t}\n\n\t\tlet isValid;\n\t\tswitch (parentNode.nodeType) {\n\t\t\tcase ELEMENT_NODE:\n\t\t\tcase DOCUMENT_FRAGMENT_NODE:\n\t\t\tcase DOCUMENT_NODE:\n\t\t\t\tisValid = true;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tisValid = false;\n\t\t}\n\n\t\tif (!isValid) {\n\t\t\tlet componentName = getDisplayName(vnode);\n\t\t\tthrow new Error(\n\t\t\t\t`Expected a valid HTML node as a second argument to render.\tReceived ${parentNode} instead: render(<${componentName} />, ${parentNode});`\n\t\t\t);\n\t\t}\n\n\t\tif (oldRoot) oldRoot(vnode, parentNode);\n\t};\n\n\toptions._diff = vnode => {\n\t\tlet { type } = vnode;\n\n\t\thooksAllowed = true;\n\n\t\tif (type === undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t'Undefined component passed to createElement()\\n\\n' +\n\t\t\t\t\t'You likely forgot to export your component or might have mixed up default and named imports' +\n\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t);\n\t\t} else if (type != null && typeof type == 'object') {\n\t\t\tif (type._children !== undefined && type._dom !== undefined) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Invalid type passed to createElement(): ${type}\\n\\n` +\n\t\t\t\t\t\t'Did you accidentally pass a JSX literal as JSX twice?\\n\\n' +\n\t\t\t\t\t\t` let My${getDisplayName(vnode)} = ${serializeVNode(type)};\\n` +\n\t\t\t\t\t\t` let vnode = ;\\n\\n` +\n\t\t\t\t\t\t'This usually happens when you export a JSX literal and not the component.' +\n\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tthrow new Error(\n\t\t\t\t'Invalid type passed to createElement(): ' +\n\t\t\t\t\t(Array.isArray(type) ? 'array' : type)\n\t\t\t);\n\t\t}\n\n\t\tif (\n\t\t\tvnode.ref !== undefined &&\n\t\t\ttypeof vnode.ref != 'function' &&\n\t\t\ttypeof vnode.ref != 'object' &&\n\t\t\t!('$$typeof' in vnode) // allow string refs when preact-compat is installed\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`Component's \"ref\" property should be a function, or an object created ` +\n\t\t\t\t\t`by createRef(), but got [${typeof vnode.ref}] instead\\n` +\n\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t);\n\t\t}\n\n\t\tif (typeof vnode.type == 'string') {\n\t\t\tfor (const key in vnode.props) {\n\t\t\t\tif (\n\t\t\t\t\tkey[0] === 'o' &&\n\t\t\t\t\tkey[1] === 'n' &&\n\t\t\t\t\ttypeof vnode.props[key] != 'function' &&\n\t\t\t\t\tvnode.props[key] != null\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Component's \"${key}\" property should be a function, ` +\n\t\t\t\t\t\t\t`but got [${typeof vnode.props[key]}] instead\\n` +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check prop-types if available\n\t\tif (typeof vnode.type == 'function' && vnode.type.propTypes) {\n\t\t\tif (\n\t\t\t\tvnode.type.displayName === 'Lazy' &&\n\t\t\t\twarnedComponents &&\n\t\t\t\t!warnedComponents.lazyPropTypes.has(vnode.type)\n\t\t\t) {\n\t\t\t\tconst m =\n\t\t\t\t\t'PropTypes are not supported on lazy(). Use propTypes on the wrapped component itself. ';\n\t\t\t\ttry {\n\t\t\t\t\tconst lazyVNode = vnode.type();\n\t\t\t\t\twarnedComponents.lazyPropTypes.set(vnode.type, true);\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\tm + `Component wrapped in lazy() is ${getDisplayName(lazyVNode)}`\n\t\t\t\t\t);\n\t\t\t\t} catch (promise) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\tm + \"We will log the wrapped component's name once it is loaded.\"\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet values = vnode.props;\n\t\t\tif (vnode.type._forwarded) {\n\t\t\t\tvalues = assign({}, values);\n\t\t\t\tdelete values.ref;\n\t\t\t}\n\n\t\t\tcheckPropTypes(\n\t\t\t\tvnode.type.propTypes,\n\t\t\t\tvalues,\n\t\t\t\t'prop',\n\t\t\t\tgetDisplayName(vnode),\n\t\t\t\t() => getOwnerStack(vnode)\n\t\t\t);\n\t\t}\n\n\t\tif (oldBeforeDiff) oldBeforeDiff(vnode);\n\t};\n\n\tlet renderCount = 0;\n\tlet currentComponent;\n\toptions._render = vnode => {\n\t\tif (oldRender) {\n\t\t\toldRender(vnode);\n\t\t}\n\t\thooksAllowed = true;\n\n\t\tconst nextComponent = vnode._component;\n\t\tif (nextComponent === currentComponent) {\n\t\t\trenderCount++;\n\t\t} else {\n\t\t\trenderCount = 1;\n\t\t}\n\n\t\tif (renderCount >= 25) {\n\t\t\tthrow new Error(\n\t\t\t\t`Too many re-renders. This is limited to prevent an infinite loop ` +\n\t\t\t\t\t`which may lock up your browser. The component causing this is: ${getDisplayName(\n\t\t\t\t\t\tvnode\n\t\t\t\t\t)}`\n\t\t\t);\n\t\t}\n\n\t\tcurrentComponent = nextComponent;\n\t};\n\n\toptions._hook = (comp, index, type) => {\n\t\tif (!comp || !hooksAllowed) {\n\t\t\tthrow new Error('Hook can only be invoked from render methods.');\n\t\t}\n\n\t\tif (oldHook) oldHook(comp, index, type);\n\t};\n\n\t// Ideally we'd want to print a warning once per component, but we\n\t// don't have access to the vnode that triggered it here. As a\n\t// compromise and to avoid flooding the console with warnings we\n\t// print each deprecation warning only once.\n\tconst warn = (property, message) => ({\n\t\tget() {\n\t\t\tconst key = 'get' + property + message;\n\t\t\tif (deprecations && deprecations.indexOf(key) < 0) {\n\t\t\t\tdeprecations.push(key);\n\t\t\t\tconsole.warn(`getting vnode.${property} is deprecated, ${message}`);\n\t\t\t}\n\t\t},\n\t\tset() {\n\t\t\tconst key = 'set' + property + message;\n\t\t\tif (deprecations && deprecations.indexOf(key) < 0) {\n\t\t\t\tdeprecations.push(key);\n\t\t\t\tconsole.warn(`setting vnode.${property} is not allowed, ${message}`);\n\t\t\t}\n\t\t}\n\t});\n\n\tconst deprecatedAttributes = {\n\t\tnodeName: warn('nodeName', 'use vnode.type'),\n\t\tattributes: warn('attributes', 'use vnode.props'),\n\t\tchildren: warn('children', 'use vnode.props.children')\n\t};\n\n\tconst deprecatedProto = Object.create({}, deprecatedAttributes);\n\n\toptions.vnode = vnode => {\n\t\tconst props = vnode.props;\n\t\tif (\n\t\t\tvnode.type !== null &&\n\t\t\tprops != null &&\n\t\t\t('__source' in props || '__self' in props)\n\t\t) {\n\t\t\tconst newProps = (vnode.props = {});\n\t\t\tfor (let i in props) {\n\t\t\t\tconst v = props[i];\n\t\t\t\tif (i === '__source') vnode.__source = v;\n\t\t\t\telse if (i === '__self') vnode.__self = v;\n\t\t\t\telse newProps[i] = v;\n\t\t\t}\n\t\t}\n\n\t\t// eslint-disable-next-line\n\t\tvnode.__proto__ = deprecatedProto;\n\t\tif (oldVnode) oldVnode(vnode);\n\t};\n\n\toptions.diffed = vnode => {\n\t\tconst { type, _parent: parent } = vnode;\n\t\t// Check if the user passed plain objects as children. Note that we cannot\n\t\t// move this check into `options.vnode` because components can receive\n\t\t// children in any shape they want (e.g.\n\t\t// `{{ foo: 123, bar: \"abc\" }}`).\n\t\t// Putting this check in `options.diffed` ensures that\n\t\t// `vnode._children` is set and that we only validate the children\n\t\t// that were actually rendered.\n\t\tif (vnode._children) {\n\t\t\tvnode._children.forEach(child => {\n\t\t\t\tif (typeof child === 'object' && child && child.type === undefined) {\n\t\t\t\t\tconst keys = Object.keys(child).join(',');\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Objects are not valid as a child. Encountered an object with the keys {${keys}}.` +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tif (vnode._component === currentComponent) {\n\t\t\trenderCount = 0;\n\t\t}\n\n\t\tif (\n\t\t\ttypeof type === 'string' &&\n\t\t\t(isTableElement(type) ||\n\t\t\t\ttype === 'p' ||\n\t\t\t\ttype === 'a' ||\n\t\t\t\ttype === 'button')\n\t\t) {\n\t\t\t// Avoid false positives when Preact only partially rendered the\n\t\t\t// HTML tree. Whilst we attempt to include the outer DOM in our\n\t\t\t// validation, this wouldn't work on the server for\n\t\t\t// `preact-render-to-string`. There we'd otherwise flood the terminal\n\t\t\t// with false positives, which we'd like to avoid.\n\t\t\tlet domParentName = getClosestDomNodeParentName(parent);\n\t\t\tif (domParentName !== '' && isTableElement(type)) {\n\t\t\t\tif (\n\t\t\t\t\ttype === 'table' &&\n\t\t\t\t\t// Tables can be nested inside each other if it's inside a cell.\n\t\t\t\t\t// See https://developer.mozilla.org/en-US/docs/Learn/HTML/Tables/Advanced#nesting_tables\n\t\t\t\t\tdomParentName !== 'td' &&\n\t\t\t\t\tisTableElement(domParentName)\n\t\t\t\t) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t'Improper nesting of table. Your
    should not have a table-node parent.' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t} else if (\n\t\t\t\t\t(type === 'thead' || type === 'tfoot' || type === 'tbody') &&\n\t\t\t\t\tdomParentName !== 'table'\n\t\t\t\t) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t'Improper nesting of table. Your should have a
    parent.' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t} else if (\n\t\t\t\t\ttype === 'tr' &&\n\t\t\t\t\tdomParentName !== 'thead' &&\n\t\t\t\t\tdomParentName !== 'tfoot' &&\n\t\t\t\t\tdomParentName !== 'tbody'\n\t\t\t\t) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t'Improper nesting of table. Your should have a parent.' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t} else if (type === 'td' && domParentName !== 'tr') {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t'Improper nesting of table. Your parent.' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t} else if (type === 'th' && domParentName !== 'tr') {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t'Improper nesting of table. Your .' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} else if (type === 'p') {\n\t\t\t\tlet illegalDomChildrenTypes = getDomChildren(vnode).filter(childType =>\n\t\t\t\t\tILLEGAL_PARAGRAPH_CHILD_ELEMENTS.test(childType)\n\t\t\t\t);\n\t\t\t\tif (illegalDomChildrenTypes.length) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t'Improper nesting of paragraph. Your

    should not have ' +\n\t\t\t\t\t\t\tillegalDomChildrenTypes.join(', ') +\n\t\t\t\t\t\t\t' as child-elements.' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} else if (type === 'a' || type === 'button') {\n\t\t\t\tif (getDomChildren(vnode).indexOf(type) !== -1) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t`Improper nesting of interactive content. Your <${type}>` +\n\t\t\t\t\t\t\t` should not have other ${type === 'a' ? 'anchor' : 'button'}` +\n\t\t\t\t\t\t\t' tags as child-elements.' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\thooksAllowed = false;\n\n\t\tif (oldDiffed) oldDiffed(vnode);\n\n\t\tif (vnode._children != null) {\n\t\t\tconst keys = [];\n\t\t\tfor (let i = 0; i < vnode._children.length; i++) {\n\t\t\t\tconst child = vnode._children[i];\n\t\t\t\tif (!child || child.key == null) continue;\n\n\t\t\t\tconst key = child.key;\n\t\t\t\tif (keys.indexOf(key) !== -1) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t'Following component has two or more children with the ' +\n\t\t\t\t\t\t\t`same key attribute: \"${key}\". This may cause glitches and misbehavior ` +\n\t\t\t\t\t\t\t'in rendering process. Component: \\n\\n' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\n\t\t\t\t\t// Break early to not spam the console\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tkeys.push(key);\n\t\t\t}\n\t\t}\n\n\t\tif (vnode._component != null && vnode._component.__hooks != null) {\n\t\t\t// Validate that none of the hooks in this component contain arguments that are NaN.\n\t\t\t// This is a common mistake that can be hard to debug, so we want to catch it early.\n\t\t\tconst hooks = vnode._component.__hooks._list;\n\t\t\tif (hooks) {\n\t\t\t\tfor (let i = 0; i < hooks.length; i += 1) {\n\t\t\t\t\tconst hook = hooks[i];\n\t\t\t\t\tif (hook._args) {\n\t\t\t\t\t\tfor (let j = 0; j < hook._args.length; j++) {\n\t\t\t\t\t\t\tconst arg = hook._args[j];\n\t\t\t\t\t\t\tif (isNaN(arg)) {\n\t\t\t\t\t\t\t\tconst componentName = getDisplayName(vnode);\n\t\t\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t\t\t`Invalid argument passed to hook. Hooks should not be called with NaN in the dependency array. Hook index ${i} in component ${componentName} was called with NaN.`\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n}\n\nconst setState = Component.prototype.setState;\nComponent.prototype.setState = function (update, callback) {\n\tif (this._vnode == null) {\n\t\t// `this._vnode` will be `null` during componentWillMount. But it\n\t\t// is perfectly valid to call `setState` during cWM. So we\n\t\t// need an additional check to verify that we are dealing with a\n\t\t// call inside constructor.\n\t\tif (this.state == null) {\n\t\t\tconsole.warn(\n\t\t\t\t`Calling \"this.setState\" inside the constructor of a component is a ` +\n\t\t\t\t\t`no-op and might be a bug in your application. Instead, set ` +\n\t\t\t\t\t`\"this.state = {}\" directly.\\n\\n${getOwnerStack(getCurrentVNode())}`\n\t\t\t);\n\t\t}\n\t}\n\n\treturn setState.call(this, update, callback);\n};\n\nfunction isTableElement(type) {\n\treturn (\n\t\ttype === 'table' ||\n\t\ttype === 'tfoot' ||\n\t\ttype === 'tbody' ||\n\t\ttype === 'thead' ||\n\t\ttype === 'td' ||\n\t\ttype === 'tr' ||\n\t\ttype === 'th'\n\t);\n}\n\nconst ILLEGAL_PARAGRAPH_CHILD_ELEMENTS =\n\t/^(address|article|aside|blockquote|details|div|dl|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hgroup|hr|main|menu|nav|ol|p|pre|search|section|table|ul)$/;\n\nconst forceUpdate = Component.prototype.forceUpdate;\nComponent.prototype.forceUpdate = function (callback) {\n\tif (this._vnode == null) {\n\t\tconsole.warn(\n\t\t\t`Calling \"this.forceUpdate\" inside the constructor of a component is a ` +\n\t\t\t\t`no-op and might be a bug in your application.\\n\\n${getOwnerStack(\n\t\t\t\t\tgetCurrentVNode()\n\t\t\t\t)}`\n\t\t);\n\t} else if (this._parentDom == null) {\n\t\tconsole.warn(\n\t\t\t`Can't call \"this.forceUpdate\" on an unmounted component. This is a no-op, ` +\n\t\t\t\t`but it indicates a memory leak in your application. To fix, cancel all ` +\n\t\t\t\t`subscriptions and asynchronous tasks in the componentWillUnmount method.` +\n\t\t\t\t`\\n\\n${getOwnerStack(this._vnode)}`\n\t\t);\n\t}\n\treturn forceUpdate.call(this, callback);\n};\n\n/**\n * Serialize a vnode tree to a string\n * @param {import('./internal').VNode} vnode\n * @returns {string}\n */\nexport function serializeVNode(vnode) {\n\tlet { props } = vnode;\n\tlet name = getDisplayName(vnode);\n\n\tlet attrs = '';\n\tfor (let prop in props) {\n\t\tif (props.hasOwnProperty(prop) && prop !== 'children') {\n\t\t\tlet value = props[prop];\n\n\t\t\t// If it is an object but doesn't have toString(), use Object.toString\n\t\t\tif (typeof value == 'function') {\n\t\t\t\tvalue = `function ${value.displayName || value.name}() {}`;\n\t\t\t}\n\n\t\t\tvalue =\n\t\t\t\tObject(value) === value && !value.toString\n\t\t\t\t\t? Object.prototype.toString.call(value)\n\t\t\t\t\t: value + '';\n\n\t\t\tattrs += ` ${prop}=${JSON.stringify(value)}`;\n\t\t}\n\t}\n\n\tlet children = props.children;\n\treturn `<${name}${attrs}${\n\t\tchildren && children.length ? '>..' : ' />'\n\t}`;\n}\n\noptions._hydrationMismatch = (newVNode, excessDomChildren) => {\n\tconst { type } = newVNode;\n\tconst availableTypes = excessDomChildren\n\t\t.map(child => child && child.localName)\n\t\t.filter(Boolean);\n\tconsole.error(\n\t\t`Expected a DOM node of type \"${type}\" but found \"${availableTypes.join(', ')}\" as available DOM-node(s), this is caused by the SSR'd HTML containing different DOM-nodes compared to the hydrated one.\\n\\n${getOwnerStack(newVNode)}`\n\t);\n};\n","export const ELEMENT_NODE = 1;\nexport const DOCUMENT_NODE = 9;\nexport const DOCUMENT_FRAGMENT_NODE = 11;\n","/**\n * Assign properties from `props` to `obj`\n * @template O, P The obj and props types\n * @param {O} obj The object to copy properties to\n * @param {P} props The object to copy properties from\n * @returns {O & P}\n */\nexport function assign(obj, props) {\n\tfor (let i in props) obj[i] = props[i];\n\treturn /** @type {O & P} */ (obj);\n}\n\nexport function isNaN(value) {\n\treturn value !== value;\n}\n","import { initDebug } from './debug';\nimport 'preact/devtools';\n\ninitDebug();\n\nexport { resetPropWarnings } from './check-props';\n\nexport {\n\tgetCurrentVNode,\n\tgetDisplayName,\n\tgetOwnerStack\n} from './component-stack';\n"],"names":["loggedTypeFailures","resetPropWarnings","getDisplayName","vnode","type","Fragment","displayName","name","renderStack","ownerStack","getCurrentVNode","length","showJsxSourcePluginWarning","isPossibleOwner","getOwnerStack","stack","next","__o","push","reduce","acc","owner","source","__source","fileName","lineNumber","console","warn","isWeakMapSupported","WeakMap","getDomChildren","domChildren","__k","forEach","child","apply","getClosestDomNodeParentName","parent","__","__e","parentNode","localName","setState","Component","prototype","isTableElement","update","callback","this","__v","state","call","ILLEGAL_PARAGRAPH_CHILD_ELEMENTS","forceUpdate","serializeVNode","props","attrs","prop","hasOwnProperty","value","Object","toString","JSON","stringify","children","__P","options","__m","newVNode","excessDomChildren","availableTypes","map","filter","Boolean","error","join","oldDiff","__b","oldDiffed","diffed","oldRoot","oldVNode","oldRender","__r","pop","setupComponentStack","hooksAllowed","oldBeforeDiff","oldVnode","oldCatchError","oldHook","__h","warnedComponents","useEffect","useLayoutEffect","lazyPropTypes","deprecations","errorInfo","__c","then","promise","Error","componentStack","setTimeout","e","isValid","nodeType","componentName","undefined","Array","isArray","ref","key","propTypes","has","m","lazyVNode","set","values","__f","obj","i","assign","typeSpecs","location","getStack","keys","typeSpecName","message","checkPropTypes","currentComponent","renderCount","nextComponent","comp","index","property","get","indexOf","deprecatedAttributes","nodeName","attributes","deprecatedProto","create","newProps","v","__self","__proto__","domParentName","illegalDomChildrenTypes","childType","test","__H","hooks","hook","j","initDebug"],"mappings":"sFAAA,IAEIA,EAAqB,CAAA,EAKlB,SAASC,IACfD,EAAqB,CAAA,CACtB,CCDO,SAASE,EAAeC,GAC9B,OAAIA,EAAMC,OAASC,EACX,WACwB,mBAAdF,EAAMC,KAChBD,EAAMC,KAAKE,aAAeH,EAAMC,KAAKG,KACb,iBAAdJ,EAAMC,KAChBD,EAAMC,KAGP,OACR,CAMA,IAAII,EAAc,GAoBdC,EAAa,YAMDC,IACf,OAAOF,EAAYG,OAAS,EAAIH,EAAYA,EAAYG,OAAS,GAAK,IACvE,CAQA,IAAIC,GAA6B,EAMjC,SAASC,EAAgBV,GACxB,MAA4B,mBAAdA,EAAMC,MAAsBD,EAAMC,MAAQC,CACzD,CAOO,SAASS,EAAcX,GAG7B,IAFA,IAAMY,EAAQ,CAACZ,GACXa,EAAOb,EACW,MAAfa,EAAIC,KACVF,EAAMG,KAAKF,EAAIC,KACfD,EAAOA,EAAIC,IAGZ,OAAOF,EAAMI,OAAO,SAACC,EAAKC,GACzBD,GAAelB,QAAAA,EAAemB,GAE9B,IAAMC,EAASD,EAAME,SAUrB,OATID,EACHF,GAAeE,QAAAA,EAAOE,SAAYF,IAAAA,EAAOG,WAC1C,IAAWb,GACVc,QAAQC,KACP,kLAGFf,GAA6B,EAErBQ,EAAO,IAChB,EAAG,GACJ,CCnFA,IAAMQ,EAAuC,mBAAXC,QAMlC,SAASC,EAAe3B,GACvB,IAAI4B,EAAc,GAElB,OAAK5B,EAAK6B,KAEV7B,EAAK6B,IAAWC,QAAQ,SAAAC,GACnBA,GAA+B,mBAAfA,EAAM9B,KACzB2B,EAAYb,KAAKiB,MAAMJ,EAAaD,EAAeI,IACzCA,GAA+B,iBAAfA,EAAM9B,MAChC2B,EAAYb,KAAKgB,EAAM9B,KAEzB,GAEO2B,GAVsBA,CAW9B,CAMA,SAASK,EAA4BC,GACpC,OAAKA,EACqB,mBAAfA,EAAOjC,KACK,MAAlBiC,EAAMC,GACU,MAAfD,EAAME,KAA2C,MAA1BF,EAAME,IAAMC,WAC/BH,EAAME,IAAMC,WAAWC,UAExB,GAEDL,EAA4BC,EAAMC,IAEZD,EAAOjC,KAVjB,EAWrB,CA2bA,IAAMsC,EAAWC,EAAUC,UAAUF,SAmBrC,SAASG,EAAezC,GACvB,MACU,UAATA,GACS,UAATA,GACS,UAATA,GACS,UAATA,GACS,OAATA,GACS,OAATA,GACS,OAATA,CAEF,CA5BAuC,EAAUC,UAAUF,SAAW,SAAUI,EAAQC,GAehD,OAdmB,MAAfC,KAAIC,KAKW,MAAdD,KAAKE,OACRxB,QAAQC,KACP,gKAEmCb,EAAcJ,MAK7CgC,EAASS,KAAKH,KAAMF,EAAQC,EACpC,EAcA,IAAMK,EACL,+KAEKC,EAAcV,EAAUC,UAAUS,YAyBjC,SAASC,EAAenD,GAC9B,IAAMoD,EAAUpD,EAAVoD,MACFhD,EAAOL,EAAeC,GAEtBqD,EAAQ,GACZ,IAAK,IAAIC,KAAQF,EAChB,GAAIA,EAAMG,eAAeD,IAAkB,aAATA,EAAqB,CACtD,IAAIE,EAAQJ,EAAME,GAGE,mBAATE,IACVA,EAAK,aAAeA,EAAMrD,aAAeqD,EAAMpD,MAAI,SAGpDoD,EACCC,OAAOD,KAAWA,GAAUA,EAAME,SAE/BF,EAAQ,GADRC,OAAOhB,UAAUiB,SAASV,KAAKQ,GAGnCH,OAAaC,EAAI,IAAIK,KAAKC,UAAUJ,EACrC,CAGD,IAAIK,EAAWT,EAAMS,SACrB,MAAA,IAAWzD,EAAOiD,GACjBQ,GAAYA,EAASrD,OAAS,QAAUJ,EAAO,IAAM,MAEvD,CAnDAoC,EAAUC,UAAUS,YAAc,SAAUN,GAgB3C,OAfmB,MAAfC,KAAIC,IACPvB,QAAQC,KACP,0HACqDb,EACnDJ,MAG0B,MAAnBsC,KAAIiB,KACdvC,QAAQC,KACP,iOAGQb,EAAckC,KAAIC,MAGrBI,EAAYF,KAAKH,KAAMD,EAC/B,EAoCAmB,EAAOC,IAAsB,SAACC,EAAUC,GACvC,IAAQjE,EAASgE,EAAThE,KACFkE,EAAiBD,EACrBE,IAAI,SAAArC,GAAK,OAAIA,GAASA,EAAMO,SAAS,GACrC+B,OAAOC,SACT/C,QAAQgD,MACyBtE,gCAAAA,EAAoBkE,gBAAAA,EAAeK,KAAK,uIAAqI7D,EAAcsD,GAE7N,EAzhBO,YDkDA,WACN,IAAIQ,EAAUV,EAAOW,IACjBC,EAAYZ,EAAQa,OACpBC,EAAUd,EAAO5B,GACjB2C,EAAWf,EAAQ/D,MACnB+E,EAAYhB,EAAOiB,IAEvBjB,EAAQa,OAAS,SAAA5E,GACZU,EAAgBV,IACnBM,EAAW2E,MAEZ5E,EAAY4E,MACRN,GAAWA,EAAU3E,EAC1B,EAEA+D,EAAOW,IAAS,SAAA1E,GACXU,EAAgBV,IACnBK,EAAYU,KAAKf,GAEdyE,GAASA,EAAQzE,EACtB,EAEA+D,EAAO5B,GAAS,SAACnC,EAAOkC,GACvB5B,EAAa,GACTuE,GAASA,EAAQ7E,EAAOkC,EAC7B,EAEA6B,EAAQ/D,MAAQ,SAAAA,GACfA,EAAKc,IACJR,EAAWE,OAAS,EAAIF,EAAWA,EAAWE,OAAS,GAAK,KACzDsE,GAAUA,EAAS9E,EACxB,EAEA+D,EAAOiB,IAAW,SAAAhF,GACbU,EAAgBV,IACnBM,EAAWS,KAAKf,GAGb+E,GAAWA,EAAU/E,EAC1B,CACD,CCzFCkF,GAEA,IAAIC,GAAe,EAGfC,EAAgBrB,EAAOW,IACvBC,EAAYZ,EAAQa,OACpBS,EAAWtB,EAAQ/D,MACnB+E,EAAYhB,EAAOiB,IACnBM,EAAgBvB,EAAO3B,IACvByC,EAAUd,EAAO5B,GACjBoD,EAAUxB,EAAOyB,IACfC,EAAoBhE,EAEvB,CACAiE,UAAW,IAAIhE,QACfiE,gBAAiB,IAAIjE,QACrBkE,cAAe,IAAIlE,SAJnB,KAMGmE,EAAe,GAErB9B,EAAO3B,IAAe,SAACmC,EAAOvE,EAAO8E,EAAUgB,GAE9C,GADgB9F,GAASA,EAAK+F,KACQ,mBAAdxB,EAAMyB,KAAoB,CACjD,IAAMC,EAAU1B,EAChBA,EAAQ,IAAI2B,MAAK,iDACiCnG,EAAeC,IAIjE,IADA,IAAIkC,EAASlC,EACNkC,EAAQA,EAASA,EAAMC,GAC7B,GAAID,EAAM6D,KAAe7D,EAAM6D,IAAAA,IAA8B,CAC5DxB,EAAQ0B,EACR,KACD,CAKD,GAAI1B,aAAiB2B,MACpB,MAAM3B,CAER,CAEA,KACCuB,EAAYA,GAAa,IACfK,eAAiBxF,EAAcX,GACzCsF,EAAcf,EAAOvE,EAAO8E,EAAUgB,GAKb,mBAAdvB,EAAMyB,MAChBI,WAAW,WACV,MAAM7B,CACP,EAIF,CAFE,MAAO8B,GACR,MAAMA,CACP,CACD,EAEAtC,EAAO5B,GAAS,SAACnC,EAAOqC,GACvB,IAAKA,EACJ,UAAU6D,MACT,uIAKF,IAAII,EACJ,OAAQjE,EAAWkE,UAClB,KChIyB,EDiIzB,KC/HmC,GDgInC,KCjI0B,EDkIzBD,GAAU,EACV,MACD,QACCA,GAAU,EAGZ,IAAKA,EAAS,CACb,IAAIE,EAAgBzG,EAAeC,GACnC,MAAM,IAAIkG,8EAC8D7D,EAAU,qBAAqBmE,EAAa,QAAQnE,EAC5H,KACD,CAEIwC,GAASA,EAAQ7E,EAAOqC,EAC7B,EAEA0B,EAAOW,IAAS,SAAA1E,GACf,IAAMC,EAASD,EAATC,KAIN,GAFAkF,GAAe,OAEFsB,IAATxG,EACH,MAAU,IAAAiG,MACT,+IAEC/C,EAAenD,UACRW,EAAcX,IAEjB,GAAY,MAARC,GAA+B,iBAARA,EAAkB,CACnD,QAAuBwG,IAAnBxG,EAAI4B,UAA0C4E,IAAdxG,EAAImC,IACvC,MAAM,IAAI8D,MACT,2CAA2CjG,EAA3C,wEAEYF,EAAeC,GAAYmD,MAAAA,EAAelD,GAFtD,uBAGqBF,EAAeC,GAHpC,wFAKQW,EAAcX,IAIxB,MAAM,IAAIkG,MACT,4CACEQ,MAAMC,QAAQ1G,GAAQ,QAAUA,GAEpC,CAEA,QACewG,IAAdzG,EAAM4G,KACc,mBAAb5G,EAAM4G,KACO,iBAAb5G,EAAM4G,OACX,aAAc5G,GAEhB,MAAU,IAAAkG,MACT,0GACoClG,EAAM4G,IAAG,cAC5CzD,EAAenD,GACRW,OAAAA,EAAcX,IAIxB,GAAyB,iBAAdA,EAAMC,KAChB,IAAK,IAAM4G,KAAO7G,EAAMoD,MACvB,GACY,MAAXyD,EAAI,IACO,MAAXA,EAAI,IACuB,mBAApB7G,EAAMoD,MAAMyD,IACC,MAApB7G,EAAMoD,MAAMyD,GAEZ,MAAU,IAAAX,MACT,iBAAgBW,EAAhB,oDACoB7G,EAAMoD,MAAMyD,GAAiB,cAChD1D,EAAenD,GAAM,OACdW,EAAcX,IAO1B,GAAyB,mBAAdA,EAAMC,MAAsBD,EAAMC,KAAK6G,UAAW,CAC5D,GAC4B,SAA3B9G,EAAMC,KAAKE,aACXsF,IACCA,EAAiBG,cAAcmB,IAAI/G,EAAMC,MACzC,CACD,IAAM+G,EACL,yFACD,IACC,IAAMC,EAAYjH,EAAMC,OACxBwF,EAAiBG,cAAcsB,IAAIlH,EAAMC,MAAM,GAC/CsB,QAAQC,KACPwF,oCAAsCjH,EAAekH,GAMvD,CAJE,MAAOhB,GACR1E,QAAQC,KACPwF,EAAI,8DAEN,CACD,CAEA,IAAIG,EAASnH,EAAMoD,MACfpD,EAAMC,KAAImH,YACbD,WElOmBE,EAAKjE,GAC3B,IAAK,IAAIkE,KAAKlE,EAAOiE,EAAIC,GAAKlE,EAAMkE,GACpC,OAA6BD,CAC9B,CF+NaE,CAAO,CAAE,EAAEJ,IACNP,IFnNX,SACNY,EACAL,EACAM,EACAjB,EACAkB,GAEAjE,OAAOkE,KAAKH,GAAW1F,QAAQ,SAAA8F,GAC9B,IAAIrD,EACJ,IACCA,EAAQiD,EAAUI,GACjBT,EACAS,EACApB,EE4MA,OF1MA,KAtCyB,+CA2C3B,CAFE,MAAOH,GACR9B,EAAQ8B,CACT,CACI9B,KAAWA,EAAMsD,WAAWhI,KAC/BA,EAAmB0E,EAAMsD,UAAW,EACpCtG,QAAQgD,2BACqBA,EAAMsD,SAChCH,GAAQ,KAASA,KAAiB,KAIvC,EACD,CEwLGI,CACC9H,EAAMC,KAAK6G,UACXK,EACA,EACApH,EAAeC,GACf,WAAM,OAAAW,EAAcX,EAAM,EAE5B,CAEIoF,GAAeA,EAAcpF,EAClC,EAEA,IACI+H,EADAC,EAAc,EAElBjE,EAAOiB,IAAW,SAAAhF,GACb+E,GACHA,EAAU/E,GAEXmF,GAAe,EAEf,IAAM8C,EAAgBjI,EAAK+F,IAO3B,GANIkC,IAAkBF,EACrBC,IAEAA,EAAc,EAGXA,GAAe,GAClB,MAAM,IAAI9B,MACT,mIACmEnG,EACjEC,IAKJ+H,EAAmBE,CACpB,EAEAlE,EAAOyB,IAAS,SAAC0C,EAAMC,EAAOlI,GAC7B,IAAKiI,IAAS/C,EACb,MAAU,IAAAe,MAAM,iDAGbX,GAASA,EAAQ2C,EAAMC,EAAOlI,EACnC,EAMA,IAAMuB,EAAO,SAAC4G,EAAUP,SAAa,CACpCQ,IAAA,WACC,IAAMxB,EAAM,MAAQuB,EAAWP,EAC3BhC,GAAgBA,EAAayC,QAAQzB,GAAO,IAC/ChB,EAAa9E,KAAK8F,GAClBtF,QAAQC,KAAsB4G,iBAAAA,qBAA2BP,GAE3D,EACAX,IAAG,WACF,IAAML,EAAM,MAAQuB,EAAWP,EAC3BhC,GAAgBA,EAAayC,QAAQzB,GAAO,IAC/ChB,EAAa9E,KAAK8F,GAClBtF,QAAQC,KAAI,iBAAkB4G,EAAQ,oBAAoBP,GAE5D,EACA,EAEKU,EAAuB,CAC5BC,SAAUhH,EAAK,WAAY,kBAC3BiH,WAAYjH,EAAK,aAAc,mBAC/BqC,SAAUrC,EAAK,WAAY,6BAGtBkH,EAAkBjF,OAAOkF,OAAO,CAAE,EAAEJ,GAE1CxE,EAAQ/D,MAAQ,SAAAA,GACf,IAAMoD,EAAQpD,EAAMoD,MACpB,GACgB,OAAfpD,EAAMC,MACG,MAATmD,IACC,aAAcA,GAAS,WAAYA,GACnC,CACD,IAAMwF,EAAY5I,EAAMoD,MAAQ,CAAA,EAChC,IAAK,IAAIkE,KAAKlE,EAAO,CACpB,IAAMyF,EAAIzF,EAAMkE,GACN,aAANA,EAAkBtH,EAAMoB,SAAWyH,EACxB,WAANvB,EAAgBtH,EAAM8I,OAASD,EACnCD,EAAStB,GAAKuB,CACpB,CACD,CAGA7I,EAAM+I,UAAYL,EACdrD,GAAUA,EAASrF,EACxB,EAEA+D,EAAQa,OAAS,SAAA5E,GAChB,IEnUoBwD,EFmUZvD,EAA0BD,EAA1BC,KAAeiC,EAAWlC,EAAKmC,GAwBvC,GAhBInC,EAAK6B,KACR7B,EAAK6B,IAAWC,QAAQ,SAAAC,GACvB,GAAqB,iBAAVA,GAAsBA,QAAwB0E,IAAf1E,EAAM9B,KAAoB,CACnE,IAAM0H,EAAOlE,OAAOkE,KAAK5F,GAAOyC,KAAK,KACrC,MAAM,IAAI0B,MACT,0EAA0EyB,EAA1E,SACQhH,EAAcX,GAExB,CACD,GAGGA,EAAK+F,MAAgBgC,IACxBC,EAAc,GAIE,iBAAT/H,IACNyC,EAAezC,IACN,MAATA,GACS,MAATA,GACS,WAATA,GACA,CAMD,IAAI+I,EAAgB/G,EAA4BC,GAChD,GAAsB,KAAlB8G,GAAwBtG,EAAezC,GAEhC,UAATA,GAGkB,OAAlB+I,GACAtG,EAAesG,GAEfzH,QAAQgD,MACP,+EACCpB,EAAenD,UACRW,EAAcX,IAGb,UAATC,GAA6B,UAATA,GAA6B,UAATA,GACvB,UAAlB+I,EAQS,OAAT/I,GACkB,UAAlB+I,GACkB,UAAlBA,GACkB,UAAlBA,EAEAzH,QAAQgD,MACP,iFACCpB,EAAenD,GAAM,OACdW,EAAcX,IAEJ,OAATC,GAAmC,OAAlB+I,EAC3BzH,QAAQgD,MACP,kEACCpB,EAAenD,GAAM,OACdW,EAAcX,IAEJ,OAATC,GAAmC,OAAlB+I,GAC3BzH,QAAQgD,MACP,2DACCpB,EAAenD,GACRW,OAAAA,EAAcX,IA1BvBuB,QAAQgD,MACP,oFACCpB,EAAenD,GAAM,OACdW,EAAcX,SA0BlB,GAAa,MAATC,EAAc,CACxB,IAAIgJ,EAA0BtH,EAAe3B,GAAOqE,OAAO,SAAA6E,GAC1D,OAAAjG,EAAiCkG,KAAKD,EAAU,GAE7CD,EAAwBzI,QAC3Be,QAAQgD,MACP,2DACC0E,EAAwBzE,KAAK,MAC7B,sBACArB,EAAenD,GACRW,OAAAA,EAAcX,GAGzB,KAAoB,MAATC,GAAyB,WAATA,IACmB,IAAzC0B,EAAe3B,GAAOsI,QAAQrI,IACjCsB,QAAQgD,MACP,kDAAkDtE,EAAlD,4BACoC,MAATA,EAAe,SAAW,UACpD,2BACAkD,EAAenD,GAAM,OACdW,EAAcX,GAI1B,CAMA,GAJAmF,GAAe,EAEXR,GAAWA,EAAU3E,GAEF,MAAnBA,EAAK6B,IAER,IADA,IAAM8F,EAAO,GACJL,EAAI,EAAGA,EAAItH,EAAK6B,IAAWrB,OAAQ8G,IAAK,CAChD,IAAMvF,EAAQ/B,EAAK6B,IAAWyF,GAC9B,GAAKvF,GAAsB,MAAbA,EAAM8E,IAApB,CAEA,IAAMA,EAAM9E,EAAM8E,IAClB,IAA2B,IAAvBc,EAAKW,QAAQzB,GAAa,CAC7BtF,QAAQgD,MACP,8EACyBsC,EADzB,mFAGC1D,EAAenD,GACRW,OAAAA,EAAcX,IAIvB,KACD,CAEA2H,EAAK5G,KAAK8F,GACX,CAGD,GAAwB,MAApB7G,EAAK+F,KAAmD,MAA5B/F,EAAK+F,IAAAqD,IAA6B,CAGjE,IAAMC,EAAQrJ,EAAK+F,IAAAqD,IAAAjH,GACnB,GAAIkH,EACH,IAAK,IAAI/B,EAAI,EAAGA,EAAI+B,EAAM7I,OAAQ8G,GAAK,EAAG,CACzC,IAAMgC,EAAOD,EAAM/B,GACnB,GAAIgC,EAAIF,IACP,IAAK,IAAIG,EAAI,EAAGA,EAAID,EAAIF,IAAO5I,OAAQ+I,IAEtC,IEtde/F,EFqdH8F,EAAIF,IAAOG,KEpdZ/F,EFqdK,CACf,IAAMgD,EAAgBzG,EAAeC,GACrCuB,QAAQC,KAAI,4GACiG8F,EAAC,iBAAiBd,EAC/H,wBACD,CAGH,CAEF,CACD,CACD,CG3eAgD"} \ No newline at end of file diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/debug/dist/debug.umd.js b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/dist/debug.umd.js new file mode 100644 index 0000000000000..363bef3e5d284 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/dist/debug.umd.js @@ -0,0 +1,2 @@ +!function(n,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("preact"),require("preact/devtools")):"function"==typeof define&&define.amd?define(["exports","preact","preact/devtools"],e):e((n||self).preactDebug={},n.preact)}(this,function(n,e){var o={};function t(n){return n.type===e.Fragment?"Fragment":"function"==typeof n.type?n.type.displayName||n.type.name:"string"==typeof n.type?n.type:"#text"}var r=[],a=[];function i(){return r.length>0?r[r.length-1]:null}var s=!0;function c(n){return"function"==typeof n.type&&n.type!=e.Fragment}function l(n){for(var e=[n],o=n;null!=o.__o;)e.push(o.__o),o=o.__o;return e.reduce(function(n,e){n+=" in "+t(e);var o=e.__source;return o?n+=" (at "+o.fileName+":"+o.lineNumber+")":s&&console.warn("Add @babel/plugin-transform-react-jsx-source to get a more detailed component stack. Note that you should not add it to production builds of your App for bundle size reasons."),s=!1,n+"\n"},"")}var u="function"==typeof WeakMap;function f(n){var e=[];return n.__k?(n.__k.forEach(function(n){n&&"function"==typeof n.type?e.push.apply(e,f(n)):n&&"string"==typeof n.type&&e.push(n.type)}),e):e}function d(n){return n?"function"==typeof n.type?null==n.__?null!=n.__e&&null!=n.__e.parentNode?n.__e.parentNode.localName:"":d(n.__):n.type:""}var p=e.Component.prototype.setState;function h(n){return"table"===n||"tfoot"===n||"tbody"===n||"thead"===n||"td"===n||"tr"===n||"th"===n}e.Component.prototype.setState=function(n,e){return null==this.__v&&null==this.state&&console.warn('Calling "this.setState" inside the constructor of a component is a no-op and might be a bug in your application. Instead, set "this.state = {}" directly.\n\n'+l(i())),p.call(this,n,e)};var v=/^(address|article|aside|blockquote|details|div|dl|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hgroup|hr|main|menu|nav|ol|p|pre|search|section|table|ul)$/,y=e.Component.prototype.forceUpdate;function m(n){var e=n.props,o=t(n),r="";for(var a in e)if(e.hasOwnProperty(a)&&"children"!==a){var i=e[a];"function"==typeof i&&(i="function "+(i.displayName||i.name)+"() {}"),i=Object(i)!==i||i.toString?i+"":Object.prototype.toString.call(i),r+=" "+a+"="+JSON.stringify(i)}var s=e.children;return"<"+o+r+(s&&s.length?">..":" />")}e.Component.prototype.forceUpdate=function(n){return null==this.__v?console.warn('Calling "this.forceUpdate" inside the constructor of a component is a no-op and might be a bug in your application.\n\n'+l(i())):null==this.__P&&console.warn('Can\'t call "this.forceUpdate" on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.\n\n'+l(this.__v)),y.call(this,n)},e.options.__m=function(n,e){var o=n.type,t=e.map(function(n){return n&&n.localName}).filter(Boolean);console.error('Expected a DOM node of type "'+o+'" but found "'+t.join(", ")+"\" as available DOM-node(s), this is caused by the SSR'd HTML containing different DOM-nodes compared to the hydrated one.\n\n"+l(n))},function(){!function(){var n=e.options.__b,o=e.options.diffed,t=e.options.__,i=e.options.vnode,s=e.options.__r;e.options.diffed=function(n){c(n)&&a.pop(),r.pop(),o&&o(n)},e.options.__b=function(e){c(e)&&r.push(e),n&&n(e)},e.options.__=function(n,e){a=[],t&&t(n,e)},e.options.vnode=function(n){n.__o=a.length>0?a[a.length-1]:null,i&&i(n)},e.options.__r=function(n){c(n)&&a.push(n),s&&s(n)}}();var n=!1,i=e.options.__b,s=e.options.diffed,p=e.options.vnode,y=e.options.__r,b=e.options.__e,g=e.options.__,w=e.options.__h,E=u?{useEffect:new WeakMap,useLayoutEffect:new WeakMap,lazyPropTypes:new WeakMap}:null,k=[];e.options.__e=function(n,e,o,r){if(e&&e.__c&&"function"==typeof n.then){var a=n;n=new Error("Missing Suspense. The throwing component was: "+t(e));for(var i=e;i;i=i.__)if(i.__c&&i.__c.__c){n=a;break}if(n instanceof Error)throw n}try{(r=r||{}).componentStack=l(e),b(n,e,o,r),"function"!=typeof n.then&&setTimeout(function(){throw n})}catch(n){throw n}},e.options.__=function(n,e){if(!e)throw new Error("Undefined parent passed to render(), this is the second argument.\nCheck if the element is available in the DOM/has the correct id.");var o;switch(e.nodeType){case 1:case 11:case 9:o=!0;break;default:o=!1}if(!o){var r=t(n);throw new Error("Expected a valid HTML node as a second argument to render.\tReceived "+e+" instead: render(<"+r+" />, "+e+");")}g&&g(n,e)},e.options.__b=function(e){var r=e.type;if(n=!0,void 0===r)throw new Error("Undefined component passed to createElement()\n\nYou likely forgot to export your component or might have mixed up default and named imports"+m(e)+"\n\n"+l(e));if(null!=r&&"object"==typeof r){if(void 0!==r.__k&&void 0!==r.__e)throw new Error("Invalid type passed to createElement(): "+r+"\n\nDid you accidentally pass a JSX literal as JSX twice?\n\n let My"+t(e)+" = "+m(r)+";\n let vnode = ;\n\nThis usually happens when you export a JSX literal and not the component.\n\n"+l(e));throw new Error("Invalid type passed to createElement(): "+(Array.isArray(r)?"array":r))}if(void 0!==e.ref&&"function"!=typeof e.ref&&"object"!=typeof e.ref&&!("$$typeof"in e))throw new Error('Component\'s "ref" property should be a function, or an object created by createRef(), but got ['+typeof e.ref+"] instead\n"+m(e)+"\n\n"+l(e));if("string"==typeof e.type)for(var a in e.props)if("o"===a[0]&&"n"===a[1]&&"function"!=typeof e.props[a]&&null!=e.props[a])throw new Error("Component's \""+a+'" property should be a function, but got ['+typeof e.props[a]+"] instead\n"+m(e)+"\n\n"+l(e));if("function"==typeof e.type&&e.type.propTypes){if("Lazy"===e.type.displayName&&E&&!E.lazyPropTypes.has(e.type)){var s="PropTypes are not supported on lazy(). Use propTypes on the wrapped component itself. ";try{var c=e.type();E.lazyPropTypes.set(e.type,!0),console.warn(s+"Component wrapped in lazy() is "+t(c))}catch(n){console.warn(s+"We will log the wrapped component's name once it is loaded.")}}var u=e.props;e.type.__f&&delete(u=function(n,e){for(var o in e)n[o]=e[o];return n}({},u)).ref,function(n,e,t,r,a){Object.keys(n).forEach(function(t){var i;try{i=n[t](e,t,r,"prop",null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(n){i=n}i&&!(i.message in o)&&(o[i.message]=!0,console.error("Failed prop type: "+i.message+(a&&"\n"+a()||"")))})}(e.type.propTypes,u,0,t(e),function(){return l(e)})}i&&i(e)};var T,_=0;e.options.__r=function(e){y&&y(e),n=!0;var o=e.__c;if(o===T?_++:_=1,_>=25)throw new Error("Too many re-renders. This is limited to prevent an infinite loop which may lock up your browser. The component causing this is: "+t(e));T=o},e.options.__h=function(e,o,t){if(!e||!n)throw new Error("Hook can only be invoked from render methods.");w&&w(e,o,t)};var O=function(n,e){return{get:function(){var o="get"+n+e;k&&k.indexOf(o)<0&&(k.push(o),console.warn("getting vnode."+n+" is deprecated, "+e))},set:function(){var o="set"+n+e;k&&k.indexOf(o)<0&&(k.push(o),console.warn("setting vnode."+n+" is not allowed, "+e))}}},I={nodeName:O("nodeName","use vnode.type"),attributes:O("attributes","use vnode.props"),children:O("children","use vnode.props.children")},j=Object.create({},I);e.options.vnode=function(n){var e=n.props;if(null!==n.type&&null!=e&&("__source"in e||"__self"in e)){var o=n.props={};for(var t in e){var r=e[t];"__source"===t?n.__source=r:"__self"===t?n.__self=r:o[t]=r}}n.__proto__=j,p&&p(n)},e.options.diffed=function(e){var o,r=e.type,a=e.__;if(e.__k&&e.__k.forEach(function(n){if("object"==typeof n&&n&&void 0===n.type){var o=Object.keys(n).join(",");throw new Error("Objects are not valid as a child. Encountered an object with the keys {"+o+"}.\n\n"+l(e))}}),e.__c===T&&(_=0),"string"==typeof r&&(h(r)||"p"===r||"a"===r||"button"===r)){var i=d(a);if(""!==i&&h(r))"table"===r&&"td"!==i&&h(i)?console.error("Improper nesting of table. Your

    should have a
    should have a
    should not have a table-node parent."+m(e)+"\n\n"+l(e)):"thead"!==r&&"tfoot"!==r&&"tbody"!==r||"table"===i?"tr"===r&&"thead"!==i&&"tfoot"!==i&&"tbody"!==i?console.error("Improper nesting of table. Your should have a parent."+m(e)+"\n\n"+l(e)):"td"===r&&"tr"!==i?console.error("Improper nesting of table. Your parent."+m(e)+"\n\n"+l(e)):"th"===r&&"tr"!==i&&console.error("Improper nesting of table. Your ."+m(e)+"\n\n"+l(e)):console.error("Improper nesting of table. Your should have a
    should have a
    should have a
    parent."+m(e)+"\n\n"+l(e));else if("p"===r){var c=f(e).filter(function(n){return v.test(n)});c.length&&console.error("Improper nesting of paragraph. Your

    should not have "+c.join(", ")+" as child-elements."+m(e)+"\n\n"+l(e))}else"a"!==r&&"button"!==r||-1!==f(e).indexOf(r)&&console.error("Improper nesting of interactive content. Your <"+r+"> should not have other "+("a"===r?"anchor":"button")+" tags as child-elements."+m(e)+"\n\n"+l(e))}if(n=!1,s&&s(e),null!=e.__k)for(var u=[],p=0;p {\n\t\tlet error;\n\t\ttry {\n\t\t\terror = typeSpecs[typeSpecName](\n\t\t\t\tvalues,\n\t\t\t\ttypeSpecName,\n\t\t\t\tcomponentName,\n\t\t\t\tlocation,\n\t\t\t\tnull,\n\t\t\t\tReactPropTypesSecret\n\t\t\t);\n\t\t} catch (e) {\n\t\t\terror = e;\n\t\t}\n\t\tif (error && !(error.message in loggedTypeFailures)) {\n\t\t\tloggedTypeFailures[error.message] = true;\n\t\t\tconsole.error(\n\t\t\t\t`Failed ${location} type: ${error.message}${\n\t\t\t\t\t(getStack && `\\n${getStack()}`) || ''\n\t\t\t\t}`\n\t\t\t);\n\t\t}\n\t});\n}\n","import { options, Fragment } from 'preact';\n\n/**\n * Get human readable name of the component/dom node\n * @param {import('./internal').VNode} vnode\n * @param {import('./internal').VNode} vnode\n * @returns {string}\n */\nexport function getDisplayName(vnode) {\n\tif (vnode.type === Fragment) {\n\t\treturn 'Fragment';\n\t} else if (typeof vnode.type == 'function') {\n\t\treturn vnode.type.displayName || vnode.type.name;\n\t} else if (typeof vnode.type == 'string') {\n\t\treturn vnode.type;\n\t}\n\n\treturn '#text';\n}\n\n/**\n * Used to keep track of the currently rendered `vnode` and print it\n * in debug messages.\n */\nlet renderStack = [];\n\n/**\n * Keep track of the current owners. An owner describes a component\n * which was responsible to render a specific `vnode`. This exclude\n * children that are passed via `props.children`, because they belong\n * to the parent owner.\n *\n * ```jsx\n * const Foo = props =>

    {props.children}
    // div's owner is Foo\n * const Bar = props => {\n * return (\n * // Foo's owner is Bar, span's owner is Bar\n * )\n * }\n * ```\n *\n * Note: A `vnode` may be hoisted to the root scope due to compiler\n * optimiztions. In these cases the `_owner` will be different.\n */\nlet ownerStack = [];\n\n/**\n * Get the currently rendered `vnode`\n * @returns {import('./internal').VNode | null}\n */\nexport function getCurrentVNode() {\n\treturn renderStack.length > 0 ? renderStack[renderStack.length - 1] : null;\n}\n\n/**\n * If the user doesn't have `@babel/plugin-transform-react-jsx-source`\n * somewhere in his tool chain we can't print the filename and source\n * location of a component. In that case we just omit that, but we'll\n * print a helpful message to the console, notifying the user of it.\n */\nlet showJsxSourcePluginWarning = true;\n\n/**\n * Check if a `vnode` is a possible owner.\n * @param {import('./internal').VNode} vnode\n */\nfunction isPossibleOwner(vnode) {\n\treturn typeof vnode.type == 'function' && vnode.type != Fragment;\n}\n\n/**\n * Return the component stack that was captured up to this point.\n * @param {import('./internal').VNode} vnode\n * @returns {string}\n */\nexport function getOwnerStack(vnode) {\n\tconst stack = [vnode];\n\tlet next = vnode;\n\twhile (next._owner != null) {\n\t\tstack.push(next._owner);\n\t\tnext = next._owner;\n\t}\n\n\treturn stack.reduce((acc, owner) => {\n\t\tacc += ` in ${getDisplayName(owner)}`;\n\n\t\tconst source = owner.__source;\n\t\tif (source) {\n\t\t\tacc += ` (at ${source.fileName}:${source.lineNumber})`;\n\t\t} else if (showJsxSourcePluginWarning) {\n\t\t\tconsole.warn(\n\t\t\t\t'Add @babel/plugin-transform-react-jsx-source to get a more detailed component stack. Note that you should not add it to production builds of your App for bundle size reasons.'\n\t\t\t);\n\t\t}\n\t\tshowJsxSourcePluginWarning = false;\n\n\t\treturn (acc += '\\n');\n\t}, '');\n}\n\n/**\n * Setup code to capture the component trace while rendering. Note that\n * we cannot simply traverse `vnode._parent` upwards, because we have some\n * debug messages for `this.setState` where the `vnode` is `undefined`.\n */\nexport function setupComponentStack() {\n\tlet oldDiff = options._diff;\n\tlet oldDiffed = options.diffed;\n\tlet oldRoot = options._root;\n\tlet oldVNode = options.vnode;\n\tlet oldRender = options._render;\n\n\toptions.diffed = vnode => {\n\t\tif (isPossibleOwner(vnode)) {\n\t\t\townerStack.pop();\n\t\t}\n\t\trenderStack.pop();\n\t\tif (oldDiffed) oldDiffed(vnode);\n\t};\n\n\toptions._diff = vnode => {\n\t\tif (isPossibleOwner(vnode)) {\n\t\t\trenderStack.push(vnode);\n\t\t}\n\t\tif (oldDiff) oldDiff(vnode);\n\t};\n\n\toptions._root = (vnode, parent) => {\n\t\townerStack = [];\n\t\tif (oldRoot) oldRoot(vnode, parent);\n\t};\n\n\toptions.vnode = vnode => {\n\t\tvnode._owner =\n\t\t\townerStack.length > 0 ? ownerStack[ownerStack.length - 1] : null;\n\t\tif (oldVNode) oldVNode(vnode);\n\t};\n\n\toptions._render = vnode => {\n\t\tif (isPossibleOwner(vnode)) {\n\t\t\townerStack.push(vnode);\n\t\t}\n\n\t\tif (oldRender) oldRender(vnode);\n\t};\n}\n","import { checkPropTypes } from './check-props';\nimport { options, Component } from 'preact';\nimport {\n\tELEMENT_NODE,\n\tDOCUMENT_NODE,\n\tDOCUMENT_FRAGMENT_NODE\n} from './constants';\nimport {\n\tgetOwnerStack,\n\tsetupComponentStack,\n\tgetCurrentVNode,\n\tgetDisplayName\n} from './component-stack';\nimport { assign, isNaN } from './util';\n\nconst isWeakMapSupported = typeof WeakMap == 'function';\n\n/**\n * @param {import('./internal').VNode} vnode\n * @returns {Array}\n */\nfunction getDomChildren(vnode) {\n\tlet domChildren = [];\n\n\tif (!vnode._children) return domChildren;\n\n\tvnode._children.forEach(child => {\n\t\tif (child && typeof child.type === 'function') {\n\t\t\tdomChildren.push.apply(domChildren, getDomChildren(child));\n\t\t} else if (child && typeof child.type === 'string') {\n\t\t\tdomChildren.push(child.type);\n\t\t}\n\t});\n\n\treturn domChildren;\n}\n\n/**\n * @param {import('./internal').VNode} parent\n * @returns {string}\n */\nfunction getClosestDomNodeParentName(parent) {\n\tif (!parent) return '';\n\tif (typeof parent.type == 'function') {\n\t\tif (parent._parent == null) {\n\t\t\tif (parent._dom != null && parent._dom.parentNode != null) {\n\t\t\t\treturn parent._dom.parentNode.localName;\n\t\t\t}\n\t\t\treturn '';\n\t\t}\n\t\treturn getClosestDomNodeParentName(parent._parent);\n\t}\n\treturn /** @type {string} */ (parent.type);\n}\n\nexport function initDebug() {\n\tsetupComponentStack();\n\n\tlet hooksAllowed = false;\n\n\t/* eslint-disable no-console */\n\tlet oldBeforeDiff = options._diff;\n\tlet oldDiffed = options.diffed;\n\tlet oldVnode = options.vnode;\n\tlet oldRender = options._render;\n\tlet oldCatchError = options._catchError;\n\tlet oldRoot = options._root;\n\tlet oldHook = options._hook;\n\tconst warnedComponents = !isWeakMapSupported\n\t\t? null\n\t\t: {\n\t\t\t\tuseEffect: new WeakMap(),\n\t\t\t\tuseLayoutEffect: new WeakMap(),\n\t\t\t\tlazyPropTypes: new WeakMap()\n\t\t\t};\n\tconst deprecations = [];\n\n\toptions._catchError = (error, vnode, oldVNode, errorInfo) => {\n\t\tlet component = vnode && vnode._component;\n\t\tif (component && typeof error.then == 'function') {\n\t\t\tconst promise = error;\n\t\t\terror = new Error(\n\t\t\t\t`Missing Suspense. The throwing component was: ${getDisplayName(vnode)}`\n\t\t\t);\n\n\t\t\tlet parent = vnode;\n\t\t\tfor (; parent; parent = parent._parent) {\n\t\t\t\tif (parent._component && parent._component._childDidSuspend) {\n\t\t\t\t\terror = promise;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// We haven't recovered and we know at this point that there is no\n\t\t\t// Suspense component higher up in the tree\n\t\t\tif (error instanceof Error) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\terrorInfo = errorInfo || {};\n\t\t\terrorInfo.componentStack = getOwnerStack(vnode);\n\t\t\toldCatchError(error, vnode, oldVNode, errorInfo);\n\n\t\t\t// when an error was handled by an ErrorBoundary we will nonetheless emit an error\n\t\t\t// event on the window object. This is to make up for react compatibility in dev mode\n\t\t\t// and thus make the Next.js dev overlay work.\n\t\t\tif (typeof error.then != 'function') {\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthrow error;\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tthrow e;\n\t\t}\n\t};\n\n\toptions._root = (vnode, parentNode) => {\n\t\tif (!parentNode) {\n\t\t\tthrow new Error(\n\t\t\t\t'Undefined parent passed to render(), this is the second argument.\\n' +\n\t\t\t\t\t'Check if the element is available in the DOM/has the correct id.'\n\t\t\t);\n\t\t}\n\n\t\tlet isValid;\n\t\tswitch (parentNode.nodeType) {\n\t\t\tcase ELEMENT_NODE:\n\t\t\tcase DOCUMENT_FRAGMENT_NODE:\n\t\t\tcase DOCUMENT_NODE:\n\t\t\t\tisValid = true;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tisValid = false;\n\t\t}\n\n\t\tif (!isValid) {\n\t\t\tlet componentName = getDisplayName(vnode);\n\t\t\tthrow new Error(\n\t\t\t\t`Expected a valid HTML node as a second argument to render.\tReceived ${parentNode} instead: render(<${componentName} />, ${parentNode});`\n\t\t\t);\n\t\t}\n\n\t\tif (oldRoot) oldRoot(vnode, parentNode);\n\t};\n\n\toptions._diff = vnode => {\n\t\tlet { type } = vnode;\n\n\t\thooksAllowed = true;\n\n\t\tif (type === undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t'Undefined component passed to createElement()\\n\\n' +\n\t\t\t\t\t'You likely forgot to export your component or might have mixed up default and named imports' +\n\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t);\n\t\t} else if (type != null && typeof type == 'object') {\n\t\t\tif (type._children !== undefined && type._dom !== undefined) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Invalid type passed to createElement(): ${type}\\n\\n` +\n\t\t\t\t\t\t'Did you accidentally pass a JSX literal as JSX twice?\\n\\n' +\n\t\t\t\t\t\t` let My${getDisplayName(vnode)} = ${serializeVNode(type)};\\n` +\n\t\t\t\t\t\t` let vnode = ;\\n\\n` +\n\t\t\t\t\t\t'This usually happens when you export a JSX literal and not the component.' +\n\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tthrow new Error(\n\t\t\t\t'Invalid type passed to createElement(): ' +\n\t\t\t\t\t(Array.isArray(type) ? 'array' : type)\n\t\t\t);\n\t\t}\n\n\t\tif (\n\t\t\tvnode.ref !== undefined &&\n\t\t\ttypeof vnode.ref != 'function' &&\n\t\t\ttypeof vnode.ref != 'object' &&\n\t\t\t!('$$typeof' in vnode) // allow string refs when preact-compat is installed\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`Component's \"ref\" property should be a function, or an object created ` +\n\t\t\t\t\t`by createRef(), but got [${typeof vnode.ref}] instead\\n` +\n\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t);\n\t\t}\n\n\t\tif (typeof vnode.type == 'string') {\n\t\t\tfor (const key in vnode.props) {\n\t\t\t\tif (\n\t\t\t\t\tkey[0] === 'o' &&\n\t\t\t\t\tkey[1] === 'n' &&\n\t\t\t\t\ttypeof vnode.props[key] != 'function' &&\n\t\t\t\t\tvnode.props[key] != null\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Component's \"${key}\" property should be a function, ` +\n\t\t\t\t\t\t\t`but got [${typeof vnode.props[key]}] instead\\n` +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Check prop-types if available\n\t\tif (typeof vnode.type == 'function' && vnode.type.propTypes) {\n\t\t\tif (\n\t\t\t\tvnode.type.displayName === 'Lazy' &&\n\t\t\t\twarnedComponents &&\n\t\t\t\t!warnedComponents.lazyPropTypes.has(vnode.type)\n\t\t\t) {\n\t\t\t\tconst m =\n\t\t\t\t\t'PropTypes are not supported on lazy(). Use propTypes on the wrapped component itself. ';\n\t\t\t\ttry {\n\t\t\t\t\tconst lazyVNode = vnode.type();\n\t\t\t\t\twarnedComponents.lazyPropTypes.set(vnode.type, true);\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\tm + `Component wrapped in lazy() is ${getDisplayName(lazyVNode)}`\n\t\t\t\t\t);\n\t\t\t\t} catch (promise) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\tm + \"We will log the wrapped component's name once it is loaded.\"\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet values = vnode.props;\n\t\t\tif (vnode.type._forwarded) {\n\t\t\t\tvalues = assign({}, values);\n\t\t\t\tdelete values.ref;\n\t\t\t}\n\n\t\t\tcheckPropTypes(\n\t\t\t\tvnode.type.propTypes,\n\t\t\t\tvalues,\n\t\t\t\t'prop',\n\t\t\t\tgetDisplayName(vnode),\n\t\t\t\t() => getOwnerStack(vnode)\n\t\t\t);\n\t\t}\n\n\t\tif (oldBeforeDiff) oldBeforeDiff(vnode);\n\t};\n\n\tlet renderCount = 0;\n\tlet currentComponent;\n\toptions._render = vnode => {\n\t\tif (oldRender) {\n\t\t\toldRender(vnode);\n\t\t}\n\t\thooksAllowed = true;\n\n\t\tconst nextComponent = vnode._component;\n\t\tif (nextComponent === currentComponent) {\n\t\t\trenderCount++;\n\t\t} else {\n\t\t\trenderCount = 1;\n\t\t}\n\n\t\tif (renderCount >= 25) {\n\t\t\tthrow new Error(\n\t\t\t\t`Too many re-renders. This is limited to prevent an infinite loop ` +\n\t\t\t\t\t`which may lock up your browser. The component causing this is: ${getDisplayName(\n\t\t\t\t\t\tvnode\n\t\t\t\t\t)}`\n\t\t\t);\n\t\t}\n\n\t\tcurrentComponent = nextComponent;\n\t};\n\n\toptions._hook = (comp, index, type) => {\n\t\tif (!comp || !hooksAllowed) {\n\t\t\tthrow new Error('Hook can only be invoked from render methods.');\n\t\t}\n\n\t\tif (oldHook) oldHook(comp, index, type);\n\t};\n\n\t// Ideally we'd want to print a warning once per component, but we\n\t// don't have access to the vnode that triggered it here. As a\n\t// compromise and to avoid flooding the console with warnings we\n\t// print each deprecation warning only once.\n\tconst warn = (property, message) => ({\n\t\tget() {\n\t\t\tconst key = 'get' + property + message;\n\t\t\tif (deprecations && deprecations.indexOf(key) < 0) {\n\t\t\t\tdeprecations.push(key);\n\t\t\t\tconsole.warn(`getting vnode.${property} is deprecated, ${message}`);\n\t\t\t}\n\t\t},\n\t\tset() {\n\t\t\tconst key = 'set' + property + message;\n\t\t\tif (deprecations && deprecations.indexOf(key) < 0) {\n\t\t\t\tdeprecations.push(key);\n\t\t\t\tconsole.warn(`setting vnode.${property} is not allowed, ${message}`);\n\t\t\t}\n\t\t}\n\t});\n\n\tconst deprecatedAttributes = {\n\t\tnodeName: warn('nodeName', 'use vnode.type'),\n\t\tattributes: warn('attributes', 'use vnode.props'),\n\t\tchildren: warn('children', 'use vnode.props.children')\n\t};\n\n\tconst deprecatedProto = Object.create({}, deprecatedAttributes);\n\n\toptions.vnode = vnode => {\n\t\tconst props = vnode.props;\n\t\tif (\n\t\t\tvnode.type !== null &&\n\t\t\tprops != null &&\n\t\t\t('__source' in props || '__self' in props)\n\t\t) {\n\t\t\tconst newProps = (vnode.props = {});\n\t\t\tfor (let i in props) {\n\t\t\t\tconst v = props[i];\n\t\t\t\tif (i === '__source') vnode.__source = v;\n\t\t\t\telse if (i === '__self') vnode.__self = v;\n\t\t\t\telse newProps[i] = v;\n\t\t\t}\n\t\t}\n\n\t\t// eslint-disable-next-line\n\t\tvnode.__proto__ = deprecatedProto;\n\t\tif (oldVnode) oldVnode(vnode);\n\t};\n\n\toptions.diffed = vnode => {\n\t\tconst { type, _parent: parent } = vnode;\n\t\t// Check if the user passed plain objects as children. Note that we cannot\n\t\t// move this check into `options.vnode` because components can receive\n\t\t// children in any shape they want (e.g.\n\t\t// `{{ foo: 123, bar: \"abc\" }}`).\n\t\t// Putting this check in `options.diffed` ensures that\n\t\t// `vnode._children` is set and that we only validate the children\n\t\t// that were actually rendered.\n\t\tif (vnode._children) {\n\t\t\tvnode._children.forEach(child => {\n\t\t\t\tif (typeof child === 'object' && child && child.type === undefined) {\n\t\t\t\t\tconst keys = Object.keys(child).join(',');\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Objects are not valid as a child. Encountered an object with the keys {${keys}}.` +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tif (vnode._component === currentComponent) {\n\t\t\trenderCount = 0;\n\t\t}\n\n\t\tif (\n\t\t\ttypeof type === 'string' &&\n\t\t\t(isTableElement(type) ||\n\t\t\t\ttype === 'p' ||\n\t\t\t\ttype === 'a' ||\n\t\t\t\ttype === 'button')\n\t\t) {\n\t\t\t// Avoid false positives when Preact only partially rendered the\n\t\t\t// HTML tree. Whilst we attempt to include the outer DOM in our\n\t\t\t// validation, this wouldn't work on the server for\n\t\t\t// `preact-render-to-string`. There we'd otherwise flood the terminal\n\t\t\t// with false positives, which we'd like to avoid.\n\t\t\tlet domParentName = getClosestDomNodeParentName(parent);\n\t\t\tif (domParentName !== '' && isTableElement(type)) {\n\t\t\t\tif (\n\t\t\t\t\ttype === 'table' &&\n\t\t\t\t\t// Tables can be nested inside each other if it's inside a cell.\n\t\t\t\t\t// See https://developer.mozilla.org/en-US/docs/Learn/HTML/Tables/Advanced#nesting_tables\n\t\t\t\t\tdomParentName !== 'td' &&\n\t\t\t\t\tisTableElement(domParentName)\n\t\t\t\t) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t'Improper nesting of table. Your
    should not have a table-node parent.' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t} else if (\n\t\t\t\t\t(type === 'thead' || type === 'tfoot' || type === 'tbody') &&\n\t\t\t\t\tdomParentName !== 'table'\n\t\t\t\t) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t'Improper nesting of table. Your should have a
    parent.' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t} else if (\n\t\t\t\t\ttype === 'tr' &&\n\t\t\t\t\tdomParentName !== 'thead' &&\n\t\t\t\t\tdomParentName !== 'tfoot' &&\n\t\t\t\t\tdomParentName !== 'tbody'\n\t\t\t\t) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t'Improper nesting of table. Your should have a parent.' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t} else if (type === 'td' && domParentName !== 'tr') {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t'Improper nesting of table. Your parent.' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t} else if (type === 'th' && domParentName !== 'tr') {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t'Improper nesting of table. Your .' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} else if (type === 'p') {\n\t\t\t\tlet illegalDomChildrenTypes = getDomChildren(vnode).filter(childType =>\n\t\t\t\t\tILLEGAL_PARAGRAPH_CHILD_ELEMENTS.test(childType)\n\t\t\t\t);\n\t\t\t\tif (illegalDomChildrenTypes.length) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t'Improper nesting of paragraph. Your

    should not have ' +\n\t\t\t\t\t\t\tillegalDomChildrenTypes.join(', ') +\n\t\t\t\t\t\t\t' as child-elements.' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} else if (type === 'a' || type === 'button') {\n\t\t\t\tif (getDomChildren(vnode).indexOf(type) !== -1) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t`Improper nesting of interactive content. Your <${type}>` +\n\t\t\t\t\t\t\t` should not have other ${type === 'a' ? 'anchor' : 'button'}` +\n\t\t\t\t\t\t\t' tags as child-elements.' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\thooksAllowed = false;\n\n\t\tif (oldDiffed) oldDiffed(vnode);\n\n\t\tif (vnode._children != null) {\n\t\t\tconst keys = [];\n\t\t\tfor (let i = 0; i < vnode._children.length; i++) {\n\t\t\t\tconst child = vnode._children[i];\n\t\t\t\tif (!child || child.key == null) continue;\n\n\t\t\t\tconst key = child.key;\n\t\t\t\tif (keys.indexOf(key) !== -1) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t'Following component has two or more children with the ' +\n\t\t\t\t\t\t\t`same key attribute: \"${key}\". This may cause glitches and misbehavior ` +\n\t\t\t\t\t\t\t'in rendering process. Component: \\n\\n' +\n\t\t\t\t\t\t\tserializeVNode(vnode) +\n\t\t\t\t\t\t\t`\\n\\n${getOwnerStack(vnode)}`\n\t\t\t\t\t);\n\n\t\t\t\t\t// Break early to not spam the console\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tkeys.push(key);\n\t\t\t}\n\t\t}\n\n\t\tif (vnode._component != null && vnode._component.__hooks != null) {\n\t\t\t// Validate that none of the hooks in this component contain arguments that are NaN.\n\t\t\t// This is a common mistake that can be hard to debug, so we want to catch it early.\n\t\t\tconst hooks = vnode._component.__hooks._list;\n\t\t\tif (hooks) {\n\t\t\t\tfor (let i = 0; i < hooks.length; i += 1) {\n\t\t\t\t\tconst hook = hooks[i];\n\t\t\t\t\tif (hook._args) {\n\t\t\t\t\t\tfor (let j = 0; j < hook._args.length; j++) {\n\t\t\t\t\t\t\tconst arg = hook._args[j];\n\t\t\t\t\t\t\tif (isNaN(arg)) {\n\t\t\t\t\t\t\t\tconst componentName = getDisplayName(vnode);\n\t\t\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t\t\t`Invalid argument passed to hook. Hooks should not be called with NaN in the dependency array. Hook index ${i} in component ${componentName} was called with NaN.`\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n}\n\nconst setState = Component.prototype.setState;\nComponent.prototype.setState = function (update, callback) {\n\tif (this._vnode == null) {\n\t\t// `this._vnode` will be `null` during componentWillMount. But it\n\t\t// is perfectly valid to call `setState` during cWM. So we\n\t\t// need an additional check to verify that we are dealing with a\n\t\t// call inside constructor.\n\t\tif (this.state == null) {\n\t\t\tconsole.warn(\n\t\t\t\t`Calling \"this.setState\" inside the constructor of a component is a ` +\n\t\t\t\t\t`no-op and might be a bug in your application. Instead, set ` +\n\t\t\t\t\t`\"this.state = {}\" directly.\\n\\n${getOwnerStack(getCurrentVNode())}`\n\t\t\t);\n\t\t}\n\t}\n\n\treturn setState.call(this, update, callback);\n};\n\nfunction isTableElement(type) {\n\treturn (\n\t\ttype === 'table' ||\n\t\ttype === 'tfoot' ||\n\t\ttype === 'tbody' ||\n\t\ttype === 'thead' ||\n\t\ttype === 'td' ||\n\t\ttype === 'tr' ||\n\t\ttype === 'th'\n\t);\n}\n\nconst ILLEGAL_PARAGRAPH_CHILD_ELEMENTS =\n\t/^(address|article|aside|blockquote|details|div|dl|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hgroup|hr|main|menu|nav|ol|p|pre|search|section|table|ul)$/;\n\nconst forceUpdate = Component.prototype.forceUpdate;\nComponent.prototype.forceUpdate = function (callback) {\n\tif (this._vnode == null) {\n\t\tconsole.warn(\n\t\t\t`Calling \"this.forceUpdate\" inside the constructor of a component is a ` +\n\t\t\t\t`no-op and might be a bug in your application.\\n\\n${getOwnerStack(\n\t\t\t\t\tgetCurrentVNode()\n\t\t\t\t)}`\n\t\t);\n\t} else if (this._parentDom == null) {\n\t\tconsole.warn(\n\t\t\t`Can't call \"this.forceUpdate\" on an unmounted component. This is a no-op, ` +\n\t\t\t\t`but it indicates a memory leak in your application. To fix, cancel all ` +\n\t\t\t\t`subscriptions and asynchronous tasks in the componentWillUnmount method.` +\n\t\t\t\t`\\n\\n${getOwnerStack(this._vnode)}`\n\t\t);\n\t}\n\treturn forceUpdate.call(this, callback);\n};\n\n/**\n * Serialize a vnode tree to a string\n * @param {import('./internal').VNode} vnode\n * @returns {string}\n */\nexport function serializeVNode(vnode) {\n\tlet { props } = vnode;\n\tlet name = getDisplayName(vnode);\n\n\tlet attrs = '';\n\tfor (let prop in props) {\n\t\tif (props.hasOwnProperty(prop) && prop !== 'children') {\n\t\t\tlet value = props[prop];\n\n\t\t\t// If it is an object but doesn't have toString(), use Object.toString\n\t\t\tif (typeof value == 'function') {\n\t\t\t\tvalue = `function ${value.displayName || value.name}() {}`;\n\t\t\t}\n\n\t\t\tvalue =\n\t\t\t\tObject(value) === value && !value.toString\n\t\t\t\t\t? Object.prototype.toString.call(value)\n\t\t\t\t\t: value + '';\n\n\t\t\tattrs += ` ${prop}=${JSON.stringify(value)}`;\n\t\t}\n\t}\n\n\tlet children = props.children;\n\treturn `<${name}${attrs}${\n\t\tchildren && children.length ? '>..' : ' />'\n\t}`;\n}\n\noptions._hydrationMismatch = (newVNode, excessDomChildren) => {\n\tconst { type } = newVNode;\n\tconst availableTypes = excessDomChildren\n\t\t.map(child => child && child.localName)\n\t\t.filter(Boolean);\n\tconsole.error(\n\t\t`Expected a DOM node of type \"${type}\" but found \"${availableTypes.join(', ')}\" as available DOM-node(s), this is caused by the SSR'd HTML containing different DOM-nodes compared to the hydrated one.\\n\\n${getOwnerStack(newVNode)}`\n\t);\n};\n","export const ELEMENT_NODE = 1;\nexport const DOCUMENT_NODE = 9;\nexport const DOCUMENT_FRAGMENT_NODE = 11;\n","/**\n * Assign properties from `props` to `obj`\n * @template O, P The obj and props types\n * @param {O} obj The object to copy properties to\n * @param {P} props The object to copy properties from\n * @returns {O & P}\n */\nexport function assign(obj, props) {\n\tfor (let i in props) obj[i] = props[i];\n\treturn /** @type {O & P} */ (obj);\n}\n\nexport function isNaN(value) {\n\treturn value !== value;\n}\n","import { initDebug } from './debug';\nimport 'preact/devtools';\n\ninitDebug();\n\nexport { resetPropWarnings } from './check-props';\n\nexport {\n\tgetCurrentVNode,\n\tgetDisplayName,\n\tgetOwnerStack\n} from './component-stack';\n"],"names":["loggedTypeFailures","getDisplayName","vnode","type","Fragment","displayName","name","renderStack","ownerStack","getCurrentVNode","length","showJsxSourcePluginWarning","isPossibleOwner","getOwnerStack","stack","next","__o","push","reduce","acc","owner","source","__source","fileName","lineNumber","console","warn","isWeakMapSupported","WeakMap","getDomChildren","domChildren","__k","forEach","child","apply","getClosestDomNodeParentName","parent","__","__e","parentNode","localName","setState","Component","prototype","isTableElement","update","callback","this","__v","state","call","ILLEGAL_PARAGRAPH_CHILD_ELEMENTS","forceUpdate","serializeVNode","props","attrs","prop","hasOwnProperty","value","Object","toString","JSON","stringify","children","__P","options","__m","newVNode","excessDomChildren","availableTypes","map","filter","Boolean","error","join","oldDiff","__b","oldDiffed","diffed","oldRoot","oldVNode","oldRender","__r","pop","setupComponentStack","hooksAllowed","oldBeforeDiff","oldVnode","oldCatchError","oldHook","__h","warnedComponents","useEffect","useLayoutEffect","lazyPropTypes","deprecations","errorInfo","__c","then","promise","Error","componentStack","setTimeout","e","isValid","nodeType","componentName","undefined","Array","isArray","ref","key","propTypes","has","m","lazyVNode","set","values","__f","obj","i","assign","typeSpecs","location","getStack","keys","typeSpecName","message","checkPropTypes","currentComponent","renderCount","nextComponent","comp","index","property","get","indexOf","deprecatedAttributes","nodeName","attributes","deprecatedProto","create","newProps","v","__self","__proto__","domParentName","illegalDomChildrenTypes","childType","test","__H","hooks","hook","j","initDebug"],"mappings":"wTAAA,IAEIA,EAAqB,CAAA,ECMlB,SAASC,EAAeC,GAC9B,OAAIA,EAAMC,OAASC,EAAAA,SACX,WACwB,mBAAdF,EAAMC,KAChBD,EAAMC,KAAKE,aAAeH,EAAMC,KAAKG,KACb,iBAAdJ,EAAMC,KAChBD,EAAMC,KAGP,OACR,CAMA,IAAII,EAAc,GAoBdC,EAAa,YAMDC,IACf,OAAOF,EAAYG,OAAS,EAAIH,EAAYA,EAAYG,OAAS,GAAK,IACvE,CAQA,IAAIC,GAA6B,EAMjC,SAASC,EAAgBV,GACxB,MAA4B,mBAAdA,EAAMC,MAAsBD,EAAMC,MAAQC,EAAAA,QACzD,CAOO,SAASS,EAAcX,GAG7B,IAFA,IAAMY,EAAQ,CAACZ,GACXa,EAAOb,EACW,MAAfa,EAAIC,KACVF,EAAMG,KAAKF,EAAIC,KACfD,EAAOA,EAAIC,IAGZ,OAAOF,EAAMI,OAAO,SAACC,EAAKC,GACzBD,GAAelB,QAAAA,EAAemB,GAE9B,IAAMC,EAASD,EAAME,SAUrB,OATID,EACHF,GAAeE,QAAAA,EAAOE,SAAYF,IAAAA,EAAOG,WAC1C,IAAWb,GACVc,QAAQC,KACP,kLAGFf,GAA6B,EAErBQ,EAAO,IAChB,EAAG,GACJ,CCnFA,IAAMQ,EAAuC,mBAAXC,QAMlC,SAASC,EAAe3B,GACvB,IAAI4B,EAAc,GAElB,OAAK5B,EAAK6B,KAEV7B,EAAK6B,IAAWC,QAAQ,SAAAC,GACnBA,GAA+B,mBAAfA,EAAM9B,KACzB2B,EAAYb,KAAKiB,MAAMJ,EAAaD,EAAeI,IACzCA,GAA+B,iBAAfA,EAAM9B,MAChC2B,EAAYb,KAAKgB,EAAM9B,KAEzB,GAEO2B,GAVsBA,CAW9B,CAMA,SAASK,EAA4BC,GACpC,OAAKA,EACqB,mBAAfA,EAAOjC,KACK,MAAlBiC,EAAMC,GACU,MAAfD,EAAME,KAA2C,MAA1BF,EAAME,IAAMC,WAC/BH,EAAME,IAAMC,WAAWC,UAExB,GAEDL,EAA4BC,EAAMC,IAEZD,EAAOjC,KAVjB,EAWrB,CA2bA,IAAMsC,EAAWC,EAASA,UAACC,UAAUF,SAmBrC,SAASG,EAAezC,GACvB,MACU,UAATA,GACS,UAATA,GACS,UAATA,GACS,UAATA,GACS,OAATA,GACS,OAATA,GACS,OAATA,CAEF,CA5BAuC,EAAAA,UAAUC,UAAUF,SAAW,SAAUI,EAAQC,GAehD,OAdmB,MAAfC,KAAIC,KAKW,MAAdD,KAAKE,OACRxB,QAAQC,KACP,gKAEmCb,EAAcJ,MAK7CgC,EAASS,KAAKH,KAAMF,EAAQC,EACpC,EAcA,IAAMK,EACL,+KAEKC,EAAcV,EAAAA,UAAUC,UAAUS,YAyBjC,SAASC,EAAenD,GAC9B,IAAMoD,EAAUpD,EAAVoD,MACFhD,EAAOL,EAAeC,GAEtBqD,EAAQ,GACZ,IAAK,IAAIC,KAAQF,EAChB,GAAIA,EAAMG,eAAeD,IAAkB,aAATA,EAAqB,CACtD,IAAIE,EAAQJ,EAAME,GAGE,mBAATE,IACVA,EAAK,aAAeA,EAAMrD,aAAeqD,EAAMpD,MAAI,SAGpDoD,EACCC,OAAOD,KAAWA,GAAUA,EAAME,SAE/BF,EAAQ,GADRC,OAAOhB,UAAUiB,SAASV,KAAKQ,GAGnCH,OAAaC,EAAI,IAAIK,KAAKC,UAAUJ,EACrC,CAGD,IAAIK,EAAWT,EAAMS,SACrB,MAAA,IAAWzD,EAAOiD,GACjBQ,GAAYA,EAASrD,OAAS,QAAUJ,EAAO,IAAM,MAEvD,CAnDAoC,EAASA,UAACC,UAAUS,YAAc,SAAUN,GAgB3C,OAfmB,MAAfC,KAAIC,IACPvB,QAAQC,KACP,0HACqDb,EACnDJ,MAG0B,MAAnBsC,KAAIiB,KACdvC,QAAQC,KACP,iOAGQb,EAAckC,KAAIC,MAGrBI,EAAYF,KAAKH,KAAMD,EAC/B,EAoCAmB,EAAOA,QAAAC,IAAsB,SAACC,EAAUC,GACvC,IAAQjE,EAASgE,EAAThE,KACFkE,EAAiBD,EACrBE,IAAI,SAAArC,GAAK,OAAIA,GAASA,EAAMO,SAAS,GACrC+B,OAAOC,SACT/C,QAAQgD,MACyBtE,gCAAAA,EAAoBkE,gBAAAA,EAAeK,KAAK,uIAAqI7D,EAAcsD,GAE7N,EAzhBO,YDkDA,WACN,IAAIQ,EAAUV,EAAAA,QAAOW,IACjBC,EAAYZ,EAAOA,QAACa,OACpBC,EAAUd,EAAOA,QAAA5B,GACjB2C,EAAWf,EAAOA,QAAC/D,MACnB+E,EAAYhB,EAAOA,QAAAiB,IAEvBjB,EAAAA,QAAQa,OAAS,SAAA5E,GACZU,EAAgBV,IACnBM,EAAW2E,MAEZ5E,EAAY4E,MACRN,GAAWA,EAAU3E,EAC1B,EAEA+D,EAAOA,QAAAW,IAAS,SAAA1E,GACXU,EAAgBV,IACnBK,EAAYU,KAAKf,GAEdyE,GAASA,EAAQzE,EACtB,EAEA+D,UAAO5B,GAAS,SAACnC,EAAOkC,GACvB5B,EAAa,GACTuE,GAASA,EAAQ7E,EAAOkC,EAC7B,EAEA6B,EAAAA,QAAQ/D,MAAQ,SAAAA,GACfA,EAAKc,IACJR,EAAWE,OAAS,EAAIF,EAAWA,EAAWE,OAAS,GAAK,KACzDsE,GAAUA,EAAS9E,EACxB,EAEA+D,EAAOA,QAAAiB,IAAW,SAAAhF,GACbU,EAAgBV,IACnBM,EAAWS,KAAKf,GAGb+E,GAAWA,EAAU/E,EAC1B,CACD,CCzFCkF,GAEA,IAAIC,GAAe,EAGfC,EAAgBrB,EAAAA,QAAOW,IACvBC,EAAYZ,EAAOA,QAACa,OACpBS,EAAWtB,EAAOA,QAAC/D,MACnB+E,EAAYhB,EAAOA,QAAAiB,IACnBM,EAAgBvB,EAAOA,QAAA3B,IACvByC,EAAUd,EAAOA,QAAA5B,GACjBoD,EAAUxB,EAAOA,QAAAyB,IACfC,EAAoBhE,EAEvB,CACAiE,UAAW,IAAIhE,QACfiE,gBAAiB,IAAIjE,QACrBkE,cAAe,IAAIlE,SAJnB,KAMGmE,EAAe,GAErB9B,EAAAA,QAAO3B,IAAe,SAACmC,EAAOvE,EAAO8E,EAAUgB,GAE9C,GADgB9F,GAASA,EAAK+F,KACQ,mBAAdxB,EAAMyB,KAAoB,CACjD,IAAMC,EAAU1B,EAChBA,EAAQ,IAAI2B,MAAK,iDACiCnG,EAAeC,IAIjE,IADA,IAAIkC,EAASlC,EACNkC,EAAQA,EAASA,EAAMC,GAC7B,GAAID,EAAM6D,KAAe7D,EAAM6D,IAAAA,IAA8B,CAC5DxB,EAAQ0B,EACR,KACD,CAKD,GAAI1B,aAAiB2B,MACpB,MAAM3B,CAER,CAEA,KACCuB,EAAYA,GAAa,IACfK,eAAiBxF,EAAcX,GACzCsF,EAAcf,EAAOvE,EAAO8E,EAAUgB,GAKb,mBAAdvB,EAAMyB,MAChBI,WAAW,WACV,MAAM7B,CACP,EAIF,CAFE,MAAO8B,GACR,MAAMA,CACP,CACD,EAEAtC,EAAOA,QAAA5B,GAAS,SAACnC,EAAOqC,GACvB,IAAKA,EACJ,UAAU6D,MACT,uIAKF,IAAII,EACJ,OAAQjE,EAAWkE,UAClB,KChIyB,EDiIzB,KC/HmC,GDgInC,KCjI0B,EDkIzBD,GAAU,EACV,MACD,QACCA,GAAU,EAGZ,IAAKA,EAAS,CACb,IAAIE,EAAgBzG,EAAeC,GACnC,MAAM,IAAIkG,8EAC8D7D,EAAU,qBAAqBmE,EAAa,QAAQnE,EAC5H,KACD,CAEIwC,GAASA,EAAQ7E,EAAOqC,EAC7B,EAEA0B,EAAOA,QAAAW,IAAS,SAAA1E,GACf,IAAMC,EAASD,EAATC,KAIN,GAFAkF,GAAe,OAEFsB,IAATxG,EACH,MAAU,IAAAiG,MACT,+IAEC/C,EAAenD,UACRW,EAAcX,IAEjB,GAAY,MAARC,GAA+B,iBAARA,EAAkB,CACnD,QAAuBwG,IAAnBxG,EAAI4B,UAA0C4E,IAAdxG,EAAImC,IACvC,MAAM,IAAI8D,MACT,2CAA2CjG,EAA3C,wEAEYF,EAAeC,GAAYmD,MAAAA,EAAelD,GAFtD,uBAGqBF,EAAeC,GAHpC,wFAKQW,EAAcX,IAIxB,MAAM,IAAIkG,MACT,4CACEQ,MAAMC,QAAQ1G,GAAQ,QAAUA,GAEpC,CAEA,QACewG,IAAdzG,EAAM4G,KACc,mBAAb5G,EAAM4G,KACO,iBAAb5G,EAAM4G,OACX,aAAc5G,GAEhB,MAAU,IAAAkG,MACT,0GACoClG,EAAM4G,IAAG,cAC5CzD,EAAenD,GACRW,OAAAA,EAAcX,IAIxB,GAAyB,iBAAdA,EAAMC,KAChB,IAAK,IAAM4G,KAAO7G,EAAMoD,MACvB,GACY,MAAXyD,EAAI,IACO,MAAXA,EAAI,IACuB,mBAApB7G,EAAMoD,MAAMyD,IACC,MAApB7G,EAAMoD,MAAMyD,GAEZ,MAAU,IAAAX,MACT,iBAAgBW,EAAhB,oDACoB7G,EAAMoD,MAAMyD,GAAiB,cAChD1D,EAAenD,GAAM,OACdW,EAAcX,IAO1B,GAAyB,mBAAdA,EAAMC,MAAsBD,EAAMC,KAAK6G,UAAW,CAC5D,GAC4B,SAA3B9G,EAAMC,KAAKE,aACXsF,IACCA,EAAiBG,cAAcmB,IAAI/G,EAAMC,MACzC,CACD,IAAM+G,EACL,yFACD,IACC,IAAMC,EAAYjH,EAAMC,OACxBwF,EAAiBG,cAAcsB,IAAIlH,EAAMC,MAAM,GAC/CsB,QAAQC,KACPwF,oCAAsCjH,EAAekH,GAMvD,CAJE,MAAOhB,GACR1E,QAAQC,KACPwF,EAAI,8DAEN,CACD,CAEA,IAAIG,EAASnH,EAAMoD,MACfpD,EAAMC,KAAImH,YACbD,WElOmBE,EAAKjE,GAC3B,IAAK,IAAIkE,KAAKlE,EAAOiE,EAAIC,GAAKlE,EAAMkE,GACpC,OAA6BD,CAC9B,CF+NaE,CAAO,CAAE,EAAEJ,IACNP,IFnNX,SACNY,EACAL,EACAM,EACAjB,EACAkB,GAEAjE,OAAOkE,KAAKH,GAAW1F,QAAQ,SAAA8F,GAC9B,IAAIrD,EACJ,IACCA,EAAQiD,EAAUI,GACjBT,EACAS,EACApB,EE4MA,OF1MA,KAtCyB,+CA2C3B,CAFE,MAAOH,GACR9B,EAAQ8B,CACT,CACI9B,KAAWA,EAAMsD,WAAW/H,KAC/BA,EAAmByE,EAAMsD,UAAW,EACpCtG,QAAQgD,2BACqBA,EAAMsD,SAChCH,GAAQ,KAASA,KAAiB,KAIvC,EACD,CEwLGI,CACC9H,EAAMC,KAAK6G,UACXK,EACA,EACApH,EAAeC,GACf,WAAM,OAAAW,EAAcX,EAAM,EAE5B,CAEIoF,GAAeA,EAAcpF,EAClC,EAEA,IACI+H,EADAC,EAAc,EAElBjE,EAAOA,QAAAiB,IAAW,SAAAhF,GACb+E,GACHA,EAAU/E,GAEXmF,GAAe,EAEf,IAAM8C,EAAgBjI,EAAK+F,IAO3B,GANIkC,IAAkBF,EACrBC,IAEAA,EAAc,EAGXA,GAAe,GAClB,MAAM,IAAI9B,MACT,mIACmEnG,EACjEC,IAKJ+H,EAAmBE,CACpB,EAEAlE,UAAOyB,IAAS,SAAC0C,EAAMC,EAAOlI,GAC7B,IAAKiI,IAAS/C,EACb,MAAU,IAAAe,MAAM,iDAGbX,GAASA,EAAQ2C,EAAMC,EAAOlI,EACnC,EAMA,IAAMuB,EAAO,SAAC4G,EAAUP,SAAa,CACpCQ,IAAA,WACC,IAAMxB,EAAM,MAAQuB,EAAWP,EAC3BhC,GAAgBA,EAAayC,QAAQzB,GAAO,IAC/ChB,EAAa9E,KAAK8F,GAClBtF,QAAQC,KAAsB4G,iBAAAA,qBAA2BP,GAE3D,EACAX,IAAG,WACF,IAAML,EAAM,MAAQuB,EAAWP,EAC3BhC,GAAgBA,EAAayC,QAAQzB,GAAO,IAC/ChB,EAAa9E,KAAK8F,GAClBtF,QAAQC,KAAI,iBAAkB4G,EAAQ,oBAAoBP,GAE5D,EACA,EAEKU,EAAuB,CAC5BC,SAAUhH,EAAK,WAAY,kBAC3BiH,WAAYjH,EAAK,aAAc,mBAC/BqC,SAAUrC,EAAK,WAAY,6BAGtBkH,EAAkBjF,OAAOkF,OAAO,CAAE,EAAEJ,GAE1CxE,EAAAA,QAAQ/D,MAAQ,SAAAA,GACf,IAAMoD,EAAQpD,EAAMoD,MACpB,GACgB,OAAfpD,EAAMC,MACG,MAATmD,IACC,aAAcA,GAAS,WAAYA,GACnC,CACD,IAAMwF,EAAY5I,EAAMoD,MAAQ,CAAA,EAChC,IAAK,IAAIkE,KAAKlE,EAAO,CACpB,IAAMyF,EAAIzF,EAAMkE,GACN,aAANA,EAAkBtH,EAAMoB,SAAWyH,EACxB,WAANvB,EAAgBtH,EAAM8I,OAASD,EACnCD,EAAStB,GAAKuB,CACpB,CACD,CAGA7I,EAAM+I,UAAYL,EACdrD,GAAUA,EAASrF,EACxB,EAEA+D,EAAAA,QAAQa,OAAS,SAAA5E,GAChB,IEnUoBwD,EFmUZvD,EAA0BD,EAA1BC,KAAeiC,EAAWlC,EAAKmC,GAwBvC,GAhBInC,EAAK6B,KACR7B,EAAK6B,IAAWC,QAAQ,SAAAC,GACvB,GAAqB,iBAAVA,GAAsBA,QAAwB0E,IAAf1E,EAAM9B,KAAoB,CACnE,IAAM0H,EAAOlE,OAAOkE,KAAK5F,GAAOyC,KAAK,KACrC,MAAM,IAAI0B,MACT,0EAA0EyB,EAA1E,SACQhH,EAAcX,GAExB,CACD,GAGGA,EAAK+F,MAAgBgC,IACxBC,EAAc,GAIE,iBAAT/H,IACNyC,EAAezC,IACN,MAATA,GACS,MAATA,GACS,WAATA,GACA,CAMD,IAAI+I,EAAgB/G,EAA4BC,GAChD,GAAsB,KAAlB8G,GAAwBtG,EAAezC,GAEhC,UAATA,GAGkB,OAAlB+I,GACAtG,EAAesG,GAEfzH,QAAQgD,MACP,+EACCpB,EAAenD,UACRW,EAAcX,IAGb,UAATC,GAA6B,UAATA,GAA6B,UAATA,GACvB,UAAlB+I,EAQS,OAAT/I,GACkB,UAAlB+I,GACkB,UAAlBA,GACkB,UAAlBA,EAEAzH,QAAQgD,MACP,iFACCpB,EAAenD,GAAM,OACdW,EAAcX,IAEJ,OAATC,GAAmC,OAAlB+I,EAC3BzH,QAAQgD,MACP,kEACCpB,EAAenD,GAAM,OACdW,EAAcX,IAEJ,OAATC,GAAmC,OAAlB+I,GAC3BzH,QAAQgD,MACP,2DACCpB,EAAenD,GACRW,OAAAA,EAAcX,IA1BvBuB,QAAQgD,MACP,oFACCpB,EAAenD,GAAM,OACdW,EAAcX,SA0BlB,GAAa,MAATC,EAAc,CACxB,IAAIgJ,EAA0BtH,EAAe3B,GAAOqE,OAAO,SAAA6E,GAC1D,OAAAjG,EAAiCkG,KAAKD,EAAU,GAE7CD,EAAwBzI,QAC3Be,QAAQgD,MACP,2DACC0E,EAAwBzE,KAAK,MAC7B,sBACArB,EAAenD,GACRW,OAAAA,EAAcX,GAGzB,KAAoB,MAATC,GAAyB,WAATA,IACmB,IAAzC0B,EAAe3B,GAAOsI,QAAQrI,IACjCsB,QAAQgD,MACP,kDAAkDtE,EAAlD,4BACoC,MAATA,EAAe,SAAW,UACpD,2BACAkD,EAAenD,GAAM,OACdW,EAAcX,GAI1B,CAMA,GAJAmF,GAAe,EAEXR,GAAWA,EAAU3E,GAEF,MAAnBA,EAAK6B,IAER,IADA,IAAM8F,EAAO,GACJL,EAAI,EAAGA,EAAItH,EAAK6B,IAAWrB,OAAQ8G,IAAK,CAChD,IAAMvF,EAAQ/B,EAAK6B,IAAWyF,GAC9B,GAAKvF,GAAsB,MAAbA,EAAM8E,IAApB,CAEA,IAAMA,EAAM9E,EAAM8E,IAClB,IAA2B,IAAvBc,EAAKW,QAAQzB,GAAa,CAC7BtF,QAAQgD,MACP,8EACyBsC,EADzB,mFAGC1D,EAAenD,GACRW,OAAAA,EAAcX,IAIvB,KACD,CAEA2H,EAAK5G,KAAK8F,GACX,CAGD,GAAwB,MAApB7G,EAAK+F,KAAmD,MAA5B/F,EAAK+F,IAAAqD,IAA6B,CAGjE,IAAMC,EAAQrJ,EAAK+F,IAAAqD,IAAAjH,GACnB,GAAIkH,EACH,IAAK,IAAI/B,EAAI,EAAGA,EAAI+B,EAAM7I,OAAQ8G,GAAK,EAAG,CACzC,IAAMgC,EAAOD,EAAM/B,GACnB,GAAIgC,EAAIF,IACP,IAAK,IAAIG,EAAI,EAAGA,EAAID,EAAIF,IAAO5I,OAAQ+I,IAEtC,IEtde/F,EFqdH8F,EAAIF,IAAOG,KEpdZ/F,EFqdK,CACf,IAAMgD,EAAgBzG,EAAeC,GACrCuB,QAAQC,KAAI,4GACiG8F,EAAC,iBAAiBd,EAC/H,wBACD,CAGH,CAEF,CACD,CACD,CG3eAgD,gFLIO,WACN1J,EAAqB,CAAA,CACtB"} \ No newline at end of file diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/debug/package.json b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/package.json new file mode 100644 index 0000000000000..836b4b49f71dc --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/package.json @@ -0,0 +1,27 @@ +{ + "name": "preact-debug", + "amdName": "preactDebug", + "version": "1.0.0", + "private": true, + "description": "Preact extensions for development", + "main": "dist/debug.js", + "module": "dist/debug.module.js", + "umd:main": "dist/debug.umd.js", + "source": "src/index.js", + "license": "MIT", + "mangle": { + "regex": "^(?!_renderer)^_" + }, + "peerDependencies": { + "preact": "^10.0.0" + }, + "exports": { + ".": { + "types": "./src/index.d.ts", + "browser": "./dist/debug.module.js", + "umd": "./dist/debug.umd.js", + "import": "./dist/debug.mjs", + "require": "./dist/debug.js" + } + } +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/check-props.js b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/check-props.js new file mode 100644 index 0000000000000..41ff74737040c --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/check-props.js @@ -0,0 +1,54 @@ +const ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; + +let loggedTypeFailures = {}; + +/** + * Reset the history of which prop type warnings have been logged. + */ +export function resetPropWarnings() { + loggedTypeFailures = {}; +} + +/** + * Assert that the values match with the type specs. + * Error messages are memorized and will only be shown once. + * + * Adapted from https://github.com/facebook/prop-types/blob/master/checkPropTypes.js + * + * @param {object} typeSpecs Map of name to a ReactPropType + * @param {object} values Runtime values that need to be type-checked + * @param {string} location e.g. "prop", "context", "child context" + * @param {string} componentName Name of the component for error messages. + * @param {?Function} getStack Returns the component stack. + */ +export function checkPropTypes( + typeSpecs, + values, + location, + componentName, + getStack +) { + Object.keys(typeSpecs).forEach(typeSpecName => { + let error; + try { + error = typeSpecs[typeSpecName]( + values, + typeSpecName, + componentName, + location, + null, + ReactPropTypesSecret + ); + } catch (e) { + error = e; + } + if (error && !(error.message in loggedTypeFailures)) { + loggedTypeFailures[error.message] = true; + console.error( + `Failed ${location} type: ${error.message}${ + (getStack && `\n${getStack()}`) || '' + }` + ); + } + }); +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/component-stack.js b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/component-stack.js new file mode 100644 index 0000000000000..52a1801273154 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/component-stack.js @@ -0,0 +1,146 @@ +import { options, Fragment } from 'preact'; + +/** + * Get human readable name of the component/dom node + * @param {import('./internal').VNode} vnode + * @param {import('./internal').VNode} vnode + * @returns {string} + */ +export function getDisplayName(vnode) { + if (vnode.type === Fragment) { + return 'Fragment'; + } else if (typeof vnode.type == 'function') { + return vnode.type.displayName || vnode.type.name; + } else if (typeof vnode.type == 'string') { + return vnode.type; + } + + return '#text'; +} + +/** + * Used to keep track of the currently rendered `vnode` and print it + * in debug messages. + */ +let renderStack = []; + +/** + * Keep track of the current owners. An owner describes a component + * which was responsible to render a specific `vnode`. This exclude + * children that are passed via `props.children`, because they belong + * to the parent owner. + * + * ```jsx + * const Foo = props =>

    {props.children}
    // div's owner is Foo + * const Bar = props => { + * return ( + * // Foo's owner is Bar, span's owner is Bar + * ) + * } + * ``` + * + * Note: A `vnode` may be hoisted to the root scope due to compiler + * optimiztions. In these cases the `_owner` will be different. + */ +let ownerStack = []; + +/** + * Get the currently rendered `vnode` + * @returns {import('./internal').VNode | null} + */ +export function getCurrentVNode() { + return renderStack.length > 0 ? renderStack[renderStack.length - 1] : null; +} + +/** + * If the user doesn't have `@babel/plugin-transform-react-jsx-source` + * somewhere in his tool chain we can't print the filename and source + * location of a component. In that case we just omit that, but we'll + * print a helpful message to the console, notifying the user of it. + */ +let showJsxSourcePluginWarning = true; + +/** + * Check if a `vnode` is a possible owner. + * @param {import('./internal').VNode} vnode + */ +function isPossibleOwner(vnode) { + return typeof vnode.type == 'function' && vnode.type != Fragment; +} + +/** + * Return the component stack that was captured up to this point. + * @param {import('./internal').VNode} vnode + * @returns {string} + */ +export function getOwnerStack(vnode) { + const stack = [vnode]; + let next = vnode; + while (next._owner != null) { + stack.push(next._owner); + next = next._owner; + } + + return stack.reduce((acc, owner) => { + acc += ` in ${getDisplayName(owner)}`; + + const source = owner.__source; + if (source) { + acc += ` (at ${source.fileName}:${source.lineNumber})`; + } else if (showJsxSourcePluginWarning) { + console.warn( + 'Add @babel/plugin-transform-react-jsx-source to get a more detailed component stack. Note that you should not add it to production builds of your App for bundle size reasons.' + ); + } + showJsxSourcePluginWarning = false; + + return (acc += '\n'); + }, ''); +} + +/** + * Setup code to capture the component trace while rendering. Note that + * we cannot simply traverse `vnode._parent` upwards, because we have some + * debug messages for `this.setState` where the `vnode` is `undefined`. + */ +export function setupComponentStack() { + let oldDiff = options._diff; + let oldDiffed = options.diffed; + let oldRoot = options._root; + let oldVNode = options.vnode; + let oldRender = options._render; + + options.diffed = vnode => { + if (isPossibleOwner(vnode)) { + ownerStack.pop(); + } + renderStack.pop(); + if (oldDiffed) oldDiffed(vnode); + }; + + options._diff = vnode => { + if (isPossibleOwner(vnode)) { + renderStack.push(vnode); + } + if (oldDiff) oldDiff(vnode); + }; + + options._root = (vnode, parent) => { + ownerStack = []; + if (oldRoot) oldRoot(vnode, parent); + }; + + options.vnode = vnode => { + vnode._owner = + ownerStack.length > 0 ? ownerStack[ownerStack.length - 1] : null; + if (oldVNode) oldVNode(vnode); + }; + + options._render = vnode => { + if (isPossibleOwner(vnode)) { + ownerStack.push(vnode); + } + + if (oldRender) oldRender(vnode); + }; +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/constants.js b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/constants.js new file mode 100644 index 0000000000000..e15b547a197ec --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/constants.js @@ -0,0 +1,3 @@ +export const ELEMENT_NODE = 1; +export const DOCUMENT_NODE = 9; +export const DOCUMENT_FRAGMENT_NODE = 11; diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/debug.js b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/debug.js new file mode 100644 index 0000000000000..8da063130fcb1 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/debug.js @@ -0,0 +1,593 @@ +import { checkPropTypes } from './check-props'; +import { options, Component } from 'preact'; +import { + ELEMENT_NODE, + DOCUMENT_NODE, + DOCUMENT_FRAGMENT_NODE +} from './constants'; +import { + getOwnerStack, + setupComponentStack, + getCurrentVNode, + getDisplayName +} from './component-stack'; +import { assign, isNaN } from './util'; + +const isWeakMapSupported = typeof WeakMap == 'function'; + +/** + * @param {import('./internal').VNode} vnode + * @returns {Array} + */ +function getDomChildren(vnode) { + let domChildren = []; + + if (!vnode._children) return domChildren; + + vnode._children.forEach(child => { + if (child && typeof child.type === 'function') { + domChildren.push.apply(domChildren, getDomChildren(child)); + } else if (child && typeof child.type === 'string') { + domChildren.push(child.type); + } + }); + + return domChildren; +} + +/** + * @param {import('./internal').VNode} parent + * @returns {string} + */ +function getClosestDomNodeParentName(parent) { + if (!parent) return ''; + if (typeof parent.type == 'function') { + if (parent._parent == null) { + if (parent._dom != null && parent._dom.parentNode != null) { + return parent._dom.parentNode.localName; + } + return ''; + } + return getClosestDomNodeParentName(parent._parent); + } + return /** @type {string} */ (parent.type); +} + +export function initDebug() { + setupComponentStack(); + + let hooksAllowed = false; + + /* eslint-disable no-console */ + let oldBeforeDiff = options._diff; + let oldDiffed = options.diffed; + let oldVnode = options.vnode; + let oldRender = options._render; + let oldCatchError = options._catchError; + let oldRoot = options._root; + let oldHook = options._hook; + const warnedComponents = !isWeakMapSupported + ? null + : { + useEffect: new WeakMap(), + useLayoutEffect: new WeakMap(), + lazyPropTypes: new WeakMap() + }; + const deprecations = []; + + options._catchError = (error, vnode, oldVNode, errorInfo) => { + let component = vnode && vnode._component; + if (component && typeof error.then == 'function') { + const promise = error; + error = new Error( + `Missing Suspense. The throwing component was: ${getDisplayName(vnode)}` + ); + + let parent = vnode; + for (; parent; parent = parent._parent) { + if (parent._component && parent._component._childDidSuspend) { + error = promise; + break; + } + } + + // We haven't recovered and we know at this point that there is no + // Suspense component higher up in the tree + if (error instanceof Error) { + throw error; + } + } + + try { + errorInfo = errorInfo || {}; + errorInfo.componentStack = getOwnerStack(vnode); + oldCatchError(error, vnode, oldVNode, errorInfo); + + // when an error was handled by an ErrorBoundary we will nonetheless emit an error + // event on the window object. This is to make up for react compatibility in dev mode + // and thus make the Next.js dev overlay work. + if (typeof error.then != 'function') { + setTimeout(() => { + throw error; + }); + } + } catch (e) { + throw e; + } + }; + + options._root = (vnode, parentNode) => { + if (!parentNode) { + throw new Error( + 'Undefined parent passed to render(), this is the second argument.\n' + + 'Check if the element is available in the DOM/has the correct id.' + ); + } + + let isValid; + switch (parentNode.nodeType) { + case ELEMENT_NODE: + case DOCUMENT_FRAGMENT_NODE: + case DOCUMENT_NODE: + isValid = true; + break; + default: + isValid = false; + } + + if (!isValid) { + let componentName = getDisplayName(vnode); + throw new Error( + `Expected a valid HTML node as a second argument to render. Received ${parentNode} instead: render(<${componentName} />, ${parentNode});` + ); + } + + if (oldRoot) oldRoot(vnode, parentNode); + }; + + options._diff = vnode => { + let { type } = vnode; + + hooksAllowed = true; + + if (type === undefined) { + throw new Error( + 'Undefined component passed to createElement()\n\n' + + 'You likely forgot to export your component or might have mixed up default and named imports' + + serializeVNode(vnode) + + `\n\n${getOwnerStack(vnode)}` + ); + } else if (type != null && typeof type == 'object') { + if (type._children !== undefined && type._dom !== undefined) { + throw new Error( + `Invalid type passed to createElement(): ${type}\n\n` + + 'Did you accidentally pass a JSX literal as JSX twice?\n\n' + + ` let My${getDisplayName(vnode)} = ${serializeVNode(type)};\n` + + ` let vnode = ;\n\n` + + 'This usually happens when you export a JSX literal and not the component.' + + `\n\n${getOwnerStack(vnode)}` + ); + } + + throw new Error( + 'Invalid type passed to createElement(): ' + + (Array.isArray(type) ? 'array' : type) + ); + } + + if ( + vnode.ref !== undefined && + typeof vnode.ref != 'function' && + typeof vnode.ref != 'object' && + !('$$typeof' in vnode) // allow string refs when preact-compat is installed + ) { + throw new Error( + `Component's "ref" property should be a function, or an object created ` + + `by createRef(), but got [${typeof vnode.ref}] instead\n` + + serializeVNode(vnode) + + `\n\n${getOwnerStack(vnode)}` + ); + } + + if (typeof vnode.type == 'string') { + for (const key in vnode.props) { + if ( + key[0] === 'o' && + key[1] === 'n' && + typeof vnode.props[key] != 'function' && + vnode.props[key] != null + ) { + throw new Error( + `Component's "${key}" property should be a function, ` + + `but got [${typeof vnode.props[key]}] instead\n` + + serializeVNode(vnode) + + `\n\n${getOwnerStack(vnode)}` + ); + } + } + } + + // Check prop-types if available + if (typeof vnode.type == 'function' && vnode.type.propTypes) { + if ( + vnode.type.displayName === 'Lazy' && + warnedComponents && + !warnedComponents.lazyPropTypes.has(vnode.type) + ) { + const m = + 'PropTypes are not supported on lazy(). Use propTypes on the wrapped component itself. '; + try { + const lazyVNode = vnode.type(); + warnedComponents.lazyPropTypes.set(vnode.type, true); + console.warn( + m + `Component wrapped in lazy() is ${getDisplayName(lazyVNode)}` + ); + } catch (promise) { + console.warn( + m + "We will log the wrapped component's name once it is loaded." + ); + } + } + + let values = vnode.props; + if (vnode.type._forwarded) { + values = assign({}, values); + delete values.ref; + } + + checkPropTypes( + vnode.type.propTypes, + values, + 'prop', + getDisplayName(vnode), + () => getOwnerStack(vnode) + ); + } + + if (oldBeforeDiff) oldBeforeDiff(vnode); + }; + + let renderCount = 0; + let currentComponent; + options._render = vnode => { + if (oldRender) { + oldRender(vnode); + } + hooksAllowed = true; + + const nextComponent = vnode._component; + if (nextComponent === currentComponent) { + renderCount++; + } else { + renderCount = 1; + } + + if (renderCount >= 25) { + throw new Error( + `Too many re-renders. This is limited to prevent an infinite loop ` + + `which may lock up your browser. The component causing this is: ${getDisplayName( + vnode + )}` + ); + } + + currentComponent = nextComponent; + }; + + options._hook = (comp, index, type) => { + if (!comp || !hooksAllowed) { + throw new Error('Hook can only be invoked from render methods.'); + } + + if (oldHook) oldHook(comp, index, type); + }; + + // Ideally we'd want to print a warning once per component, but we + // don't have access to the vnode that triggered it here. As a + // compromise and to avoid flooding the console with warnings we + // print each deprecation warning only once. + const warn = (property, message) => ({ + get() { + const key = 'get' + property + message; + if (deprecations && deprecations.indexOf(key) < 0) { + deprecations.push(key); + console.warn(`getting vnode.${property} is deprecated, ${message}`); + } + }, + set() { + const key = 'set' + property + message; + if (deprecations && deprecations.indexOf(key) < 0) { + deprecations.push(key); + console.warn(`setting vnode.${property} is not allowed, ${message}`); + } + } + }); + + const deprecatedAttributes = { + nodeName: warn('nodeName', 'use vnode.type'), + attributes: warn('attributes', 'use vnode.props'), + children: warn('children', 'use vnode.props.children') + }; + + const deprecatedProto = Object.create({}, deprecatedAttributes); + + options.vnode = vnode => { + const props = vnode.props; + if ( + vnode.type !== null && + props != null && + ('__source' in props || '__self' in props) + ) { + const newProps = (vnode.props = {}); + for (let i in props) { + const v = props[i]; + if (i === '__source') vnode.__source = v; + else if (i === '__self') vnode.__self = v; + else newProps[i] = v; + } + } + + // eslint-disable-next-line + vnode.__proto__ = deprecatedProto; + if (oldVnode) oldVnode(vnode); + }; + + options.diffed = vnode => { + const { type, _parent: parent } = vnode; + // Check if the user passed plain objects as children. Note that we cannot + // move this check into `options.vnode` because components can receive + // children in any shape they want (e.g. + // `{{ foo: 123, bar: "abc" }}`). + // Putting this check in `options.diffed` ensures that + // `vnode._children` is set and that we only validate the children + // that were actually rendered. + if (vnode._children) { + vnode._children.forEach(child => { + if (typeof child === 'object' && child && child.type === undefined) { + const keys = Object.keys(child).join(','); + throw new Error( + `Objects are not valid as a child. Encountered an object with the keys {${keys}}.` + + `\n\n${getOwnerStack(vnode)}` + ); + } + }); + } + + if (vnode._component === currentComponent) { + renderCount = 0; + } + + if ( + typeof type === 'string' && + (isTableElement(type) || + type === 'p' || + type === 'a' || + type === 'button') + ) { + // Avoid false positives when Preact only partially rendered the + // HTML tree. Whilst we attempt to include the outer DOM in our + // validation, this wouldn't work on the server for + // `preact-render-to-string`. There we'd otherwise flood the terminal + // with false positives, which we'd like to avoid. + let domParentName = getClosestDomNodeParentName(parent); + if (domParentName !== '' && isTableElement(type)) { + if ( + type === 'table' && + // Tables can be nested inside each other if it's inside a cell. + // See https://developer.mozilla.org/en-US/docs/Learn/HTML/Tables/Advanced#nesting_tables + domParentName !== 'td' && + isTableElement(domParentName) + ) { + console.error( + 'Improper nesting of table. Your
    should have a
    should have a
    should not have a table-node parent.' + + serializeVNode(vnode) + + `\n\n${getOwnerStack(vnode)}` + ); + } else if ( + (type === 'thead' || type === 'tfoot' || type === 'tbody') && + domParentName !== 'table' + ) { + console.error( + 'Improper nesting of table. Your should have a
    parent.' + + serializeVNode(vnode) + + `\n\n${getOwnerStack(vnode)}` + ); + } else if ( + type === 'tr' && + domParentName !== 'thead' && + domParentName !== 'tfoot' && + domParentName !== 'tbody' + ) { + console.error( + 'Improper nesting of table. Your should have a parent.' + + serializeVNode(vnode) + + `\n\n${getOwnerStack(vnode)}` + ); + } else if (type === 'td' && domParentName !== 'tr') { + console.error( + 'Improper nesting of table. Your parent.' + + serializeVNode(vnode) + + `\n\n${getOwnerStack(vnode)}` + ); + } else if (type === 'th' && domParentName !== 'tr') { + console.error( + 'Improper nesting of table. Your .' + + serializeVNode(vnode) + + `\n\n${getOwnerStack(vnode)}` + ); + } + } else if (type === 'p') { + let illegalDomChildrenTypes = getDomChildren(vnode).filter(childType => + ILLEGAL_PARAGRAPH_CHILD_ELEMENTS.test(childType) + ); + if (illegalDomChildrenTypes.length) { + console.error( + 'Improper nesting of paragraph. Your

    should not have ' + + illegalDomChildrenTypes.join(', ') + + ' as child-elements.' + + serializeVNode(vnode) + + `\n\n${getOwnerStack(vnode)}` + ); + } + } else if (type === 'a' || type === 'button') { + if (getDomChildren(vnode).indexOf(type) !== -1) { + console.error( + `Improper nesting of interactive content. Your <${type}>` + + ` should not have other ${type === 'a' ? 'anchor' : 'button'}` + + ' tags as child-elements.' + + serializeVNode(vnode) + + `\n\n${getOwnerStack(vnode)}` + ); + } + } + } + + hooksAllowed = false; + + if (oldDiffed) oldDiffed(vnode); + + if (vnode._children != null) { + const keys = []; + for (let i = 0; i < vnode._children.length; i++) { + const child = vnode._children[i]; + if (!child || child.key == null) continue; + + const key = child.key; + if (keys.indexOf(key) !== -1) { + console.error( + 'Following component has two or more children with the ' + + `same key attribute: "${key}". This may cause glitches and misbehavior ` + + 'in rendering process. Component: \n\n' + + serializeVNode(vnode) + + `\n\n${getOwnerStack(vnode)}` + ); + + // Break early to not spam the console + break; + } + + keys.push(key); + } + } + + if (vnode._component != null && vnode._component.__hooks != null) { + // Validate that none of the hooks in this component contain arguments that are NaN. + // This is a common mistake that can be hard to debug, so we want to catch it early. + const hooks = vnode._component.__hooks._list; + if (hooks) { + for (let i = 0; i < hooks.length; i += 1) { + const hook = hooks[i]; + if (hook._args) { + for (let j = 0; j < hook._args.length; j++) { + const arg = hook._args[j]; + if (isNaN(arg)) { + const componentName = getDisplayName(vnode); + console.warn( + `Invalid argument passed to hook. Hooks should not be called with NaN in the dependency array. Hook index ${i} in component ${componentName} was called with NaN.` + ); + } + } + } + } + } + } + }; +} + +const setState = Component.prototype.setState; +Component.prototype.setState = function (update, callback) { + if (this._vnode == null) { + // `this._vnode` will be `null` during componentWillMount. But it + // is perfectly valid to call `setState` during cWM. So we + // need an additional check to verify that we are dealing with a + // call inside constructor. + if (this.state == null) { + console.warn( + `Calling "this.setState" inside the constructor of a component is a ` + + `no-op and might be a bug in your application. Instead, set ` + + `"this.state = {}" directly.\n\n${getOwnerStack(getCurrentVNode())}` + ); + } + } + + return setState.call(this, update, callback); +}; + +function isTableElement(type) { + return ( + type === 'table' || + type === 'tfoot' || + type === 'tbody' || + type === 'thead' || + type === 'td' || + type === 'tr' || + type === 'th' + ); +} + +const ILLEGAL_PARAGRAPH_CHILD_ELEMENTS = + /^(address|article|aside|blockquote|details|div|dl|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hgroup|hr|main|menu|nav|ol|p|pre|search|section|table|ul)$/; + +const forceUpdate = Component.prototype.forceUpdate; +Component.prototype.forceUpdate = function (callback) { + if (this._vnode == null) { + console.warn( + `Calling "this.forceUpdate" inside the constructor of a component is a ` + + `no-op and might be a bug in your application.\n\n${getOwnerStack( + getCurrentVNode() + )}` + ); + } else if (this._parentDom == null) { + console.warn( + `Can't call "this.forceUpdate" on an unmounted component. This is a no-op, ` + + `but it indicates a memory leak in your application. To fix, cancel all ` + + `subscriptions and asynchronous tasks in the componentWillUnmount method.` + + `\n\n${getOwnerStack(this._vnode)}` + ); + } + return forceUpdate.call(this, callback); +}; + +/** + * Serialize a vnode tree to a string + * @param {import('./internal').VNode} vnode + * @returns {string} + */ +export function serializeVNode(vnode) { + let { props } = vnode; + let name = getDisplayName(vnode); + + let attrs = ''; + for (let prop in props) { + if (props.hasOwnProperty(prop) && prop !== 'children') { + let value = props[prop]; + + // If it is an object but doesn't have toString(), use Object.toString + if (typeof value == 'function') { + value = `function ${value.displayName || value.name}() {}`; + } + + value = + Object(value) === value && !value.toString + ? Object.prototype.toString.call(value) + : value + ''; + + attrs += ` ${prop}=${JSON.stringify(value)}`; + } + } + + let children = props.children; + return `<${name}${attrs}${ + children && children.length ? '>..' : ' />' + }`; +} + +options._hydrationMismatch = (newVNode, excessDomChildren) => { + const { type } = newVNode; + const availableTypes = excessDomChildren + .map(child => child && child.localName) + .filter(Boolean); + console.error( + `Expected a DOM node of type "${type}" but found "${availableTypes.join(', ')}" as available DOM-node(s), this is caused by the SSR'd HTML containing different DOM-nodes compared to the hydrated one.\n\n${getOwnerStack(newVNode)}` + ); +}; diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/index.d.ts b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/index.d.ts new file mode 100644 index 0000000000000..5bb5d22261a89 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/index.d.ts @@ -0,0 +1,23 @@ +import { VNode } from 'preact'; + +/** + * Get the currently rendered `vnode` + */ +export function getCurrentVNode(): VNode | null; + +/** + * Return the component stack that was captured up to this point. + */ +export function getOwnerStack(vnode: VNode): string; + +/** + * Setup code to capture the component trace while rendering. Note that + * we cannot simply traverse `vnode._parent` upwards, because we have some + * debug messages for `this.setState` where the `vnode` is `undefined`. + */ +export function setupComponentStack(): void; + +/** + * Reset the history of which prop type warnings have been logged. + */ +export function resetPropWarnings(): void; diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/index.js b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/index.js new file mode 100644 index 0000000000000..adea553687b20 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/index.js @@ -0,0 +1,12 @@ +import { initDebug } from './debug'; +import 'preact/devtools'; + +initDebug(); + +export { resetPropWarnings } from './check-props'; + +export { + getCurrentVNode, + getDisplayName, + getOwnerStack +} from './component-stack'; diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/internal.d.ts b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/internal.d.ts new file mode 100644 index 0000000000000..866943c948441 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/internal.d.ts @@ -0,0 +1,82 @@ +import { Component, PreactElement, VNode, Options } from '../../src/internal'; + +export { Component, PreactElement, VNode, Options }; + +export interface DevtoolsInjectOptions { + /** 1 = DEV, 0 = production */ + bundleType: 1 | 0; + /** The devtools enable different features for different versions of react */ + version: string; + /** Informative string, currently unused in the devtools */ + rendererPackageName: string; + /** Find the root dom node of a vnode */ + findHostInstanceByFiber(vnode: VNode): HTMLElement | null; + /** Find the closest vnode given a dom node */ + findFiberByHostInstance(instance: HTMLElement): VNode | null; +} + +export interface DevtoolsUpdater { + setState(objOrFn: any): void; + forceUpdate(): void; + setInState(path: Array, value: any): void; + setInProps(path: Array, value: any): void; + setInContext(): void; +} + +export type NodeType = 'Composite' | 'Native' | 'Wrapper' | 'Text'; + +export interface DevtoolData { + nodeType: NodeType; + // Component type + type: any; + name: string; + ref: any; + key: string | number; + updater: DevtoolsUpdater | null; + text: string | number | null; + state: any; + props: any; + children: VNode[] | string | number | null; + publicInstance: PreactElement | Text | Component; + memoizedInteractions: any[]; + + actualDuration: number; + actualStartTime: number; + treeBaseDuration: number; +} + +export type EventType = + | 'unmount' + | 'rootCommitted' + | 'root' + | 'mount' + | 'update' + | 'updateProfileTimes'; + +export interface DevtoolsEvent { + data?: DevtoolData; + internalInstance: VNode; + renderer: string; + type: EventType; +} + +export interface DevtoolsHook { + _renderers: Record; + _roots: Set; + on(ev: string, listener: () => void): void; + emit(ev: string, data?: object): void; + helpers: Record; + getFiberRoots(rendererId: string): Set; + inject(config: DevtoolsInjectOptions): string; + onCommitFiberRoot(rendererId: string, root: VNode): void; + onCommitFiberUnmount(rendererId: string, vnode: VNode): void; +} + +export interface DevtoolsWindow extends Window { + /** + * If the devtools extension is installed it will inject this object into + * the dom. This hook handles all communications between preact and the + * devtools panel. + */ + __REACT_DEVTOOLS_GLOBAL_HOOK__?: DevtoolsHook; +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/util.js b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/util.js new file mode 100644 index 0000000000000..be4228b9b67f7 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/debug/src/util.js @@ -0,0 +1,15 @@ +/** + * Assign properties from `props` to `obj` + * @template O, P The obj and props types + * @param {O} obj The object to copy properties to + * @param {P} props The object to copy properties from + * @returns {O & P} + */ +export function assign(obj, props) { + for (let i in props) obj[i] = props[i]; + return /** @type {O & P} */ (obj); +} + +export function isNaN(value) { + return value !== value; +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/dist/devtools.js b/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/dist/devtools.js new file mode 100644 index 0000000000000..4bd96abf70282 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/dist/devtools.js @@ -0,0 +1,2 @@ +var e,n=require("preact");null!=(e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0)&&e.__PREACT_DEVTOOLS__&&e.__PREACT_DEVTOOLS__.attachPreact("10.28.2",n.options,{Fragment:n.Fragment,Component:n.Component}),exports.addHookName=function(e,o){return n.options.__a&&n.options.__a(o),e}; +//# sourceMappingURL=devtools.js.map diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/dist/devtools.js.map b/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/dist/devtools.js.map new file mode 100644 index 0000000000000..6a838ed58c892 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/dist/devtools.js.map @@ -0,0 +1 @@ +{"version":3,"file":"devtools.js","sources":["../src/devtools.js","../src/index.js"],"sourcesContent":["import { Component, Fragment, options } from 'preact';\n\nexport function initDevTools() {\n\tconst globalVar =\n\t\ttypeof globalThis !== 'undefined'\n\t\t\t? globalThis\n\t\t\t: typeof window !== 'undefined'\n\t\t\t\t? window\n\t\t\t\t: undefined;\n\n\tif (\n\t\tglobalVar !== null &&\n\t\tglobalVar !== undefined &&\n\t\tglobalVar.__PREACT_DEVTOOLS__\n\t) {\n\t\tglobalVar.__PREACT_DEVTOOLS__.attachPreact('10.28.2', options, {\n\t\t\tFragment,\n\t\t\tComponent\n\t\t});\n\t}\n}\n","import { options } from 'preact';\nimport { initDevTools } from './devtools';\n\ninitDevTools();\n\n/**\n * Display a custom label for a custom hook for the devtools panel\n * @type {(value: T, name: string) => T}\n */\nexport function addHookName(value, name) {\n\tif (options._addHookName) {\n\t\toptions._addHookName(name);\n\t}\n\treturn value;\n}\n"],"names":["globalVar","globalThis","window","undefined","__PREACT_DEVTOOLS__","attachPreact","options","Fragment","Component","value","name","__a"],"mappings":"IAGOA,sBAQLA,OARKA,EACiB,oBAAfC,WACJA,WACkB,oBAAXC,OACNA,YACAC,IAKJH,EAAUI,qBAEVJ,EAAUI,oBAAoBC,aAAa,UAAWC,EAAOA,QAAE,CAC9DC,SAAAA,EAAAA,SACAC,UAAAA,EAAAA,gCCRa,SAAYC,EAAOC,GAIlC,OAHIJ,EAAAA,QAAOK,KACVL,EAAAA,QAAOK,IAAcD,GAEfD,CACR"} \ No newline at end of file diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/dist/devtools.mjs b/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/dist/devtools.mjs new file mode 100644 index 0000000000000..f19c5f9b1842b --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/dist/devtools.mjs @@ -0,0 +1,2 @@ +import{options as n,Fragment as o,Component as e}from"preact";var i;function t(o,e){return n.__a&&n.__a(e),o}null!=(i="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0)&&i.__PREACT_DEVTOOLS__&&i.__PREACT_DEVTOOLS__.attachPreact("10.28.2",n,{Fragment:o,Component:e});export{t as addHookName}; +//# sourceMappingURL=devtools.module.js.map diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/dist/devtools.module.js b/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/dist/devtools.module.js new file mode 100644 index 0000000000000..f19c5f9b1842b --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/dist/devtools.module.js @@ -0,0 +1,2 @@ +import{options as n,Fragment as o,Component as e}from"preact";var i;function t(o,e){return n.__a&&n.__a(e),o}null!=(i="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0)&&i.__PREACT_DEVTOOLS__&&i.__PREACT_DEVTOOLS__.attachPreact("10.28.2",n,{Fragment:o,Component:e});export{t as addHookName}; +//# sourceMappingURL=devtools.module.js.map diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/dist/devtools.module.js.map b/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/dist/devtools.module.js.map new file mode 100644 index 0000000000000..c1972779ce276 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/dist/devtools.module.js.map @@ -0,0 +1 @@ +{"version":3,"file":"devtools.module.js","sources":["../src/devtools.js","../src/index.js"],"sourcesContent":["import { Component, Fragment, options } from 'preact';\n\nexport function initDevTools() {\n\tconst globalVar =\n\t\ttypeof globalThis !== 'undefined'\n\t\t\t? globalThis\n\t\t\t: typeof window !== 'undefined'\n\t\t\t\t? window\n\t\t\t\t: undefined;\n\n\tif (\n\t\tglobalVar !== null &&\n\t\tglobalVar !== undefined &&\n\t\tglobalVar.__PREACT_DEVTOOLS__\n\t) {\n\t\tglobalVar.__PREACT_DEVTOOLS__.attachPreact('10.28.2', options, {\n\t\t\tFragment,\n\t\t\tComponent\n\t\t});\n\t}\n}\n","import { options } from 'preact';\nimport { initDevTools } from './devtools';\n\ninitDevTools();\n\n/**\n * Display a custom label for a custom hook for the devtools panel\n * @type {(value: T, name: string) => T}\n */\nexport function addHookName(value, name) {\n\tif (options._addHookName) {\n\t\toptions._addHookName(name);\n\t}\n\treturn value;\n}\n"],"names":["globalVar","addHookName","value","name","options","__a","globalThis","window","undefined","__PREACT_DEVTOOLS__","attachPreact","Fragment","Component"],"mappings":"8DAEgB,IACTA,ECMS,SAAAC,EAAYC,EAAOC,GAIlC,OAHIC,EAAOC,KACVD,EAAOC,IAAcF,GAEfD,CACR,CDHEF,OARKA,EACiB,oBAAfM,WACJA,WACkB,oBAAXC,OACNA,YACAC,IAKJR,EAAUS,qBAEVT,EAAUS,oBAAoBC,aAAa,UAAWN,EAAS,CAC9DO,SAAAA,EACAC,UAAAA"} \ No newline at end of file diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/dist/devtools.umd.js b/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/dist/devtools.umd.js new file mode 100644 index 0000000000000..f85952236eb1f --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/dist/devtools.umd.js @@ -0,0 +1,2 @@ +!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports,require("preact")):"function"==typeof define&&define.amd?define(["exports","preact"],n):n((e||self).preactDevtools={},e.preact)}(this,function(e,n){var o;null!=(o="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0)&&o.__PREACT_DEVTOOLS__&&o.__PREACT_DEVTOOLS__.attachPreact("10.28.2",n.options,{Fragment:n.Fragment,Component:n.Component}),e.addHookName=function(e,o){return n.options.__a&&n.options.__a(o),e}}); +//# sourceMappingURL=devtools.umd.js.map diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/dist/devtools.umd.js.map b/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/dist/devtools.umd.js.map new file mode 100644 index 0000000000000..038c9dcce6956 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/dist/devtools.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"devtools.umd.js","sources":["../src/devtools.js","../src/index.js"],"sourcesContent":["import { Component, Fragment, options } from 'preact';\n\nexport function initDevTools() {\n\tconst globalVar =\n\t\ttypeof globalThis !== 'undefined'\n\t\t\t? globalThis\n\t\t\t: typeof window !== 'undefined'\n\t\t\t\t? window\n\t\t\t\t: undefined;\n\n\tif (\n\t\tglobalVar !== null &&\n\t\tglobalVar !== undefined &&\n\t\tglobalVar.__PREACT_DEVTOOLS__\n\t) {\n\t\tglobalVar.__PREACT_DEVTOOLS__.attachPreact('10.28.2', options, {\n\t\t\tFragment,\n\t\t\tComponent\n\t\t});\n\t}\n}\n","import { options } from 'preact';\nimport { initDevTools } from './devtools';\n\ninitDevTools();\n\n/**\n * Display a custom label for a custom hook for the devtools panel\n * @type {(value: T, name: string) => T}\n */\nexport function addHookName(value, name) {\n\tif (options._addHookName) {\n\t\toptions._addHookName(name);\n\t}\n\treturn value;\n}\n"],"names":["globalVar","globalThis","window","undefined","__PREACT_DEVTOOLS__","attachPreact","options","Fragment","Component","value","name","__a"],"mappings":"8QAEgB,IACTA,EAQLA,OARKA,EACiB,oBAAfC,WACJA,WACkB,oBAAXC,OACNA,YACAC,IAKJH,EAAUI,qBAEVJ,EAAUI,oBAAoBC,aAAa,UAAWC,EAAOA,QAAE,CAC9DC,SAAAA,EAAAA,SACAC,UAAAA,EAAAA,0BCRa,SAAYC,EAAOC,GAIlC,OAHIJ,EAAAA,QAAOK,KACVL,EAAAA,QAAOK,IAAcD,GAEfD,CACR"} \ No newline at end of file diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/package.json b/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/package.json new file mode 100644 index 0000000000000..c12ac730f0b31 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/package.json @@ -0,0 +1,25 @@ +{ + "name": "preact-devtools", + "amdName": "preactDevtools", + "version": "1.0.0", + "private": true, + "description": "Preact bridge for Preact devtools", + "main": "dist/devtools.js", + "module": "dist/devtools.module.js", + "umd:main": "dist/devtools.umd.js", + "source": "src/index.js", + "license": "MIT", + "types": "src/index.d.ts", + "peerDependencies": { + "preact": "^10.0.0" + }, + "exports": { + ".": { + "types": "./src/index.d.ts", + "browser": "./dist/devtools.module.js", + "umd": "./dist/devtools.umd.js", + "import": "./dist/devtools.mjs", + "require": "./dist/devtools.js" + } + } +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/src/devtools.js b/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/src/devtools.js new file mode 100644 index 0000000000000..cbfcd565e7537 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/src/devtools.js @@ -0,0 +1,21 @@ +import { Component, Fragment, options } from 'preact'; + +export function initDevTools() { + const globalVar = + typeof globalThis !== 'undefined' + ? globalThis + : typeof window !== 'undefined' + ? window + : undefined; + + if ( + globalVar !== null && + globalVar !== undefined && + globalVar.__PREACT_DEVTOOLS__ + ) { + globalVar.__PREACT_DEVTOOLS__.attachPreact('10.28.2', options, { + Fragment, + Component + }); + } +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/src/index.d.ts b/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/src/index.d.ts new file mode 100644 index 0000000000000..230e5ab6ecab3 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/src/index.d.ts @@ -0,0 +1,8 @@ +/** + * Customize the displayed name of a useState, useReducer or useRef hook + * in the devtools panel. + * + * @param value Wrapped native hook. + * @param name Custom name + */ +export function addHookName(value: T, name: string): T; diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/src/index.js b/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/src/index.js new file mode 100644 index 0000000000000..693429f56c190 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/devtools/src/index.js @@ -0,0 +1,15 @@ +import { options } from 'preact'; +import { initDevTools } from './devtools'; + +initDevTools(); + +/** + * Display a custom label for a custom hook for the devtools panel + * @type {(value: T, name: string) => T} + */ +export function addHookName(value, name) { + if (options._addHookName) { + options._addHookName(name); + } + return value; +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/dist/preact.js b/browser/base/content/assistant/ui-preact/node_modules/preact/dist/preact.js new file mode 100644 index 0000000000000..b2a8c33ea50fd --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/dist/preact.js @@ -0,0 +1,2 @@ +var n,l,t,u,i,r,o,e,f,c,s,p,a,h={},v=[],y=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,d=Array.isArray;function w(n,l){for(var t in l)n[t]=l[t];return n}function g(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function _(l,t,u){var i,r,o,e={};for(o in t)"key"==o?i=t[o]:"ref"==o?r=t[o]:e[o]=t[o];if(arguments.length>2&&(e.children=arguments.length>3?n.call(arguments,2):u),"function"==typeof l&&null!=l.defaultProps)for(o in l.defaultProps)void 0===e[o]&&(e[o]=l.defaultProps[o]);return x(l,e,i,r,null)}function x(n,u,i,r,o){var e={type:n,props:u,key:i,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==o?++t:o,__i:-1,__u:0};return null==o&&null!=l.vnode&&l.vnode(e),e}function m(n){return n.children}function b(n,l){this.props=n,this.context=l}function k(n,l){if(null==l)return n.__?k(n.__,n.__i+1):null;for(var t;ls&&i.sort(e),n=i.shift(),s=i.length,n.__d&&(u=void 0,r=void 0,o=(r=(t=n).__v).__e,f=[],c=[],t.__P&&((u=w({},r)).__v=r.__v+1,l.vnode&&l.vnode(u),j(t.__P,u,r,t.__n,t.__P.namespaceURI,32&r.__u?[o]:null,f,null==o?k(r):o,!!(32&r.__u),c),u.__v=r.__v,u.__.__k[u.__i]=u,O(f,u,c),r.__e=r.__=null,u.__e!=o&&S(u)));$.__r=0}function C(n,l,t,u,i,r,o,e,f,c,s){var p,a,y,d,w,g,_,x=u&&u.__k||v,m=l.length;for(f=I(t,l,x,f,m),p=0;p0?o=n.__k[r]=x(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):n.__k[r]=o,f=r+a,o.__=n,o.__b=n.__b+1,e=null,-1!=(c=o.__i=A(o,t,f,p))&&(p--,(e=t[c])&&(e.__u|=2)),null==e||null==e.__v?(-1==c&&(i>s?a--:if?a--:a++,o.__u|=4))):n.__k[r]=null;if(p)for(r=0;r(s?1:0))for(i=t-1,r=t+1;i>=0||r=0?i--:r++])&&0==(2&c.__u)&&e==c.key&&f==c.type)return o;return-1}function H(n,l,t){"-"==l[0]?n.setProperty(l,null==t?"":t):n[l]=null==t?"":"number"!=typeof t||y.test(l)?t:t+"px"}function L(n,l,t,u,i){var r,o;n:if("style"==l)if("string"==typeof t)n.style.cssText=t;else{if("string"==typeof u&&(n.style.cssText=u=""),u)for(l in u)t&&l in t||H(n.style,l,"");if(t)for(l in t)u&&t[l]==u[l]||H(n.style,l,t[l])}else if("o"==l[0]&&"n"==l[1])r=l!=(l=l.replace(f,"$1")),o=l.toLowerCase(),l=o in n||"onFocusOut"==l||"onFocusIn"==l?o.slice(2):l.slice(2),n.l||(n.l={}),n.l[l+r]=t,t?u?t.t=u.t:(t.t=c,n.addEventListener(l,r?p:s,r)):n.removeEventListener(l,r?p:s,r);else{if("http://www.w3.org/2000/svg"==i)l=l.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=l&&"height"!=l&&"href"!=l&&"list"!=l&&"form"!=l&&"tabIndex"!=l&&"download"!=l&&"rowSpan"!=l&&"colSpan"!=l&&"role"!=l&&"popover"!=l&&l in n)try{n[l]=null==t?"":t;break n}catch(n){}"function"==typeof t||(null==t||!1===t&&"-"!=l[4]?n.removeAttribute(l):n.setAttribute(l,"popover"==l&&1==t?"":t))}}function T(n){return function(t){if(this.l){var u=this.l[t.type+n];if(null==t.u)t.u=c++;else if(t.u0?n:d(n)?n.map(z):w({},n)}function N(t,u,i,r,o,e,f,c,s){var p,a,v,y,w,_,x,m=i.props||h,b=u.props,S=u.type;if("svg"==S?o="http://www.w3.org/2000/svg":"math"==S?o="http://www.w3.org/1998/Math/MathML":o||(o="http://www.w3.org/1999/xhtml"),null!=e)for(p=0;p2&&(f.children=arguments.length>3?n.call(arguments,2):u),x(l.type,f,i||l.key,r||l.ref,null)},exports.createContext=function(n){function l(n){var t,u;return this.getChildContext||(t=new Set,(u={})[l.__c]=this,this.getChildContext=function(){return u},this.componentWillUnmount=function(){t=null},this.shouldComponentUpdate=function(n){this.props.value!=n.value&&t.forEach(function(n){n.__e=!0,M(n)})},this.sub=function(n){t.add(n);var l=n.componentWillUnmount;n.componentWillUnmount=function(){t&&t.delete(n),l&&l.call(n)}}),n.children}return l.__c="__cC"+a++,l.__=n,l.Provider=l.__l=(l.Consumer=function(n,l){return n.children(l)}).contextType=l,l},exports.createElement=_,exports.createRef=function(){return{current:null}},exports.h=_,exports.hydrate=function n(l,t){D(l,t,n)},exports.isValidElement=u,exports.options=l,exports.render=D,exports.toChildArray=function n(l,t){return t=t||[],null==l||"boolean"==typeof l||(d(l)?l.some(function(l){n(l,t)}):t.push(l)),t}; +//# sourceMappingURL=preact.js.map diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/dist/preact.js.map b/browser/base/content/assistant/ui-preact/node_modules/preact/dist/preact.js.map new file mode 100644 index 0000000000000..ae3c9ca531ed1 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/dist/preact.js.map @@ -0,0 +1 @@ +{"version":3,"file":"preact.js","sources":["../src/constants.js","../src/util.js","../src/options.js","../src/create-element.js","../src/component.js","../src/diff/props.js","../src/create-context.js","../src/diff/children.js","../src/diff/index.js","../src/render.js","../src/diff/catch-error.js","../src/clone-element.js"],"sourcesContent":["/** Normal hydration that attaches to a DOM tree but does not diff it. */\nexport const MODE_HYDRATE = 1 << 5;\n/** Signifies this VNode suspended on the previous render */\nexport const MODE_SUSPENDED = 1 << 7;\n/** Indicates that this node needs to be inserted while patching children */\nexport const INSERT_VNODE = 1 << 2;\n/** Indicates a VNode has been matched with another VNode in the diff */\nexport const MATCHED = 1 << 1;\n\n/** Reset all mode flags */\nexport const RESET_MODE = ~(MODE_HYDRATE | MODE_SUSPENDED);\n\nexport const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\nexport const XHTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\nexport const MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n\nexport const NULL = null;\nexport const UNDEFINED = undefined;\nexport const EMPTY_OBJ = /** @type {any} */ ({});\nexport const EMPTY_ARR = [];\nexport const IS_NON_DIMENSIONAL =\n\t/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;\n","import { EMPTY_ARR } from './constants';\n\nexport const isArray = Array.isArray;\n\n/**\n * Assign properties from `props` to `obj`\n * @template O, P The obj and props types\n * @param {O} obj The object to copy properties to\n * @param {P} props The object to copy properties from\n * @returns {O & P}\n */\nexport function assign(obj, props) {\n\t// @ts-expect-error We change the type of `obj` to be `O & P`\n\tfor (let i in props) obj[i] = props[i];\n\treturn /** @type {O & P} */ (obj);\n}\n\n/**\n * Remove a child node from its parent if attached. This is a workaround for\n * IE11 which doesn't support `Element.prototype.remove()`. Using this function\n * is smaller than including a dedicated polyfill.\n * @param {import('./index').ContainerNode} node The node to remove\n */\nexport function removeNode(node) {\n\tif (node && node.parentNode) node.parentNode.removeChild(node);\n}\n\nexport const slice = EMPTY_ARR.slice;\n","import { _catchError } from './diff/catch-error';\n\n/**\n * The `option` object can potentially contain callback functions\n * that are called during various stages of our renderer. This is the\n * foundation on which all our addons like `preact/debug`, `preact/compat`,\n * and `preact/hooks` are based on. See the `Options` type in `internal.d.ts`\n * for a full list of available option hooks (most editors/IDEs allow you to\n * ctrl+click or cmd+click on mac the type definition below).\n * @type {import('./internal').Options}\n */\nconst options = {\n\t_catchError\n};\n\nexport default options;\n","import { slice } from './util';\nimport options from './options';\nimport { NULL, UNDEFINED } from './constants';\n\nlet vnodeId = 0;\n\n/**\n * Create an virtual node (used for JSX)\n * @param {import('./internal').VNode[\"type\"]} type The node name or Component constructor for this\n * virtual node\n * @param {object | null | undefined} [props] The properties of the virtual node\n * @param {Array} [children] The children of the\n * virtual node\n * @returns {import('./internal').VNode}\n */\nexport function createElement(type, props, children) {\n\tlet normalizedProps = {},\n\t\tkey,\n\t\tref,\n\t\ti;\n\tfor (i in props) {\n\t\tif (i == 'key') key = props[i];\n\t\telse if (i == 'ref') ref = props[i];\n\t\telse normalizedProps[i] = props[i];\n\t}\n\n\tif (arguments.length > 2) {\n\t\tnormalizedProps.children =\n\t\t\targuments.length > 3 ? slice.call(arguments, 2) : children;\n\t}\n\n\t// If a Component VNode, check for and apply defaultProps\n\t// Note: type may be undefined in development, must never error here.\n\tif (typeof type == 'function' && type.defaultProps != NULL) {\n\t\tfor (i in type.defaultProps) {\n\t\t\tif (normalizedProps[i] === UNDEFINED) {\n\t\t\t\tnormalizedProps[i] = type.defaultProps[i];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn createVNode(type, normalizedProps, key, ref, NULL);\n}\n\n/**\n * Create a VNode (used internally by Preact)\n * @param {import('./internal').VNode[\"type\"]} type The node name or Component\n * Constructor for this virtual node\n * @param {object | string | number | null} props The properties of this virtual node.\n * If this virtual node represents a text node, this is the text of the node (string or number).\n * @param {string | number | null} key The key for this virtual node, used when\n * diffing it against its children\n * @param {import('./internal').VNode[\"ref\"]} ref The ref property that will\n * receive a reference to its created child\n * @returns {import('./internal').VNode}\n */\nexport function createVNode(type, props, key, ref, original) {\n\t// V8 seems to be better at detecting type shapes if the object is allocated from the same call site\n\t// Do not inline into createElement and coerceToVNode!\n\t/** @type {import('./internal').VNode} */\n\tconst vnode = {\n\t\ttype,\n\t\tprops,\n\t\tkey,\n\t\tref,\n\t\t_children: NULL,\n\t\t_parent: NULL,\n\t\t_depth: 0,\n\t\t_dom: NULL,\n\t\t_component: NULL,\n\t\tconstructor: UNDEFINED,\n\t\t_original: original == NULL ? ++vnodeId : original,\n\t\t_index: -1,\n\t\t_flags: 0\n\t};\n\n\t// Only invoke the vnode hook if this was *not* a direct copy:\n\tif (original == NULL && options.vnode != NULL) options.vnode(vnode);\n\n\treturn vnode;\n}\n\nexport function createRef() {\n\treturn { current: NULL };\n}\n\nexport function Fragment(props) {\n\treturn props.children;\n}\n\n/**\n * Check if a the argument is a valid Preact VNode.\n * @param {*} vnode\n * @returns {vnode is VNode}\n */\nexport const isValidElement = vnode =>\n\tvnode != NULL && vnode.constructor === UNDEFINED;\n","import { assign } from './util';\nimport { diff, commitRoot } from './diff/index';\nimport options from './options';\nimport { Fragment } from './create-element';\nimport { MODE_HYDRATE, NULL } from './constants';\n\n/**\n * Base Component class. Provides `setState()` and `forceUpdate()`, which\n * trigger rendering\n * @param {object} props The initial component props\n * @param {object} context The initial context from parent components'\n * getChildContext\n */\nexport function BaseComponent(props, context) {\n\tthis.props = props;\n\tthis.context = context;\n}\n\n/**\n * Update component state and schedule a re-render.\n * @this {import('./internal').Component}\n * @param {object | ((s: object, p: object) => object)} update A hash of state\n * properties to update with new values or a function that given the current\n * state and props returns a new partial state\n * @param {() => void} [callback] A function to be called once component state is\n * updated\n */\nBaseComponent.prototype.setState = function (update, callback) {\n\t// only clone state when copying to nextState the first time.\n\tlet s;\n\tif (this._nextState != NULL && this._nextState != this.state) {\n\t\ts = this._nextState;\n\t} else {\n\t\ts = this._nextState = assign({}, this.state);\n\t}\n\n\tif (typeof update == 'function') {\n\t\t// Some libraries like `immer` mark the current state as readonly,\n\t\t// preventing us from mutating it, so we need to clone it. See #2716\n\t\tupdate = update(assign({}, s), this.props);\n\t}\n\n\tif (update) {\n\t\tassign(s, update);\n\t}\n\n\t// Skip update if updater function returned null\n\tif (update == NULL) return;\n\n\tif (this._vnode) {\n\t\tif (callback) {\n\t\t\tthis._stateCallbacks.push(callback);\n\t\t}\n\t\tenqueueRender(this);\n\t}\n};\n\n/**\n * Immediately perform a synchronous re-render of the component\n * @this {import('./internal').Component}\n * @param {() => void} [callback] A function to be called after component is\n * re-rendered\n */\nBaseComponent.prototype.forceUpdate = function (callback) {\n\tif (this._vnode) {\n\t\t// Set render mode so that we can differentiate where the render request\n\t\t// is coming from. We need this because forceUpdate should never call\n\t\t// shouldComponentUpdate\n\t\tthis._force = true;\n\t\tif (callback) this._renderCallbacks.push(callback);\n\t\tenqueueRender(this);\n\t}\n};\n\n/**\n * Accepts `props` and `state`, and returns a new Virtual DOM tree to build.\n * Virtual DOM is generally constructed via [JSX](https://jasonformat.com/wtf-is-jsx).\n * @param {object} props Props (eg: JSX attributes) received from parent\n * element/component\n * @param {object} state The component's current state\n * @param {object} context Context object, as returned by the nearest\n * ancestor's `getChildContext()`\n * @returns {ComponentChildren | void}\n */\nBaseComponent.prototype.render = Fragment;\n\n/**\n * @param {import('./internal').VNode} vnode\n * @param {number | null} [childIndex]\n */\nexport function getDomSibling(vnode, childIndex) {\n\tif (childIndex == NULL) {\n\t\t// Use childIndex==null as a signal to resume the search from the vnode's sibling\n\t\treturn vnode._parent\n\t\t\t? getDomSibling(vnode._parent, vnode._index + 1)\n\t\t\t: NULL;\n\t}\n\n\tlet sibling;\n\tfor (; childIndex < vnode._children.length; childIndex++) {\n\t\tsibling = vnode._children[childIndex];\n\n\t\tif (sibling != NULL && sibling._dom != NULL) {\n\t\t\t// Since updateParentDomPointers keeps _dom pointer correct,\n\t\t\t// we can rely on _dom to tell us if this subtree contains a\n\t\t\t// rendered DOM node, and what the first rendered DOM node is\n\t\t\treturn sibling._dom;\n\t\t}\n\t}\n\n\t// If we get here, we have not found a DOM node in this vnode's children.\n\t// We must resume from this vnode's sibling (in it's parent _children array)\n\t// Only climb up and search the parent if we aren't searching through a DOM\n\t// VNode (meaning we reached the DOM parent of the original vnode that began\n\t// the search)\n\treturn typeof vnode.type == 'function' ? getDomSibling(vnode) : NULL;\n}\n\n/**\n * Trigger in-place re-rendering of a component.\n * @param {import('./internal').Component} component The component to rerender\n */\nfunction renderComponent(component) {\n\tlet oldVNode = component._vnode,\n\t\toldDom = oldVNode._dom,\n\t\tcommitQueue = [],\n\t\trefQueue = [];\n\n\tif (component._parentDom) {\n\t\tconst newVNode = assign({}, oldVNode);\n\t\tnewVNode._original = oldVNode._original + 1;\n\t\tif (options.vnode) options.vnode(newVNode);\n\n\t\tdiff(\n\t\t\tcomponent._parentDom,\n\t\t\tnewVNode,\n\t\t\toldVNode,\n\t\t\tcomponent._globalContext,\n\t\t\tcomponent._parentDom.namespaceURI,\n\t\t\toldVNode._flags & MODE_HYDRATE ? [oldDom] : NULL,\n\t\t\tcommitQueue,\n\t\t\toldDom == NULL ? getDomSibling(oldVNode) : oldDom,\n\t\t\t!!(oldVNode._flags & MODE_HYDRATE),\n\t\t\trefQueue\n\t\t);\n\n\t\tnewVNode._original = oldVNode._original;\n\t\tnewVNode._parent._children[newVNode._index] = newVNode;\n\t\tcommitRoot(commitQueue, newVNode, refQueue);\n\t\toldVNode._dom = oldVNode._parent = null;\n\n\t\tif (newVNode._dom != oldDom) {\n\t\t\tupdateParentDomPointers(newVNode);\n\t\t}\n\t}\n}\n\n/**\n * @param {import('./internal').VNode} vnode\n */\nfunction updateParentDomPointers(vnode) {\n\tif ((vnode = vnode._parent) != NULL && vnode._component != NULL) {\n\t\tvnode._dom = vnode._component.base = NULL;\n\t\tfor (let i = 0; i < vnode._children.length; i++) {\n\t\t\tlet child = vnode._children[i];\n\t\t\tif (child != NULL && child._dom != NULL) {\n\t\t\t\tvnode._dom = vnode._component.base = child._dom;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn updateParentDomPointers(vnode);\n\t}\n}\n\n/**\n * The render queue\n * @type {Array}\n */\nlet rerenderQueue = [];\n\n/*\n * The value of `Component.debounce` must asynchronously invoke the passed in callback. It is\n * important that contributors to Preact can consistently reason about what calls to `setState`, etc.\n * do, and when their effects will be applied. See the links below for some further reading on designing\n * asynchronous APIs.\n * * [Designing APIs for Asynchrony](https://blog.izs.me/2013/08/designing-apis-for-asynchrony)\n * * [Callbacks synchronous and asynchronous](https://blog.ometer.com/2011/07/24/callbacks-synchronous-and-asynchronous/)\n */\n\nlet prevDebounce;\n\nconst defer =\n\ttypeof Promise == 'function'\n\t\t? Promise.prototype.then.bind(Promise.resolve())\n\t\t: setTimeout;\n\n/**\n * Enqueue a rerender of a component\n * @param {import('./internal').Component} c The component to rerender\n */\nexport function enqueueRender(c) {\n\tif (\n\t\t(!c._dirty &&\n\t\t\t(c._dirty = true) &&\n\t\t\trerenderQueue.push(c) &&\n\t\t\t!process._rerenderCount++) ||\n\t\tprevDebounce != options.debounceRendering\n\t) {\n\t\tprevDebounce = options.debounceRendering;\n\t\t(prevDebounce || defer)(process);\n\t}\n}\n\n/**\n * @param {import('./internal').Component} a\n * @param {import('./internal').Component} b\n */\nconst depthSort = (a, b) => a._vnode._depth - b._vnode._depth;\n\n/** Flush the render queue by rerendering all queued components */\nfunction process() {\n\tlet c,\n\t\tl = 1;\n\n\t// Don't update `renderCount` yet. Keep its value non-zero to prevent unnecessary\n\t// process() calls from getting scheduled while `queue` is still being consumed.\n\twhile (rerenderQueue.length) {\n\t\t// Keep the rerender queue sorted by (depth, insertion order). The queue\n\t\t// will initially be sorted on the first iteration only if it has more than 1 item.\n\t\t//\n\t\t// New items can be added to the queue e.g. when rerendering a provider, so we want to\n\t\t// keep the order from top to bottom with those new items so we can handle them in a\n\t\t// single pass\n\t\tif (rerenderQueue.length > l) {\n\t\t\trerenderQueue.sort(depthSort);\n\t\t}\n\n\t\tc = rerenderQueue.shift();\n\t\tl = rerenderQueue.length;\n\n\t\tif (c._dirty) {\n\t\t\trenderComponent(c);\n\t\t}\n\t}\n\tprocess._rerenderCount = 0;\n}\n\nprocess._rerenderCount = 0;\n","import { IS_NON_DIMENSIONAL, NULL, SVG_NAMESPACE } from '../constants';\nimport options from '../options';\n\nfunction setStyle(style, key, value) {\n\tif (key[0] == '-') {\n\t\tstyle.setProperty(key, value == NULL ? '' : value);\n\t} else if (value == NULL) {\n\t\tstyle[key] = '';\n\t} else if (typeof value != 'number' || IS_NON_DIMENSIONAL.test(key)) {\n\t\tstyle[key] = value;\n\t} else {\n\t\tstyle[key] = value + 'px';\n\t}\n}\n\nconst CAPTURE_REGEX = /(PointerCapture)$|Capture$/i;\n\n// A logical clock to solve issues like https://github.com/preactjs/preact/issues/3927.\n// When the DOM performs an event it leaves micro-ticks in between bubbling up which means that\n// an event can trigger on a newly reated DOM-node while the event bubbles up.\n//\n// Originally inspired by Vue\n// (https://github.com/vuejs/core/blob/caeb8a68811a1b0f79/packages/runtime-dom/src/modules/events.ts#L90-L101),\n// but modified to use a logical clock instead of Date.now() in case event handlers get attached\n// and events get dispatched during the same millisecond.\n//\n// The clock is incremented after each new event dispatch. This allows 1 000 000 new events\n// per second for over 280 years before the value reaches Number.MAX_SAFE_INTEGER (2**53 - 1).\nlet eventClock = 0;\n\n/**\n * Set a property value on a DOM node\n * @param {import('../internal').PreactElement} dom The DOM node to modify\n * @param {string} name The name of the property to set\n * @param {*} value The value to set the property to\n * @param {*} oldValue The old value the property had\n * @param {string} namespace Whether or not this DOM node is an SVG node or not\n */\nexport function setProperty(dom, name, value, oldValue, namespace) {\n\tlet useCapture;\n\n\to: if (name == 'style') {\n\t\tif (typeof value == 'string') {\n\t\t\tdom.style.cssText = value;\n\t\t} else {\n\t\t\tif (typeof oldValue == 'string') {\n\t\t\t\tdom.style.cssText = oldValue = '';\n\t\t\t}\n\n\t\t\tif (oldValue) {\n\t\t\t\tfor (name in oldValue) {\n\t\t\t\t\tif (!(value && name in value)) {\n\t\t\t\t\t\tsetStyle(dom.style, name, '');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (value) {\n\t\t\t\tfor (name in value) {\n\t\t\t\t\tif (!oldValue || value[name] != oldValue[name]) {\n\t\t\t\t\t\tsetStyle(dom.style, name, value[name]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// Benchmark for comparison: https://esbench.com/bench/574c954bdb965b9a00965ac6\n\telse if (name[0] == 'o' && name[1] == 'n') {\n\t\tuseCapture = name != (name = name.replace(CAPTURE_REGEX, '$1'));\n\t\tconst lowerCaseName = name.toLowerCase();\n\n\t\t// Infer correct casing for DOM built-in events:\n\t\tif (lowerCaseName in dom || name == 'onFocusOut' || name == 'onFocusIn')\n\t\t\tname = lowerCaseName.slice(2);\n\t\telse name = name.slice(2);\n\n\t\tif (!dom._listeners) dom._listeners = {};\n\t\tdom._listeners[name + useCapture] = value;\n\n\t\tif (value) {\n\t\t\tif (!oldValue) {\n\t\t\t\tvalue._attached = eventClock;\n\t\t\t\tdom.addEventListener(\n\t\t\t\t\tname,\n\t\t\t\t\tuseCapture ? eventProxyCapture : eventProxy,\n\t\t\t\t\tuseCapture\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tvalue._attached = oldValue._attached;\n\t\t\t}\n\t\t} else {\n\t\t\tdom.removeEventListener(\n\t\t\t\tname,\n\t\t\t\tuseCapture ? eventProxyCapture : eventProxy,\n\t\t\t\tuseCapture\n\t\t\t);\n\t\t}\n\t} else {\n\t\tif (namespace == SVG_NAMESPACE) {\n\t\t\t// Normalize incorrect prop usage for SVG:\n\t\t\t// - xlink:href / xlinkHref --> href (xlink:href was removed from SVG and isn't needed)\n\t\t\t// - className --> class\n\t\t\tname = name.replace(/xlink(H|:h)/, 'h').replace(/sName$/, 's');\n\t\t} else if (\n\t\t\tname != 'width' &&\n\t\t\tname != 'height' &&\n\t\t\tname != 'href' &&\n\t\t\tname != 'list' &&\n\t\t\tname != 'form' &&\n\t\t\t// Default value in browsers is `-1` and an empty string is\n\t\t\t// cast to `0` instead\n\t\t\tname != 'tabIndex' &&\n\t\t\tname != 'download' &&\n\t\t\tname != 'rowSpan' &&\n\t\t\tname != 'colSpan' &&\n\t\t\tname != 'role' &&\n\t\t\tname != 'popover' &&\n\t\t\tname in dom\n\t\t) {\n\t\t\ttry {\n\t\t\t\tdom[name] = value == NULL ? '' : value;\n\t\t\t\t// labelled break is 1b smaller here than a return statement (sorry)\n\t\t\t\tbreak o;\n\t\t\t} catch (e) {}\n\t\t}\n\n\t\t// aria- and data- attributes have no boolean representation.\n\t\t// A `false` value is different from the attribute not being\n\t\t// present, so we can't remove it. For non-boolean aria\n\t\t// attributes we could treat false as a removal, but the\n\t\t// amount of exceptions would cost too many bytes. On top of\n\t\t// that other frameworks generally stringify `false`.\n\n\t\tif (typeof value == 'function') {\n\t\t\t// never serialize functions as attribute values\n\t\t} else if (value != NULL && (value !== false || name[4] == '-')) {\n\t\t\tdom.setAttribute(name, name == 'popover' && value == true ? '' : value);\n\t\t} else {\n\t\t\tdom.removeAttribute(name);\n\t\t}\n\t}\n}\n\n/**\n * Create an event proxy function.\n * @param {boolean} useCapture Is the event handler for the capture phase.\n * @private\n */\nfunction createEventProxy(useCapture) {\n\t/**\n\t * Proxy an event to hooked event handlers\n\t * @param {import('../internal').PreactEvent} e The event object from the browser\n\t * @private\n\t */\n\treturn function (e) {\n\t\tif (this._listeners) {\n\t\t\tconst eventHandler = this._listeners[e.type + useCapture];\n\t\t\tif (e._dispatched == NULL) {\n\t\t\t\te._dispatched = eventClock++;\n\n\t\t\t\t// When `e._dispatched` is smaller than the time when the targeted event\n\t\t\t\t// handler was attached we know we have bubbled up to an element that was added\n\t\t\t\t// during patching the DOM.\n\t\t\t} else if (e._dispatched < eventHandler._attached) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treturn eventHandler(options.event ? options.event(e) : e);\n\t\t}\n\t};\n}\n\nconst eventProxy = createEventProxy(false);\nconst eventProxyCapture = createEventProxy(true);\n","import { enqueueRender } from './component';\nimport { NULL } from './constants';\n\nexport let i = 0;\n\nexport function createContext(defaultValue) {\n\tfunction Context(props) {\n\t\tif (!this.getChildContext) {\n\t\t\t/** @type {Set | null} */\n\t\t\tlet subs = new Set();\n\t\t\tlet ctx = {};\n\t\t\tctx[Context._id] = this;\n\n\t\t\tthis.getChildContext = () => ctx;\n\n\t\t\tthis.componentWillUnmount = () => {\n\t\t\t\tsubs = NULL;\n\t\t\t};\n\n\t\t\tthis.shouldComponentUpdate = function (_props) {\n\t\t\t\t// @ts-expect-error even\n\t\t\t\tif (this.props.value != _props.value) {\n\t\t\t\t\tsubs.forEach(c => {\n\t\t\t\t\t\tc._force = true;\n\t\t\t\t\t\tenqueueRender(c);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tthis.sub = c => {\n\t\t\t\tsubs.add(c);\n\t\t\t\tlet old = c.componentWillUnmount;\n\t\t\t\tc.componentWillUnmount = () => {\n\t\t\t\t\tif (subs) {\n\t\t\t\t\t\tsubs.delete(c);\n\t\t\t\t\t}\n\t\t\t\t\tif (old) old.call(c);\n\t\t\t\t};\n\t\t\t};\n\t\t}\n\n\t\treturn props.children;\n\t}\n\n\tContext._id = '__cC' + i++;\n\tContext._defaultValue = defaultValue;\n\n\t/** @type {import('./internal').FunctionComponent} */\n\tContext.Consumer = (props, contextValue) => {\n\t\treturn props.children(contextValue);\n\t};\n\n\t// we could also get rid of _contextRef entirely\n\tContext.Provider =\n\t\tContext._contextRef =\n\t\tContext.Consumer.contextType =\n\t\t\tContext;\n\n\treturn Context;\n}\n","import { diff, unmount, applyRef } from './index';\nimport { createVNode, Fragment } from '../create-element';\nimport {\n\tEMPTY_OBJ,\n\tEMPTY_ARR,\n\tINSERT_VNODE,\n\tMATCHED,\n\tUNDEFINED,\n\tNULL\n} from '../constants';\nimport { isArray } from '../util';\nimport { getDomSibling } from '../component';\n\n/**\n * @typedef {import('../internal').ComponentChildren} ComponentChildren\n * @typedef {import('../internal').Component} Component\n * @typedef {import('../internal').PreactElement} PreactElement\n * @typedef {import('../internal').VNode} VNode\n */\n\n/**\n * Diff the children of a virtual node\n * @param {PreactElement} parentDom The DOM element whose children are being\n * diffed\n * @param {ComponentChildren[]} renderResult\n * @param {VNode} newParentVNode The new virtual node whose children should be\n * diff'ed against oldParentVNode\n * @param {VNode} oldParentVNode The old virtual node whose children should be\n * diff'ed against newParentVNode\n * @param {object} globalContext The current context object - modified by\n * getChildContext\n * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML)\n * @param {Array} excessDomChildren\n * @param {Array} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {PreactElement} oldDom The current attached DOM element any new dom\n * elements should be placed around. Likely `null` on first render (except when\n * hydrating). Can be a sibling DOM element when diffing Fragments that have\n * siblings. In most cases, it starts out as `oldChildren[0]._dom`.\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n */\nexport function diffChildren(\n\tparentDom,\n\trenderResult,\n\tnewParentVNode,\n\toldParentVNode,\n\tglobalContext,\n\tnamespace,\n\texcessDomChildren,\n\tcommitQueue,\n\toldDom,\n\tisHydrating,\n\trefQueue\n) {\n\tlet i,\n\t\t/** @type {VNode} */\n\t\toldVNode,\n\t\t/** @type {VNode} */\n\t\tchildVNode,\n\t\t/** @type {PreactElement} */\n\t\tnewDom,\n\t\t/** @type {PreactElement} */\n\t\tfirstChildDom;\n\n\t// This is a compression of oldParentVNode!=null && oldParentVNode != EMPTY_OBJ && oldParentVNode._children || EMPTY_ARR\n\t// as EMPTY_OBJ._children should be `undefined`.\n\t/** @type {VNode[]} */\n\tlet oldChildren = (oldParentVNode && oldParentVNode._children) || EMPTY_ARR;\n\n\tlet newChildrenLength = renderResult.length;\n\n\toldDom = constructNewChildrenArray(\n\t\tnewParentVNode,\n\t\trenderResult,\n\t\toldChildren,\n\t\toldDom,\n\t\tnewChildrenLength\n\t);\n\n\tfor (i = 0; i < newChildrenLength; i++) {\n\t\tchildVNode = newParentVNode._children[i];\n\t\tif (childVNode == NULL) continue;\n\n\t\t// At this point, constructNewChildrenArray has assigned _index to be the\n\t\t// matchingIndex for this VNode's oldVNode (or -1 if there is no oldVNode).\n\t\tif (childVNode._index == -1) {\n\t\t\toldVNode = EMPTY_OBJ;\n\t\t} else {\n\t\t\toldVNode = oldChildren[childVNode._index] || EMPTY_OBJ;\n\t\t}\n\n\t\t// Update childVNode._index to its final index\n\t\tchildVNode._index = i;\n\n\t\t// Morph the old element into the new one, but don't append it to the dom yet\n\t\tlet result = diff(\n\t\t\tparentDom,\n\t\t\tchildVNode,\n\t\t\toldVNode,\n\t\t\tglobalContext,\n\t\t\tnamespace,\n\t\t\texcessDomChildren,\n\t\t\tcommitQueue,\n\t\t\toldDom,\n\t\t\tisHydrating,\n\t\t\trefQueue\n\t\t);\n\n\t\t// Adjust DOM nodes\n\t\tnewDom = childVNode._dom;\n\t\tif (childVNode.ref && oldVNode.ref != childVNode.ref) {\n\t\t\tif (oldVNode.ref) {\n\t\t\t\tapplyRef(oldVNode.ref, NULL, childVNode);\n\t\t\t}\n\t\t\trefQueue.push(\n\t\t\t\tchildVNode.ref,\n\t\t\t\tchildVNode._component || newDom,\n\t\t\t\tchildVNode\n\t\t\t);\n\t\t}\n\n\t\tif (firstChildDom == NULL && newDom != NULL) {\n\t\t\tfirstChildDom = newDom;\n\t\t}\n\n\t\tlet shouldPlace = !!(childVNode._flags & INSERT_VNODE);\n\t\tif (shouldPlace || oldVNode._children === childVNode._children) {\n\t\t\toldDom = insert(childVNode, oldDom, parentDom, shouldPlace);\n\t\t} else if (typeof childVNode.type == 'function' && result !== UNDEFINED) {\n\t\t\toldDom = result;\n\t\t} else if (newDom) {\n\t\t\toldDom = newDom.nextSibling;\n\t\t}\n\n\t\t// Unset diffing flags\n\t\tchildVNode._flags &= ~(INSERT_VNODE | MATCHED);\n\t}\n\n\tnewParentVNode._dom = firstChildDom;\n\n\treturn oldDom;\n}\n\n/**\n * @param {VNode} newParentVNode\n * @param {ComponentChildren[]} renderResult\n * @param {VNode[]} oldChildren\n */\nfunction constructNewChildrenArray(\n\tnewParentVNode,\n\trenderResult,\n\toldChildren,\n\toldDom,\n\tnewChildrenLength\n) {\n\t/** @type {number} */\n\tlet i;\n\t/** @type {VNode} */\n\tlet childVNode;\n\t/** @type {VNode} */\n\tlet oldVNode;\n\n\tlet oldChildrenLength = oldChildren.length,\n\t\tremainingOldChildren = oldChildrenLength;\n\n\tlet skew = 0;\n\n\tnewParentVNode._children = new Array(newChildrenLength);\n\tfor (i = 0; i < newChildrenLength; i++) {\n\t\t// @ts-expect-error We are reusing the childVNode variable to hold both the\n\t\t// pre and post normalized childVNode\n\t\tchildVNode = renderResult[i];\n\n\t\tif (\n\t\t\tchildVNode == NULL ||\n\t\t\ttypeof childVNode == 'boolean' ||\n\t\t\ttypeof childVNode == 'function'\n\t\t) {\n\t\t\tnewParentVNode._children[i] = NULL;\n\t\t\tcontinue;\n\t\t}\n\t\t// If this newVNode is being reused (e.g.

    {reuse}{reuse}
    ) in the same diff,\n\t\t// or we are rendering a component (e.g. setState) copy the oldVNodes so it can have\n\t\t// it's own DOM & etc. pointers\n\t\telse if (\n\t\t\ttypeof childVNode == 'string' ||\n\t\t\ttypeof childVNode == 'number' ||\n\t\t\t// eslint-disable-next-line valid-typeof\n\t\t\ttypeof childVNode == 'bigint' ||\n\t\t\tchildVNode.constructor == String\n\t\t) {\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tNULL,\n\t\t\t\tchildVNode,\n\t\t\t\tNULL,\n\t\t\t\tNULL,\n\t\t\t\tNULL\n\t\t\t);\n\t\t} else if (isArray(childVNode)) {\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tFragment,\n\t\t\t\t{ children: childVNode },\n\t\t\t\tNULL,\n\t\t\t\tNULL,\n\t\t\t\tNULL\n\t\t\t);\n\t\t} else if (childVNode.constructor === UNDEFINED && childVNode._depth > 0) {\n\t\t\t// VNode is already in use, clone it. This can happen in the following\n\t\t\t// scenario:\n\t\t\t// const reuse =
    \n\t\t\t//
    {reuse}{reuse}
    \n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tchildVNode.type,\n\t\t\t\tchildVNode.props,\n\t\t\t\tchildVNode.key,\n\t\t\t\tchildVNode.ref ? childVNode.ref : NULL,\n\t\t\t\tchildVNode._original\n\t\t\t);\n\t\t} else {\n\t\t\tnewParentVNode._children[i] = childVNode;\n\t\t}\n\n\t\tconst skewedIndex = i + skew;\n\t\tchildVNode._parent = newParentVNode;\n\t\tchildVNode._depth = newParentVNode._depth + 1;\n\n\t\t// Temporarily store the matchingIndex on the _index property so we can pull\n\t\t// out the oldVNode in diffChildren. We'll override this to the VNode's\n\t\t// final index after using this property to get the oldVNode\n\t\tconst matchingIndex = (childVNode._index = findMatchingIndex(\n\t\t\tchildVNode,\n\t\t\toldChildren,\n\t\t\tskewedIndex,\n\t\t\tremainingOldChildren\n\t\t));\n\n\t\toldVNode = NULL;\n\t\tif (matchingIndex != -1) {\n\t\t\toldVNode = oldChildren[matchingIndex];\n\t\t\tremainingOldChildren--;\n\t\t\tif (oldVNode) {\n\t\t\t\toldVNode._flags |= MATCHED;\n\t\t\t}\n\t\t}\n\n\t\t// Here, we define isMounting for the purposes of the skew diffing\n\t\t// algorithm. Nodes that are unsuspending are considered mounting and we detect\n\t\t// this by checking if oldVNode._original == null\n\t\tconst isMounting = oldVNode == NULL || oldVNode._original == NULL;\n\n\t\tif (isMounting) {\n\t\t\tif (matchingIndex == -1) {\n\t\t\t\t// When the array of children is growing we need to decrease the skew\n\t\t\t\t// as we are adding a new element to the array.\n\t\t\t\t// Example:\n\t\t\t\t// [1, 2, 3] --> [0, 1, 2, 3]\n\t\t\t\t// oldChildren newChildren\n\t\t\t\t//\n\t\t\t\t// The new element is at index 0, so our skew is 0,\n\t\t\t\t// we need to decrease the skew as we are adding a new element.\n\t\t\t\t// The decrease will cause us to compare the element at position 1\n\t\t\t\t// with value 1 with the element at position 0 with value 0.\n\t\t\t\t//\n\t\t\t\t// A linear concept is applied when the array is shrinking,\n\t\t\t\t// if the length is unchanged we can assume that no skew\n\t\t\t\t// changes are needed.\n\t\t\t\tif (newChildrenLength > oldChildrenLength) {\n\t\t\t\t\tskew--;\n\t\t\t\t} else if (newChildrenLength < oldChildrenLength) {\n\t\t\t\t\tskew++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If we are mounting a DOM VNode, mark it for insertion\n\t\t\tif (typeof childVNode.type != 'function') {\n\t\t\t\tchildVNode._flags |= INSERT_VNODE;\n\t\t\t}\n\t\t} else if (matchingIndex != skewedIndex) {\n\t\t\t// When we move elements around i.e. [0, 1, 2] --> [1, 0, 2]\n\t\t\t// --> we diff 1, we find it at position 1 while our skewed index is 0 and our skew is 0\n\t\t\t// we set the skew to 1 as we found an offset.\n\t\t\t// --> we diff 0, we find it at position 0 while our skewed index is at 2 and our skew is 1\n\t\t\t// this makes us increase the skew again.\n\t\t\t// --> we diff 2, we find it at position 2 while our skewed index is at 4 and our skew is 2\n\t\t\t//\n\t\t\t// this becomes an optimization question where currently we see a 1 element offset as an insertion\n\t\t\t// or deletion i.e. we optimize for [0, 1, 2] --> [9, 0, 1, 2]\n\t\t\t// while a more than 1 offset we see as a swap.\n\t\t\t// We could probably build heuristics for having an optimized course of action here as well, but\n\t\t\t// might go at the cost of some bytes.\n\t\t\t//\n\t\t\t// If we wanted to optimize for i.e. only swaps we'd just do the last two code-branches and have\n\t\t\t// only the first item be a re-scouting and all the others fall in their skewed counter-part.\n\t\t\t// We could also further optimize for swaps\n\t\t\tif (matchingIndex == skewedIndex - 1) {\n\t\t\t\tskew--;\n\t\t\t} else if (matchingIndex == skewedIndex + 1) {\n\t\t\t\tskew++;\n\t\t\t} else {\n\t\t\t\tif (matchingIndex > skewedIndex) {\n\t\t\t\t\tskew--;\n\t\t\t\t} else {\n\t\t\t\t\tskew++;\n\t\t\t\t}\n\n\t\t\t\t// Move this VNode's DOM if the original index (matchingIndex) doesn't\n\t\t\t\t// match the new skew index (i + new skew)\n\t\t\t\t// In the former two branches we know that it matches after skewing\n\t\t\t\tchildVNode._flags |= INSERT_VNODE;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Remove remaining oldChildren if there are any. Loop forwards so that as we\n\t// unmount DOM from the beginning of the oldChildren, we can adjust oldDom to\n\t// point to the next child, which needs to be the first DOM node that won't be\n\t// unmounted.\n\tif (remainingOldChildren) {\n\t\tfor (i = 0; i < oldChildrenLength; i++) {\n\t\t\toldVNode = oldChildren[i];\n\t\t\tif (oldVNode != NULL && (oldVNode._flags & MATCHED) == 0) {\n\t\t\t\tif (oldVNode._dom == oldDom) {\n\t\t\t\t\toldDom = getDomSibling(oldVNode);\n\t\t\t\t}\n\n\t\t\t\tunmount(oldVNode, oldVNode);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn oldDom;\n}\n\n/**\n * @param {VNode} parentVNode\n * @param {PreactElement} oldDom\n * @param {PreactElement} parentDom\n * @param {boolean} shouldPlace\n * @returns {PreactElement}\n */\nfunction insert(parentVNode, oldDom, parentDom, shouldPlace) {\n\t// Note: VNodes in nested suspended trees may be missing _children.\n\n\tif (typeof parentVNode.type == 'function') {\n\t\tlet children = parentVNode._children;\n\t\tfor (let i = 0; children && i < children.length; i++) {\n\t\t\tif (children[i]) {\n\t\t\t\t// If we enter this code path on sCU bailout, where we copy\n\t\t\t\t// oldVNode._children to newVNode._children, we need to update the old\n\t\t\t\t// children's _parent pointer to point to the newVNode (parentVNode\n\t\t\t\t// here).\n\t\t\t\tchildren[i]._parent = parentVNode;\n\t\t\t\toldDom = insert(children[i], oldDom, parentDom, shouldPlace);\n\t\t\t}\n\t\t}\n\n\t\treturn oldDom;\n\t} else if (parentVNode._dom != oldDom) {\n\t\tif (shouldPlace) {\n\t\t\tif (oldDom && parentVNode.type && !oldDom.parentNode) {\n\t\t\t\toldDom = getDomSibling(parentVNode);\n\t\t\t}\n\t\t\tparentDom.insertBefore(parentVNode._dom, oldDom || NULL);\n\t\t}\n\t\toldDom = parentVNode._dom;\n\t}\n\n\tdo {\n\t\toldDom = oldDom && oldDom.nextSibling;\n\t} while (oldDom != NULL && oldDom.nodeType == 8);\n\n\treturn oldDom;\n}\n\n/**\n * Flatten and loop through the children of a virtual node\n * @param {ComponentChildren} children The unflattened children of a virtual\n * node\n * @returns {VNode[]}\n */\nexport function toChildArray(children, out) {\n\tout = out || [];\n\tif (children == NULL || typeof children == 'boolean') {\n\t} else if (isArray(children)) {\n\t\tchildren.some(child => {\n\t\t\ttoChildArray(child, out);\n\t\t});\n\t} else {\n\t\tout.push(children);\n\t}\n\treturn out;\n}\n\n/**\n * @param {VNode} childVNode\n * @param {VNode[]} oldChildren\n * @param {number} skewedIndex\n * @param {number} remainingOldChildren\n * @returns {number}\n */\nfunction findMatchingIndex(\n\tchildVNode,\n\toldChildren,\n\tskewedIndex,\n\tremainingOldChildren\n) {\n\tconst key = childVNode.key;\n\tconst type = childVNode.type;\n\tlet oldVNode = oldChildren[skewedIndex];\n\tconst matched = oldVNode != NULL && (oldVNode._flags & MATCHED) == 0;\n\n\t// We only need to perform a search if there are more children\n\t// (remainingOldChildren) to search. However, if the oldVNode we just looked\n\t// at skewedIndex was not already used in this diff, then there must be at\n\t// least 1 other (so greater than 1) remainingOldChildren to attempt to match\n\t// against. So the following condition checks that ensuring\n\t// remainingOldChildren > 1 if the oldVNode is not already used/matched. Else\n\t// if the oldVNode was null or matched, then there could needs to be at least\n\t// 1 (aka `remainingOldChildren > 0`) children to find and compare against.\n\t//\n\t// If there is an unkeyed functional VNode, that isn't a built-in like our Fragment,\n\t// we should not search as we risk re-using state of an unrelated VNode. (reverted for now)\n\tlet shouldSearch =\n\t\t// (typeof type != 'function' || type === Fragment || key) &&\n\t\tremainingOldChildren > (matched ? 1 : 0);\n\n\tif (\n\t\t(oldVNode === NULL && key == null) ||\n\t\t(matched && key == oldVNode.key && type == oldVNode.type)\n\t) {\n\t\treturn skewedIndex;\n\t} else if (shouldSearch) {\n\t\tlet x = skewedIndex - 1;\n\t\tlet y = skewedIndex + 1;\n\t\twhile (x >= 0 || y < oldChildren.length) {\n\t\t\tconst childIndex = x >= 0 ? x-- : y++;\n\t\t\toldVNode = oldChildren[childIndex];\n\t\t\tif (\n\t\t\t\toldVNode != NULL &&\n\t\t\t\t(oldVNode._flags & MATCHED) == 0 &&\n\t\t\t\tkey == oldVNode.key &&\n\t\t\t\ttype == oldVNode.type\n\t\t\t) {\n\t\t\t\treturn childIndex;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn -1;\n}\n","import {\n\tEMPTY_OBJ,\n\tMATH_NAMESPACE,\n\tMODE_HYDRATE,\n\tMODE_SUSPENDED,\n\tNULL,\n\tRESET_MODE,\n\tSVG_NAMESPACE,\n\tUNDEFINED,\n\tXHTML_NAMESPACE\n} from '../constants';\nimport { BaseComponent, getDomSibling } from '../component';\nimport { Fragment } from '../create-element';\nimport { diffChildren } from './children';\nimport { setProperty } from './props';\nimport { assign, isArray, removeNode, slice } from '../util';\nimport options from '../options';\n\n/**\n * @typedef {import('../internal').ComponentChildren} ComponentChildren\n * @typedef {import('../internal').Component} Component\n * @typedef {import('../internal').PreactElement} PreactElement\n * @typedef {import('../internal').VNode} VNode\n */\n\n/**\n * @template {any} T\n * @typedef {import('../internal').Ref} Ref\n */\n\n/**\n * Diff two virtual nodes and apply proper changes to the DOM\n * @param {PreactElement} parentDom The parent of the DOM element\n * @param {VNode} newVNode The new virtual node\n * @param {VNode} oldVNode The old virtual node\n * @param {object} globalContext The current context object. Modified by\n * getChildContext\n * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML)\n * @param {Array} excessDomChildren\n * @param {Array} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {PreactElement} oldDom The current attached DOM element any new dom\n * elements should be placed around. Likely `null` on first render (except when\n * hydrating). Can be a sibling DOM element when diffing Fragments that have\n * siblings. In most cases, it starts out as `oldChildren[0]._dom`.\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n */\nexport function diff(\n\tparentDom,\n\tnewVNode,\n\toldVNode,\n\tglobalContext,\n\tnamespace,\n\texcessDomChildren,\n\tcommitQueue,\n\toldDom,\n\tisHydrating,\n\trefQueue\n) {\n\t/** @type {any} */\n\tlet tmp,\n\t\tnewType = newVNode.type;\n\n\t// When passing through createElement it assigns the object\n\t// constructor as undefined. This to prevent JSON-injection.\n\tif (newVNode.constructor !== UNDEFINED) return NULL;\n\n\t// If the previous diff bailed out, resume creating/hydrating.\n\tif (oldVNode._flags & MODE_SUSPENDED) {\n\t\tisHydrating = !!(oldVNode._flags & MODE_HYDRATE);\n\t\toldDom = newVNode._dom = oldVNode._dom;\n\t\texcessDomChildren = [oldDom];\n\t}\n\n\tif ((tmp = options._diff)) tmp(newVNode);\n\n\touter: if (typeof newType == 'function') {\n\t\ttry {\n\t\t\tlet c, isNew, oldProps, oldState, snapshot, clearProcessingException;\n\t\t\tlet newProps = newVNode.props;\n\t\t\tconst isClassComponent =\n\t\t\t\t'prototype' in newType && newType.prototype.render;\n\n\t\t\t// Necessary for createContext api. Setting this property will pass\n\t\t\t// the context value as `this.context` just for this component.\n\t\t\ttmp = newType.contextType;\n\t\t\tlet provider = tmp && globalContext[tmp._id];\n\t\t\tlet componentContext = tmp\n\t\t\t\t? provider\n\t\t\t\t\t? provider.props.value\n\t\t\t\t\t: tmp._defaultValue\n\t\t\t\t: globalContext;\n\n\t\t\t// Get component and set it to `c`\n\t\t\tif (oldVNode._component) {\n\t\t\t\tc = newVNode._component = oldVNode._component;\n\t\t\t\tclearProcessingException = c._processingException = c._pendingError;\n\t\t\t} else {\n\t\t\t\t// Instantiate the new component\n\t\t\t\tif (isClassComponent) {\n\t\t\t\t\t// @ts-expect-error The check above verifies that newType is suppose to be constructed\n\t\t\t\t\tnewVNode._component = c = new newType(newProps, componentContext); // eslint-disable-line new-cap\n\t\t\t\t} else {\n\t\t\t\t\t// @ts-expect-error Trust me, Component implements the interface we want\n\t\t\t\t\tnewVNode._component = c = new BaseComponent(\n\t\t\t\t\t\tnewProps,\n\t\t\t\t\t\tcomponentContext\n\t\t\t\t\t);\n\t\t\t\t\tc.constructor = newType;\n\t\t\t\t\tc.render = doRender;\n\t\t\t\t}\n\t\t\t\tif (provider) provider.sub(c);\n\n\t\t\t\tif (!c.state) c.state = {};\n\t\t\t\tc._globalContext = globalContext;\n\t\t\t\tisNew = c._dirty = true;\n\t\t\t\tc._renderCallbacks = [];\n\t\t\t\tc._stateCallbacks = [];\n\t\t\t}\n\n\t\t\t// Invoke getDerivedStateFromProps\n\t\t\tif (isClassComponent && c._nextState == NULL) {\n\t\t\t\tc._nextState = c.state;\n\t\t\t}\n\n\t\t\tif (isClassComponent && newType.getDerivedStateFromProps != NULL) {\n\t\t\t\tif (c._nextState == c.state) {\n\t\t\t\t\tc._nextState = assign({}, c._nextState);\n\t\t\t\t}\n\n\t\t\t\tassign(\n\t\t\t\t\tc._nextState,\n\t\t\t\t\tnewType.getDerivedStateFromProps(newProps, c._nextState)\n\t\t\t\t);\n\t\t\t}\n\n\t\t\toldProps = c.props;\n\t\t\toldState = c.state;\n\t\t\tc._vnode = newVNode;\n\n\t\t\t// Invoke pre-render lifecycle methods\n\t\t\tif (isNew) {\n\t\t\t\tif (\n\t\t\t\t\tisClassComponent &&\n\t\t\t\t\tnewType.getDerivedStateFromProps == NULL &&\n\t\t\t\t\tc.componentWillMount != NULL\n\t\t\t\t) {\n\t\t\t\t\tc.componentWillMount();\n\t\t\t\t}\n\n\t\t\t\tif (isClassComponent && c.componentDidMount != NULL) {\n\t\t\t\t\tc._renderCallbacks.push(c.componentDidMount);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (\n\t\t\t\t\tisClassComponent &&\n\t\t\t\t\tnewType.getDerivedStateFromProps == NULL &&\n\t\t\t\t\tnewProps !== oldProps &&\n\t\t\t\t\tc.componentWillReceiveProps != NULL\n\t\t\t\t) {\n\t\t\t\t\tc.componentWillReceiveProps(newProps, componentContext);\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\tnewVNode._original == oldVNode._original ||\n\t\t\t\t\t(!c._force &&\n\t\t\t\t\t\tc.shouldComponentUpdate != NULL &&\n\t\t\t\t\t\tc.shouldComponentUpdate(\n\t\t\t\t\t\t\tnewProps,\n\t\t\t\t\t\t\tc._nextState,\n\t\t\t\t\t\t\tcomponentContext\n\t\t\t\t\t\t) === false)\n\t\t\t\t) {\n\t\t\t\t\t// More info about this here: https://gist.github.com/JoviDeCroock/bec5f2ce93544d2e6070ef8e0036e4e8\n\t\t\t\t\tif (newVNode._original != oldVNode._original) {\n\t\t\t\t\t\t// When we are dealing with a bail because of sCU we have to update\n\t\t\t\t\t\t// the props, state and dirty-state.\n\t\t\t\t\t\t// when we are dealing with strict-equality we don't as the child could still\n\t\t\t\t\t\t// be dirtied see #3883\n\t\t\t\t\t\tc.props = newProps;\n\t\t\t\t\t\tc.state = c._nextState;\n\t\t\t\t\t\tc._dirty = false;\n\t\t\t\t\t}\n\n\t\t\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t\t\t\tnewVNode._children = oldVNode._children;\n\t\t\t\t\tnewVNode._children.some(vnode => {\n\t\t\t\t\t\tif (vnode) vnode._parent = newVNode;\n\t\t\t\t\t});\n\n\t\t\t\t\tfor (let i = 0; i < c._stateCallbacks.length; i++) {\n\t\t\t\t\t\tc._renderCallbacks.push(c._stateCallbacks[i]);\n\t\t\t\t\t}\n\t\t\t\t\tc._stateCallbacks = [];\n\n\t\t\t\t\tif (c._renderCallbacks.length) {\n\t\t\t\t\t\tcommitQueue.push(c);\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak outer;\n\t\t\t\t}\n\n\t\t\t\tif (c.componentWillUpdate != NULL) {\n\t\t\t\t\tc.componentWillUpdate(newProps, c._nextState, componentContext);\n\t\t\t\t}\n\n\t\t\t\tif (isClassComponent && c.componentDidUpdate != NULL) {\n\t\t\t\t\tc._renderCallbacks.push(() => {\n\t\t\t\t\t\tc.componentDidUpdate(oldProps, oldState, snapshot);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tc.context = componentContext;\n\t\t\tc.props = newProps;\n\t\t\tc._parentDom = parentDom;\n\t\t\tc._force = false;\n\n\t\t\tlet renderHook = options._render,\n\t\t\t\tcount = 0;\n\t\t\tif (isClassComponent) {\n\t\t\t\tc.state = c._nextState;\n\t\t\t\tc._dirty = false;\n\n\t\t\t\tif (renderHook) renderHook(newVNode);\n\n\t\t\t\ttmp = c.render(c.props, c.state, c.context);\n\n\t\t\t\tfor (let i = 0; i < c._stateCallbacks.length; i++) {\n\t\t\t\t\tc._renderCallbacks.push(c._stateCallbacks[i]);\n\t\t\t\t}\n\t\t\t\tc._stateCallbacks = [];\n\t\t\t} else {\n\t\t\t\tdo {\n\t\t\t\t\tc._dirty = false;\n\t\t\t\t\tif (renderHook) renderHook(newVNode);\n\n\t\t\t\t\ttmp = c.render(c.props, c.state, c.context);\n\n\t\t\t\t\t// Handle setState called in render, see #2553\n\t\t\t\t\tc.state = c._nextState;\n\t\t\t\t} while (c._dirty && ++count < 25);\n\t\t\t}\n\n\t\t\t// Handle setState called in render, see #2553\n\t\t\tc.state = c._nextState;\n\n\t\t\tif (c.getChildContext != NULL) {\n\t\t\t\tglobalContext = assign(assign({}, globalContext), c.getChildContext());\n\t\t\t}\n\n\t\t\tif (isClassComponent && !isNew && c.getSnapshotBeforeUpdate != NULL) {\n\t\t\t\tsnapshot = c.getSnapshotBeforeUpdate(oldProps, oldState);\n\t\t\t}\n\n\t\t\tlet isTopLevelFragment =\n\t\t\t\ttmp != NULL && tmp.type === Fragment && tmp.key == NULL;\n\t\t\tlet renderResult = tmp;\n\n\t\t\tif (isTopLevelFragment) {\n\t\t\t\trenderResult = cloneNode(tmp.props.children);\n\t\t\t}\n\n\t\t\toldDom = diffChildren(\n\t\t\t\tparentDom,\n\t\t\t\tisArray(renderResult) ? renderResult : [renderResult],\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tnamespace,\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\toldDom,\n\t\t\t\tisHydrating,\n\t\t\t\trefQueue\n\t\t\t);\n\n\t\t\tc.base = newVNode._dom;\n\n\t\t\t// We successfully rendered this VNode, unset any stored hydration/bailout state:\n\t\t\tnewVNode._flags &= RESET_MODE;\n\n\t\t\tif (c._renderCallbacks.length) {\n\t\t\t\tcommitQueue.push(c);\n\t\t\t}\n\n\t\t\tif (clearProcessingException) {\n\t\t\t\tc._pendingError = c._processingException = NULL;\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tnewVNode._original = NULL;\n\t\t\t// if hydrating or creating initial tree, bailout preserves DOM:\n\t\t\tif (isHydrating || excessDomChildren != NULL) {\n\t\t\t\tif (e.then) {\n\t\t\t\t\tnewVNode._flags |= isHydrating\n\t\t\t\t\t\t? MODE_HYDRATE | MODE_SUSPENDED\n\t\t\t\t\t\t: MODE_SUSPENDED;\n\n\t\t\t\t\twhile (oldDom && oldDom.nodeType == 8 && oldDom.nextSibling) {\n\t\t\t\t\t\toldDom = oldDom.nextSibling;\n\t\t\t\t\t}\n\n\t\t\t\t\texcessDomChildren[excessDomChildren.indexOf(oldDom)] = NULL;\n\t\t\t\t\tnewVNode._dom = oldDom;\n\t\t\t\t} else {\n\t\t\t\t\tfor (let i = excessDomChildren.length; i--; ) {\n\t\t\t\t\t\tremoveNode(excessDomChildren[i]);\n\t\t\t\t\t}\n\t\t\t\t\tmarkAsForce(newVNode);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t\t\tnewVNode._children = oldVNode._children;\n\t\t\t\tif (!e.then) markAsForce(newVNode);\n\t\t\t}\n\t\t\toptions._catchError(e, newVNode, oldVNode);\n\t\t}\n\t} else if (\n\t\texcessDomChildren == NULL &&\n\t\tnewVNode._original == oldVNode._original\n\t) {\n\t\tnewVNode._children = oldVNode._children;\n\t\tnewVNode._dom = oldVNode._dom;\n\t} else {\n\t\toldDom = newVNode._dom = diffElementNodes(\n\t\t\toldVNode._dom,\n\t\t\tnewVNode,\n\t\t\toldVNode,\n\t\t\tglobalContext,\n\t\t\tnamespace,\n\t\t\texcessDomChildren,\n\t\t\tcommitQueue,\n\t\t\tisHydrating,\n\t\t\trefQueue\n\t\t);\n\t}\n\n\tif ((tmp = options.diffed)) tmp(newVNode);\n\n\treturn newVNode._flags & MODE_SUSPENDED ? undefined : oldDom;\n}\n\nfunction markAsForce(vnode) {\n\tif (vnode && vnode._component) vnode._component._force = true;\n\tif (vnode && vnode._children) vnode._children.forEach(markAsForce);\n}\n\n/**\n * @param {Array} commitQueue List of components\n * which have callbacks to invoke in commitRoot\n * @param {VNode} root\n */\nexport function commitRoot(commitQueue, root, refQueue) {\n\tfor (let i = 0; i < refQueue.length; i++) {\n\t\tapplyRef(refQueue[i], refQueue[++i], refQueue[++i]);\n\t}\n\n\tif (options._commit) options._commit(root, commitQueue);\n\n\tcommitQueue.some(c => {\n\t\ttry {\n\t\t\t// @ts-expect-error Reuse the commitQueue variable here so the type changes\n\t\t\tcommitQueue = c._renderCallbacks;\n\t\t\tc._renderCallbacks = [];\n\t\t\tcommitQueue.some(cb => {\n\t\t\t\t// @ts-expect-error See above comment on commitQueue\n\t\t\t\tcb.call(c);\n\t\t\t});\n\t\t} catch (e) {\n\t\t\toptions._catchError(e, c._vnode);\n\t\t}\n\t});\n}\n\nfunction cloneNode(node) {\n\tif (\n\t\ttypeof node != 'object' ||\n\t\tnode == NULL ||\n\t\t(node._depth && node._depth > 0)\n\t) {\n\t\treturn node;\n\t}\n\n\tif (isArray(node)) {\n\t\treturn node.map(cloneNode);\n\t}\n\n\treturn assign({}, node);\n}\n\n/**\n * Diff two virtual nodes representing DOM element\n * @param {PreactElement} dom The DOM element representing the virtual nodes\n * being diffed\n * @param {VNode} newVNode The new virtual node\n * @param {VNode} oldVNode The old virtual node\n * @param {object} globalContext The current context object\n * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML)\n * @param {Array} excessDomChildren\n * @param {Array} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n * @returns {PreactElement}\n */\nfunction diffElementNodes(\n\tdom,\n\tnewVNode,\n\toldVNode,\n\tglobalContext,\n\tnamespace,\n\texcessDomChildren,\n\tcommitQueue,\n\tisHydrating,\n\trefQueue\n) {\n\tlet oldProps = oldVNode.props || EMPTY_OBJ;\n\tlet newProps = newVNode.props;\n\tlet nodeType = /** @type {string} */ (newVNode.type);\n\t/** @type {any} */\n\tlet i;\n\t/** @type {{ __html?: string }} */\n\tlet newHtml;\n\t/** @type {{ __html?: string }} */\n\tlet oldHtml;\n\t/** @type {ComponentChildren} */\n\tlet newChildren;\n\tlet value;\n\tlet inputValue;\n\tlet checked;\n\n\t// Tracks entering and exiting namespaces when descending through the tree.\n\tif (nodeType == 'svg') namespace = SVG_NAMESPACE;\n\telse if (nodeType == 'math') namespace = MATH_NAMESPACE;\n\telse if (!namespace) namespace = XHTML_NAMESPACE;\n\n\tif (excessDomChildren != NULL) {\n\t\tfor (i = 0; i < excessDomChildren.length; i++) {\n\t\t\tvalue = excessDomChildren[i];\n\n\t\t\t// if newVNode matches an element in excessDomChildren or the `dom`\n\t\t\t// argument matches an element in excessDomChildren, remove it from\n\t\t\t// excessDomChildren so it isn't later removed in diffChildren\n\t\t\tif (\n\t\t\t\tvalue &&\n\t\t\t\t'setAttribute' in value == !!nodeType &&\n\t\t\t\t(nodeType ? value.localName == nodeType : value.nodeType == 3)\n\t\t\t) {\n\t\t\t\tdom = value;\n\t\t\t\texcessDomChildren[i] = NULL;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (dom == NULL) {\n\t\tif (nodeType == NULL) {\n\t\t\treturn document.createTextNode(newProps);\n\t\t}\n\n\t\tdom = document.createElementNS(\n\t\t\tnamespace,\n\t\t\tnodeType,\n\t\t\tnewProps.is && newProps\n\t\t);\n\n\t\t// we are creating a new node, so we can assume this is a new subtree (in\n\t\t// case we are hydrating), this deopts the hydrate\n\t\tif (isHydrating) {\n\t\t\tif (options._hydrationMismatch)\n\t\t\t\toptions._hydrationMismatch(newVNode, excessDomChildren);\n\t\t\tisHydrating = false;\n\t\t}\n\t\t// we created a new parent, so none of the previously attached children can be reused:\n\t\texcessDomChildren = NULL;\n\t}\n\n\tif (nodeType == NULL) {\n\t\t// During hydration, we still have to split merged text from SSR'd HTML.\n\t\tif (oldProps !== newProps && (!isHydrating || dom.data != newProps)) {\n\t\t\tdom.data = newProps;\n\t\t}\n\t} else {\n\t\t// If excessDomChildren was not null, repopulate it with the current element's children:\n\t\texcessDomChildren = excessDomChildren && slice.call(dom.childNodes);\n\n\t\t// If we are in a situation where we are not hydrating but are using\n\t\t// existing DOM (e.g. replaceNode) we should read the existing DOM\n\t\t// attributes to diff them\n\t\tif (!isHydrating && excessDomChildren != NULL) {\n\t\t\toldProps = {};\n\t\t\tfor (i = 0; i < dom.attributes.length; i++) {\n\t\t\t\tvalue = dom.attributes[i];\n\t\t\t\toldProps[value.name] = value.value;\n\t\t\t}\n\t\t}\n\n\t\tfor (i in oldProps) {\n\t\t\tvalue = oldProps[i];\n\t\t\tif (i == 'children') {\n\t\t\t} else if (i == 'dangerouslySetInnerHTML') {\n\t\t\t\toldHtml = value;\n\t\t\t} else if (!(i in newProps)) {\n\t\t\t\tif (\n\t\t\t\t\t(i == 'value' && 'defaultValue' in newProps) ||\n\t\t\t\t\t(i == 'checked' && 'defaultChecked' in newProps)\n\t\t\t\t) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tsetProperty(dom, i, NULL, value, namespace);\n\t\t\t}\n\t\t}\n\n\t\t// During hydration, props are not diffed at all (including dangerouslySetInnerHTML)\n\t\t// @TODO we should warn in debug mode when props don't match here.\n\t\tfor (i in newProps) {\n\t\t\tvalue = newProps[i];\n\t\t\tif (i == 'children') {\n\t\t\t\tnewChildren = value;\n\t\t\t} else if (i == 'dangerouslySetInnerHTML') {\n\t\t\t\tnewHtml = value;\n\t\t\t} else if (i == 'value') {\n\t\t\t\tinputValue = value;\n\t\t\t} else if (i == 'checked') {\n\t\t\t\tchecked = value;\n\t\t\t} else if (\n\t\t\t\t(!isHydrating || typeof value == 'function') &&\n\t\t\t\toldProps[i] !== value\n\t\t\t) {\n\t\t\t\tsetProperty(dom, i, value, oldProps[i], namespace);\n\t\t\t}\n\t\t}\n\n\t\t// If the new vnode didn't have dangerouslySetInnerHTML, diff its children\n\t\tif (newHtml) {\n\t\t\t// Avoid re-applying the same '__html' if it did not changed between re-render\n\t\t\tif (\n\t\t\t\t!isHydrating &&\n\t\t\t\t(!oldHtml ||\n\t\t\t\t\t(newHtml.__html != oldHtml.__html && newHtml.__html != dom.innerHTML))\n\t\t\t) {\n\t\t\t\tdom.innerHTML = newHtml.__html;\n\t\t\t}\n\n\t\t\tnewVNode._children = [];\n\t\t} else {\n\t\t\tif (oldHtml) dom.innerHTML = '';\n\n\t\t\tdiffChildren(\n\t\t\t\t// @ts-expect-error\n\t\t\t\tnewVNode.type == 'template' ? dom.content : dom,\n\t\t\t\tisArray(newChildren) ? newChildren : [newChildren],\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tnodeType == 'foreignObject' ? XHTML_NAMESPACE : namespace,\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\texcessDomChildren\n\t\t\t\t\t? excessDomChildren[0]\n\t\t\t\t\t: oldVNode._children && getDomSibling(oldVNode, 0),\n\t\t\t\tisHydrating,\n\t\t\t\trefQueue\n\t\t\t);\n\n\t\t\t// Remove children that are not part of any vnode.\n\t\t\tif (excessDomChildren != NULL) {\n\t\t\t\tfor (i = excessDomChildren.length; i--; ) {\n\t\t\t\t\tremoveNode(excessDomChildren[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// As above, don't diff props during hydration\n\t\tif (!isHydrating) {\n\t\t\ti = 'value';\n\t\t\tif (nodeType == 'progress' && inputValue == NULL) {\n\t\t\t\tdom.removeAttribute('value');\n\t\t\t} else if (\n\t\t\t\tinputValue != UNDEFINED &&\n\t\t\t\t// #2756 For the -element the initial value is 0,\n\t\t\t\t// despite the attribute not being present. When the attribute\n\t\t\t\t// is missing the progress bar is treated as indeterminate.\n\t\t\t\t// To fix that we'll always update it when it is 0 for progress elements\n\t\t\t\t(inputValue !== dom[i] ||\n\t\t\t\t\t(nodeType == 'progress' && !inputValue) ||\n\t\t\t\t\t// This is only for IE 11 to fix value not being updated.\n\t\t\t\t\t// To avoid a stale select value we need to set the option.value\n\t\t\t\t\t// again, which triggers IE11 to re-evaluate the select value\n\t\t\t\t\t(nodeType == 'option' && inputValue != oldProps[i]))\n\t\t\t) {\n\t\t\t\tsetProperty(dom, i, inputValue, oldProps[i], namespace);\n\t\t\t}\n\n\t\t\ti = 'checked';\n\t\t\tif (checked != UNDEFINED && checked != dom[i]) {\n\t\t\t\tsetProperty(dom, i, checked, oldProps[i], namespace);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dom;\n}\n\n/**\n * Invoke or update a ref, depending on whether it is a function or object ref.\n * @param {Ref & { _unmount?: unknown }} ref\n * @param {any} value\n * @param {VNode} vnode\n */\nexport function applyRef(ref, value, vnode) {\n\ttry {\n\t\tif (typeof ref == 'function') {\n\t\t\tlet hasRefUnmount = typeof ref._unmount == 'function';\n\t\t\tif (hasRefUnmount) {\n\t\t\t\t// @ts-ignore TS doesn't like moving narrowing checks into variables\n\t\t\t\tref._unmount();\n\t\t\t}\n\n\t\t\tif (!hasRefUnmount || value != NULL) {\n\t\t\t\t// Store the cleanup function on the function\n\t\t\t\t// instance object itself to avoid shape\n\t\t\t\t// transitioning vnode\n\t\t\t\tref._unmount = ref(value);\n\t\t\t}\n\t\t} else ref.current = value;\n\t} catch (e) {\n\t\toptions._catchError(e, vnode);\n\t}\n}\n\n/**\n * Unmount a virtual node from the tree and apply DOM changes\n * @param {VNode} vnode The virtual node to unmount\n * @param {VNode} parentVNode The parent of the VNode that initiated the unmount\n * @param {boolean} [skipRemove] Flag that indicates that a parent node of the\n * current element is already detached from the DOM.\n */\nexport function unmount(vnode, parentVNode, skipRemove) {\n\tlet r;\n\tif (options.unmount) options.unmount(vnode);\n\n\tif ((r = vnode.ref)) {\n\t\tif (!r.current || r.current == vnode._dom) {\n\t\t\tapplyRef(r, NULL, parentVNode);\n\t\t}\n\t}\n\n\tif ((r = vnode._component) != NULL) {\n\t\tif (r.componentWillUnmount) {\n\t\t\ttry {\n\t\t\t\tr.componentWillUnmount();\n\t\t\t} catch (e) {\n\t\t\t\toptions._catchError(e, parentVNode);\n\t\t\t}\n\t\t}\n\n\t\tr.base = r._parentDom = NULL;\n\t}\n\n\tif ((r = vnode._children)) {\n\t\tfor (let i = 0; i < r.length; i++) {\n\t\t\tif (r[i]) {\n\t\t\t\tunmount(\n\t\t\t\t\tr[i],\n\t\t\t\t\tparentVNode,\n\t\t\t\t\tskipRemove || typeof vnode.type != 'function'\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!skipRemove) {\n\t\tremoveNode(vnode._dom);\n\t}\n\n\tvnode._component = vnode._parent = vnode._dom = UNDEFINED;\n}\n\n/** The `.render()` method for a PFC backing instance. */\nfunction doRender(props, state, context) {\n\treturn this.constructor(props, context);\n}\n","import { EMPTY_OBJ, NULL } from './constants';\nimport { commitRoot, diff } from './diff/index';\nimport { createElement, Fragment } from './create-element';\nimport options from './options';\nimport { slice } from './util';\n\n/**\n * Render a Preact virtual node into a DOM element\n * @param {import('./internal').ComponentChild} vnode The virtual node to render\n * @param {import('./internal').PreactElement} parentDom The DOM element to render into\n * @param {import('./internal').PreactElement | object} [replaceNode] Optional: Attempt to re-use an\n * existing DOM tree rooted at `replaceNode`\n */\nexport function render(vnode, parentDom, replaceNode) {\n\t// https://github.com/preactjs/preact/issues/3794\n\tif (parentDom == document) {\n\t\tparentDom = document.documentElement;\n\t}\n\n\tif (options._root) options._root(vnode, parentDom);\n\n\t// We abuse the `replaceNode` parameter in `hydrate()` to signal if we are in\n\t// hydration mode or not by passing the `hydrate` function instead of a DOM\n\t// element..\n\tlet isHydrating = typeof replaceNode == 'function';\n\n\t// To be able to support calling `render()` multiple times on the same\n\t// DOM node, we need to obtain a reference to the previous tree. We do\n\t// this by assigning a new `_children` property to DOM nodes which points\n\t// to the last rendered tree. By default this property is not present, which\n\t// means that we are mounting a new tree for the first time.\n\tlet oldVNode = isHydrating\n\t\t? NULL\n\t\t: (replaceNode && replaceNode._children) || parentDom._children;\n\n\tvnode = ((!isHydrating && replaceNode) || parentDom)._children =\n\t\tcreateElement(Fragment, NULL, [vnode]);\n\n\t// List of effects that need to be called after diffing.\n\tlet commitQueue = [],\n\t\trefQueue = [];\n\tdiff(\n\t\tparentDom,\n\t\t// Determine the new vnode tree and store it on the DOM element on\n\t\t// our custom `_children` property.\n\t\tvnode,\n\t\toldVNode || EMPTY_OBJ,\n\t\tEMPTY_OBJ,\n\t\tparentDom.namespaceURI,\n\t\t!isHydrating && replaceNode\n\t\t\t? [replaceNode]\n\t\t\t: oldVNode\n\t\t\t\t? NULL\n\t\t\t\t: parentDom.firstChild\n\t\t\t\t\t? slice.call(parentDom.childNodes)\n\t\t\t\t\t: NULL,\n\t\tcommitQueue,\n\t\t!isHydrating && replaceNode\n\t\t\t? replaceNode\n\t\t\t: oldVNode\n\t\t\t\t? oldVNode._dom\n\t\t\t\t: parentDom.firstChild,\n\t\tisHydrating,\n\t\trefQueue\n\t);\n\n\t// Flush all queued effects\n\tcommitRoot(commitQueue, vnode, refQueue);\n}\n\n/**\n * Update an existing DOM element with data from a Preact virtual node\n * @param {import('./internal').ComponentChild} vnode The virtual node to render\n * @param {import('./internal').PreactElement} parentDom The DOM element to update\n */\nexport function hydrate(vnode, parentDom) {\n\trender(vnode, parentDom, hydrate);\n}\n","import { NULL } from '../constants';\n\n/**\n * Find the closest error boundary to a thrown error and call it\n * @param {object} error The thrown value\n * @param {import('../internal').VNode} vnode The vnode that threw the error that was caught (except\n * for unmounting when this parameter is the highest parent that was being\n * unmounted)\n * @param {import('../internal').VNode} [oldVNode]\n * @param {import('../internal').ErrorInfo} [errorInfo]\n */\nexport function _catchError(error, vnode, oldVNode, errorInfo) {\n\t/** @type {import('../internal').Component} */\n\tlet component,\n\t\t/** @type {import('../internal').ComponentType} */\n\t\tctor,\n\t\t/** @type {boolean} */\n\t\thandled;\n\n\tfor (; (vnode = vnode._parent); ) {\n\t\tif ((component = vnode._component) && !component._processingException) {\n\t\t\ttry {\n\t\t\t\tctor = component.constructor;\n\n\t\t\t\tif (ctor && ctor.getDerivedStateFromError != NULL) {\n\t\t\t\t\tcomponent.setState(ctor.getDerivedStateFromError(error));\n\t\t\t\t\thandled = component._dirty;\n\t\t\t\t}\n\n\t\t\t\tif (component.componentDidCatch != NULL) {\n\t\t\t\t\tcomponent.componentDidCatch(error, errorInfo || {});\n\t\t\t\t\thandled = component._dirty;\n\t\t\t\t}\n\n\t\t\t\t// This is an error boundary. Mark it as having bailed out, and whether it was mid-hydration.\n\t\t\t\tif (handled) {\n\t\t\t\t\treturn (component._pendingError = component);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\terror = e;\n\t\t\t}\n\t\t}\n\t}\n\n\tthrow error;\n}\n","import { assign, slice } from './util';\nimport { createVNode } from './create-element';\nimport { NULL, UNDEFINED } from './constants';\n\n/**\n * Clones the given VNode, optionally adding attributes/props and replacing its\n * children.\n * @param {import('./internal').VNode} vnode The virtual DOM element to clone\n * @param {object} props Attributes/props to add when cloning\n * @param {Array} rest Any additional arguments will be used\n * as replacement children.\n * @returns {import('./internal').VNode}\n */\nexport function cloneElement(vnode, props, children) {\n\tlet normalizedProps = assign({}, vnode.props),\n\t\tkey,\n\t\tref,\n\t\ti;\n\n\tlet defaultProps;\n\n\tif (vnode.type && vnode.type.defaultProps) {\n\t\tdefaultProps = vnode.type.defaultProps;\n\t}\n\n\tfor (i in props) {\n\t\tif (i == 'key') key = props[i];\n\t\telse if (i == 'ref') ref = props[i];\n\t\telse if (props[i] === UNDEFINED && defaultProps != UNDEFINED) {\n\t\t\tnormalizedProps[i] = defaultProps[i];\n\t\t} else {\n\t\t\tnormalizedProps[i] = props[i];\n\t\t}\n\t}\n\n\tif (arguments.length > 2) {\n\t\tnormalizedProps.children =\n\t\t\targuments.length > 3 ? slice.call(arguments, 2) : children;\n\t}\n\n\treturn createVNode(\n\t\tvnode.type,\n\t\tnormalizedProps,\n\t\tkey || vnode.key,\n\t\tref || vnode.ref,\n\t\tNULL\n\t);\n}\n","import * as preact from './index.js';\nif (typeof module < 'u') module.exports = preact;\nelse self.preact = preact;\n"],"names":["slice","options","vnodeId","isValidElement","rerenderQueue","prevDebounce","defer","depthSort","CAPTURE_REGEX","eventClock","eventProxy","eventProxyCapture","i","SVG_NAMESPACE","XHTML_NAMESPACE","NULL","UNDEFINED","undefined","EMPTY_OBJ","EMPTY_ARR","IS_NON_DIMENSIONAL","isArray","Array","assign","obj","props","removeNode","node","parentNode","removeChild","createElement","type","children","key","ref","normalizedProps","arguments","length","call","defaultProps","createVNode","original","vnode","__k","__","__b","__e","__c","constructor","__v","__i","__u","Fragment","BaseComponent","context","this","getDomSibling","childIndex","sibling","updateParentDomPointers","child","base","enqueueRender","c","__d","push","process","__r","debounceRendering","component","newVNode","oldVNode","oldDom","commitQueue","refQueue","l","sort","shift","__P","diff","__n","namespaceURI","commitRoot","diffChildren","parentDom","renderResult","newParentVNode","oldParentVNode","globalContext","namespace","excessDomChildren","isHydrating","childVNode","newDom","firstChildDom","result","shouldPlace","oldChildren","newChildrenLength","constructNewChildrenArray","applyRef","insert","nextSibling","skewedIndex","matchingIndex","oldChildrenLength","remainingOldChildren","skew","String","findMatchingIndex","unmount","parentVNode","insertBefore","nodeType","x","y","matched","setStyle","style","value","setProperty","test","dom","name","oldValue","useCapture","lowerCaseName","o","cssText","replace","toLowerCase","_attached","addEventListener","removeEventListener","e","removeAttribute","setAttribute","createEventProxy","eventHandler","_dispatched","event","tmp","isNew","oldProps","oldState","snapshot","clearProcessingException","newProps","isClassComponent","provider","componentContext","renderHook","count","newType","outer","prototype","render","contextType","__E","doRender","sub","state","__h","_sb","__s","getDerivedStateFromProps","componentWillMount","componentDidMount","componentWillReceiveProps","shouldComponentUpdate","some","componentWillUpdate","componentDidUpdate","getChildContext","getSnapshotBeforeUpdate","cloneNode","then","MODE_HYDRATE","indexOf","markAsForce","diffElementNodes","diffed","forEach","root","cb","map","newHtml","oldHtml","newChildren","inputValue","checked","localName","document","createTextNode","createElementNS","is","__m","data","childNodes","attributes","__html","innerHTML","content","hasRefUnmount","current","skipRemove","r","componentWillUnmount","replaceNode","documentElement","firstChild","error","errorInfo","ctor","handled","getDerivedStateFromError","setState","componentDidCatch","update","callback","s","forceUpdate","Promise","bind","resolve","setTimeout","a","b","hydrate","defaultValue","Context","subs","ctx","Set","_props","add","old","delete","Provider","__l","Consumer","contextValue","toChildArray","out","module","exports","preact","self"],"mappings":"gBA2BaA,EChBPC,ECPFC,EA2FSC,ECoFTC,EAWAC,EAEEC,EA0BAC,EC3MAC,EAaFC,EA+IEC,EACAC,ECzKKC,ICSEC,EAAgB,6BAChBC,EAAkB,+BAGlBC,EAAO,KACPC,OAAYC,EACZC,EAAgC,CAAG,EACnCC,EAAY,GACZC,EACZ,oENnBYC,EAAUC,MAAMD,QAStB,SAASE,EAAOC,EAAKC,GAE3B,IAAK,IAAIb,KAAKa,EAAOD,EAAIZ,GAAKa,EAAMb,GACpC,OAA6BY,CAC9B,CAQgB,SAAAE,EAAWC,GACtBA,GAAQA,EAAKC,YAAYD,EAAKC,WAAWC,YAAYF,EAC1D,CEVgB,SAAAG,EAAcC,EAAMN,EAAOO,GAC1C,IACCC,EACAC,EACAtB,EAHGuB,EAAkB,CAAA,EAItB,IAAKvB,KAAKa,EACA,OAALb,EAAYqB,EAAMR,EAAMb,GACd,OAALA,EAAYsB,EAAMT,EAAMb,GAC5BuB,EAAgBvB,GAAKa,EAAMb,GAUjC,GAPIwB,UAAUC,OAAS,IACtBF,EAAgBH,SACfI,UAAUC,OAAS,EAAIrC,EAAMsC,KAAKF,UAAW,GAAKJ,GAKjC,mBAARD,GAAsBA,EAAKQ,cAAgBxB,EACrD,IAAKH,KAAKmB,EAAKQ,aACVJ,EAAgBvB,KAAOI,IAC1BmB,EAAgBvB,GAAKmB,EAAKQ,aAAa3B,IAK1C,OAAO4B,EAAYT,EAAMI,EAAiBF,EAAKC,EAAKnB,EACrD,CAcgB,SAAAyB,EAAYT,EAAMN,EAAOQ,EAAKC,EAAKO,GAIlD,IAAMC,EAAQ,CACbX,KAAAA,EACAN,MAAAA,EACAQ,IAAAA,EACAC,IAAAA,EACAS,IAAW5B,EACX6B,GAAS7B,EACT8B,IAAQ,EACRC,IAAM/B,EACNgC,IAAYhC,EACZiC,YAAahC,EACbiC,IAAWR,GAAY1B,IAASb,EAAUuC,EAC1CS,KAAS,EACTC,IAAQ,GAMT,OAFIV,GAAY1B,GAAQd,EAAQyC,OAAS3B,GAAMd,EAAQyC,MAAMA,GAEtDA,CACR,CAMgB,SAAAU,EAAS3B,GACxB,OAAOA,EAAMO,QACd,CC3EO,SAASqB,EAAc5B,EAAO6B,GACpCC,KAAK9B,MAAQA,EACb8B,KAAKD,QAAUA,CAChB,UA0EgBE,EAAcd,EAAOe,GACpC,GAAIA,GAAc1C,EAEjB,OAAO2B,EAAKE,GACTY,EAAcd,EAAKE,GAAUF,EAAKQ,IAAU,GAC5CnC,EAIJ,IADA,IAAI2C,EACGD,EAAaf,EAAKC,IAAWN,OAAQoB,IAG3C,IAFAC,EAAUhB,EAAKC,IAAWc,KAEX1C,GAAQ2C,EAAOZ,KAAS/B,EAItC,OAAO2C,EAAOZ,IAShB,MAA4B,mBAAdJ,EAAMX,KAAqByB,EAAcd,GAAS3B,CACjE,CA4CA,SAAS4C,EAAwBjB,GAAjC,IAGW9B,EACJgD,EAHN,IAAKlB,EAAQA,EAAKE,KAAa7B,GAAQ2B,EAAKK,KAAehC,EAAM,CAEhE,IADA2B,EAAKI,IAAQJ,EAAKK,IAAYc,KAAO9C,EAC5BH,EAAI,EAAGA,EAAI8B,EAAKC,IAAWN,OAAQzB,IAE3C,IADIgD,EAAQlB,EAAKC,IAAW/B,KACfG,GAAQ6C,EAAKd,KAAS/B,EAAM,CACxC2B,EAAKI,IAAQJ,EAAKK,IAAYc,KAAOD,EAAKd,IAC1C,KACD,CAGD,OAAOa,EAAwBjB,EAChC,CACD,CA4BO,SAASoB,EAAcC,KAE1BA,EAACC,MACDD,EAACC,KAAU,IACZ5D,EAAc6D,KAAKF,KAClBG,EAAOC,OACT9D,GAAgBJ,EAAQmE,sBAExB/D,EAAeJ,EAAQmE,oBACN9D,GAAO4D,EAE1B,CASA,SAASA,IAMR,IALA,IAAIH,EApGoBM,EAOjBC,EANHC,EACHC,EACAC,EACAC,EAiGAC,EAAI,EAIEvE,EAAciC,QAOhBjC,EAAciC,OAASsC,GAC1BvE,EAAcwE,KAAKrE,GAGpBwD,EAAI3D,EAAcyE,QAClBF,EAAIvE,EAAciC,OAEd0B,EAACC,MAhHCM,SANHC,SACHC,GADGD,GADoBF,EAwHNN,GAvHMd,KACNH,IACjB2B,EAAc,GACdC,EAAW,GAERL,EAASS,OACNR,EAAW/C,EAAO,CAAE,EAAEgD,IACpBtB,IAAasB,EAAQtB,IAAa,EACtChD,EAAQyC,OAAOzC,EAAQyC,MAAM4B,GAEjCS,EACCV,EAASS,IACTR,EACAC,EACAF,EAASW,IACTX,EAASS,IAAYG,aGzII,GH0IzBV,EAAQpB,IAAyB,CAACqB,GAAUzD,EAC5C0D,EACAD,GAAUzD,EAAOyC,EAAce,GAAYC,KG5IlB,GH6ItBD,EAAQpB,KACXuB,GAGDJ,EAAQrB,IAAasB,EAAQtB,IAC7BqB,EAAQ1B,GAAAD,IAAmB2B,EAAQpB,KAAWoB,EAC9CY,EAAWT,EAAaH,EAAUI,GAClCH,EAAQzB,IAAQyB,EAAQ3B,GAAW,KAE/B0B,EAAQxB,KAAS0B,GACpBb,EAAwBW,KA6F1BJ,EAAOC,IAAkB,CAC1B,CI5MgB,SAAAgB,EACfC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAjB,EACAD,EACAmB,EACAjB,GAXe,IAaX9D,EAEH2D,EAEAqB,EAEAC,EAEAC,EAiCIC,EA8BAC,EA1DDC,EAAeV,GAAkBA,EAAc5C,KAAexB,EAE9D+E,EAAoBb,EAAahD,OAUrC,IARAmC,EAAS2B,EACRb,EACAD,EACAY,EACAzB,EACA0B,GAGItF,EAAI,EAAGA,EAAIsF,EAAmBtF,KAClCgF,EAAaN,EAAc3C,IAAW/B,KACpBG,IAKjBwD,GADyB,GAAtBqB,EAAU1C,IACFhC,EAEA+E,EAAYL,EAAU1C,MAAYhC,EAI9C0E,EAAU1C,IAAUtC,EAGhBmF,EAAShB,EACZK,EACAQ,EACArB,EACAiB,EACAC,EACAC,EACAjB,EACAD,EACAmB,EACAjB,GAIDmB,EAASD,EAAU9C,IACf8C,EAAW1D,KAAOqC,EAASrC,KAAO0D,EAAW1D,MAC5CqC,EAASrC,KACZkE,EAAS7B,EAASrC,IAAKnB,EAAM6E,GAE9BlB,EAAST,KACR2B,EAAW1D,IACX0D,EAAU7C,KAAe8C,EACzBD,IAIEE,GAAiB/E,GAAQ8E,GAAU9E,IACtC+E,EAAgBD,IAGbG,KDzHsB,ECyHLJ,EAAUzC,OACZoB,EAAQ5B,MAAeiD,EAAUjD,IACnD6B,EAAS6B,EAAOT,EAAYpB,EAAQY,EAAWY,GACX,mBAAnBJ,EAAW7D,MAAsBgE,IAAW/E,EAC7DwD,EAASuB,EACCF,IACVrB,EAASqB,EAAOS,aAIjBV,EAAUzC,MAAW,GAKtB,OAFAmC,EAAcxC,IAAQgD,EAEftB,CACR,CAOA,SAAS2B,EACRb,EACAD,EACAY,EACAzB,EACA0B,GALD,IAQKtF,EAEAgF,EAEArB,EA8DGgC,EAOAC,EAnEHC,EAAoBR,EAAY5D,OACnCqE,EAAuBD,EAEpBE,EAAO,EAGX,IADArB,EAAc3C,IAAa,IAAIrB,MAAM4E,GAChCtF,EAAI,EAAGA,EAAIsF,EAAmBtF,KAGlCgF,EAAaP,EAAazE,KAGXG,GACO,kBAAd6E,GACc,mBAAdA,GASc,iBAAdA,GACc,iBAAdA,GAEc,iBAAdA,GACPA,EAAW5C,aAAe4D,OAE1BhB,EAAaN,EAAc3C,IAAW/B,GAAK4B,EAC1CzB,EACA6E,EACA7E,EACAA,EACAA,GAESM,EAAQuE,GAClBA,EAAaN,EAAc3C,IAAW/B,GAAK4B,EAC1CY,EACA,CAAEpB,SAAU4D,GACZ7E,EACAA,EACAA,GAES6E,EAAW5C,cAAgBhC,GAAa4E,EAAU/C,IAAU,EAKtE+C,EAAaN,EAAc3C,IAAW/B,GAAK4B,EAC1CoD,EAAW7D,KACX6D,EAAWnE,MACXmE,EAAW3D,IACX2D,EAAW1D,IAAM0D,EAAW1D,IAAMnB,EAClC6E,EAAU3C,KAGXqC,EAAc3C,IAAW/B,GAAKgF,EAGzBW,EAAc3F,EAAI+F,EACxBf,EAAUhD,GAAW0C,EACrBM,EAAU/C,IAAUyC,EAAczC,IAAU,EAKtC2D,EAAiBZ,EAAU1C,IAAU2D,EAC1CjB,EACAK,EACAM,EACAG,GAGDnC,EAAWxD,GACW,GAAlByF,IAEHE,KADAnC,EAAW0B,EAAYO,MAGtBjC,EAAQpB,KD3OW,ICkPFoB,GAAYxD,GAAQwD,EAAQtB,KAAclC,IAGtC,GAAlByF,IAeCN,EAAoBO,EACvBE,IACUT,EAAoBO,GAC9BE,KAK4B,mBAAnBf,EAAW7D,OACrB6D,EAAUzC,KD/Qc,ICiRfqD,GAAiBD,IAiBvBC,GAAiBD,EAAc,EAClCI,IACUH,GAAiBD,EAAc,EACzCI,KAEIH,EAAgBD,EACnBI,IAEAA,IAMDf,EAAUzC,KDhTc,KC8KzBmC,EAAc3C,IAAW/B,GAAKG,EA2IhC,GAAI2F,EACH,IAAK9F,EAAI,EAAGA,EAAI6F,EAAmB7F,KAClC2D,EAAW0B,EAAYrF,KACPG,GAAuC,ID1TnC,EC0TKwD,EAAQpB,OAC5BoB,EAAQzB,KAAS0B,IACpBA,EAAShB,EAAce,IAGxBuC,EAAQvC,EAAUA,IAKrB,OAAOC,CACR,CASA,SAAS6B,EAAOU,EAAavC,EAAQY,EAAWY,GAAhD,IAIMhE,EACKpB,EAFV,GAA+B,mBAApBmG,EAAYhF,KAAoB,CAE1C,IADIC,EAAW+E,EAAWpE,IACjB/B,EAAI,EAAGoB,GAAYpB,EAAIoB,EAASK,OAAQzB,IAC5CoB,EAASpB,KAKZoB,EAASpB,GAAEgC,GAAWmE,EACtBvC,EAAS6B,EAAOrE,EAASpB,GAAI4D,EAAQY,EAAWY,IAIlD,OAAOxB,CACR,CAAWuC,EAAWjE,KAAS0B,IAC1BwB,IACCxB,GAAUuC,EAAYhF,OAASyC,EAAO5C,aACzC4C,EAAShB,EAAcuD,IAExB3B,EAAU4B,aAAaD,EAAWjE,IAAO0B,GAAUzD,IAEpDyD,EAASuC,EAAWjE,KAGrB,GACC0B,EAASA,GAAUA,EAAO8B,kBAClB9B,GAAUzD,GAA2B,GAAnByD,EAAOyC,UAElC,OAAOzC,CACR,CA4BA,SAASqC,EACRjB,EACAK,EACAM,EACAG,GAJD,IAgCMQ,EACAC,EAEG1D,EA7BFxB,EAAM2D,EAAW3D,IACjBF,EAAO6D,EAAW7D,KACpBwC,EAAW0B,EAAYM,GACrBa,EAAU7C,GAAYxD,GAAuC,IDnZ7C,ECmZewD,EAAQpB,KAiB7C,GACEoB,IAAaxD,GAAe,MAAPkB,GACrBmF,GAAWnF,GAAOsC,EAAStC,KAAOF,GAAQwC,EAASxC,KAEpD,OAAOwE,EACD,GAPNG,GAAwBU,EAAU,EAAI,GAUtC,IAFIF,EAAIX,EAAc,EAClBY,EAAIZ,EAAc,EACfW,GAAK,GAAKC,EAAIlB,EAAY5D,QAGhC,IADAkC,EAAW0B,EADLxC,EAAayD,GAAK,EAAIA,IAAMC,OAGrBpG,GACmB,IDjbZ,ECiblBwD,EAAQpB,MACTlB,GAAOsC,EAAStC,KAChBF,GAAQwC,EAASxC,KAEjB,OAAO0B,EAKV,OAAQ,CACT,CH/bA,SAAS4D,EAASC,EAAOrF,EAAKsF,GACf,KAAVtF,EAAI,GACPqF,EAAME,YAAYvF,EAAKsF,GAASxG,EAAO,GAAKwG,GAE5CD,EAAMrF,GADIsF,GAASxG,EACN,GACa,iBAATwG,GAAqBnG,EAAmBqG,KAAKxF,GACjDsF,EAEAA,EAAQ,IAEvB,CAyBgB,SAAAC,EAAYE,EAAKC,EAAMJ,EAAOK,EAAUnC,GAAxC,IACXoC,EA8BGC,EA5BPC,EAAG,GAAY,SAARJ,EACN,GAAoB,iBAATJ,EACVG,EAAIJ,MAAMU,QAAUT,MACd,CAKN,GAJuB,iBAAZK,IACVF,EAAIJ,MAAMU,QAAUJ,EAAW,IAG5BA,EACH,IAAKD,KAAQC,EACNL,GAASI,KAAQJ,GACtBF,EAASK,EAAIJ,MAAOK,EAAM,IAK7B,GAAIJ,EACH,IAAKI,KAAQJ,EACPK,GAAYL,EAAMI,IAASC,EAASD,IACxCN,EAASK,EAAIJ,MAAOK,EAAMJ,EAAMI,GAIpC,MAGI,GAAe,KAAXA,EAAK,IAAwB,KAAXA,EAAK,GAC/BE,EAAaF,IAASA,EAAOA,EAAKM,QAAQzH,EAAe,OACnDsH,EAAgBH,EAAKO,cAI1BP,EADGG,KAAiBJ,GAAe,cAARC,GAAgC,aAARA,EAC5CG,EAAc9H,MAAM,GAChB2H,EAAK3H,MAAM,GAElB0H,EAAG/C,IAAa+C,EAAG/C,EAAc,CAAE,GACxC+C,EAAG/C,EAAYgD,EAAOE,GAAcN,EAEhCA,EACEK,EAQJL,EAAMY,EAAYP,EAASO,GAP3BZ,EAAMY,EAAY1H,EAClBiH,EAAIU,iBACHT,EACAE,EAAalH,EAAoBD,EACjCmH,IAMFH,EAAIW,oBACHV,EACAE,EAAalH,EAAoBD,EACjCmH,OAGI,CACN,GAAIpC,GAAa5E,EAIhB8G,EAAOA,EAAKM,QAAQ,cAAe,KAAKA,QAAQ,SAAU,UAE1DN,GAAQ,SAARA,GACQ,UAARA,GACQ,QAARA,GACQ,QAARA,GACQ,QAARA,GAGQ,YAARA,GACQ,YAARA,GACQ,WAARA,GACQ,WAARA,GACQ,QAARA,GACQ,WAARA,GACAA,KAAQD,EAER,IACCA,EAAIC,GAAQJ,GAASxG,EAAO,GAAKwG,EAEjC,MAAMQ,CAER,CADG,MAAOO,GACV,CASoB,mBAATf,IAEAA,GAASxG,IAAmB,IAAVwG,GAA8B,KAAXI,EAAK,GAGpDD,EAAIa,gBAAgBZ,GAFpBD,EAAIc,aAAab,EAAc,WAARA,GAA8B,GAATJ,EAAgB,GAAKA,GAInE,CACD,CAOA,SAASkB,EAAiBZ,GAMzB,gBAAiBS,GAChB,GAAI/E,KAAIoB,EAAa,CACpB,IAAM+D,EAAenF,KAAIoB,EAAY2D,EAAEvG,KAAO8F,GAC9C,GAAIS,EAAEK,GAAe5H,EACpBuH,EAAEK,EAAclI,SAKV,GAAI6H,EAAEK,EAAcD,EAAaP,EACvC,OAED,OAAOO,EAAazI,EAAQ2I,MAAQ3I,EAAQ2I,MAAMN,GAAKA,EACxD,CACD,CACD,UIzHgBvD,EACfK,EACAd,EACAC,EACAiB,EACAC,EACAC,EACAjB,EACAD,EACAmB,EACAjB,OAGImE,EAkBE9E,EAAG+E,EAAOC,EAAUC,EAAUC,EAAUC,EACxCC,EACEC,EAMFC,EACAC,EAuGO1I,EA4BP2I,EACHC,EASS5I,EA6BNyE,EAgDOzE,EApPZ6I,EAAUnF,EAASvC,KAIpB,GAAIuC,EAAStB,cAAgBhC,EAAW,OAAOD,EF/DlB,IEkEzBwD,EAAQpB,MACXwC,KFrE0B,GEqETpB,EAAQpB,KAEzBuC,EAAoB,CADpBlB,EAASF,EAAQxB,IAAQyB,EAAQzB,OAI7B+F,EAAM5I,EAAO4C,MAASgG,EAAIvE,GAE/BoF,EAAO,GAAsB,mBAAXD,EACjB,IAgEC,GA9DIN,EAAW7E,EAAS7C,MAClB2H,EACL,cAAeK,GAAWA,EAAQE,UAAUC,OAKzCP,GADJR,EAAMY,EAAQI,cACQrE,EAAcqD,EAAG9F,KACnCuG,EAAmBT,EACpBQ,EACCA,EAAS5H,MAAM8F,MACfsB,EAAGjG,GACJ4C,EAGCjB,EAAQxB,IAEXmG,GADAnF,EAAIO,EAAQvB,IAAcwB,EAAQxB,KACNH,GAAwBmB,EAAC+F,KAGjDV,EAEH9E,EAAQvB,IAAcgB,EAAI,IAAI0F,EAAQN,EAAUG,IAGhDhF,EAAQvB,IAAcgB,EAAI,IAAIV,EAC7B8F,EACAG,GAEDvF,EAAEf,YAAcyG,EAChB1F,EAAE6F,OAASG,GAERV,GAAUA,EAASW,IAAIjG,GAEtBA,EAAEkG,QAAOlG,EAAEkG,MAAQ,CAAE,GAC1BlG,EAACiB,IAAkBQ,EACnBsD,EAAQ/E,EAACC,KAAU,EACnBD,EAACmG,IAAoB,GACrBnG,EAACoG,IAAmB,IAIjBf,GAAoBrF,EAACqG,KAAerJ,IACvCgD,EAACqG,IAAcrG,EAAEkG,OAGdb,GAAoBK,EAAQY,0BAA4BtJ,IACvDgD,EAACqG,KAAerG,EAAEkG,QACrBlG,EAACqG,IAAc7I,EAAO,CAAE,EAAEwC,EAACqG,MAG5B7I,EACCwC,EAACqG,IACDX,EAAQY,yBAAyBlB,EAAUpF,EAACqG,OAI9CrB,EAAWhF,EAAEtC,MACbuH,EAAWjF,EAAEkG,MACblG,EAACd,IAAUqB,EAGPwE,EAEFM,GACAK,EAAQY,0BAA4BtJ,GACpCgD,EAAEuG,oBAAsBvJ,GAExBgD,EAAEuG,qBAGClB,GAAoBrF,EAAEwG,mBAAqBxJ,GAC9CgD,EAACmG,IAAkBjG,KAAKF,EAAEwG,uBAErB,CAUN,GARCnB,GACAK,EAAQY,0BAA4BtJ,GACpCoI,IAAaJ,GACbhF,EAAEyG,2BAA6BzJ,GAE/BgD,EAAEyG,0BAA0BrB,EAAUG,GAItChF,EAAQrB,KAAcsB,EAAQtB,MAC5Bc,EAACjB,KACFiB,EAAE0G,uBAAyB1J,IAKrB,IAJNgD,EAAE0G,sBACDtB,EACApF,EAACqG,IACDd,GAED,CAkBD,IAhBIhF,EAAQrB,KAAcsB,EAAQtB,MAKjCc,EAAEtC,MAAQ0H,EACVpF,EAAEkG,MAAQlG,EAACqG,IACXrG,EAACC,KAAU,GAGZM,EAAQxB,IAAQyB,EAAQzB,IACxBwB,EAAQ3B,IAAa4B,EAAQ5B,IAC7B2B,EAAQ3B,IAAW+H,KAAK,SAAAhI,GACnBA,IAAOA,EAAKE,GAAW0B,EAC5B,GAES1D,EAAI,EAAGA,EAAImD,EAACoG,IAAiB9H,OAAQzB,IAC7CmD,EAACmG,IAAkBjG,KAAKF,EAACoG,IAAiBvJ,IAE3CmD,EAACoG,IAAmB,GAEhBpG,EAACmG,IAAkB7H,QACtBoC,EAAYR,KAAKF,GAGlB,MAAM2F,CACP,CAEI3F,EAAE4G,qBAAuB5J,GAC5BgD,EAAE4G,oBAAoBxB,EAAUpF,EAACqG,IAAad,GAG3CF,GAAoBrF,EAAE6G,oBAAsB7J,GAC/CgD,EAACmG,IAAkBjG,KAAK,WACvBF,EAAE6G,mBAAmB7B,EAAUC,EAAUC,EAC1C,EAEF,CASA,GAPAlF,EAAET,QAAUgG,EACZvF,EAAEtC,MAAQ0H,EACVpF,EAACe,IAAcM,EACfrB,EAACjB,KAAU,EAEPyG,EAAatJ,EAAOkE,IACvBqF,EAAQ,EACLJ,EAAkB,CAQrB,IAPArF,EAAEkG,MAAQlG,EAACqG,IACXrG,EAACC,KAAU,EAEPuF,GAAYA,EAAWjF,GAE3BuE,EAAM9E,EAAE6F,OAAO7F,EAAEtC,MAAOsC,EAAEkG,MAAOlG,EAAET,SAE1B1C,EAAI,EAAGA,EAAImD,EAACoG,IAAiB9H,OAAQzB,IAC7CmD,EAACmG,IAAkBjG,KAAKF,EAACoG,IAAiBvJ,IAE3CmD,EAACoG,IAAmB,EACrB,MACC,GACCpG,EAACC,KAAU,EACPuF,GAAYA,EAAWjF,GAE3BuE,EAAM9E,EAAE6F,OAAO7F,EAAEtC,MAAOsC,EAAEkG,MAAOlG,EAAET,SAGnCS,EAAEkG,MAAQlG,EAACqG,UACHrG,EAACC,OAAawF,EAAQ,IAIhCzF,EAAEkG,MAAQlG,EAACqG,IAEPrG,EAAE8G,iBAAmB9J,IACxByE,EAAgBjE,EAAOA,EAAO,CAAE,EAAEiE,GAAgBzB,EAAE8G,oBAGjDzB,IAAqBN,GAAS/E,EAAE+G,yBAA2B/J,IAC9DkI,EAAWlF,EAAE+G,wBAAwB/B,EAAUC,IAK5C3D,EAAewD,EADlBA,GAAO9H,GAAQ8H,EAAI9G,OAASqB,GAAYyF,EAAI5G,KAAOlB,IAInDsE,EAAe0F,EAAUlC,EAAIpH,MAAMO,WAGpCwC,EAASW,EACRC,EACA/D,EAAQgE,GAAgBA,EAAe,CAACA,GACxCf,EACAC,EACAiB,EACAC,EACAC,EACAjB,EACAD,EACAmB,EACAjB,GAGDX,EAAEF,KAAOS,EAAQxB,IAGjBwB,EAAQnB,MF/Qe,IEiRnBY,EAACmG,IAAkB7H,QACtBoC,EAAYR,KAAKF,GAGdmF,IACHnF,EAAC+F,IAAiB/F,EAACnB,GAAwB7B,EA6B7C,CA3BE,MAAOuH,GAGR,GAFAhE,EAAQrB,IAAalC,EAEjB4E,GAAeD,GAAqB3E,EACvC,GAAIuH,EAAE0C,KAAM,CAKX,IAJA1G,EAAQnB,KAAWwC,EAChBsF,IFrSsB,IEwSlBzG,GAA6B,GAAnBA,EAAOyC,UAAiBzC,EAAO8B,aAC/C9B,EAASA,EAAO8B,YAGjBZ,EAAkBA,EAAkBwF,QAAQ1G,IAAWzD,EACvDuD,EAAQxB,IAAQ0B,CACjB,KAAO,CACN,IAAS5D,EAAI8E,EAAkBrD,OAAQzB,KACtCc,EAAWgE,EAAkB9E,IAE9BuK,EAAY7G,EACb,MAEAA,EAAQxB,IAAQyB,EAAQzB,IACxBwB,EAAQ3B,IAAa4B,EAAQ5B,IACxB2F,EAAE0C,MAAMG,EAAY7G,GAE1BrE,EAAO6C,IAAawF,EAAGhE,EAAUC,EAClC,MAEAmB,GAAqB3E,GACrBuD,EAAQrB,KAAcsB,EAAQtB,KAE9BqB,EAAQ3B,IAAa4B,EAAQ5B,IAC7B2B,EAAQxB,IAAQyB,EAAQzB,KAExB0B,EAASF,EAAQxB,IAAQsI,EACxB7G,EAAQzB,IACRwB,EACAC,EACAiB,EACAC,EACAC,EACAjB,EACAkB,EACAjB,GAMF,OAFKmE,EAAM5I,EAAQoL,SAASxC,EAAIvE,GF/UH,IEiVtBA,EAAQnB,SAA2BlC,EAAYuD,CACvD,CAEA,SAAS2G,EAAYzI,GAChBA,GAASA,EAAKK,MAAaL,EAAKK,IAAAD,KAAqB,GACrDJ,GAASA,EAAKC,KAAYD,EAAKC,IAAW2I,QAAQH,EACvD,CAOO,SAASjG,EAAWT,EAAa8G,EAAM7G,GAC7C,IAAK,IAAI9D,EAAI,EAAGA,EAAI8D,EAASrC,OAAQzB,IACpCwF,EAAS1B,EAAS9D,GAAI8D,IAAW9D,GAAI8D,IAAW9D,IAG7CX,EAAO8C,KAAU9C,EAAO8C,IAASwI,EAAM9G,GAE3CA,EAAYiG,KAAK,SAAA3G,GAChB,IAECU,EAAcV,EAACmG,IACfnG,EAACmG,IAAoB,GACrBzF,EAAYiG,KAAK,SAAAc,GAEhBA,EAAGlJ,KAAKyB,EACT,EAGD,CAFE,MAAOuE,GACRrI,EAAO6C,IAAawF,EAAGvE,EAACd,IACzB,CACD,EACD,CAEA,SAAS8H,EAAUpJ,GAClB,MACgB,iBAARA,GACPA,GAAQZ,GACPY,EAAIkB,KAAWlB,EAAIkB,IAAU,EAEvBlB,EAGJN,EAAQM,GACJA,EAAK8J,IAAIV,GAGVxJ,EAAO,GAAII,EACnB,CAiBA,SAASyJ,EACR1D,EACApD,EACAC,EACAiB,EACAC,EACAC,EACAjB,EACAkB,EACAjB,GATD,IAeK9D,EAEA8K,EAEAC,EAEAC,EACArE,EACAsE,EACAC,EAbA/C,EAAWxE,EAAS9C,OAASP,EAC7BiI,EAAW7E,EAAS7C,MACpBwF,EAAkC3C,EAASvC,KAkB/C,GAJgB,OAAZkF,EAAmBxB,EAAY5E,EACd,QAAZoG,EAAoBxB,EFpaA,qCEqanBA,IAAWA,EAAY3E,GAE7B4E,GAAqB3E,EACxB,IAAKH,EAAI,EAAGA,EAAI8E,EAAkBrD,OAAQzB,IAMzC,IALA2G,EAAQ7B,EAAkB9E,KAOzB,iBAAkB2G,KAAWN,IAC5BA,EAAWM,EAAMwE,WAAa9E,EAA6B,GAAlBM,EAAMN,UAC/C,CACDS,EAAMH,EACN7B,EAAkB9E,GAAKG,EACvB,KACD,CAIF,GAAI2G,GAAO3G,EAAM,CAChB,GAAIkG,GAAYlG,EACf,OAAOiL,SAASC,eAAe9C,GAGhCzB,EAAMsE,SAASE,gBACdzG,EACAwB,EACAkC,EAASgD,IAAMhD,GAKZxD,IACC1F,EAAOmM,KACVnM,EAAOmM,IAAoB9H,EAAUoB,GACtCC,GAAc,GAGfD,EAAoB3E,CACrB,CAEA,GAAIkG,GAAYlG,EAEXgI,IAAaI,GAAcxD,GAAe+B,EAAI2E,MAAQlD,IACzDzB,EAAI2E,KAAOlD,OAEN,CAON,GALAzD,EAAoBA,GAAqB1F,EAAMsC,KAAKoF,EAAI4E,aAKnD3G,GAAeD,GAAqB3E,EAExC,IADAgI,EAAW,GACNnI,EAAI,EAAGA,EAAI8G,EAAI6E,WAAWlK,OAAQzB,IAEtCmI,GADAxB,EAAQG,EAAI6E,WAAW3L,IACR+G,MAAQJ,EAAMA,MAI/B,IAAK3G,KAAKmI,EAET,GADAxB,EAAQwB,EAASnI,GACR,YAALA,QACOA,GAAK,2BAALA,EACV+K,EAAUpE,OACA,KAAE3G,KAAKuI,GAAW,CAC5B,GACO,SAALvI,GAAgB,iBAAkBuI,GAC7B,WAALvI,GAAkB,mBAAoBuI,EAEvC,SAED3B,EAAYE,EAAK9G,EAAGG,EAAMwG,EAAO9B,EAClC,CAKD,IAAK7E,KAAKuI,EACT5B,EAAQ4B,EAASvI,GACR,YAALA,EACHgL,EAAcrE,EACC,2BAAL3G,EACV8K,EAAUnE,EACK,SAAL3G,EACViL,EAAatE,EACE,WAAL3G,EACVkL,EAAUvE,EAER5B,GAA+B,mBAAT4B,GACxBwB,EAASnI,KAAO2G,GAEhBC,EAAYE,EAAK9G,EAAG2G,EAAOwB,EAASnI,GAAI6E,GAK1C,GAAIiG,EAGD/F,GACCgG,IACAD,EAAOc,QAAWb,EAAOa,QAAWd,EAAOc,QAAW9E,EAAI+E,aAE5D/E,EAAI+E,UAAYf,EAAOc,QAGxBlI,EAAQ3B,IAAa,QAsBrB,GApBIgJ,IAASjE,EAAI+E,UAAY,IAE7BtH,EAEkB,YAAjBb,EAASvC,KAAqB2F,EAAIgF,QAAUhF,EAC5CrG,EAAQuK,GAAeA,EAAc,CAACA,GACtCtH,EACAC,EACAiB,EACY,iBAAZyB,EAA8BnG,EAAkB2E,EAChDC,EACAjB,EACAiB,EACGA,EAAkB,GAClBnB,EAAQ5B,KAAca,EAAce,EAAU,GACjDoB,EACAjB,GAIGgB,GAAqB3E,EACxB,IAAKH,EAAI8E,EAAkBrD,OAAQzB,KAClCc,EAAWgE,EAAkB9E,IAM3B+E,IACJ/E,EAAI,QACY,YAAZqG,GAA0B4E,GAAc9K,EAC3C2G,EAAIa,gBAAgB,SAEpBsD,GAAc7K,IAKb6K,IAAenE,EAAI9G,IACN,YAAZqG,IAA2B4E,GAIf,UAAZ5E,GAAwB4E,GAAc9C,EAASnI,KAEjD4G,EAAYE,EAAK9G,EAAGiL,EAAY9C,EAASnI,GAAI6E,GAG9C7E,EAAI,UACAkL,GAAW9K,GAAa8K,GAAWpE,EAAI9G,IAC1C4G,EAAYE,EAAK9G,EAAGkL,EAAS/C,EAASnI,GAAI6E,GAG7C,CAEA,OAAOiC,CACR,CAQgB,SAAAtB,EAASlE,EAAKqF,EAAO7E,GACpC,IACC,GAAkB,mBAAPR,EAAmB,CAC7B,IAAIyK,EAAuC,mBAAhBzK,EAAGiB,IAC1BwJ,GAEHzK,EAAGiB,MAGCwJ,GAAiBpF,GAASxG,IAI9BmB,EAAGiB,IAAYjB,EAAIqF,GAErB,MAAOrF,EAAI0K,QAAUrF,CAGtB,CAFE,MAAOe,GACRrI,EAAO6C,IAAawF,EAAG5F,EACxB,CACD,CASgB,SAAAoE,EAAQpE,EAAOqE,EAAa8F,GAA5B,IACXC,EAsBMlM,EAbV,GARIX,EAAQ6G,SAAS7G,EAAQ6G,QAAQpE,IAEhCoK,EAAIpK,EAAMR,OACT4K,EAAEF,SAAWE,EAAEF,SAAWlK,EAAKI,KACnCsD,EAAS0G,EAAG/L,EAAMgG,KAIf+F,EAAIpK,EAAKK,MAAgBhC,EAAM,CACnC,GAAI+L,EAAEC,qBACL,IACCD,EAAEC,sBAGH,CAFE,MAAOzE,GACRrI,EAAO6C,IAAawF,EAAGvB,EACxB,CAGD+F,EAAEjJ,KAAOiJ,EAAChI,IAAc/D,CACzB,CAEA,GAAK+L,EAAIpK,EAAKC,IACb,IAAS/B,EAAI,EAAGA,EAAIkM,EAAEzK,OAAQzB,IACzBkM,EAAElM,IACLkG,EACCgG,EAAElM,GACFmG,EACA8F,GAAmC,mBAAdnK,EAAMX,MAM1B8K,GACJnL,EAAWgB,EAAKI,KAGjBJ,EAAKK,IAAcL,EAAKE,GAAWF,EAAKI,IAAQ9B,CACjD,CAGA,SAAS+I,EAAStI,EAAOwI,EAAO3G,GAC/B,YAAYN,YAAYvB,EAAO6B,EAChC,CC9pBO,SAASsG,EAAOlH,EAAO0C,EAAW4H,GAAlC,IAWFrH,EAOApB,EAQAE,EACHC,EAzBGU,GAAa4G,WAChB5G,EAAY4G,SAASiB,iBAGlBhN,EAAO2C,IAAQ3C,EAAO2C,GAAOF,EAAO0C,GAYpCb,GAPAoB,EAAoC,mBAAfqH,GAQtBjM,EACCiM,GAAeA,EAAWrK,KAAeyC,EAASzC,IAMlD8B,EAAc,GACjBC,EAAW,GACZK,EACCK,EAPD1C,IAAWiD,GAAeqH,GAAgB5H,GAASzC,IAClDb,EAAcsB,EAAUrC,EAAM,CAAC2B,IAU/B6B,GAAYrD,EACZA,EACAkE,EAAUH,cACTU,GAAeqH,EACb,CAACA,GACDzI,EACCxD,EACAqE,EAAU8H,WACTlN,EAAMsC,KAAK8C,EAAUkH,YACrBvL,EACL0D,GACCkB,GAAeqH,EACbA,EACAzI,EACCA,EAAQzB,IACRsC,EAAU8H,WACdvH,EACAjB,GAIDQ,EAAWT,EAAa/B,EAAOgC,EAChC,CTzCa1E,EAAQmB,EAAUnB,MChBzBC,EAAU,CACf6C,ISDM,SAAqBqK,EAAOzK,EAAO6B,EAAU6I,GAQnD,IANA,IAAI/I,EAEHgJ,EAEAC,EAEO5K,EAAQA,EAAKE,IACpB,IAAKyB,EAAY3B,EAAKK,OAAiBsB,EAASzB,GAC/C,IAcC,IAbAyK,EAAOhJ,EAAUrB,cAELqK,EAAKE,0BAA4BxM,IAC5CsD,EAAUmJ,SAASH,EAAKE,yBAAyBJ,IACjDG,EAAUjJ,EAASL,KAGhBK,EAAUoJ,mBAAqB1M,IAClCsD,EAAUoJ,kBAAkBN,EAAOC,GAAa,CAAE,GAClDE,EAAUjJ,EAASL,KAIhBsJ,EACH,OAAQjJ,EAASyF,IAAiBzF,CAIpC,CAFE,MAAOiE,GACR6E,EAAQ7E,CACT,CAIF,MAAM6E,CACP,GRzCIjN,EAAU,EA2FDC,EAAiB,SAAAuC,GAAK,OAClCA,GAAS3B,GAAQ2B,EAAMM,cAAgBhC,CAAS,ECrEjDqC,EAAcsG,UAAU6D,SAAW,SAAUE,EAAQC,GAEpD,IAAIC,EAEHA,EADGrK,KAAI6G,KAAerJ,GAAQwC,KAAI6G,KAAe7G,KAAK0G,MAClD1G,KAAI6G,IAEJ7G,KAAI6G,IAAc7I,EAAO,CAAA,EAAIgC,KAAK0G,OAGlB,mBAAVyD,IAGVA,EAASA,EAAOnM,EAAO,CAAA,EAAIqM,GAAIrK,KAAK9B,QAGjCiM,GACHnM,EAAOqM,EAAGF,GAIPA,GAAU3M,GAEVwC,KAAIN,MACH0K,GACHpK,KAAI4G,IAAiBlG,KAAK0J,GAE3B7J,EAAcP,MAEhB,EAQAF,EAAcsG,UAAUkE,YAAc,SAAUF,GAC3CpK,KAAIN,MAIPM,KAAIT,KAAU,EACV6K,GAAUpK,KAAI2G,IAAkBjG,KAAK0J,GACzC7J,EAAcP,MAEhB,EAYAF,EAAcsG,UAAUC,OAASxG,EA+F7BhD,EAAgB,GAadE,EACa,mBAAXwN,QACJA,QAAQnE,UAAUqB,KAAK+C,KAAKD,QAAQE,WACpCC,WAuBE1N,EAAY,SAAC2N,EAAGC,GAAM,OAAAD,EAACjL,IAAAJ,IAAiBsL,EAAClL,IAAAJ,GAAc,EA8B7DqB,EAAOC,IAAkB,ECzOnB3D,EAAgB,8BAalBC,EAAa,EA+IXC,EAAa+H,GAAiB,GAC9B9H,EAAoB8H,GAAiB,GCzKhC7H,EAAI,qCIwER,SAASwN,EAAQ1L,EAAO0C,GAC9BwE,EAAOlH,EAAO0C,EAAWgJ,EAC1B,sDPMC,MAAO,CAAExB,QAAS7L,EACnB,qDSvE6B2B,EAAOjB,EAAOO,OAEzCC,EACAC,EACAtB,EAEG2B,EALAJ,EAAkBZ,EAAO,CAAE,EAAEmB,EAAMjB,OAWvC,IAAKb,KAJD8B,EAAMX,MAAQW,EAAMX,KAAKQ,eAC5BA,EAAeG,EAAMX,KAAKQ,cAGjBd,EACA,OAALb,EAAYqB,EAAMR,EAAMb,GACd,OAALA,EAAYsB,EAAMT,EAAMb,GAEhCuB,EAAgBvB,GADRa,EAAMb,KAAOI,GAAauB,GAAgBvB,EAC7BuB,EAAa3B,GAEba,EAAMb,GAS7B,OALIwB,UAAUC,OAAS,IACtBF,EAAgBH,SACfI,UAAUC,OAAS,EAAIrC,EAAMsC,KAAKF,UAAW,GAAKJ,GAG7CQ,EACNE,EAAMX,KACNI,EACAF,GAAOS,EAAMT,IACbC,GAAOQ,EAAMR,IACbnB,EAEF,gBN1CgB,SAAcsN,GAC7B,SAASC,EAAQ7M,GAAjB,IAGM8M,EACAC,EA+BL,OAlCKjL,KAAKsH,kBAEL0D,EAAO,IAAIE,KACXD,EAAM,CAAE,GACRF,EAAOvL,KAAQQ,KAEnBA,KAAKsH,gBAAkB,WAAM,OAAA2D,CAAG,EAEhCjL,KAAKwJ,qBAAuB,WAC3BwB,EAAOxN,CACR,EAEAwC,KAAKkH,sBAAwB,SAAUiE,GAElCnL,KAAK9B,MAAM8F,OAASmH,EAAOnH,OAC9BgH,EAAKjD,QAAQ,SAAAvH,GACZA,EAACjB,KAAU,EACXgB,EAAcC,EACf,EAEF,EAEAR,KAAKyG,IAAM,SAAAjG,GACVwK,EAAKI,IAAI5K,GACT,IAAI6K,EAAM7K,EAAEgJ,qBACZhJ,EAAEgJ,qBAAuB,WACpBwB,GACHA,EAAKM,OAAO9K,GAET6K,GAAKA,EAAItM,KAAKyB,EACnB,CACD,GAGMtC,EAAMO,QACd,CAgBA,OAdAsM,EAAOvL,IAAO,OAASnC,IACvB0N,EAAO1L,GAAiByL,EAQxBC,EAAQQ,SACPR,EAAOS,KANRT,EAAQU,SAAW,SAACvN,EAAOwN,GAC1B,OAAOxN,EAAMO,SAASiN,EACvB,GAKkBpF,YAChByE,EAEKA,CACR,eEkUO,SAASY,EAAalN,EAAUmN,GAUtC,OATAA,EAAMA,GAAO,GACTnN,GAAYjB,GAA2B,kBAAZiB,IACpBX,EAAQW,GAClBA,EAAS0I,KAAK,SAAA9G,GACbsL,EAAatL,EAAOuL,EACrB,GAEAA,EAAIlL,KAAKjC,IAEHmN,CACR,oBKvYWC,OAAS,IAAKA,OAAOC,QAAUC,EACrCC,KAAKD,OAASA"} \ No newline at end of file diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/dist/preact.min.module.js b/browser/base/content/assistant/ui-preact/node_modules/preact/dist/preact.min.module.js new file mode 100644 index 0000000000000..ac16472ef8d3f --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/dist/preact.min.module.js @@ -0,0 +1,2 @@ +var n,l,t,u,i,e,o,r,f,c,s,a,h,p,v={},y=[],d=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,w=Array.isArray;function m(n,l){for(var t in l)n[t]=l[t];return n}function _(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function g(l,t,u){var i,e,o,r={};for(o in t)"key"==o?i=t[o]:"ref"==o?e=t[o]:r[o]=t[o];if(arguments.length>2&&(r.children=arguments.length>3?n.call(arguments,2):u),"function"==typeof l&&null!=l.defaultProps)for(o in l.defaultProps)void 0===r[o]&&(r[o]=l.defaultProps[o]);return b(l,r,i,e,null)}function b(n,u,i,e,o){var r={type:n,props:u,key:i,ref:e,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==o?++t:o,__i:-1,__u:0};return null==o&&null!=l.vnode&&l.vnode(r),r}function k(n){return n.children}function x(n,l){this.props=n,this.context=l}function C(n,l){if(null==l)return n.__?C(n.__,n.__i+1):null;for(var t;ls&&i.sort(r),n=i.shift(),s=i.length,n.__d&&(u=void 0,e=void 0,o=(e=(t=n).__v).__e,f=[],c=[],t.__P&&((u=m({},e)).__v=e.__v+1,l.vnode&&l.vnode(u),T(t.__P,u,e,t.__n,t.__P.namespaceURI,32&e.__u?[o]:null,f,null==o?C(e):o,!!(32&e.__u),c),u.__v=e.__v,u.__.__k[u.__i]=u,O(f,u,c),e.__e=e.__=null,u.__e!=o&&S(u)));$.__r=0}function A(n,l,t,u,i,e,o,r,f,c,s){var a,h,p,d,w,m,_,g=u&&u.__k||y,b=l.length;for(f=I(t,l,g,f,b),a=0;a0?o=n.__k[e]=b(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):n.__k[e]=o,f=e+h,o.__=n,o.__b=n.__b+1,r=null,-1!=(c=o.__i=E(o,t,f,a))&&(a--,(r=t[c])&&(r.__u|=2)),null==r||null==r.__v?(-1==c&&(i>s?h--:if?h--:h++,o.__u|=4))):n.__k[e]=null;if(a)for(e=0;e(s?1:0))for(i=t-1,e=t+1;i>=0||e=0?i--:e++])&&0==(2&c.__u)&&r==c.key&&f==c.type)return o;return-1}function F(n,l,t){"-"==l[0]?n.setProperty(l,null==t?"":t):n[l]=null==t?"":"number"!=typeof t||d.test(l)?t:t+"px"}function H(n,l,t,u,i){var e,o;n:if("style"==l)if("string"==typeof t)n.style.cssText=t;else{if("string"==typeof u&&(n.style.cssText=u=""),u)for(l in u)t&&l in t||F(n.style,l,"");if(t)for(l in t)u&&t[l]==u[l]||F(n.style,l,t[l])}else if("o"==l[0]&&"n"==l[1])e=l!=(l=l.replace(f,"$1")),o=l.toLowerCase(),l=o in n||"onFocusOut"==l||"onFocusIn"==l?o.slice(2):l.slice(2),n.l||(n.l={}),n.l[l+e]=t,t?u?t.t=u.t:(t.t=c,n.addEventListener(l,e?a:s,e)):n.removeEventListener(l,e?a:s,e);else{if("http://www.w3.org/2000/svg"==i)l=l.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=l&&"height"!=l&&"href"!=l&&"list"!=l&&"form"!=l&&"tabIndex"!=l&&"download"!=l&&"rowSpan"!=l&&"colSpan"!=l&&"role"!=l&&"popover"!=l&&l in n)try{n[l]=null==t?"":t;break n}catch(n){}"function"==typeof t||(null==t||!1===t&&"-"!=l[4]?n.removeAttribute(l):n.setAttribute(l,"popover"==l&&1==t?"":t))}}function L(n){return function(t){if(this.l){var u=this.l[t.type+n];if(null==t.u)t.u=c++;else if(t.u0?n:w(n)?n.map(V):m({},n)}function z(t,u,i,e,o,r,f,c,s){var a,h,p,y,d,m,g,b=i.props||v,k=u.props,x=u.type;if("svg"==x?o="http://www.w3.org/2000/svg":"math"==x?o="http://www.w3.org/1998/Math/MathML":o||(o="http://www.w3.org/1999/xhtml"),null!=r)for(a=0;a2&&(f.children=arguments.length>3?n.call(arguments,2):u),b(l.type,f,i||l.key,e||l.ref,null)},createContext:function(n){function l(n){var t,u;return this.getChildContext||(t=new Set,(u={})[l.__c]=this,this.getChildContext=function(){return u},this.componentWillUnmount=function(){t=null},this.shouldComponentUpdate=function(n){this.props.value!=n.value&&t.forEach(function(n){n.__e=!0,M(n)})},this.sub=function(n){t.add(n);var l=n.componentWillUnmount;n.componentWillUnmount=function(){t&&t.delete(n),l&&l.call(n)}}),n.children}return l.__c="__cC"+h++,l.__=n,l.Provider=l.__l=(l.Consumer=function(n,l){return n.children(l)}).contextType=l,l},toChildArray:function n(l,t){return t=t||[],null==l||"boolean"==typeof l||(w(l)?l.some(function(l){n(l,t)}):t.push(l)),t},options:l},typeof module<"u"?module.exports=p:self.preact=p; +//# sourceMappingURL=preact.min.module.js.map diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/dist/preact.min.module.js.map b/browser/base/content/assistant/ui-preact/node_modules/preact/dist/preact.min.module.js.map new file mode 100644 index 0000000000000..f5f4bdc3a20be --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/dist/preact.min.module.js.map @@ -0,0 +1 @@ +{"version":3,"file":"preact.min.module.js","sources":["../src/constants.js","../src/util.js","../src/options.js","../src/create-element.js","../src/component.js","../src/diff/props.js","../src/create-context.js","../src/diff/children.js","../src/diff/index.js","../src/render.js","../src/diff/catch-error.js","../src/clone-element.js","../src/cjs.js"],"sourcesContent":["/** Normal hydration that attaches to a DOM tree but does not diff it. */\nexport const MODE_HYDRATE = 1 << 5;\n/** Signifies this VNode suspended on the previous render */\nexport const MODE_SUSPENDED = 1 << 7;\n/** Indicates that this node needs to be inserted while patching children */\nexport const INSERT_VNODE = 1 << 2;\n/** Indicates a VNode has been matched with another VNode in the diff */\nexport const MATCHED = 1 << 1;\n\n/** Reset all mode flags */\nexport const RESET_MODE = ~(MODE_HYDRATE | MODE_SUSPENDED);\n\nexport const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\nexport const XHTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\nexport const MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n\nexport const NULL = null;\nexport const UNDEFINED = undefined;\nexport const EMPTY_OBJ = /** @type {any} */ ({});\nexport const EMPTY_ARR = [];\nexport const IS_NON_DIMENSIONAL =\n\t/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;\n","import { EMPTY_ARR } from './constants';\n\nexport const isArray = Array.isArray;\n\n/**\n * Assign properties from `props` to `obj`\n * @template O, P The obj and props types\n * @param {O} obj The object to copy properties to\n * @param {P} props The object to copy properties from\n * @returns {O & P}\n */\nexport function assign(obj, props) {\n\t// @ts-expect-error We change the type of `obj` to be `O & P`\n\tfor (let i in props) obj[i] = props[i];\n\treturn /** @type {O & P} */ (obj);\n}\n\n/**\n * Remove a child node from its parent if attached. This is a workaround for\n * IE11 which doesn't support `Element.prototype.remove()`. Using this function\n * is smaller than including a dedicated polyfill.\n * @param {import('./index').ContainerNode} node The node to remove\n */\nexport function removeNode(node) {\n\tif (node && node.parentNode) node.parentNode.removeChild(node);\n}\n\nexport const slice = EMPTY_ARR.slice;\n","import { _catchError } from './diff/catch-error';\n\n/**\n * The `option` object can potentially contain callback functions\n * that are called during various stages of our renderer. This is the\n * foundation on which all our addons like `preact/debug`, `preact/compat`,\n * and `preact/hooks` are based on. See the `Options` type in `internal.d.ts`\n * for a full list of available option hooks (most editors/IDEs allow you to\n * ctrl+click or cmd+click on mac the type definition below).\n * @type {import('./internal').Options}\n */\nconst options = {\n\t_catchError\n};\n\nexport default options;\n","import { slice } from './util';\nimport options from './options';\nimport { NULL, UNDEFINED } from './constants';\n\nlet vnodeId = 0;\n\n/**\n * Create an virtual node (used for JSX)\n * @param {import('./internal').VNode[\"type\"]} type The node name or Component constructor for this\n * virtual node\n * @param {object | null | undefined} [props] The properties of the virtual node\n * @param {Array} [children] The children of the\n * virtual node\n * @returns {import('./internal').VNode}\n */\nexport function createElement(type, props, children) {\n\tlet normalizedProps = {},\n\t\tkey,\n\t\tref,\n\t\ti;\n\tfor (i in props) {\n\t\tif (i == 'key') key = props[i];\n\t\telse if (i == 'ref') ref = props[i];\n\t\telse normalizedProps[i] = props[i];\n\t}\n\n\tif (arguments.length > 2) {\n\t\tnormalizedProps.children =\n\t\t\targuments.length > 3 ? slice.call(arguments, 2) : children;\n\t}\n\n\t// If a Component VNode, check for and apply defaultProps\n\t// Note: type may be undefined in development, must never error here.\n\tif (typeof type == 'function' && type.defaultProps != NULL) {\n\t\tfor (i in type.defaultProps) {\n\t\t\tif (normalizedProps[i] === UNDEFINED) {\n\t\t\t\tnormalizedProps[i] = type.defaultProps[i];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn createVNode(type, normalizedProps, key, ref, NULL);\n}\n\n/**\n * Create a VNode (used internally by Preact)\n * @param {import('./internal').VNode[\"type\"]} type The node name or Component\n * Constructor for this virtual node\n * @param {object | string | number | null} props The properties of this virtual node.\n * If this virtual node represents a text node, this is the text of the node (string or number).\n * @param {string | number | null} key The key for this virtual node, used when\n * diffing it against its children\n * @param {import('./internal').VNode[\"ref\"]} ref The ref property that will\n * receive a reference to its created child\n * @returns {import('./internal').VNode}\n */\nexport function createVNode(type, props, key, ref, original) {\n\t// V8 seems to be better at detecting type shapes if the object is allocated from the same call site\n\t// Do not inline into createElement and coerceToVNode!\n\t/** @type {import('./internal').VNode} */\n\tconst vnode = {\n\t\ttype,\n\t\tprops,\n\t\tkey,\n\t\tref,\n\t\t_children: NULL,\n\t\t_parent: NULL,\n\t\t_depth: 0,\n\t\t_dom: NULL,\n\t\t_component: NULL,\n\t\tconstructor: UNDEFINED,\n\t\t_original: original == NULL ? ++vnodeId : original,\n\t\t_index: -1,\n\t\t_flags: 0\n\t};\n\n\t// Only invoke the vnode hook if this was *not* a direct copy:\n\tif (original == NULL && options.vnode != NULL) options.vnode(vnode);\n\n\treturn vnode;\n}\n\nexport function createRef() {\n\treturn { current: NULL };\n}\n\nexport function Fragment(props) {\n\treturn props.children;\n}\n\n/**\n * Check if a the argument is a valid Preact VNode.\n * @param {*} vnode\n * @returns {vnode is VNode}\n */\nexport const isValidElement = vnode =>\n\tvnode != NULL && vnode.constructor === UNDEFINED;\n","import { assign } from './util';\nimport { diff, commitRoot } from './diff/index';\nimport options from './options';\nimport { Fragment } from './create-element';\nimport { MODE_HYDRATE, NULL } from './constants';\n\n/**\n * Base Component class. Provides `setState()` and `forceUpdate()`, which\n * trigger rendering\n * @param {object} props The initial component props\n * @param {object} context The initial context from parent components'\n * getChildContext\n */\nexport function BaseComponent(props, context) {\n\tthis.props = props;\n\tthis.context = context;\n}\n\n/**\n * Update component state and schedule a re-render.\n * @this {import('./internal').Component}\n * @param {object | ((s: object, p: object) => object)} update A hash of state\n * properties to update with new values or a function that given the current\n * state and props returns a new partial state\n * @param {() => void} [callback] A function to be called once component state is\n * updated\n */\nBaseComponent.prototype.setState = function (update, callback) {\n\t// only clone state when copying to nextState the first time.\n\tlet s;\n\tif (this._nextState != NULL && this._nextState != this.state) {\n\t\ts = this._nextState;\n\t} else {\n\t\ts = this._nextState = assign({}, this.state);\n\t}\n\n\tif (typeof update == 'function') {\n\t\t// Some libraries like `immer` mark the current state as readonly,\n\t\t// preventing us from mutating it, so we need to clone it. See #2716\n\t\tupdate = update(assign({}, s), this.props);\n\t}\n\n\tif (update) {\n\t\tassign(s, update);\n\t}\n\n\t// Skip update if updater function returned null\n\tif (update == NULL) return;\n\n\tif (this._vnode) {\n\t\tif (callback) {\n\t\t\tthis._stateCallbacks.push(callback);\n\t\t}\n\t\tenqueueRender(this);\n\t}\n};\n\n/**\n * Immediately perform a synchronous re-render of the component\n * @this {import('./internal').Component}\n * @param {() => void} [callback] A function to be called after component is\n * re-rendered\n */\nBaseComponent.prototype.forceUpdate = function (callback) {\n\tif (this._vnode) {\n\t\t// Set render mode so that we can differentiate where the render request\n\t\t// is coming from. We need this because forceUpdate should never call\n\t\t// shouldComponentUpdate\n\t\tthis._force = true;\n\t\tif (callback) this._renderCallbacks.push(callback);\n\t\tenqueueRender(this);\n\t}\n};\n\n/**\n * Accepts `props` and `state`, and returns a new Virtual DOM tree to build.\n * Virtual DOM is generally constructed via [JSX](https://jasonformat.com/wtf-is-jsx).\n * @param {object} props Props (eg: JSX attributes) received from parent\n * element/component\n * @param {object} state The component's current state\n * @param {object} context Context object, as returned by the nearest\n * ancestor's `getChildContext()`\n * @returns {ComponentChildren | void}\n */\nBaseComponent.prototype.render = Fragment;\n\n/**\n * @param {import('./internal').VNode} vnode\n * @param {number | null} [childIndex]\n */\nexport function getDomSibling(vnode, childIndex) {\n\tif (childIndex == NULL) {\n\t\t// Use childIndex==null as a signal to resume the search from the vnode's sibling\n\t\treturn vnode._parent\n\t\t\t? getDomSibling(vnode._parent, vnode._index + 1)\n\t\t\t: NULL;\n\t}\n\n\tlet sibling;\n\tfor (; childIndex < vnode._children.length; childIndex++) {\n\t\tsibling = vnode._children[childIndex];\n\n\t\tif (sibling != NULL && sibling._dom != NULL) {\n\t\t\t// Since updateParentDomPointers keeps _dom pointer correct,\n\t\t\t// we can rely on _dom to tell us if this subtree contains a\n\t\t\t// rendered DOM node, and what the first rendered DOM node is\n\t\t\treturn sibling._dom;\n\t\t}\n\t}\n\n\t// If we get here, we have not found a DOM node in this vnode's children.\n\t// We must resume from this vnode's sibling (in it's parent _children array)\n\t// Only climb up and search the parent if we aren't searching through a DOM\n\t// VNode (meaning we reached the DOM parent of the original vnode that began\n\t// the search)\n\treturn typeof vnode.type == 'function' ? getDomSibling(vnode) : NULL;\n}\n\n/**\n * Trigger in-place re-rendering of a component.\n * @param {import('./internal').Component} component The component to rerender\n */\nfunction renderComponent(component) {\n\tlet oldVNode = component._vnode,\n\t\toldDom = oldVNode._dom,\n\t\tcommitQueue = [],\n\t\trefQueue = [];\n\n\tif (component._parentDom) {\n\t\tconst newVNode = assign({}, oldVNode);\n\t\tnewVNode._original = oldVNode._original + 1;\n\t\tif (options.vnode) options.vnode(newVNode);\n\n\t\tdiff(\n\t\t\tcomponent._parentDom,\n\t\t\tnewVNode,\n\t\t\toldVNode,\n\t\t\tcomponent._globalContext,\n\t\t\tcomponent._parentDom.namespaceURI,\n\t\t\toldVNode._flags & MODE_HYDRATE ? [oldDom] : NULL,\n\t\t\tcommitQueue,\n\t\t\toldDom == NULL ? getDomSibling(oldVNode) : oldDom,\n\t\t\t!!(oldVNode._flags & MODE_HYDRATE),\n\t\t\trefQueue\n\t\t);\n\n\t\tnewVNode._original = oldVNode._original;\n\t\tnewVNode._parent._children[newVNode._index] = newVNode;\n\t\tcommitRoot(commitQueue, newVNode, refQueue);\n\t\toldVNode._dom = oldVNode._parent = null;\n\n\t\tif (newVNode._dom != oldDom) {\n\t\t\tupdateParentDomPointers(newVNode);\n\t\t}\n\t}\n}\n\n/**\n * @param {import('./internal').VNode} vnode\n */\nfunction updateParentDomPointers(vnode) {\n\tif ((vnode = vnode._parent) != NULL && vnode._component != NULL) {\n\t\tvnode._dom = vnode._component.base = NULL;\n\t\tfor (let i = 0; i < vnode._children.length; i++) {\n\t\t\tlet child = vnode._children[i];\n\t\t\tif (child != NULL && child._dom != NULL) {\n\t\t\t\tvnode._dom = vnode._component.base = child._dom;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn updateParentDomPointers(vnode);\n\t}\n}\n\n/**\n * The render queue\n * @type {Array}\n */\nlet rerenderQueue = [];\n\n/*\n * The value of `Component.debounce` must asynchronously invoke the passed in callback. It is\n * important that contributors to Preact can consistently reason about what calls to `setState`, etc.\n * do, and when their effects will be applied. See the links below for some further reading on designing\n * asynchronous APIs.\n * * [Designing APIs for Asynchrony](https://blog.izs.me/2013/08/designing-apis-for-asynchrony)\n * * [Callbacks synchronous and asynchronous](https://blog.ometer.com/2011/07/24/callbacks-synchronous-and-asynchronous/)\n */\n\nlet prevDebounce;\n\nconst defer =\n\ttypeof Promise == 'function'\n\t\t? Promise.prototype.then.bind(Promise.resolve())\n\t\t: setTimeout;\n\n/**\n * Enqueue a rerender of a component\n * @param {import('./internal').Component} c The component to rerender\n */\nexport function enqueueRender(c) {\n\tif (\n\t\t(!c._dirty &&\n\t\t\t(c._dirty = true) &&\n\t\t\trerenderQueue.push(c) &&\n\t\t\t!process._rerenderCount++) ||\n\t\tprevDebounce != options.debounceRendering\n\t) {\n\t\tprevDebounce = options.debounceRendering;\n\t\t(prevDebounce || defer)(process);\n\t}\n}\n\n/**\n * @param {import('./internal').Component} a\n * @param {import('./internal').Component} b\n */\nconst depthSort = (a, b) => a._vnode._depth - b._vnode._depth;\n\n/** Flush the render queue by rerendering all queued components */\nfunction process() {\n\tlet c,\n\t\tl = 1;\n\n\t// Don't update `renderCount` yet. Keep its value non-zero to prevent unnecessary\n\t// process() calls from getting scheduled while `queue` is still being consumed.\n\twhile (rerenderQueue.length) {\n\t\t// Keep the rerender queue sorted by (depth, insertion order). The queue\n\t\t// will initially be sorted on the first iteration only if it has more than 1 item.\n\t\t//\n\t\t// New items can be added to the queue e.g. when rerendering a provider, so we want to\n\t\t// keep the order from top to bottom with those new items so we can handle them in a\n\t\t// single pass\n\t\tif (rerenderQueue.length > l) {\n\t\t\trerenderQueue.sort(depthSort);\n\t\t}\n\n\t\tc = rerenderQueue.shift();\n\t\tl = rerenderQueue.length;\n\n\t\tif (c._dirty) {\n\t\t\trenderComponent(c);\n\t\t}\n\t}\n\tprocess._rerenderCount = 0;\n}\n\nprocess._rerenderCount = 0;\n","import { IS_NON_DIMENSIONAL, NULL, SVG_NAMESPACE } from '../constants';\nimport options from '../options';\n\nfunction setStyle(style, key, value) {\n\tif (key[0] == '-') {\n\t\tstyle.setProperty(key, value == NULL ? '' : value);\n\t} else if (value == NULL) {\n\t\tstyle[key] = '';\n\t} else if (typeof value != 'number' || IS_NON_DIMENSIONAL.test(key)) {\n\t\tstyle[key] = value;\n\t} else {\n\t\tstyle[key] = value + 'px';\n\t}\n}\n\nconst CAPTURE_REGEX = /(PointerCapture)$|Capture$/i;\n\n// A logical clock to solve issues like https://github.com/preactjs/preact/issues/3927.\n// When the DOM performs an event it leaves micro-ticks in between bubbling up which means that\n// an event can trigger on a newly reated DOM-node while the event bubbles up.\n//\n// Originally inspired by Vue\n// (https://github.com/vuejs/core/blob/caeb8a68811a1b0f79/packages/runtime-dom/src/modules/events.ts#L90-L101),\n// but modified to use a logical clock instead of Date.now() in case event handlers get attached\n// and events get dispatched during the same millisecond.\n//\n// The clock is incremented after each new event dispatch. This allows 1 000 000 new events\n// per second for over 280 years before the value reaches Number.MAX_SAFE_INTEGER (2**53 - 1).\nlet eventClock = 0;\n\n/**\n * Set a property value on a DOM node\n * @param {import('../internal').PreactElement} dom The DOM node to modify\n * @param {string} name The name of the property to set\n * @param {*} value The value to set the property to\n * @param {*} oldValue The old value the property had\n * @param {string} namespace Whether or not this DOM node is an SVG node or not\n */\nexport function setProperty(dom, name, value, oldValue, namespace) {\n\tlet useCapture;\n\n\to: if (name == 'style') {\n\t\tif (typeof value == 'string') {\n\t\t\tdom.style.cssText = value;\n\t\t} else {\n\t\t\tif (typeof oldValue == 'string') {\n\t\t\t\tdom.style.cssText = oldValue = '';\n\t\t\t}\n\n\t\t\tif (oldValue) {\n\t\t\t\tfor (name in oldValue) {\n\t\t\t\t\tif (!(value && name in value)) {\n\t\t\t\t\t\tsetStyle(dom.style, name, '');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (value) {\n\t\t\t\tfor (name in value) {\n\t\t\t\t\tif (!oldValue || value[name] != oldValue[name]) {\n\t\t\t\t\t\tsetStyle(dom.style, name, value[name]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// Benchmark for comparison: https://esbench.com/bench/574c954bdb965b9a00965ac6\n\telse if (name[0] == 'o' && name[1] == 'n') {\n\t\tuseCapture = name != (name = name.replace(CAPTURE_REGEX, '$1'));\n\t\tconst lowerCaseName = name.toLowerCase();\n\n\t\t// Infer correct casing for DOM built-in events:\n\t\tif (lowerCaseName in dom || name == 'onFocusOut' || name == 'onFocusIn')\n\t\t\tname = lowerCaseName.slice(2);\n\t\telse name = name.slice(2);\n\n\t\tif (!dom._listeners) dom._listeners = {};\n\t\tdom._listeners[name + useCapture] = value;\n\n\t\tif (value) {\n\t\t\tif (!oldValue) {\n\t\t\t\tvalue._attached = eventClock;\n\t\t\t\tdom.addEventListener(\n\t\t\t\t\tname,\n\t\t\t\t\tuseCapture ? eventProxyCapture : eventProxy,\n\t\t\t\t\tuseCapture\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tvalue._attached = oldValue._attached;\n\t\t\t}\n\t\t} else {\n\t\t\tdom.removeEventListener(\n\t\t\t\tname,\n\t\t\t\tuseCapture ? eventProxyCapture : eventProxy,\n\t\t\t\tuseCapture\n\t\t\t);\n\t\t}\n\t} else {\n\t\tif (namespace == SVG_NAMESPACE) {\n\t\t\t// Normalize incorrect prop usage for SVG:\n\t\t\t// - xlink:href / xlinkHref --> href (xlink:href was removed from SVG and isn't needed)\n\t\t\t// - className --> class\n\t\t\tname = name.replace(/xlink(H|:h)/, 'h').replace(/sName$/, 's');\n\t\t} else if (\n\t\t\tname != 'width' &&\n\t\t\tname != 'height' &&\n\t\t\tname != 'href' &&\n\t\t\tname != 'list' &&\n\t\t\tname != 'form' &&\n\t\t\t// Default value in browsers is `-1` and an empty string is\n\t\t\t// cast to `0` instead\n\t\t\tname != 'tabIndex' &&\n\t\t\tname != 'download' &&\n\t\t\tname != 'rowSpan' &&\n\t\t\tname != 'colSpan' &&\n\t\t\tname != 'role' &&\n\t\t\tname != 'popover' &&\n\t\t\tname in dom\n\t\t) {\n\t\t\ttry {\n\t\t\t\tdom[name] = value == NULL ? '' : value;\n\t\t\t\t// labelled break is 1b smaller here than a return statement (sorry)\n\t\t\t\tbreak o;\n\t\t\t} catch (e) {}\n\t\t}\n\n\t\t// aria- and data- attributes have no boolean representation.\n\t\t// A `false` value is different from the attribute not being\n\t\t// present, so we can't remove it. For non-boolean aria\n\t\t// attributes we could treat false as a removal, but the\n\t\t// amount of exceptions would cost too many bytes. On top of\n\t\t// that other frameworks generally stringify `false`.\n\n\t\tif (typeof value == 'function') {\n\t\t\t// never serialize functions as attribute values\n\t\t} else if (value != NULL && (value !== false || name[4] == '-')) {\n\t\t\tdom.setAttribute(name, name == 'popover' && value == true ? '' : value);\n\t\t} else {\n\t\t\tdom.removeAttribute(name);\n\t\t}\n\t}\n}\n\n/**\n * Create an event proxy function.\n * @param {boolean} useCapture Is the event handler for the capture phase.\n * @private\n */\nfunction createEventProxy(useCapture) {\n\t/**\n\t * Proxy an event to hooked event handlers\n\t * @param {import('../internal').PreactEvent} e The event object from the browser\n\t * @private\n\t */\n\treturn function (e) {\n\t\tif (this._listeners) {\n\t\t\tconst eventHandler = this._listeners[e.type + useCapture];\n\t\t\tif (e._dispatched == NULL) {\n\t\t\t\te._dispatched = eventClock++;\n\n\t\t\t\t// When `e._dispatched` is smaller than the time when the targeted event\n\t\t\t\t// handler was attached we know we have bubbled up to an element that was added\n\t\t\t\t// during patching the DOM.\n\t\t\t} else if (e._dispatched < eventHandler._attached) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treturn eventHandler(options.event ? options.event(e) : e);\n\t\t}\n\t};\n}\n\nconst eventProxy = createEventProxy(false);\nconst eventProxyCapture = createEventProxy(true);\n","import { enqueueRender } from './component';\nimport { NULL } from './constants';\n\nexport let i = 0;\n\nexport function createContext(defaultValue) {\n\tfunction Context(props) {\n\t\tif (!this.getChildContext) {\n\t\t\t/** @type {Set | null} */\n\t\t\tlet subs = new Set();\n\t\t\tlet ctx = {};\n\t\t\tctx[Context._id] = this;\n\n\t\t\tthis.getChildContext = () => ctx;\n\n\t\t\tthis.componentWillUnmount = () => {\n\t\t\t\tsubs = NULL;\n\t\t\t};\n\n\t\t\tthis.shouldComponentUpdate = function (_props) {\n\t\t\t\t// @ts-expect-error even\n\t\t\t\tif (this.props.value != _props.value) {\n\t\t\t\t\tsubs.forEach(c => {\n\t\t\t\t\t\tc._force = true;\n\t\t\t\t\t\tenqueueRender(c);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tthis.sub = c => {\n\t\t\t\tsubs.add(c);\n\t\t\t\tlet old = c.componentWillUnmount;\n\t\t\t\tc.componentWillUnmount = () => {\n\t\t\t\t\tif (subs) {\n\t\t\t\t\t\tsubs.delete(c);\n\t\t\t\t\t}\n\t\t\t\t\tif (old) old.call(c);\n\t\t\t\t};\n\t\t\t};\n\t\t}\n\n\t\treturn props.children;\n\t}\n\n\tContext._id = '__cC' + i++;\n\tContext._defaultValue = defaultValue;\n\n\t/** @type {import('./internal').FunctionComponent} */\n\tContext.Consumer = (props, contextValue) => {\n\t\treturn props.children(contextValue);\n\t};\n\n\t// we could also get rid of _contextRef entirely\n\tContext.Provider =\n\t\tContext._contextRef =\n\t\tContext.Consumer.contextType =\n\t\t\tContext;\n\n\treturn Context;\n}\n","import { diff, unmount, applyRef } from './index';\nimport { createVNode, Fragment } from '../create-element';\nimport {\n\tEMPTY_OBJ,\n\tEMPTY_ARR,\n\tINSERT_VNODE,\n\tMATCHED,\n\tUNDEFINED,\n\tNULL\n} from '../constants';\nimport { isArray } from '../util';\nimport { getDomSibling } from '../component';\n\n/**\n * @typedef {import('../internal').ComponentChildren} ComponentChildren\n * @typedef {import('../internal').Component} Component\n * @typedef {import('../internal').PreactElement} PreactElement\n * @typedef {import('../internal').VNode} VNode\n */\n\n/**\n * Diff the children of a virtual node\n * @param {PreactElement} parentDom The DOM element whose children are being\n * diffed\n * @param {ComponentChildren[]} renderResult\n * @param {VNode} newParentVNode The new virtual node whose children should be\n * diff'ed against oldParentVNode\n * @param {VNode} oldParentVNode The old virtual node whose children should be\n * diff'ed against newParentVNode\n * @param {object} globalContext The current context object - modified by\n * getChildContext\n * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML)\n * @param {Array} excessDomChildren\n * @param {Array} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {PreactElement} oldDom The current attached DOM element any new dom\n * elements should be placed around. Likely `null` on first render (except when\n * hydrating). Can be a sibling DOM element when diffing Fragments that have\n * siblings. In most cases, it starts out as `oldChildren[0]._dom`.\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n */\nexport function diffChildren(\n\tparentDom,\n\trenderResult,\n\tnewParentVNode,\n\toldParentVNode,\n\tglobalContext,\n\tnamespace,\n\texcessDomChildren,\n\tcommitQueue,\n\toldDom,\n\tisHydrating,\n\trefQueue\n) {\n\tlet i,\n\t\t/** @type {VNode} */\n\t\toldVNode,\n\t\t/** @type {VNode} */\n\t\tchildVNode,\n\t\t/** @type {PreactElement} */\n\t\tnewDom,\n\t\t/** @type {PreactElement} */\n\t\tfirstChildDom;\n\n\t// This is a compression of oldParentVNode!=null && oldParentVNode != EMPTY_OBJ && oldParentVNode._children || EMPTY_ARR\n\t// as EMPTY_OBJ._children should be `undefined`.\n\t/** @type {VNode[]} */\n\tlet oldChildren = (oldParentVNode && oldParentVNode._children) || EMPTY_ARR;\n\n\tlet newChildrenLength = renderResult.length;\n\n\toldDom = constructNewChildrenArray(\n\t\tnewParentVNode,\n\t\trenderResult,\n\t\toldChildren,\n\t\toldDom,\n\t\tnewChildrenLength\n\t);\n\n\tfor (i = 0; i < newChildrenLength; i++) {\n\t\tchildVNode = newParentVNode._children[i];\n\t\tif (childVNode == NULL) continue;\n\n\t\t// At this point, constructNewChildrenArray has assigned _index to be the\n\t\t// matchingIndex for this VNode's oldVNode (or -1 if there is no oldVNode).\n\t\tif (childVNode._index == -1) {\n\t\t\toldVNode = EMPTY_OBJ;\n\t\t} else {\n\t\t\toldVNode = oldChildren[childVNode._index] || EMPTY_OBJ;\n\t\t}\n\n\t\t// Update childVNode._index to its final index\n\t\tchildVNode._index = i;\n\n\t\t// Morph the old element into the new one, but don't append it to the dom yet\n\t\tlet result = diff(\n\t\t\tparentDom,\n\t\t\tchildVNode,\n\t\t\toldVNode,\n\t\t\tglobalContext,\n\t\t\tnamespace,\n\t\t\texcessDomChildren,\n\t\t\tcommitQueue,\n\t\t\toldDom,\n\t\t\tisHydrating,\n\t\t\trefQueue\n\t\t);\n\n\t\t// Adjust DOM nodes\n\t\tnewDom = childVNode._dom;\n\t\tif (childVNode.ref && oldVNode.ref != childVNode.ref) {\n\t\t\tif (oldVNode.ref) {\n\t\t\t\tapplyRef(oldVNode.ref, NULL, childVNode);\n\t\t\t}\n\t\t\trefQueue.push(\n\t\t\t\tchildVNode.ref,\n\t\t\t\tchildVNode._component || newDom,\n\t\t\t\tchildVNode\n\t\t\t);\n\t\t}\n\n\t\tif (firstChildDom == NULL && newDom != NULL) {\n\t\t\tfirstChildDom = newDom;\n\t\t}\n\n\t\tlet shouldPlace = !!(childVNode._flags & INSERT_VNODE);\n\t\tif (shouldPlace || oldVNode._children === childVNode._children) {\n\t\t\toldDom = insert(childVNode, oldDom, parentDom, shouldPlace);\n\t\t} else if (typeof childVNode.type == 'function' && result !== UNDEFINED) {\n\t\t\toldDom = result;\n\t\t} else if (newDom) {\n\t\t\toldDom = newDom.nextSibling;\n\t\t}\n\n\t\t// Unset diffing flags\n\t\tchildVNode._flags &= ~(INSERT_VNODE | MATCHED);\n\t}\n\n\tnewParentVNode._dom = firstChildDom;\n\n\treturn oldDom;\n}\n\n/**\n * @param {VNode} newParentVNode\n * @param {ComponentChildren[]} renderResult\n * @param {VNode[]} oldChildren\n */\nfunction constructNewChildrenArray(\n\tnewParentVNode,\n\trenderResult,\n\toldChildren,\n\toldDom,\n\tnewChildrenLength\n) {\n\t/** @type {number} */\n\tlet i;\n\t/** @type {VNode} */\n\tlet childVNode;\n\t/** @type {VNode} */\n\tlet oldVNode;\n\n\tlet oldChildrenLength = oldChildren.length,\n\t\tremainingOldChildren = oldChildrenLength;\n\n\tlet skew = 0;\n\n\tnewParentVNode._children = new Array(newChildrenLength);\n\tfor (i = 0; i < newChildrenLength; i++) {\n\t\t// @ts-expect-error We are reusing the childVNode variable to hold both the\n\t\t// pre and post normalized childVNode\n\t\tchildVNode = renderResult[i];\n\n\t\tif (\n\t\t\tchildVNode == NULL ||\n\t\t\ttypeof childVNode == 'boolean' ||\n\t\t\ttypeof childVNode == 'function'\n\t\t) {\n\t\t\tnewParentVNode._children[i] = NULL;\n\t\t\tcontinue;\n\t\t}\n\t\t// If this newVNode is being reused (e.g.
    {reuse}{reuse}
    ) in the same diff,\n\t\t// or we are rendering a component (e.g. setState) copy the oldVNodes so it can have\n\t\t// it's own DOM & etc. pointers\n\t\telse if (\n\t\t\ttypeof childVNode == 'string' ||\n\t\t\ttypeof childVNode == 'number' ||\n\t\t\t// eslint-disable-next-line valid-typeof\n\t\t\ttypeof childVNode == 'bigint' ||\n\t\t\tchildVNode.constructor == String\n\t\t) {\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tNULL,\n\t\t\t\tchildVNode,\n\t\t\t\tNULL,\n\t\t\t\tNULL,\n\t\t\t\tNULL\n\t\t\t);\n\t\t} else if (isArray(childVNode)) {\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tFragment,\n\t\t\t\t{ children: childVNode },\n\t\t\t\tNULL,\n\t\t\t\tNULL,\n\t\t\t\tNULL\n\t\t\t);\n\t\t} else if (childVNode.constructor === UNDEFINED && childVNode._depth > 0) {\n\t\t\t// VNode is already in use, clone it. This can happen in the following\n\t\t\t// scenario:\n\t\t\t// const reuse =
    \n\t\t\t//
    {reuse}{reuse}
    \n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tchildVNode.type,\n\t\t\t\tchildVNode.props,\n\t\t\t\tchildVNode.key,\n\t\t\t\tchildVNode.ref ? childVNode.ref : NULL,\n\t\t\t\tchildVNode._original\n\t\t\t);\n\t\t} else {\n\t\t\tnewParentVNode._children[i] = childVNode;\n\t\t}\n\n\t\tconst skewedIndex = i + skew;\n\t\tchildVNode._parent = newParentVNode;\n\t\tchildVNode._depth = newParentVNode._depth + 1;\n\n\t\t// Temporarily store the matchingIndex on the _index property so we can pull\n\t\t// out the oldVNode in diffChildren. We'll override this to the VNode's\n\t\t// final index after using this property to get the oldVNode\n\t\tconst matchingIndex = (childVNode._index = findMatchingIndex(\n\t\t\tchildVNode,\n\t\t\toldChildren,\n\t\t\tskewedIndex,\n\t\t\tremainingOldChildren\n\t\t));\n\n\t\toldVNode = NULL;\n\t\tif (matchingIndex != -1) {\n\t\t\toldVNode = oldChildren[matchingIndex];\n\t\t\tremainingOldChildren--;\n\t\t\tif (oldVNode) {\n\t\t\t\toldVNode._flags |= MATCHED;\n\t\t\t}\n\t\t}\n\n\t\t// Here, we define isMounting for the purposes of the skew diffing\n\t\t// algorithm. Nodes that are unsuspending are considered mounting and we detect\n\t\t// this by checking if oldVNode._original == null\n\t\tconst isMounting = oldVNode == NULL || oldVNode._original == NULL;\n\n\t\tif (isMounting) {\n\t\t\tif (matchingIndex == -1) {\n\t\t\t\t// When the array of children is growing we need to decrease the skew\n\t\t\t\t// as we are adding a new element to the array.\n\t\t\t\t// Example:\n\t\t\t\t// [1, 2, 3] --> [0, 1, 2, 3]\n\t\t\t\t// oldChildren newChildren\n\t\t\t\t//\n\t\t\t\t// The new element is at index 0, so our skew is 0,\n\t\t\t\t// we need to decrease the skew as we are adding a new element.\n\t\t\t\t// The decrease will cause us to compare the element at position 1\n\t\t\t\t// with value 1 with the element at position 0 with value 0.\n\t\t\t\t//\n\t\t\t\t// A linear concept is applied when the array is shrinking,\n\t\t\t\t// if the length is unchanged we can assume that no skew\n\t\t\t\t// changes are needed.\n\t\t\t\tif (newChildrenLength > oldChildrenLength) {\n\t\t\t\t\tskew--;\n\t\t\t\t} else if (newChildrenLength < oldChildrenLength) {\n\t\t\t\t\tskew++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If we are mounting a DOM VNode, mark it for insertion\n\t\t\tif (typeof childVNode.type != 'function') {\n\t\t\t\tchildVNode._flags |= INSERT_VNODE;\n\t\t\t}\n\t\t} else if (matchingIndex != skewedIndex) {\n\t\t\t// When we move elements around i.e. [0, 1, 2] --> [1, 0, 2]\n\t\t\t// --> we diff 1, we find it at position 1 while our skewed index is 0 and our skew is 0\n\t\t\t// we set the skew to 1 as we found an offset.\n\t\t\t// --> we diff 0, we find it at position 0 while our skewed index is at 2 and our skew is 1\n\t\t\t// this makes us increase the skew again.\n\t\t\t// --> we diff 2, we find it at position 2 while our skewed index is at 4 and our skew is 2\n\t\t\t//\n\t\t\t// this becomes an optimization question where currently we see a 1 element offset as an insertion\n\t\t\t// or deletion i.e. we optimize for [0, 1, 2] --> [9, 0, 1, 2]\n\t\t\t// while a more than 1 offset we see as a swap.\n\t\t\t// We could probably build heuristics for having an optimized course of action here as well, but\n\t\t\t// might go at the cost of some bytes.\n\t\t\t//\n\t\t\t// If we wanted to optimize for i.e. only swaps we'd just do the last two code-branches and have\n\t\t\t// only the first item be a re-scouting and all the others fall in their skewed counter-part.\n\t\t\t// We could also further optimize for swaps\n\t\t\tif (matchingIndex == skewedIndex - 1) {\n\t\t\t\tskew--;\n\t\t\t} else if (matchingIndex == skewedIndex + 1) {\n\t\t\t\tskew++;\n\t\t\t} else {\n\t\t\t\tif (matchingIndex > skewedIndex) {\n\t\t\t\t\tskew--;\n\t\t\t\t} else {\n\t\t\t\t\tskew++;\n\t\t\t\t}\n\n\t\t\t\t// Move this VNode's DOM if the original index (matchingIndex) doesn't\n\t\t\t\t// match the new skew index (i + new skew)\n\t\t\t\t// In the former two branches we know that it matches after skewing\n\t\t\t\tchildVNode._flags |= INSERT_VNODE;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Remove remaining oldChildren if there are any. Loop forwards so that as we\n\t// unmount DOM from the beginning of the oldChildren, we can adjust oldDom to\n\t// point to the next child, which needs to be the first DOM node that won't be\n\t// unmounted.\n\tif (remainingOldChildren) {\n\t\tfor (i = 0; i < oldChildrenLength; i++) {\n\t\t\toldVNode = oldChildren[i];\n\t\t\tif (oldVNode != NULL && (oldVNode._flags & MATCHED) == 0) {\n\t\t\t\tif (oldVNode._dom == oldDom) {\n\t\t\t\t\toldDom = getDomSibling(oldVNode);\n\t\t\t\t}\n\n\t\t\t\tunmount(oldVNode, oldVNode);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn oldDom;\n}\n\n/**\n * @param {VNode} parentVNode\n * @param {PreactElement} oldDom\n * @param {PreactElement} parentDom\n * @param {boolean} shouldPlace\n * @returns {PreactElement}\n */\nfunction insert(parentVNode, oldDom, parentDom, shouldPlace) {\n\t// Note: VNodes in nested suspended trees may be missing _children.\n\n\tif (typeof parentVNode.type == 'function') {\n\t\tlet children = parentVNode._children;\n\t\tfor (let i = 0; children && i < children.length; i++) {\n\t\t\tif (children[i]) {\n\t\t\t\t// If we enter this code path on sCU bailout, where we copy\n\t\t\t\t// oldVNode._children to newVNode._children, we need to update the old\n\t\t\t\t// children's _parent pointer to point to the newVNode (parentVNode\n\t\t\t\t// here).\n\t\t\t\tchildren[i]._parent = parentVNode;\n\t\t\t\toldDom = insert(children[i], oldDom, parentDom, shouldPlace);\n\t\t\t}\n\t\t}\n\n\t\treturn oldDom;\n\t} else if (parentVNode._dom != oldDom) {\n\t\tif (shouldPlace) {\n\t\t\tif (oldDom && parentVNode.type && !oldDom.parentNode) {\n\t\t\t\toldDom = getDomSibling(parentVNode);\n\t\t\t}\n\t\t\tparentDom.insertBefore(parentVNode._dom, oldDom || NULL);\n\t\t}\n\t\toldDom = parentVNode._dom;\n\t}\n\n\tdo {\n\t\toldDom = oldDom && oldDom.nextSibling;\n\t} while (oldDom != NULL && oldDom.nodeType == 8);\n\n\treturn oldDom;\n}\n\n/**\n * Flatten and loop through the children of a virtual node\n * @param {ComponentChildren} children The unflattened children of a virtual\n * node\n * @returns {VNode[]}\n */\nexport function toChildArray(children, out) {\n\tout = out || [];\n\tif (children == NULL || typeof children == 'boolean') {\n\t} else if (isArray(children)) {\n\t\tchildren.some(child => {\n\t\t\ttoChildArray(child, out);\n\t\t});\n\t} else {\n\t\tout.push(children);\n\t}\n\treturn out;\n}\n\n/**\n * @param {VNode} childVNode\n * @param {VNode[]} oldChildren\n * @param {number} skewedIndex\n * @param {number} remainingOldChildren\n * @returns {number}\n */\nfunction findMatchingIndex(\n\tchildVNode,\n\toldChildren,\n\tskewedIndex,\n\tremainingOldChildren\n) {\n\tconst key = childVNode.key;\n\tconst type = childVNode.type;\n\tlet oldVNode = oldChildren[skewedIndex];\n\tconst matched = oldVNode != NULL && (oldVNode._flags & MATCHED) == 0;\n\n\t// We only need to perform a search if there are more children\n\t// (remainingOldChildren) to search. However, if the oldVNode we just looked\n\t// at skewedIndex was not already used in this diff, then there must be at\n\t// least 1 other (so greater than 1) remainingOldChildren to attempt to match\n\t// against. So the following condition checks that ensuring\n\t// remainingOldChildren > 1 if the oldVNode is not already used/matched. Else\n\t// if the oldVNode was null or matched, then there could needs to be at least\n\t// 1 (aka `remainingOldChildren > 0`) children to find and compare against.\n\t//\n\t// If there is an unkeyed functional VNode, that isn't a built-in like our Fragment,\n\t// we should not search as we risk re-using state of an unrelated VNode. (reverted for now)\n\tlet shouldSearch =\n\t\t// (typeof type != 'function' || type === Fragment || key) &&\n\t\tremainingOldChildren > (matched ? 1 : 0);\n\n\tif (\n\t\t(oldVNode === NULL && key == null) ||\n\t\t(matched && key == oldVNode.key && type == oldVNode.type)\n\t) {\n\t\treturn skewedIndex;\n\t} else if (shouldSearch) {\n\t\tlet x = skewedIndex - 1;\n\t\tlet y = skewedIndex + 1;\n\t\twhile (x >= 0 || y < oldChildren.length) {\n\t\t\tconst childIndex = x >= 0 ? x-- : y++;\n\t\t\toldVNode = oldChildren[childIndex];\n\t\t\tif (\n\t\t\t\toldVNode != NULL &&\n\t\t\t\t(oldVNode._flags & MATCHED) == 0 &&\n\t\t\t\tkey == oldVNode.key &&\n\t\t\t\ttype == oldVNode.type\n\t\t\t) {\n\t\t\t\treturn childIndex;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn -1;\n}\n","import {\n\tEMPTY_OBJ,\n\tMATH_NAMESPACE,\n\tMODE_HYDRATE,\n\tMODE_SUSPENDED,\n\tNULL,\n\tRESET_MODE,\n\tSVG_NAMESPACE,\n\tUNDEFINED,\n\tXHTML_NAMESPACE\n} from '../constants';\nimport { BaseComponent, getDomSibling } from '../component';\nimport { Fragment } from '../create-element';\nimport { diffChildren } from './children';\nimport { setProperty } from './props';\nimport { assign, isArray, removeNode, slice } from '../util';\nimport options from '../options';\n\n/**\n * @typedef {import('../internal').ComponentChildren} ComponentChildren\n * @typedef {import('../internal').Component} Component\n * @typedef {import('../internal').PreactElement} PreactElement\n * @typedef {import('../internal').VNode} VNode\n */\n\n/**\n * @template {any} T\n * @typedef {import('../internal').Ref} Ref\n */\n\n/**\n * Diff two virtual nodes and apply proper changes to the DOM\n * @param {PreactElement} parentDom The parent of the DOM element\n * @param {VNode} newVNode The new virtual node\n * @param {VNode} oldVNode The old virtual node\n * @param {object} globalContext The current context object. Modified by\n * getChildContext\n * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML)\n * @param {Array} excessDomChildren\n * @param {Array} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {PreactElement} oldDom The current attached DOM element any new dom\n * elements should be placed around. Likely `null` on first render (except when\n * hydrating). Can be a sibling DOM element when diffing Fragments that have\n * siblings. In most cases, it starts out as `oldChildren[0]._dom`.\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n */\nexport function diff(\n\tparentDom,\n\tnewVNode,\n\toldVNode,\n\tglobalContext,\n\tnamespace,\n\texcessDomChildren,\n\tcommitQueue,\n\toldDom,\n\tisHydrating,\n\trefQueue\n) {\n\t/** @type {any} */\n\tlet tmp,\n\t\tnewType = newVNode.type;\n\n\t// When passing through createElement it assigns the object\n\t// constructor as undefined. This to prevent JSON-injection.\n\tif (newVNode.constructor !== UNDEFINED) return NULL;\n\n\t// If the previous diff bailed out, resume creating/hydrating.\n\tif (oldVNode._flags & MODE_SUSPENDED) {\n\t\tisHydrating = !!(oldVNode._flags & MODE_HYDRATE);\n\t\toldDom = newVNode._dom = oldVNode._dom;\n\t\texcessDomChildren = [oldDom];\n\t}\n\n\tif ((tmp = options._diff)) tmp(newVNode);\n\n\touter: if (typeof newType == 'function') {\n\t\ttry {\n\t\t\tlet c, isNew, oldProps, oldState, snapshot, clearProcessingException;\n\t\t\tlet newProps = newVNode.props;\n\t\t\tconst isClassComponent =\n\t\t\t\t'prototype' in newType && newType.prototype.render;\n\n\t\t\t// Necessary for createContext api. Setting this property will pass\n\t\t\t// the context value as `this.context` just for this component.\n\t\t\ttmp = newType.contextType;\n\t\t\tlet provider = tmp && globalContext[tmp._id];\n\t\t\tlet componentContext = tmp\n\t\t\t\t? provider\n\t\t\t\t\t? provider.props.value\n\t\t\t\t\t: tmp._defaultValue\n\t\t\t\t: globalContext;\n\n\t\t\t// Get component and set it to `c`\n\t\t\tif (oldVNode._component) {\n\t\t\t\tc = newVNode._component = oldVNode._component;\n\t\t\t\tclearProcessingException = c._processingException = c._pendingError;\n\t\t\t} else {\n\t\t\t\t// Instantiate the new component\n\t\t\t\tif (isClassComponent) {\n\t\t\t\t\t// @ts-expect-error The check above verifies that newType is suppose to be constructed\n\t\t\t\t\tnewVNode._component = c = new newType(newProps, componentContext); // eslint-disable-line new-cap\n\t\t\t\t} else {\n\t\t\t\t\t// @ts-expect-error Trust me, Component implements the interface we want\n\t\t\t\t\tnewVNode._component = c = new BaseComponent(\n\t\t\t\t\t\tnewProps,\n\t\t\t\t\t\tcomponentContext\n\t\t\t\t\t);\n\t\t\t\t\tc.constructor = newType;\n\t\t\t\t\tc.render = doRender;\n\t\t\t\t}\n\t\t\t\tif (provider) provider.sub(c);\n\n\t\t\t\tif (!c.state) c.state = {};\n\t\t\t\tc._globalContext = globalContext;\n\t\t\t\tisNew = c._dirty = true;\n\t\t\t\tc._renderCallbacks = [];\n\t\t\t\tc._stateCallbacks = [];\n\t\t\t}\n\n\t\t\t// Invoke getDerivedStateFromProps\n\t\t\tif (isClassComponent && c._nextState == NULL) {\n\t\t\t\tc._nextState = c.state;\n\t\t\t}\n\n\t\t\tif (isClassComponent && newType.getDerivedStateFromProps != NULL) {\n\t\t\t\tif (c._nextState == c.state) {\n\t\t\t\t\tc._nextState = assign({}, c._nextState);\n\t\t\t\t}\n\n\t\t\t\tassign(\n\t\t\t\t\tc._nextState,\n\t\t\t\t\tnewType.getDerivedStateFromProps(newProps, c._nextState)\n\t\t\t\t);\n\t\t\t}\n\n\t\t\toldProps = c.props;\n\t\t\toldState = c.state;\n\t\t\tc._vnode = newVNode;\n\n\t\t\t// Invoke pre-render lifecycle methods\n\t\t\tif (isNew) {\n\t\t\t\tif (\n\t\t\t\t\tisClassComponent &&\n\t\t\t\t\tnewType.getDerivedStateFromProps == NULL &&\n\t\t\t\t\tc.componentWillMount != NULL\n\t\t\t\t) {\n\t\t\t\t\tc.componentWillMount();\n\t\t\t\t}\n\n\t\t\t\tif (isClassComponent && c.componentDidMount != NULL) {\n\t\t\t\t\tc._renderCallbacks.push(c.componentDidMount);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (\n\t\t\t\t\tisClassComponent &&\n\t\t\t\t\tnewType.getDerivedStateFromProps == NULL &&\n\t\t\t\t\tnewProps !== oldProps &&\n\t\t\t\t\tc.componentWillReceiveProps != NULL\n\t\t\t\t) {\n\t\t\t\t\tc.componentWillReceiveProps(newProps, componentContext);\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\tnewVNode._original == oldVNode._original ||\n\t\t\t\t\t(!c._force &&\n\t\t\t\t\t\tc.shouldComponentUpdate != NULL &&\n\t\t\t\t\t\tc.shouldComponentUpdate(\n\t\t\t\t\t\t\tnewProps,\n\t\t\t\t\t\t\tc._nextState,\n\t\t\t\t\t\t\tcomponentContext\n\t\t\t\t\t\t) === false)\n\t\t\t\t) {\n\t\t\t\t\t// More info about this here: https://gist.github.com/JoviDeCroock/bec5f2ce93544d2e6070ef8e0036e4e8\n\t\t\t\t\tif (newVNode._original != oldVNode._original) {\n\t\t\t\t\t\t// When we are dealing with a bail because of sCU we have to update\n\t\t\t\t\t\t// the props, state and dirty-state.\n\t\t\t\t\t\t// when we are dealing with strict-equality we don't as the child could still\n\t\t\t\t\t\t// be dirtied see #3883\n\t\t\t\t\t\tc.props = newProps;\n\t\t\t\t\t\tc.state = c._nextState;\n\t\t\t\t\t\tc._dirty = false;\n\t\t\t\t\t}\n\n\t\t\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t\t\t\tnewVNode._children = oldVNode._children;\n\t\t\t\t\tnewVNode._children.some(vnode => {\n\t\t\t\t\t\tif (vnode) vnode._parent = newVNode;\n\t\t\t\t\t});\n\n\t\t\t\t\tfor (let i = 0; i < c._stateCallbacks.length; i++) {\n\t\t\t\t\t\tc._renderCallbacks.push(c._stateCallbacks[i]);\n\t\t\t\t\t}\n\t\t\t\t\tc._stateCallbacks = [];\n\n\t\t\t\t\tif (c._renderCallbacks.length) {\n\t\t\t\t\t\tcommitQueue.push(c);\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak outer;\n\t\t\t\t}\n\n\t\t\t\tif (c.componentWillUpdate != NULL) {\n\t\t\t\t\tc.componentWillUpdate(newProps, c._nextState, componentContext);\n\t\t\t\t}\n\n\t\t\t\tif (isClassComponent && c.componentDidUpdate != NULL) {\n\t\t\t\t\tc._renderCallbacks.push(() => {\n\t\t\t\t\t\tc.componentDidUpdate(oldProps, oldState, snapshot);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tc.context = componentContext;\n\t\t\tc.props = newProps;\n\t\t\tc._parentDom = parentDom;\n\t\t\tc._force = false;\n\n\t\t\tlet renderHook = options._render,\n\t\t\t\tcount = 0;\n\t\t\tif (isClassComponent) {\n\t\t\t\tc.state = c._nextState;\n\t\t\t\tc._dirty = false;\n\n\t\t\t\tif (renderHook) renderHook(newVNode);\n\n\t\t\t\ttmp = c.render(c.props, c.state, c.context);\n\n\t\t\t\tfor (let i = 0; i < c._stateCallbacks.length; i++) {\n\t\t\t\t\tc._renderCallbacks.push(c._stateCallbacks[i]);\n\t\t\t\t}\n\t\t\t\tc._stateCallbacks = [];\n\t\t\t} else {\n\t\t\t\tdo {\n\t\t\t\t\tc._dirty = false;\n\t\t\t\t\tif (renderHook) renderHook(newVNode);\n\n\t\t\t\t\ttmp = c.render(c.props, c.state, c.context);\n\n\t\t\t\t\t// Handle setState called in render, see #2553\n\t\t\t\t\tc.state = c._nextState;\n\t\t\t\t} while (c._dirty && ++count < 25);\n\t\t\t}\n\n\t\t\t// Handle setState called in render, see #2553\n\t\t\tc.state = c._nextState;\n\n\t\t\tif (c.getChildContext != NULL) {\n\t\t\t\tglobalContext = assign(assign({}, globalContext), c.getChildContext());\n\t\t\t}\n\n\t\t\tif (isClassComponent && !isNew && c.getSnapshotBeforeUpdate != NULL) {\n\t\t\t\tsnapshot = c.getSnapshotBeforeUpdate(oldProps, oldState);\n\t\t\t}\n\n\t\t\tlet isTopLevelFragment =\n\t\t\t\ttmp != NULL && tmp.type === Fragment && tmp.key == NULL;\n\t\t\tlet renderResult = tmp;\n\n\t\t\tif (isTopLevelFragment) {\n\t\t\t\trenderResult = cloneNode(tmp.props.children);\n\t\t\t}\n\n\t\t\toldDom = diffChildren(\n\t\t\t\tparentDom,\n\t\t\t\tisArray(renderResult) ? renderResult : [renderResult],\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tnamespace,\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\toldDom,\n\t\t\t\tisHydrating,\n\t\t\t\trefQueue\n\t\t\t);\n\n\t\t\tc.base = newVNode._dom;\n\n\t\t\t// We successfully rendered this VNode, unset any stored hydration/bailout state:\n\t\t\tnewVNode._flags &= RESET_MODE;\n\n\t\t\tif (c._renderCallbacks.length) {\n\t\t\t\tcommitQueue.push(c);\n\t\t\t}\n\n\t\t\tif (clearProcessingException) {\n\t\t\t\tc._pendingError = c._processingException = NULL;\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tnewVNode._original = NULL;\n\t\t\t// if hydrating or creating initial tree, bailout preserves DOM:\n\t\t\tif (isHydrating || excessDomChildren != NULL) {\n\t\t\t\tif (e.then) {\n\t\t\t\t\tnewVNode._flags |= isHydrating\n\t\t\t\t\t\t? MODE_HYDRATE | MODE_SUSPENDED\n\t\t\t\t\t\t: MODE_SUSPENDED;\n\n\t\t\t\t\twhile (oldDom && oldDom.nodeType == 8 && oldDom.nextSibling) {\n\t\t\t\t\t\toldDom = oldDom.nextSibling;\n\t\t\t\t\t}\n\n\t\t\t\t\texcessDomChildren[excessDomChildren.indexOf(oldDom)] = NULL;\n\t\t\t\t\tnewVNode._dom = oldDom;\n\t\t\t\t} else {\n\t\t\t\t\tfor (let i = excessDomChildren.length; i--; ) {\n\t\t\t\t\t\tremoveNode(excessDomChildren[i]);\n\t\t\t\t\t}\n\t\t\t\t\tmarkAsForce(newVNode);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t\t\tnewVNode._children = oldVNode._children;\n\t\t\t\tif (!e.then) markAsForce(newVNode);\n\t\t\t}\n\t\t\toptions._catchError(e, newVNode, oldVNode);\n\t\t}\n\t} else if (\n\t\texcessDomChildren == NULL &&\n\t\tnewVNode._original == oldVNode._original\n\t) {\n\t\tnewVNode._children = oldVNode._children;\n\t\tnewVNode._dom = oldVNode._dom;\n\t} else {\n\t\toldDom = newVNode._dom = diffElementNodes(\n\t\t\toldVNode._dom,\n\t\t\tnewVNode,\n\t\t\toldVNode,\n\t\t\tglobalContext,\n\t\t\tnamespace,\n\t\t\texcessDomChildren,\n\t\t\tcommitQueue,\n\t\t\tisHydrating,\n\t\t\trefQueue\n\t\t);\n\t}\n\n\tif ((tmp = options.diffed)) tmp(newVNode);\n\n\treturn newVNode._flags & MODE_SUSPENDED ? undefined : oldDom;\n}\n\nfunction markAsForce(vnode) {\n\tif (vnode && vnode._component) vnode._component._force = true;\n\tif (vnode && vnode._children) vnode._children.forEach(markAsForce);\n}\n\n/**\n * @param {Array} commitQueue List of components\n * which have callbacks to invoke in commitRoot\n * @param {VNode} root\n */\nexport function commitRoot(commitQueue, root, refQueue) {\n\tfor (let i = 0; i < refQueue.length; i++) {\n\t\tapplyRef(refQueue[i], refQueue[++i], refQueue[++i]);\n\t}\n\n\tif (options._commit) options._commit(root, commitQueue);\n\n\tcommitQueue.some(c => {\n\t\ttry {\n\t\t\t// @ts-expect-error Reuse the commitQueue variable here so the type changes\n\t\t\tcommitQueue = c._renderCallbacks;\n\t\t\tc._renderCallbacks = [];\n\t\t\tcommitQueue.some(cb => {\n\t\t\t\t// @ts-expect-error See above comment on commitQueue\n\t\t\t\tcb.call(c);\n\t\t\t});\n\t\t} catch (e) {\n\t\t\toptions._catchError(e, c._vnode);\n\t\t}\n\t});\n}\n\nfunction cloneNode(node) {\n\tif (\n\t\ttypeof node != 'object' ||\n\t\tnode == NULL ||\n\t\t(node._depth && node._depth > 0)\n\t) {\n\t\treturn node;\n\t}\n\n\tif (isArray(node)) {\n\t\treturn node.map(cloneNode);\n\t}\n\n\treturn assign({}, node);\n}\n\n/**\n * Diff two virtual nodes representing DOM element\n * @param {PreactElement} dom The DOM element representing the virtual nodes\n * being diffed\n * @param {VNode} newVNode The new virtual node\n * @param {VNode} oldVNode The old virtual node\n * @param {object} globalContext The current context object\n * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML)\n * @param {Array} excessDomChildren\n * @param {Array} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n * @returns {PreactElement}\n */\nfunction diffElementNodes(\n\tdom,\n\tnewVNode,\n\toldVNode,\n\tglobalContext,\n\tnamespace,\n\texcessDomChildren,\n\tcommitQueue,\n\tisHydrating,\n\trefQueue\n) {\n\tlet oldProps = oldVNode.props || EMPTY_OBJ;\n\tlet newProps = newVNode.props;\n\tlet nodeType = /** @type {string} */ (newVNode.type);\n\t/** @type {any} */\n\tlet i;\n\t/** @type {{ __html?: string }} */\n\tlet newHtml;\n\t/** @type {{ __html?: string }} */\n\tlet oldHtml;\n\t/** @type {ComponentChildren} */\n\tlet newChildren;\n\tlet value;\n\tlet inputValue;\n\tlet checked;\n\n\t// Tracks entering and exiting namespaces when descending through the tree.\n\tif (nodeType == 'svg') namespace = SVG_NAMESPACE;\n\telse if (nodeType == 'math') namespace = MATH_NAMESPACE;\n\telse if (!namespace) namespace = XHTML_NAMESPACE;\n\n\tif (excessDomChildren != NULL) {\n\t\tfor (i = 0; i < excessDomChildren.length; i++) {\n\t\t\tvalue = excessDomChildren[i];\n\n\t\t\t// if newVNode matches an element in excessDomChildren or the `dom`\n\t\t\t// argument matches an element in excessDomChildren, remove it from\n\t\t\t// excessDomChildren so it isn't later removed in diffChildren\n\t\t\tif (\n\t\t\t\tvalue &&\n\t\t\t\t'setAttribute' in value == !!nodeType &&\n\t\t\t\t(nodeType ? value.localName == nodeType : value.nodeType == 3)\n\t\t\t) {\n\t\t\t\tdom = value;\n\t\t\t\texcessDomChildren[i] = NULL;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (dom == NULL) {\n\t\tif (nodeType == NULL) {\n\t\t\treturn document.createTextNode(newProps);\n\t\t}\n\n\t\tdom = document.createElementNS(\n\t\t\tnamespace,\n\t\t\tnodeType,\n\t\t\tnewProps.is && newProps\n\t\t);\n\n\t\t// we are creating a new node, so we can assume this is a new subtree (in\n\t\t// case we are hydrating), this deopts the hydrate\n\t\tif (isHydrating) {\n\t\t\tif (options._hydrationMismatch)\n\t\t\t\toptions._hydrationMismatch(newVNode, excessDomChildren);\n\t\t\tisHydrating = false;\n\t\t}\n\t\t// we created a new parent, so none of the previously attached children can be reused:\n\t\texcessDomChildren = NULL;\n\t}\n\n\tif (nodeType == NULL) {\n\t\t// During hydration, we still have to split merged text from SSR'd HTML.\n\t\tif (oldProps !== newProps && (!isHydrating || dom.data != newProps)) {\n\t\t\tdom.data = newProps;\n\t\t}\n\t} else {\n\t\t// If excessDomChildren was not null, repopulate it with the current element's children:\n\t\texcessDomChildren = excessDomChildren && slice.call(dom.childNodes);\n\n\t\t// If we are in a situation where we are not hydrating but are using\n\t\t// existing DOM (e.g. replaceNode) we should read the existing DOM\n\t\t// attributes to diff them\n\t\tif (!isHydrating && excessDomChildren != NULL) {\n\t\t\toldProps = {};\n\t\t\tfor (i = 0; i < dom.attributes.length; i++) {\n\t\t\t\tvalue = dom.attributes[i];\n\t\t\t\toldProps[value.name] = value.value;\n\t\t\t}\n\t\t}\n\n\t\tfor (i in oldProps) {\n\t\t\tvalue = oldProps[i];\n\t\t\tif (i == 'children') {\n\t\t\t} else if (i == 'dangerouslySetInnerHTML') {\n\t\t\t\toldHtml = value;\n\t\t\t} else if (!(i in newProps)) {\n\t\t\t\tif (\n\t\t\t\t\t(i == 'value' && 'defaultValue' in newProps) ||\n\t\t\t\t\t(i == 'checked' && 'defaultChecked' in newProps)\n\t\t\t\t) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tsetProperty(dom, i, NULL, value, namespace);\n\t\t\t}\n\t\t}\n\n\t\t// During hydration, props are not diffed at all (including dangerouslySetInnerHTML)\n\t\t// @TODO we should warn in debug mode when props don't match here.\n\t\tfor (i in newProps) {\n\t\t\tvalue = newProps[i];\n\t\t\tif (i == 'children') {\n\t\t\t\tnewChildren = value;\n\t\t\t} else if (i == 'dangerouslySetInnerHTML') {\n\t\t\t\tnewHtml = value;\n\t\t\t} else if (i == 'value') {\n\t\t\t\tinputValue = value;\n\t\t\t} else if (i == 'checked') {\n\t\t\t\tchecked = value;\n\t\t\t} else if (\n\t\t\t\t(!isHydrating || typeof value == 'function') &&\n\t\t\t\toldProps[i] !== value\n\t\t\t) {\n\t\t\t\tsetProperty(dom, i, value, oldProps[i], namespace);\n\t\t\t}\n\t\t}\n\n\t\t// If the new vnode didn't have dangerouslySetInnerHTML, diff its children\n\t\tif (newHtml) {\n\t\t\t// Avoid re-applying the same '__html' if it did not changed between re-render\n\t\t\tif (\n\t\t\t\t!isHydrating &&\n\t\t\t\t(!oldHtml ||\n\t\t\t\t\t(newHtml.__html != oldHtml.__html && newHtml.__html != dom.innerHTML))\n\t\t\t) {\n\t\t\t\tdom.innerHTML = newHtml.__html;\n\t\t\t}\n\n\t\t\tnewVNode._children = [];\n\t\t} else {\n\t\t\tif (oldHtml) dom.innerHTML = '';\n\n\t\t\tdiffChildren(\n\t\t\t\t// @ts-expect-error\n\t\t\t\tnewVNode.type == 'template' ? dom.content : dom,\n\t\t\t\tisArray(newChildren) ? newChildren : [newChildren],\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tnodeType == 'foreignObject' ? XHTML_NAMESPACE : namespace,\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\texcessDomChildren\n\t\t\t\t\t? excessDomChildren[0]\n\t\t\t\t\t: oldVNode._children && getDomSibling(oldVNode, 0),\n\t\t\t\tisHydrating,\n\t\t\t\trefQueue\n\t\t\t);\n\n\t\t\t// Remove children that are not part of any vnode.\n\t\t\tif (excessDomChildren != NULL) {\n\t\t\t\tfor (i = excessDomChildren.length; i--; ) {\n\t\t\t\t\tremoveNode(excessDomChildren[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// As above, don't diff props during hydration\n\t\tif (!isHydrating) {\n\t\t\ti = 'value';\n\t\t\tif (nodeType == 'progress' && inputValue == NULL) {\n\t\t\t\tdom.removeAttribute('value');\n\t\t\t} else if (\n\t\t\t\tinputValue != UNDEFINED &&\n\t\t\t\t// #2756 For the -element the initial value is 0,\n\t\t\t\t// despite the attribute not being present. When the attribute\n\t\t\t\t// is missing the progress bar is treated as indeterminate.\n\t\t\t\t// To fix that we'll always update it when it is 0 for progress elements\n\t\t\t\t(inputValue !== dom[i] ||\n\t\t\t\t\t(nodeType == 'progress' && !inputValue) ||\n\t\t\t\t\t// This is only for IE 11 to fix value not being updated.\n\t\t\t\t\t// To avoid a stale select value we need to set the option.value\n\t\t\t\t\t// again, which triggers IE11 to re-evaluate the select value\n\t\t\t\t\t(nodeType == 'option' && inputValue != oldProps[i]))\n\t\t\t) {\n\t\t\t\tsetProperty(dom, i, inputValue, oldProps[i], namespace);\n\t\t\t}\n\n\t\t\ti = 'checked';\n\t\t\tif (checked != UNDEFINED && checked != dom[i]) {\n\t\t\t\tsetProperty(dom, i, checked, oldProps[i], namespace);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dom;\n}\n\n/**\n * Invoke or update a ref, depending on whether it is a function or object ref.\n * @param {Ref & { _unmount?: unknown }} ref\n * @param {any} value\n * @param {VNode} vnode\n */\nexport function applyRef(ref, value, vnode) {\n\ttry {\n\t\tif (typeof ref == 'function') {\n\t\t\tlet hasRefUnmount = typeof ref._unmount == 'function';\n\t\t\tif (hasRefUnmount) {\n\t\t\t\t// @ts-ignore TS doesn't like moving narrowing checks into variables\n\t\t\t\tref._unmount();\n\t\t\t}\n\n\t\t\tif (!hasRefUnmount || value != NULL) {\n\t\t\t\t// Store the cleanup function on the function\n\t\t\t\t// instance object itself to avoid shape\n\t\t\t\t// transitioning vnode\n\t\t\t\tref._unmount = ref(value);\n\t\t\t}\n\t\t} else ref.current = value;\n\t} catch (e) {\n\t\toptions._catchError(e, vnode);\n\t}\n}\n\n/**\n * Unmount a virtual node from the tree and apply DOM changes\n * @param {VNode} vnode The virtual node to unmount\n * @param {VNode} parentVNode The parent of the VNode that initiated the unmount\n * @param {boolean} [skipRemove] Flag that indicates that a parent node of the\n * current element is already detached from the DOM.\n */\nexport function unmount(vnode, parentVNode, skipRemove) {\n\tlet r;\n\tif (options.unmount) options.unmount(vnode);\n\n\tif ((r = vnode.ref)) {\n\t\tif (!r.current || r.current == vnode._dom) {\n\t\t\tapplyRef(r, NULL, parentVNode);\n\t\t}\n\t}\n\n\tif ((r = vnode._component) != NULL) {\n\t\tif (r.componentWillUnmount) {\n\t\t\ttry {\n\t\t\t\tr.componentWillUnmount();\n\t\t\t} catch (e) {\n\t\t\t\toptions._catchError(e, parentVNode);\n\t\t\t}\n\t\t}\n\n\t\tr.base = r._parentDom = NULL;\n\t}\n\n\tif ((r = vnode._children)) {\n\t\tfor (let i = 0; i < r.length; i++) {\n\t\t\tif (r[i]) {\n\t\t\t\tunmount(\n\t\t\t\t\tr[i],\n\t\t\t\t\tparentVNode,\n\t\t\t\t\tskipRemove || typeof vnode.type != 'function'\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!skipRemove) {\n\t\tremoveNode(vnode._dom);\n\t}\n\n\tvnode._component = vnode._parent = vnode._dom = UNDEFINED;\n}\n\n/** The `.render()` method for a PFC backing instance. */\nfunction doRender(props, state, context) {\n\treturn this.constructor(props, context);\n}\n","import { EMPTY_OBJ, NULL } from './constants';\nimport { commitRoot, diff } from './diff/index';\nimport { createElement, Fragment } from './create-element';\nimport options from './options';\nimport { slice } from './util';\n\n/**\n * Render a Preact virtual node into a DOM element\n * @param {import('./internal').ComponentChild} vnode The virtual node to render\n * @param {import('./internal').PreactElement} parentDom The DOM element to render into\n * @param {import('./internal').PreactElement | object} [replaceNode] Optional: Attempt to re-use an\n * existing DOM tree rooted at `replaceNode`\n */\nexport function render(vnode, parentDom, replaceNode) {\n\t// https://github.com/preactjs/preact/issues/3794\n\tif (parentDom == document) {\n\t\tparentDom = document.documentElement;\n\t}\n\n\tif (options._root) options._root(vnode, parentDom);\n\n\t// We abuse the `replaceNode` parameter in `hydrate()` to signal if we are in\n\t// hydration mode or not by passing the `hydrate` function instead of a DOM\n\t// element..\n\tlet isHydrating = typeof replaceNode == 'function';\n\n\t// To be able to support calling `render()` multiple times on the same\n\t// DOM node, we need to obtain a reference to the previous tree. We do\n\t// this by assigning a new `_children` property to DOM nodes which points\n\t// to the last rendered tree. By default this property is not present, which\n\t// means that we are mounting a new tree for the first time.\n\tlet oldVNode = isHydrating\n\t\t? NULL\n\t\t: (replaceNode && replaceNode._children) || parentDom._children;\n\n\tvnode = ((!isHydrating && replaceNode) || parentDom)._children =\n\t\tcreateElement(Fragment, NULL, [vnode]);\n\n\t// List of effects that need to be called after diffing.\n\tlet commitQueue = [],\n\t\trefQueue = [];\n\tdiff(\n\t\tparentDom,\n\t\t// Determine the new vnode tree and store it on the DOM element on\n\t\t// our custom `_children` property.\n\t\tvnode,\n\t\toldVNode || EMPTY_OBJ,\n\t\tEMPTY_OBJ,\n\t\tparentDom.namespaceURI,\n\t\t!isHydrating && replaceNode\n\t\t\t? [replaceNode]\n\t\t\t: oldVNode\n\t\t\t\t? NULL\n\t\t\t\t: parentDom.firstChild\n\t\t\t\t\t? slice.call(parentDom.childNodes)\n\t\t\t\t\t: NULL,\n\t\tcommitQueue,\n\t\t!isHydrating && replaceNode\n\t\t\t? replaceNode\n\t\t\t: oldVNode\n\t\t\t\t? oldVNode._dom\n\t\t\t\t: parentDom.firstChild,\n\t\tisHydrating,\n\t\trefQueue\n\t);\n\n\t// Flush all queued effects\n\tcommitRoot(commitQueue, vnode, refQueue);\n}\n\n/**\n * Update an existing DOM element with data from a Preact virtual node\n * @param {import('./internal').ComponentChild} vnode The virtual node to render\n * @param {import('./internal').PreactElement} parentDom The DOM element to update\n */\nexport function hydrate(vnode, parentDom) {\n\trender(vnode, parentDom, hydrate);\n}\n","import { NULL } from '../constants';\n\n/**\n * Find the closest error boundary to a thrown error and call it\n * @param {object} error The thrown value\n * @param {import('../internal').VNode} vnode The vnode that threw the error that was caught (except\n * for unmounting when this parameter is the highest parent that was being\n * unmounted)\n * @param {import('../internal').VNode} [oldVNode]\n * @param {import('../internal').ErrorInfo} [errorInfo]\n */\nexport function _catchError(error, vnode, oldVNode, errorInfo) {\n\t/** @type {import('../internal').Component} */\n\tlet component,\n\t\t/** @type {import('../internal').ComponentType} */\n\t\tctor,\n\t\t/** @type {boolean} */\n\t\thandled;\n\n\tfor (; (vnode = vnode._parent); ) {\n\t\tif ((component = vnode._component) && !component._processingException) {\n\t\t\ttry {\n\t\t\t\tctor = component.constructor;\n\n\t\t\t\tif (ctor && ctor.getDerivedStateFromError != NULL) {\n\t\t\t\t\tcomponent.setState(ctor.getDerivedStateFromError(error));\n\t\t\t\t\thandled = component._dirty;\n\t\t\t\t}\n\n\t\t\t\tif (component.componentDidCatch != NULL) {\n\t\t\t\t\tcomponent.componentDidCatch(error, errorInfo || {});\n\t\t\t\t\thandled = component._dirty;\n\t\t\t\t}\n\n\t\t\t\t// This is an error boundary. Mark it as having bailed out, and whether it was mid-hydration.\n\t\t\t\tif (handled) {\n\t\t\t\t\treturn (component._pendingError = component);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\terror = e;\n\t\t\t}\n\t\t}\n\t}\n\n\tthrow error;\n}\n","import { assign, slice } from './util';\nimport { createVNode } from './create-element';\nimport { NULL, UNDEFINED } from './constants';\n\n/**\n * Clones the given VNode, optionally adding attributes/props and replacing its\n * children.\n * @param {import('./internal').VNode} vnode The virtual DOM element to clone\n * @param {object} props Attributes/props to add when cloning\n * @param {Array} rest Any additional arguments will be used\n * as replacement children.\n * @returns {import('./internal').VNode}\n */\nexport function cloneElement(vnode, props, children) {\n\tlet normalizedProps = assign({}, vnode.props),\n\t\tkey,\n\t\tref,\n\t\ti;\n\n\tlet defaultProps;\n\n\tif (vnode.type && vnode.type.defaultProps) {\n\t\tdefaultProps = vnode.type.defaultProps;\n\t}\n\n\tfor (i in props) {\n\t\tif (i == 'key') key = props[i];\n\t\telse if (i == 'ref') ref = props[i];\n\t\telse if (props[i] === UNDEFINED && defaultProps != UNDEFINED) {\n\t\t\tnormalizedProps[i] = defaultProps[i];\n\t\t} else {\n\t\t\tnormalizedProps[i] = props[i];\n\t\t}\n\t}\n\n\tif (arguments.length > 2) {\n\t\tnormalizedProps.children =\n\t\t\targuments.length > 3 ? slice.call(arguments, 2) : children;\n\t}\n\n\treturn createVNode(\n\t\tvnode.type,\n\t\tnormalizedProps,\n\t\tkey || vnode.key,\n\t\tref || vnode.ref,\n\t\tNULL\n\t);\n}\n","import * as preact from './index.js';\nif (typeof module < 'u') module.exports = preact;\nelse self.preact = preact;\n"],"names":["slice","options","vnodeId","isValidElement","rerenderQueue","prevDebounce","defer","depthSort","CAPTURE_REGEX","eventClock","eventProxy","eventProxyCapture","i","SVG_NAMESPACE","XHTML_NAMESPACE","NULL","UNDEFINED","undefined","EMPTY_OBJ","EMPTY_ARR","IS_NON_DIMENSIONAL","isArray","Array","assign","obj","props","removeNode","node","parentNode","removeChild","createElement","type","children","key","ref","normalizedProps","arguments","length","call","defaultProps","createVNode","original","vnode","__k","__","__b","__e","__c","constructor","__v","__i","__u","Fragment","BaseComponent","context","this","getDomSibling","childIndex","sibling","updateParentDomPointers","child","base","enqueueRender","c","__d","push","process","__r","debounceRendering","component","newVNode","oldVNode","oldDom","commitQueue","refQueue","l","sort","shift","__P","diff","__n","namespaceURI","commitRoot","diffChildren","parentDom","renderResult","newParentVNode","oldParentVNode","globalContext","namespace","excessDomChildren","isHydrating","childVNode","newDom","firstChildDom","result","shouldPlace","oldChildren","newChildrenLength","constructNewChildrenArray","applyRef","insert","nextSibling","skewedIndex","matchingIndex","oldChildrenLength","remainingOldChildren","skew","String","findMatchingIndex","unmount","parentVNode","insertBefore","nodeType","x","y","matched","setStyle","style","value","setProperty","test","dom","name","oldValue","useCapture","lowerCaseName","o","cssText","replace","toLowerCase","_attached","addEventListener","removeEventListener","e","removeAttribute","setAttribute","createEventProxy","eventHandler","_dispatched","event","tmp","isNew","oldProps","oldState","snapshot","clearProcessingException","newProps","isClassComponent","provider","componentContext","renderHook","count","newType","outer","prototype","render","contextType","__E","doRender","sub","state","__h","_sb","__s","getDerivedStateFromProps","componentWillMount","componentDidMount","componentWillReceiveProps","shouldComponentUpdate","some","componentWillUpdate","componentDidUpdate","getChildContext","getSnapshotBeforeUpdate","cloneNode","then","MODE_HYDRATE","indexOf","markAsForce","diffElementNodes","diffed","forEach","root","cb","map","newHtml","oldHtml","newChildren","inputValue","checked","localName","document","createTextNode","createElementNS","is","__m","data","childNodes","attributes","__html","innerHTML","content","hasRefUnmount","current","skipRemove","r","componentWillUnmount","replaceNode","documentElement","firstChild","error","errorInfo","ctor","handled","getDerivedStateFromError","setState","componentDidCatch","update","callback","s","forceUpdate","Promise","bind","resolve","setTimeout","a","b","hydrate","defaultValue","Context","subs","ctx","Set","_props","add","old","delete","Provider","__l","Consumer","contextValue","toChildArray","out","module","exports","preact","self"],"mappings":"iFA2BaA,EChBPC,ECPFC,EA2FSC,ECoFTC,EAWAC,EAEEC,EA0BAC,EC3MAC,EAaFC,EA+IEC,EACAC,ECzKKC,ICSEC,EAAgB,6BAChBC,EAAkB,+BAGlBC,EAAO,KACPC,OAAYC,EACZC,EAAgC,CAAG,EACnCC,EAAY,GACZC,EACZ,oENnBYC,EAAUC,MAAMD,QAStB,SAASE,EAAOC,EAAKC,GAE3B,IAAK,IAAIb,KAAKa,EAAOD,EAAIZ,GAAKa,EAAMb,GACpC,OAA6BY,CAC9B,CAQgB,SAAAE,EAAWC,GACtBA,GAAQA,EAAKC,YAAYD,EAAKC,WAAWC,YAAYF,EAC1D,CEVgB,SAAAG,EAAcC,EAAMN,EAAOO,GAC1C,IACCC,EACAC,EACAtB,EAHGuB,EAAkB,CAAA,EAItB,IAAKvB,KAAKa,EACA,OAALb,EAAYqB,EAAMR,EAAMb,GACd,OAALA,EAAYsB,EAAMT,EAAMb,GAC5BuB,EAAgBvB,GAAKa,EAAMb,GAUjC,GAPIwB,UAAUC,OAAS,IACtBF,EAAgBH,SACfI,UAAUC,OAAS,EAAIrC,EAAMsC,KAAKF,UAAW,GAAKJ,GAKjC,mBAARD,GAAsBA,EAAKQ,cAAgBxB,EACrD,IAAKH,KAAKmB,EAAKQ,aACVJ,EAAgBvB,KAAOI,IAC1BmB,EAAgBvB,GAAKmB,EAAKQ,aAAa3B,IAK1C,OAAO4B,EAAYT,EAAMI,EAAiBF,EAAKC,EAAKnB,EACrD,CAcgB,SAAAyB,EAAYT,EAAMN,EAAOQ,EAAKC,EAAKO,GAIlD,IAAMC,EAAQ,CACbX,KAAAA,EACAN,MAAAA,EACAQ,IAAAA,EACAC,IAAAA,EACAS,IAAW5B,EACX6B,GAAS7B,EACT8B,IAAQ,EACRC,IAAM/B,EACNgC,IAAYhC,EACZiC,YAAahC,EACbiC,IAAWR,GAAY1B,IAASb,EAAUuC,EAC1CS,KAAS,EACTC,IAAQ,GAMT,OAFIV,GAAY1B,GAAQd,EAAQyC,OAAS3B,GAAMd,EAAQyC,MAAMA,GAEtDA,CACR,CAMgB,SAAAU,EAAS3B,GACxB,OAAOA,EAAMO,QACd,CC3EO,SAASqB,EAAc5B,EAAO6B,GACpCC,KAAK9B,MAAQA,EACb8B,KAAKD,QAAUA,CAChB,UA0EgBE,EAAcd,EAAOe,GACpC,GAAIA,GAAc1C,EAEjB,OAAO2B,EAAKE,GACTY,EAAcd,EAAKE,GAAUF,EAAKQ,IAAU,GAC5CnC,EAIJ,IADA,IAAI2C,EACGD,EAAaf,EAAKC,IAAWN,OAAQoB,IAG3C,IAFAC,EAAUhB,EAAKC,IAAWc,KAEX1C,GAAQ2C,EAAOZ,KAAS/B,EAItC,OAAO2C,EAAOZ,IAShB,MAA4B,mBAAdJ,EAAMX,KAAqByB,EAAcd,GAAS3B,CACjE,CA4CA,SAAS4C,EAAwBjB,GAAjC,IAGW9B,EACJgD,EAHN,IAAKlB,EAAQA,EAAKE,KAAa7B,GAAQ2B,EAAKK,KAAehC,EAAM,CAEhE,IADA2B,EAAKI,IAAQJ,EAAKK,IAAYc,KAAO9C,EAC5BH,EAAI,EAAGA,EAAI8B,EAAKC,IAAWN,OAAQzB,IAE3C,IADIgD,EAAQlB,EAAKC,IAAW/B,KACfG,GAAQ6C,EAAKd,KAAS/B,EAAM,CACxC2B,EAAKI,IAAQJ,EAAKK,IAAYc,KAAOD,EAAKd,IAC1C,KACD,CAGD,OAAOa,EAAwBjB,EAChC,CACD,CA4BO,SAASoB,EAAcC,KAE1BA,EAACC,MACDD,EAACC,KAAU,IACZ5D,EAAc6D,KAAKF,KAClBG,EAAOC,OACT9D,GAAgBJ,EAAQmE,sBAExB/D,EAAeJ,EAAQmE,oBACN9D,GAAO4D,EAE1B,CASA,SAASA,IAMR,IALA,IAAIH,EApGoBM,EAOjBC,EANHC,EACHC,EACAC,EACAC,EAiGAC,EAAI,EAIEvE,EAAciC,QAOhBjC,EAAciC,OAASsC,GAC1BvE,EAAcwE,KAAKrE,GAGpBwD,EAAI3D,EAAcyE,QAClBF,EAAIvE,EAAciC,OAEd0B,EAACC,MAhHCM,SANHC,SACHC,GADGD,GADoBF,EAwHNN,GAvHMd,KACNH,IACjB2B,EAAc,GACdC,EAAW,GAERL,EAASS,OACNR,EAAW/C,EAAO,CAAE,EAAEgD,IACpBtB,IAAasB,EAAQtB,IAAa,EACtChD,EAAQyC,OAAOzC,EAAQyC,MAAM4B,GAEjCS,EACCV,EAASS,IACTR,EACAC,EACAF,EAASW,IACTX,EAASS,IAAYG,aGzII,GH0IzBV,EAAQpB,IAAyB,CAACqB,GAAUzD,EAC5C0D,EACAD,GAAUzD,EAAOyC,EAAce,GAAYC,KG5IlB,GH6ItBD,EAAQpB,KACXuB,GAGDJ,EAAQrB,IAAasB,EAAQtB,IAC7BqB,EAAQ1B,GAAAD,IAAmB2B,EAAQpB,KAAWoB,EAC9CY,EAAWT,EAAaH,EAAUI,GAClCH,EAAQzB,IAAQyB,EAAQ3B,GAAW,KAE/B0B,EAAQxB,KAAS0B,GACpBb,EAAwBW,KA6F1BJ,EAAOC,IAAkB,CAC1B,CI5MgB,SAAAgB,EACfC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAjB,EACAD,EACAmB,EACAjB,GAXe,IAaX9D,EAEH2D,EAEAqB,EAEAC,EAEAC,EAiCIC,EA8BAC,EA1DDC,EAAeV,GAAkBA,EAAc5C,KAAexB,EAE9D+E,EAAoBb,EAAahD,OAUrC,IARAmC,EAAS2B,EACRb,EACAD,EACAY,EACAzB,EACA0B,GAGItF,EAAI,EAAGA,EAAIsF,EAAmBtF,KAClCgF,EAAaN,EAAc3C,IAAW/B,KACpBG,IAKjBwD,GADyB,GAAtBqB,EAAU1C,IACFhC,EAEA+E,EAAYL,EAAU1C,MAAYhC,EAI9C0E,EAAU1C,IAAUtC,EAGhBmF,EAAShB,EACZK,EACAQ,EACArB,EACAiB,EACAC,EACAC,EACAjB,EACAD,EACAmB,EACAjB,GAIDmB,EAASD,EAAU9C,IACf8C,EAAW1D,KAAOqC,EAASrC,KAAO0D,EAAW1D,MAC5CqC,EAASrC,KACZkE,EAAS7B,EAASrC,IAAKnB,EAAM6E,GAE9BlB,EAAST,KACR2B,EAAW1D,IACX0D,EAAU7C,KAAe8C,EACzBD,IAIEE,GAAiB/E,GAAQ8E,GAAU9E,IACtC+E,EAAgBD,IAGbG,KDzHsB,ECyHLJ,EAAUzC,OACZoB,EAAQ5B,MAAeiD,EAAUjD,IACnD6B,EAAS6B,EAAOT,EAAYpB,EAAQY,EAAWY,GACX,mBAAnBJ,EAAW7D,MAAsBgE,IAAW/E,EAC7DwD,EAASuB,EACCF,IACVrB,EAASqB,EAAOS,aAIjBV,EAAUzC,MAAW,GAKtB,OAFAmC,EAAcxC,IAAQgD,EAEftB,CACR,CAOA,SAAS2B,EACRb,EACAD,EACAY,EACAzB,EACA0B,GALD,IAQKtF,EAEAgF,EAEArB,EA8DGgC,EAOAC,EAnEHC,EAAoBR,EAAY5D,OACnCqE,EAAuBD,EAEpBE,EAAO,EAGX,IADArB,EAAc3C,IAAa,IAAIrB,MAAM4E,GAChCtF,EAAI,EAAGA,EAAIsF,EAAmBtF,KAGlCgF,EAAaP,EAAazE,KAGXG,GACO,kBAAd6E,GACc,mBAAdA,GASc,iBAAdA,GACc,iBAAdA,GAEc,iBAAdA,GACPA,EAAW5C,aAAe4D,OAE1BhB,EAAaN,EAAc3C,IAAW/B,GAAK4B,EAC1CzB,EACA6E,EACA7E,EACAA,EACAA,GAESM,EAAQuE,GAClBA,EAAaN,EAAc3C,IAAW/B,GAAK4B,EAC1CY,EACA,CAAEpB,SAAU4D,GACZ7E,EACAA,EACAA,GAES6E,EAAW5C,cAAgBhC,GAAa4E,EAAU/C,IAAU,EAKtE+C,EAAaN,EAAc3C,IAAW/B,GAAK4B,EAC1CoD,EAAW7D,KACX6D,EAAWnE,MACXmE,EAAW3D,IACX2D,EAAW1D,IAAM0D,EAAW1D,IAAMnB,EAClC6E,EAAU3C,KAGXqC,EAAc3C,IAAW/B,GAAKgF,EAGzBW,EAAc3F,EAAI+F,EACxBf,EAAUhD,GAAW0C,EACrBM,EAAU/C,IAAUyC,EAAczC,IAAU,EAKtC2D,EAAiBZ,EAAU1C,IAAU2D,EAC1CjB,EACAK,EACAM,EACAG,GAGDnC,EAAWxD,GACW,GAAlByF,IAEHE,KADAnC,EAAW0B,EAAYO,MAGtBjC,EAAQpB,KD3OW,ICkPFoB,GAAYxD,GAAQwD,EAAQtB,KAAclC,IAGtC,GAAlByF,IAeCN,EAAoBO,EACvBE,IACUT,EAAoBO,GAC9BE,KAK4B,mBAAnBf,EAAW7D,OACrB6D,EAAUzC,KD/Qc,ICiRfqD,GAAiBD,IAiBvBC,GAAiBD,EAAc,EAClCI,IACUH,GAAiBD,EAAc,EACzCI,KAEIH,EAAgBD,EACnBI,IAEAA,IAMDf,EAAUzC,KDhTc,KC8KzBmC,EAAc3C,IAAW/B,GAAKG,EA2IhC,GAAI2F,EACH,IAAK9F,EAAI,EAAGA,EAAI6F,EAAmB7F,KAClC2D,EAAW0B,EAAYrF,KACPG,GAAuC,ID1TnC,EC0TKwD,EAAQpB,OAC5BoB,EAAQzB,KAAS0B,IACpBA,EAAShB,EAAce,IAGxBuC,EAAQvC,EAAUA,IAKrB,OAAOC,CACR,CASA,SAAS6B,EAAOU,EAAavC,EAAQY,EAAWY,GAAhD,IAIMhE,EACKpB,EAFV,GAA+B,mBAApBmG,EAAYhF,KAAoB,CAE1C,IADIC,EAAW+E,EAAWpE,IACjB/B,EAAI,EAAGoB,GAAYpB,EAAIoB,EAASK,OAAQzB,IAC5CoB,EAASpB,KAKZoB,EAASpB,GAAEgC,GAAWmE,EACtBvC,EAAS6B,EAAOrE,EAASpB,GAAI4D,EAAQY,EAAWY,IAIlD,OAAOxB,CACR,CAAWuC,EAAWjE,KAAS0B,IAC1BwB,IACCxB,GAAUuC,EAAYhF,OAASyC,EAAO5C,aACzC4C,EAAShB,EAAcuD,IAExB3B,EAAU4B,aAAaD,EAAWjE,IAAO0B,GAAUzD,IAEpDyD,EAASuC,EAAWjE,KAGrB,GACC0B,EAASA,GAAUA,EAAO8B,kBAClB9B,GAAUzD,GAA2B,GAAnByD,EAAOyC,UAElC,OAAOzC,CACR,CA4BA,SAASqC,EACRjB,EACAK,EACAM,EACAG,GAJD,IAgCMQ,EACAC,EAEG1D,EA7BFxB,EAAM2D,EAAW3D,IACjBF,EAAO6D,EAAW7D,KACpBwC,EAAW0B,EAAYM,GACrBa,EAAU7C,GAAYxD,GAAuC,IDnZ7C,ECmZewD,EAAQpB,KAiB7C,GACEoB,IAAaxD,GAAe,MAAPkB,GACrBmF,GAAWnF,GAAOsC,EAAStC,KAAOF,GAAQwC,EAASxC,KAEpD,OAAOwE,EACD,GAPNG,GAAwBU,EAAU,EAAI,GAUtC,IAFIF,EAAIX,EAAc,EAClBY,EAAIZ,EAAc,EACfW,GAAK,GAAKC,EAAIlB,EAAY5D,QAGhC,IADAkC,EAAW0B,EADLxC,EAAayD,GAAK,EAAIA,IAAMC,OAGrBpG,GACmB,IDjbZ,ECiblBwD,EAAQpB,MACTlB,GAAOsC,EAAStC,KAChBF,GAAQwC,EAASxC,KAEjB,OAAO0B,EAKV,OAAQ,CACT,CH/bA,SAAS4D,EAASC,EAAOrF,EAAKsF,GACf,KAAVtF,EAAI,GACPqF,EAAME,YAAYvF,EAAKsF,GAASxG,EAAO,GAAKwG,GAE5CD,EAAMrF,GADIsF,GAASxG,EACN,GACa,iBAATwG,GAAqBnG,EAAmBqG,KAAKxF,GACjDsF,EAEAA,EAAQ,IAEvB,CAyBgB,SAAAC,EAAYE,EAAKC,EAAMJ,EAAOK,EAAUnC,GAAxC,IACXoC,EA8BGC,EA5BPC,EAAG,GAAY,SAARJ,EACN,GAAoB,iBAATJ,EACVG,EAAIJ,MAAMU,QAAUT,MACd,CAKN,GAJuB,iBAAZK,IACVF,EAAIJ,MAAMU,QAAUJ,EAAW,IAG5BA,EACH,IAAKD,KAAQC,EACNL,GAASI,KAAQJ,GACtBF,EAASK,EAAIJ,MAAOK,EAAM,IAK7B,GAAIJ,EACH,IAAKI,KAAQJ,EACPK,GAAYL,EAAMI,IAASC,EAASD,IACxCN,EAASK,EAAIJ,MAAOK,EAAMJ,EAAMI,GAIpC,MAGI,GAAe,KAAXA,EAAK,IAAwB,KAAXA,EAAK,GAC/BE,EAAaF,IAASA,EAAOA,EAAKM,QAAQzH,EAAe,OACnDsH,EAAgBH,EAAKO,cAI1BP,EADGG,KAAiBJ,GAAe,cAARC,GAAgC,aAARA,EAC5CG,EAAc9H,MAAM,GAChB2H,EAAK3H,MAAM,GAElB0H,EAAG/C,IAAa+C,EAAG/C,EAAc,CAAE,GACxC+C,EAAG/C,EAAYgD,EAAOE,GAAcN,EAEhCA,EACEK,EAQJL,EAAMY,EAAYP,EAASO,GAP3BZ,EAAMY,EAAY1H,EAClBiH,EAAIU,iBACHT,EACAE,EAAalH,EAAoBD,EACjCmH,IAMFH,EAAIW,oBACHV,EACAE,EAAalH,EAAoBD,EACjCmH,OAGI,CACN,GAAIpC,GAAa5E,EAIhB8G,EAAOA,EAAKM,QAAQ,cAAe,KAAKA,QAAQ,SAAU,UAE1DN,GAAQ,SAARA,GACQ,UAARA,GACQ,QAARA,GACQ,QAARA,GACQ,QAARA,GAGQ,YAARA,GACQ,YAARA,GACQ,WAARA,GACQ,WAARA,GACQ,QAARA,GACQ,WAARA,GACAA,KAAQD,EAER,IACCA,EAAIC,GAAQJ,GAASxG,EAAO,GAAKwG,EAEjC,MAAMQ,CAER,CADG,MAAOO,GACV,CASoB,mBAATf,IAEAA,GAASxG,IAAmB,IAAVwG,GAA8B,KAAXI,EAAK,GAGpDD,EAAIa,gBAAgBZ,GAFpBD,EAAIc,aAAab,EAAc,WAARA,GAA8B,GAATJ,EAAgB,GAAKA,GAInE,CACD,CAOA,SAASkB,EAAiBZ,GAMzB,gBAAiBS,GAChB,GAAI/E,KAAIoB,EAAa,CACpB,IAAM+D,EAAenF,KAAIoB,EAAY2D,EAAEvG,KAAO8F,GAC9C,GAAIS,EAAEK,GAAe5H,EACpBuH,EAAEK,EAAclI,SAKV,GAAI6H,EAAEK,EAAcD,EAAaP,EACvC,OAED,OAAOO,EAAazI,EAAQ2I,MAAQ3I,EAAQ2I,MAAMN,GAAKA,EACxD,CACD,CACD,UIzHgBvD,EACfK,EACAd,EACAC,EACAiB,EACAC,EACAC,EACAjB,EACAD,EACAmB,EACAjB,OAGImE,EAkBE9E,EAAG+E,EAAOC,EAAUC,EAAUC,EAAUC,EACxCC,EACEC,EAMFC,EACAC,EAuGO1I,EA4BP2I,EACHC,EASS5I,EA6BNyE,EAgDOzE,EApPZ6I,EAAUnF,EAASvC,KAIpB,GAAIuC,EAAStB,cAAgBhC,EAAW,OAAOD,EF/DlB,IEkEzBwD,EAAQpB,MACXwC,KFrE0B,GEqETpB,EAAQpB,KAEzBuC,EAAoB,CADpBlB,EAASF,EAAQxB,IAAQyB,EAAQzB,OAI7B+F,EAAM5I,EAAO4C,MAASgG,EAAIvE,GAE/BoF,EAAO,GAAsB,mBAAXD,EACjB,IAgEC,GA9DIN,EAAW7E,EAAS7C,MAClB2H,EACL,cAAeK,GAAWA,EAAQE,UAAUC,OAKzCP,GADJR,EAAMY,EAAQI,cACQrE,EAAcqD,EAAG9F,KACnCuG,EAAmBT,EACpBQ,EACCA,EAAS5H,MAAM8F,MACfsB,EAAGjG,GACJ4C,EAGCjB,EAAQxB,IAEXmG,GADAnF,EAAIO,EAAQvB,IAAcwB,EAAQxB,KACNH,GAAwBmB,EAAC+F,KAGjDV,EAEH9E,EAAQvB,IAAcgB,EAAI,IAAI0F,EAAQN,EAAUG,IAGhDhF,EAAQvB,IAAcgB,EAAI,IAAIV,EAC7B8F,EACAG,GAEDvF,EAAEf,YAAcyG,EAChB1F,EAAE6F,OAASG,GAERV,GAAUA,EAASW,IAAIjG,GAEtBA,EAAEkG,QAAOlG,EAAEkG,MAAQ,CAAE,GAC1BlG,EAACiB,IAAkBQ,EACnBsD,EAAQ/E,EAACC,KAAU,EACnBD,EAACmG,IAAoB,GACrBnG,EAACoG,IAAmB,IAIjBf,GAAoBrF,EAACqG,KAAerJ,IACvCgD,EAACqG,IAAcrG,EAAEkG,OAGdb,GAAoBK,EAAQY,0BAA4BtJ,IACvDgD,EAACqG,KAAerG,EAAEkG,QACrBlG,EAACqG,IAAc7I,EAAO,CAAE,EAAEwC,EAACqG,MAG5B7I,EACCwC,EAACqG,IACDX,EAAQY,yBAAyBlB,EAAUpF,EAACqG,OAI9CrB,EAAWhF,EAAEtC,MACbuH,EAAWjF,EAAEkG,MACblG,EAACd,IAAUqB,EAGPwE,EAEFM,GACAK,EAAQY,0BAA4BtJ,GACpCgD,EAAEuG,oBAAsBvJ,GAExBgD,EAAEuG,qBAGClB,GAAoBrF,EAAEwG,mBAAqBxJ,GAC9CgD,EAACmG,IAAkBjG,KAAKF,EAAEwG,uBAErB,CAUN,GARCnB,GACAK,EAAQY,0BAA4BtJ,GACpCoI,IAAaJ,GACbhF,EAAEyG,2BAA6BzJ,GAE/BgD,EAAEyG,0BAA0BrB,EAAUG,GAItChF,EAAQrB,KAAcsB,EAAQtB,MAC5Bc,EAACjB,KACFiB,EAAE0G,uBAAyB1J,IAKrB,IAJNgD,EAAE0G,sBACDtB,EACApF,EAACqG,IACDd,GAED,CAkBD,IAhBIhF,EAAQrB,KAAcsB,EAAQtB,MAKjCc,EAAEtC,MAAQ0H,EACVpF,EAAEkG,MAAQlG,EAACqG,IACXrG,EAACC,KAAU,GAGZM,EAAQxB,IAAQyB,EAAQzB,IACxBwB,EAAQ3B,IAAa4B,EAAQ5B,IAC7B2B,EAAQ3B,IAAW+H,KAAK,SAAAhI,GACnBA,IAAOA,EAAKE,GAAW0B,EAC5B,GAES1D,EAAI,EAAGA,EAAImD,EAACoG,IAAiB9H,OAAQzB,IAC7CmD,EAACmG,IAAkBjG,KAAKF,EAACoG,IAAiBvJ,IAE3CmD,EAACoG,IAAmB,GAEhBpG,EAACmG,IAAkB7H,QACtBoC,EAAYR,KAAKF,GAGlB,MAAM2F,CACP,CAEI3F,EAAE4G,qBAAuB5J,GAC5BgD,EAAE4G,oBAAoBxB,EAAUpF,EAACqG,IAAad,GAG3CF,GAAoBrF,EAAE6G,oBAAsB7J,GAC/CgD,EAACmG,IAAkBjG,KAAK,WACvBF,EAAE6G,mBAAmB7B,EAAUC,EAAUC,EAC1C,EAEF,CASA,GAPAlF,EAAET,QAAUgG,EACZvF,EAAEtC,MAAQ0H,EACVpF,EAACe,IAAcM,EACfrB,EAACjB,KAAU,EAEPyG,EAAatJ,EAAOkE,IACvBqF,EAAQ,EACLJ,EAAkB,CAQrB,IAPArF,EAAEkG,MAAQlG,EAACqG,IACXrG,EAACC,KAAU,EAEPuF,GAAYA,EAAWjF,GAE3BuE,EAAM9E,EAAE6F,OAAO7F,EAAEtC,MAAOsC,EAAEkG,MAAOlG,EAAET,SAE1B1C,EAAI,EAAGA,EAAImD,EAACoG,IAAiB9H,OAAQzB,IAC7CmD,EAACmG,IAAkBjG,KAAKF,EAACoG,IAAiBvJ,IAE3CmD,EAACoG,IAAmB,EACrB,MACC,GACCpG,EAACC,KAAU,EACPuF,GAAYA,EAAWjF,GAE3BuE,EAAM9E,EAAE6F,OAAO7F,EAAEtC,MAAOsC,EAAEkG,MAAOlG,EAAET,SAGnCS,EAAEkG,MAAQlG,EAACqG,UACHrG,EAACC,OAAawF,EAAQ,IAIhCzF,EAAEkG,MAAQlG,EAACqG,IAEPrG,EAAE8G,iBAAmB9J,IACxByE,EAAgBjE,EAAOA,EAAO,CAAE,EAAEiE,GAAgBzB,EAAE8G,oBAGjDzB,IAAqBN,GAAS/E,EAAE+G,yBAA2B/J,IAC9DkI,EAAWlF,EAAE+G,wBAAwB/B,EAAUC,IAK5C3D,EAAewD,EADlBA,GAAO9H,GAAQ8H,EAAI9G,OAASqB,GAAYyF,EAAI5G,KAAOlB,IAInDsE,EAAe0F,EAAUlC,EAAIpH,MAAMO,WAGpCwC,EAASW,EACRC,EACA/D,EAAQgE,GAAgBA,EAAe,CAACA,GACxCf,EACAC,EACAiB,EACAC,EACAC,EACAjB,EACAD,EACAmB,EACAjB,GAGDX,EAAEF,KAAOS,EAAQxB,IAGjBwB,EAAQnB,MF/Qe,IEiRnBY,EAACmG,IAAkB7H,QACtBoC,EAAYR,KAAKF,GAGdmF,IACHnF,EAAC+F,IAAiB/F,EAACnB,GAAwB7B,EA6B7C,CA3BE,MAAOuH,GAGR,GAFAhE,EAAQrB,IAAalC,EAEjB4E,GAAeD,GAAqB3E,EACvC,GAAIuH,EAAE0C,KAAM,CAKX,IAJA1G,EAAQnB,KAAWwC,EAChBsF,IFrSsB,IEwSlBzG,GAA6B,GAAnBA,EAAOyC,UAAiBzC,EAAO8B,aAC/C9B,EAASA,EAAO8B,YAGjBZ,EAAkBA,EAAkBwF,QAAQ1G,IAAWzD,EACvDuD,EAAQxB,IAAQ0B,CACjB,KAAO,CACN,IAAS5D,EAAI8E,EAAkBrD,OAAQzB,KACtCc,EAAWgE,EAAkB9E,IAE9BuK,EAAY7G,EACb,MAEAA,EAAQxB,IAAQyB,EAAQzB,IACxBwB,EAAQ3B,IAAa4B,EAAQ5B,IACxB2F,EAAE0C,MAAMG,EAAY7G,GAE1BrE,EAAO6C,IAAawF,EAAGhE,EAAUC,EAClC,MAEAmB,GAAqB3E,GACrBuD,EAAQrB,KAAcsB,EAAQtB,KAE9BqB,EAAQ3B,IAAa4B,EAAQ5B,IAC7B2B,EAAQxB,IAAQyB,EAAQzB,KAExB0B,EAASF,EAAQxB,IAAQsI,EACxB7G,EAAQzB,IACRwB,EACAC,EACAiB,EACAC,EACAC,EACAjB,EACAkB,EACAjB,GAMF,OAFKmE,EAAM5I,EAAQoL,SAASxC,EAAIvE,GF/UH,IEiVtBA,EAAQnB,SAA2BlC,EAAYuD,CACvD,CAEA,SAAS2G,EAAYzI,GAChBA,GAASA,EAAKK,MAAaL,EAAKK,IAAAD,KAAqB,GACrDJ,GAASA,EAAKC,KAAYD,EAAKC,IAAW2I,QAAQH,EACvD,CAOO,SAASjG,EAAWT,EAAa8G,EAAM7G,GAC7C,IAAK,IAAI9D,EAAI,EAAGA,EAAI8D,EAASrC,OAAQzB,IACpCwF,EAAS1B,EAAS9D,GAAI8D,IAAW9D,GAAI8D,IAAW9D,IAG7CX,EAAO8C,KAAU9C,EAAO8C,IAASwI,EAAM9G,GAE3CA,EAAYiG,KAAK,SAAA3G,GAChB,IAECU,EAAcV,EAACmG,IACfnG,EAACmG,IAAoB,GACrBzF,EAAYiG,KAAK,SAAAc,GAEhBA,EAAGlJ,KAAKyB,EACT,EAGD,CAFE,MAAOuE,GACRrI,EAAO6C,IAAawF,EAAGvE,EAACd,IACzB,CACD,EACD,CAEA,SAAS8H,EAAUpJ,GAClB,MACgB,iBAARA,GACPA,GAAQZ,GACPY,EAAIkB,KAAWlB,EAAIkB,IAAU,EAEvBlB,EAGJN,EAAQM,GACJA,EAAK8J,IAAIV,GAGVxJ,EAAO,GAAII,EACnB,CAiBA,SAASyJ,EACR1D,EACApD,EACAC,EACAiB,EACAC,EACAC,EACAjB,EACAkB,EACAjB,GATD,IAeK9D,EAEA8K,EAEAC,EAEAC,EACArE,EACAsE,EACAC,EAbA/C,EAAWxE,EAAS9C,OAASP,EAC7BiI,EAAW7E,EAAS7C,MACpBwF,EAAkC3C,EAASvC,KAkB/C,GAJgB,OAAZkF,EAAmBxB,EAAY5E,EACd,QAAZoG,EAAoBxB,EFpaA,qCEqanBA,IAAWA,EAAY3E,GAE7B4E,GAAqB3E,EACxB,IAAKH,EAAI,EAAGA,EAAI8E,EAAkBrD,OAAQzB,IAMzC,IALA2G,EAAQ7B,EAAkB9E,KAOzB,iBAAkB2G,KAAWN,IAC5BA,EAAWM,EAAMwE,WAAa9E,EAA6B,GAAlBM,EAAMN,UAC/C,CACDS,EAAMH,EACN7B,EAAkB9E,GAAKG,EACvB,KACD,CAIF,GAAI2G,GAAO3G,EAAM,CAChB,GAAIkG,GAAYlG,EACf,OAAOiL,SAASC,eAAe9C,GAGhCzB,EAAMsE,SAASE,gBACdzG,EACAwB,EACAkC,EAASgD,IAAMhD,GAKZxD,IACC1F,EAAOmM,KACVnM,EAAOmM,IAAoB9H,EAAUoB,GACtCC,GAAc,GAGfD,EAAoB3E,CACrB,CAEA,GAAIkG,GAAYlG,EAEXgI,IAAaI,GAAcxD,GAAe+B,EAAI2E,MAAQlD,IACzDzB,EAAI2E,KAAOlD,OAEN,CAON,GALAzD,EAAoBA,GAAqB1F,EAAMsC,KAAKoF,EAAI4E,aAKnD3G,GAAeD,GAAqB3E,EAExC,IADAgI,EAAW,GACNnI,EAAI,EAAGA,EAAI8G,EAAI6E,WAAWlK,OAAQzB,IAEtCmI,GADAxB,EAAQG,EAAI6E,WAAW3L,IACR+G,MAAQJ,EAAMA,MAI/B,IAAK3G,KAAKmI,EAET,GADAxB,EAAQwB,EAASnI,GACR,YAALA,QACOA,GAAK,2BAALA,EACV+K,EAAUpE,OACA,KAAE3G,KAAKuI,GAAW,CAC5B,GACO,SAALvI,GAAgB,iBAAkBuI,GAC7B,WAALvI,GAAkB,mBAAoBuI,EAEvC,SAED3B,EAAYE,EAAK9G,EAAGG,EAAMwG,EAAO9B,EAClC,CAKD,IAAK7E,KAAKuI,EACT5B,EAAQ4B,EAASvI,GACR,YAALA,EACHgL,EAAcrE,EACC,2BAAL3G,EACV8K,EAAUnE,EACK,SAAL3G,EACViL,EAAatE,EACE,WAAL3G,EACVkL,EAAUvE,EAER5B,GAA+B,mBAAT4B,GACxBwB,EAASnI,KAAO2G,GAEhBC,EAAYE,EAAK9G,EAAG2G,EAAOwB,EAASnI,GAAI6E,GAK1C,GAAIiG,EAGD/F,GACCgG,IACAD,EAAOc,QAAWb,EAAOa,QAAWd,EAAOc,QAAW9E,EAAI+E,aAE5D/E,EAAI+E,UAAYf,EAAOc,QAGxBlI,EAAQ3B,IAAa,QAsBrB,GApBIgJ,IAASjE,EAAI+E,UAAY,IAE7BtH,EAEkB,YAAjBb,EAASvC,KAAqB2F,EAAIgF,QAAUhF,EAC5CrG,EAAQuK,GAAeA,EAAc,CAACA,GACtCtH,EACAC,EACAiB,EACY,iBAAZyB,EAA8BnG,EAAkB2E,EAChDC,EACAjB,EACAiB,EACGA,EAAkB,GAClBnB,EAAQ5B,KAAca,EAAce,EAAU,GACjDoB,EACAjB,GAIGgB,GAAqB3E,EACxB,IAAKH,EAAI8E,EAAkBrD,OAAQzB,KAClCc,EAAWgE,EAAkB9E,IAM3B+E,IACJ/E,EAAI,QACY,YAAZqG,GAA0B4E,GAAc9K,EAC3C2G,EAAIa,gBAAgB,SAEpBsD,GAAc7K,IAKb6K,IAAenE,EAAI9G,IACN,YAAZqG,IAA2B4E,GAIf,UAAZ5E,GAAwB4E,GAAc9C,EAASnI,KAEjD4G,EAAYE,EAAK9G,EAAGiL,EAAY9C,EAASnI,GAAI6E,GAG9C7E,EAAI,UACAkL,GAAW9K,GAAa8K,GAAWpE,EAAI9G,IAC1C4G,EAAYE,EAAK9G,EAAGkL,EAAS/C,EAASnI,GAAI6E,GAG7C,CAEA,OAAOiC,CACR,CAQgB,SAAAtB,EAASlE,EAAKqF,EAAO7E,GACpC,IACC,GAAkB,mBAAPR,EAAmB,CAC7B,IAAIyK,EAAuC,mBAAhBzK,EAAGiB,IAC1BwJ,GAEHzK,EAAGiB,MAGCwJ,GAAiBpF,GAASxG,IAI9BmB,EAAGiB,IAAYjB,EAAIqF,GAErB,MAAOrF,EAAI0K,QAAUrF,CAGtB,CAFE,MAAOe,GACRrI,EAAO6C,IAAawF,EAAG5F,EACxB,CACD,CASgB,SAAAoE,EAAQpE,EAAOqE,EAAa8F,GAA5B,IACXC,EAsBMlM,EAbV,GARIX,EAAQ6G,SAAS7G,EAAQ6G,QAAQpE,IAEhCoK,EAAIpK,EAAMR,OACT4K,EAAEF,SAAWE,EAAEF,SAAWlK,EAAKI,KACnCsD,EAAS0G,EAAG/L,EAAMgG,KAIf+F,EAAIpK,EAAKK,MAAgBhC,EAAM,CACnC,GAAI+L,EAAEC,qBACL,IACCD,EAAEC,sBAGH,CAFE,MAAOzE,GACRrI,EAAO6C,IAAawF,EAAGvB,EACxB,CAGD+F,EAAEjJ,KAAOiJ,EAAChI,IAAc/D,CACzB,CAEA,GAAK+L,EAAIpK,EAAKC,IACb,IAAS/B,EAAI,EAAGA,EAAIkM,EAAEzK,OAAQzB,IACzBkM,EAAElM,IACLkG,EACCgG,EAAElM,GACFmG,EACA8F,GAAmC,mBAAdnK,EAAMX,MAM1B8K,GACJnL,EAAWgB,EAAKI,KAGjBJ,EAAKK,IAAcL,EAAKE,GAAWF,EAAKI,IAAQ9B,CACjD,CAGA,SAAS+I,EAAStI,EAAOwI,EAAO3G,GAC/B,YAAYN,YAAYvB,EAAO6B,EAChC,CC9pBO,SAASsG,EAAOlH,EAAO0C,EAAW4H,GAAlC,IAWFrH,EAOApB,EAQAE,EACHC,EAzBGU,GAAa4G,WAChB5G,EAAY4G,SAASiB,iBAGlBhN,EAAO2C,IAAQ3C,EAAO2C,GAAOF,EAAO0C,GAYpCb,GAPAoB,EAAoC,mBAAfqH,GAQtBjM,EACCiM,GAAeA,EAAWrK,KAAeyC,EAASzC,IAMlD8B,EAAc,GACjBC,EAAW,GACZK,EACCK,EAPD1C,IAAWiD,GAAeqH,GAAgB5H,GAASzC,IAClDb,EAAcsB,EAAUrC,EAAM,CAAC2B,IAU/B6B,GAAYrD,EACZA,EACAkE,EAAUH,cACTU,GAAeqH,EACb,CAACA,GACDzI,EACCxD,EACAqE,EAAU8H,WACTlN,EAAMsC,KAAK8C,EAAUkH,YACrBvL,EACL0D,GACCkB,GAAeqH,EACbA,EACAzI,EACCA,EAAQzB,IACRsC,EAAU8H,WACdvH,EACAjB,GAIDQ,EAAWT,EAAa/B,EAAOgC,EAChC,CTzCa1E,EAAQmB,EAAUnB,MChBzBC,EAAU,CACf6C,ISDM,SAAqBqK,EAAOzK,EAAO6B,EAAU6I,GAQnD,IANA,IAAI/I,EAEHgJ,EAEAC,EAEO5K,EAAQA,EAAKE,IACpB,IAAKyB,EAAY3B,EAAKK,OAAiBsB,EAASzB,GAC/C,IAcC,IAbAyK,EAAOhJ,EAAUrB,cAELqK,EAAKE,0BAA4BxM,IAC5CsD,EAAUmJ,SAASH,EAAKE,yBAAyBJ,IACjDG,EAAUjJ,EAASL,KAGhBK,EAAUoJ,mBAAqB1M,IAClCsD,EAAUoJ,kBAAkBN,EAAOC,GAAa,CAAE,GAClDE,EAAUjJ,EAASL,KAIhBsJ,EACH,OAAQjJ,EAASyF,IAAiBzF,CAIpC,CAFE,MAAOiE,GACR6E,EAAQ7E,CACT,CAIF,MAAM6E,CACP,GRzCIjN,EAAU,EA2FDC,EAAiB,SAAAuC,GAAK,OAClCA,GAAS3B,GAAQ2B,EAAMM,cAAgBhC,CAAS,ECrEjDqC,EAAcsG,UAAU6D,SAAW,SAAUE,EAAQC,GAEpD,IAAIC,EAEHA,EADGrK,KAAI6G,KAAerJ,GAAQwC,KAAI6G,KAAe7G,KAAK0G,MAClD1G,KAAI6G,IAEJ7G,KAAI6G,IAAc7I,EAAO,CAAA,EAAIgC,KAAK0G,OAGlB,mBAAVyD,IAGVA,EAASA,EAAOnM,EAAO,CAAA,EAAIqM,GAAIrK,KAAK9B,QAGjCiM,GACHnM,EAAOqM,EAAGF,GAIPA,GAAU3M,GAEVwC,KAAIN,MACH0K,GACHpK,KAAI4G,IAAiBlG,KAAK0J,GAE3B7J,EAAcP,MAEhB,EAQAF,EAAcsG,UAAUkE,YAAc,SAAUF,GAC3CpK,KAAIN,MAIPM,KAAIT,KAAU,EACV6K,GAAUpK,KAAI2G,IAAkBjG,KAAK0J,GACzC7J,EAAcP,MAEhB,EAYAF,EAAcsG,UAAUC,OAASxG,EA+F7BhD,EAAgB,GAadE,EACa,mBAAXwN,QACJA,QAAQnE,UAAUqB,KAAK+C,KAAKD,QAAQE,WACpCC,WAuBE1N,EAAY,SAAC2N,EAAGC,GAAM,OAAAD,EAACjL,IAAAJ,IAAiBsL,EAAClL,IAAAJ,GAAc,EA8B7DqB,EAAOC,IAAkB,ECzOnB3D,EAAgB,8BAalBC,EAAa,EA+IXC,EAAa+H,GAAiB,GAC9B9H,EAAoB8H,GAAiB,GCzKhC7H,EAAI,qCIwER,SAASwN,EAAQ1L,EAAO0C,GAC9BwE,EAAOlH,EAAO0C,EAAWgJ,EAC1B,sDPMC,MAAO,CAAExB,QAAS7L,EACnB,qDSvE6B2B,EAAOjB,EAAOO,OAEzCC,EACAC,EACAtB,EAEG2B,EALAJ,EAAkBZ,EAAO,CAAE,EAAEmB,EAAMjB,OAWvC,IAAKb,KAJD8B,EAAMX,MAAQW,EAAMX,KAAKQ,eAC5BA,EAAeG,EAAMX,KAAKQ,cAGjBd,EACA,OAALb,EAAYqB,EAAMR,EAAMb,GACd,OAALA,EAAYsB,EAAMT,EAAMb,GAEhCuB,EAAgBvB,GADRa,EAAMb,KAAOI,GAAauB,GAAgBvB,EAC7BuB,EAAa3B,GAEba,EAAMb,GAS7B,OALIwB,UAAUC,OAAS,IACtBF,EAAgBH,SACfI,UAAUC,OAAS,EAAIrC,EAAMsC,KAAKF,UAAW,GAAKJ,GAG7CQ,EACNE,EAAMX,KACNI,EACAF,GAAOS,EAAMT,IACbC,GAAOQ,EAAMR,IACbnB,EAEF,gBN1CgB,SAAcsN,GAC7B,SAASC,EAAQ7M,GAAjB,IAGM8M,EACAC,EA+BL,OAlCKjL,KAAKsH,kBAEL0D,EAAO,IAAIE,KACXD,EAAM,CAAE,GACRF,EAAOvL,KAAQQ,KAEnBA,KAAKsH,gBAAkB,WAAM,OAAA2D,CAAG,EAEhCjL,KAAKwJ,qBAAuB,WAC3BwB,EAAOxN,CACR,EAEAwC,KAAKkH,sBAAwB,SAAUiE,GAElCnL,KAAK9B,MAAM8F,OAASmH,EAAOnH,OAC9BgH,EAAKjD,QAAQ,SAAAvH,GACZA,EAACjB,KAAU,EACXgB,EAAcC,EACf,EAEF,EAEAR,KAAKyG,IAAM,SAAAjG,GACVwK,EAAKI,IAAI5K,GACT,IAAI6K,EAAM7K,EAAEgJ,qBACZhJ,EAAEgJ,qBAAuB,WACpBwB,GACHA,EAAKM,OAAO9K,GAET6K,GAAKA,EAAItM,KAAKyB,EACnB,CACD,GAGMtC,EAAMO,QACd,CAgBA,OAdAsM,EAAOvL,IAAO,OAASnC,IACvB0N,EAAO1L,GAAiByL,EAQxBC,EAAQQ,SACPR,EAAOS,KANRT,EAAQU,SAAW,SAACvN,EAAOwN,GAC1B,OAAOxN,EAAMO,SAASiN,EACvB,GAKkBpF,YAChByE,EAEKA,CACR,eEkUO,SAASY,EAAalN,EAAUmN,GAUtC,OATAA,EAAMA,GAAO,GACTnN,GAAYjB,GAA2B,kBAAZiB,IACpBX,EAAQW,GAClBA,EAAS0I,KAAK,SAAA9G,GACbsL,EAAatL,EAAOuL,EACrB,GAEAA,EAAIlL,KAAKjC,IAEHmN,CACR,oBKvYWC,OAAS,IAAKA,OAAOC,QAAUC,EACrCC,KAAKD,OAASA"} \ No newline at end of file diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/dist/preact.mjs b/browser/base/content/assistant/ui-preact/node_modules/preact/dist/preact.mjs new file mode 100644 index 0000000000000..5d8574dd208ac --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/dist/preact.mjs @@ -0,0 +1,2 @@ +var n,l,u,t,i,o,r,e,f,c,s,a,h,p={},v=[],y=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,d=Array.isArray;function w(n,l){for(var u in l)n[u]=l[u];return n}function g(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function _(l,u,t){var i,o,r,e={};for(r in u)"key"==r?i=u[r]:"ref"==r?o=u[r]:e[r]=u[r];if(arguments.length>2&&(e.children=arguments.length>3?n.call(arguments,2):t),"function"==typeof l&&null!=l.defaultProps)for(r in l.defaultProps)void 0===e[r]&&(e[r]=l.defaultProps[r]);return m(l,e,i,o,null)}function m(n,t,i,o,r){var e={type:n,props:t,key:i,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==r?++u:r,__i:-1,__u:0};return null==r&&null!=l.vnode&&l.vnode(e),e}function b(){return{current:null}}function k(n){return n.children}function x(n,l){this.props=n,this.context=l}function S(n,l){if(null==l)return n.__?S(n.__,n.__i+1):null;for(var u;ls&&i.sort(e),n=i.shift(),s=i.length,n.__d&&(t=void 0,o=void 0,r=(o=(u=n).__v).__e,f=[],c=[],u.__P&&((t=w({},o)).__v=o.__v+1,l.vnode&&l.vnode(t),O(u.__P,t,o,u.__n,u.__P.namespaceURI,32&o.__u?[r]:null,f,null==r?S(o):r,!!(32&o.__u),c),t.__v=o.__v,t.__.__k[t.__i]=t,N(f,t,c),o.__e=o.__=null,t.__e!=r&&C(t)));$.__r=0}function I(n,l,u,t,i,o,r,e,f,c,s){var a,h,y,d,w,g,_,m=t&&t.__k||v,b=l.length;for(f=P(u,l,m,f,b),a=0;a0?r=n.__k[o]=m(r.type,r.props,r.key,r.ref?r.ref:null,r.__v):n.__k[o]=r,f=o+h,r.__=n,r.__b=n.__b+1,e=null,-1!=(c=r.__i=L(r,u,f,a))&&(a--,(e=u[c])&&(e.__u|=2)),null==e||null==e.__v?(-1==c&&(i>s?h--:if?h--:h++,r.__u|=4))):n.__k[o]=null;if(a)for(o=0;o(s?1:0))for(i=u-1,o=u+1;i>=0||o=0?i--:o++])&&0==(2&c.__u)&&e==c.key&&f==c.type)return r;return-1}function T(n,l,u){"-"==l[0]?n.setProperty(l,null==u?"":u):n[l]=null==u?"":"number"!=typeof u||y.test(l)?u:u+"px"}function j(n,l,u,t,i){var o,r;n:if("style"==l)if("string"==typeof u)n.style.cssText=u;else{if("string"==typeof t&&(n.style.cssText=t=""),t)for(l in t)u&&l in u||T(n.style,l,"");if(u)for(l in u)t&&u[l]==t[l]||T(n.style,l,u[l])}else if("o"==l[0]&&"n"==l[1])o=l!=(l=l.replace(f,"$1")),r=l.toLowerCase(),l=r in n||"onFocusOut"==l||"onFocusIn"==l?r.slice(2):l.slice(2),n.l||(n.l={}),n.l[l+o]=u,u?t?u.u=t.u:(u.u=c,n.addEventListener(l,o?a:s,o)):n.removeEventListener(l,o?a:s,o);else{if("http://www.w3.org/2000/svg"==i)l=l.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=l&&"height"!=l&&"href"!=l&&"list"!=l&&"form"!=l&&"tabIndex"!=l&&"download"!=l&&"rowSpan"!=l&&"colSpan"!=l&&"role"!=l&&"popover"!=l&&l in n)try{n[l]=null==u?"":u;break n}catch(n){}"function"==typeof u||(null==u||!1===u&&"-"!=l[4]?n.removeAttribute(l):n.setAttribute(l,"popover"==l&&1==u?"":u))}}function F(n){return function(u){if(this.l){var t=this.l[u.type+n];if(null==u.t)u.t=c++;else if(u.t0?n:d(n)?n.map(V):w({},n)}function q(u,t,i,o,r,e,f,c,s){var a,h,v,y,w,_,m,b=i.props||p,k=t.props,x=t.type;if("svg"==x?r="http://www.w3.org/2000/svg":"math"==x?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),null!=e)for(a=0;a2&&(f.children=arguments.length>3?n.call(arguments,2):t),m(l.type,f,i||l.key,o||l.ref,null)}function Q(n){function l(n){var u,t;return this.getChildContext||(u=new Set,(t={})[l.__c]=this,this.getChildContext=function(){return t},this.componentWillUnmount=function(){u=null},this.shouldComponentUpdate=function(n){this.props.value!=n.value&&u.forEach(function(n){n.__e=!0,M(n)})},this.sub=function(n){u.add(n);var l=n.componentWillUnmount;n.componentWillUnmount=function(){u&&u.delete(n),l&&l.call(n)}}),n.children}return l.__c="__cC"+h++,l.__=n,l.Provider=l.__l=(l.Consumer=function(n,l){return n.children(l)}).contextType=l,l}n=v.slice,l={__e:function(n,l,u,t){for(var i,o,r;l=l.__;)if((i=l.__c)&&!i.__)try{if((o=i.constructor)&&null!=o.getDerivedStateFromError&&(i.setState(o.getDerivedStateFromError(n)),r=i.__d),null!=i.componentDidCatch&&(i.componentDidCatch(n,t||{}),r=i.__d),r)return i.__E=i}catch(l){n=l}throw n}},u=0,t=function(n){return null!=n&&void 0===n.constructor},x.prototype.setState=function(n,l){var u;u=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=w({},this.state),"function"==typeof n&&(n=n(w({},u),this.props)),n&&w(u,n),null!=n&&this.__v&&(l&&this._sb.push(l),M(this))},x.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),M(this))},x.prototype.render=k,i=[],r="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,e=function(n,l){return n.__v.__b-l.__v.__b},$.__r=0,f=/(PointerCapture)$|Capture$/i,c=0,s=F(!1),a=F(!0),h=0;export{x as Component,k as Fragment,K as cloneElement,Q as createContext,_ as createElement,b as createRef,_ as h,J as hydrate,t as isValidElement,l as options,G as render,H as toChildArray}; +//# sourceMappingURL=preact.module.js.map diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/dist/preact.module.js b/browser/base/content/assistant/ui-preact/node_modules/preact/dist/preact.module.js new file mode 100644 index 0000000000000..5d8574dd208ac --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/dist/preact.module.js @@ -0,0 +1,2 @@ +var n,l,u,t,i,o,r,e,f,c,s,a,h,p={},v=[],y=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,d=Array.isArray;function w(n,l){for(var u in l)n[u]=l[u];return n}function g(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function _(l,u,t){var i,o,r,e={};for(r in u)"key"==r?i=u[r]:"ref"==r?o=u[r]:e[r]=u[r];if(arguments.length>2&&(e.children=arguments.length>3?n.call(arguments,2):t),"function"==typeof l&&null!=l.defaultProps)for(r in l.defaultProps)void 0===e[r]&&(e[r]=l.defaultProps[r]);return m(l,e,i,o,null)}function m(n,t,i,o,r){var e={type:n,props:t,key:i,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==r?++u:r,__i:-1,__u:0};return null==r&&null!=l.vnode&&l.vnode(e),e}function b(){return{current:null}}function k(n){return n.children}function x(n,l){this.props=n,this.context=l}function S(n,l){if(null==l)return n.__?S(n.__,n.__i+1):null;for(var u;ls&&i.sort(e),n=i.shift(),s=i.length,n.__d&&(t=void 0,o=void 0,r=(o=(u=n).__v).__e,f=[],c=[],u.__P&&((t=w({},o)).__v=o.__v+1,l.vnode&&l.vnode(t),O(u.__P,t,o,u.__n,u.__P.namespaceURI,32&o.__u?[r]:null,f,null==r?S(o):r,!!(32&o.__u),c),t.__v=o.__v,t.__.__k[t.__i]=t,N(f,t,c),o.__e=o.__=null,t.__e!=r&&C(t)));$.__r=0}function I(n,l,u,t,i,o,r,e,f,c,s){var a,h,y,d,w,g,_,m=t&&t.__k||v,b=l.length;for(f=P(u,l,m,f,b),a=0;a0?r=n.__k[o]=m(r.type,r.props,r.key,r.ref?r.ref:null,r.__v):n.__k[o]=r,f=o+h,r.__=n,r.__b=n.__b+1,e=null,-1!=(c=r.__i=L(r,u,f,a))&&(a--,(e=u[c])&&(e.__u|=2)),null==e||null==e.__v?(-1==c&&(i>s?h--:if?h--:h++,r.__u|=4))):n.__k[o]=null;if(a)for(o=0;o(s?1:0))for(i=u-1,o=u+1;i>=0||o=0?i--:o++])&&0==(2&c.__u)&&e==c.key&&f==c.type)return r;return-1}function T(n,l,u){"-"==l[0]?n.setProperty(l,null==u?"":u):n[l]=null==u?"":"number"!=typeof u||y.test(l)?u:u+"px"}function j(n,l,u,t,i){var o,r;n:if("style"==l)if("string"==typeof u)n.style.cssText=u;else{if("string"==typeof t&&(n.style.cssText=t=""),t)for(l in t)u&&l in u||T(n.style,l,"");if(u)for(l in u)t&&u[l]==t[l]||T(n.style,l,u[l])}else if("o"==l[0]&&"n"==l[1])o=l!=(l=l.replace(f,"$1")),r=l.toLowerCase(),l=r in n||"onFocusOut"==l||"onFocusIn"==l?r.slice(2):l.slice(2),n.l||(n.l={}),n.l[l+o]=u,u?t?u.u=t.u:(u.u=c,n.addEventListener(l,o?a:s,o)):n.removeEventListener(l,o?a:s,o);else{if("http://www.w3.org/2000/svg"==i)l=l.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=l&&"height"!=l&&"href"!=l&&"list"!=l&&"form"!=l&&"tabIndex"!=l&&"download"!=l&&"rowSpan"!=l&&"colSpan"!=l&&"role"!=l&&"popover"!=l&&l in n)try{n[l]=null==u?"":u;break n}catch(n){}"function"==typeof u||(null==u||!1===u&&"-"!=l[4]?n.removeAttribute(l):n.setAttribute(l,"popover"==l&&1==u?"":u))}}function F(n){return function(u){if(this.l){var t=this.l[u.type+n];if(null==u.t)u.t=c++;else if(u.t0?n:d(n)?n.map(V):w({},n)}function q(u,t,i,o,r,e,f,c,s){var a,h,v,y,w,_,m,b=i.props||p,k=t.props,x=t.type;if("svg"==x?r="http://www.w3.org/2000/svg":"math"==x?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),null!=e)for(a=0;a2&&(f.children=arguments.length>3?n.call(arguments,2):t),m(l.type,f,i||l.key,o||l.ref,null)}function Q(n){function l(n){var u,t;return this.getChildContext||(u=new Set,(t={})[l.__c]=this,this.getChildContext=function(){return t},this.componentWillUnmount=function(){u=null},this.shouldComponentUpdate=function(n){this.props.value!=n.value&&u.forEach(function(n){n.__e=!0,M(n)})},this.sub=function(n){u.add(n);var l=n.componentWillUnmount;n.componentWillUnmount=function(){u&&u.delete(n),l&&l.call(n)}}),n.children}return l.__c="__cC"+h++,l.__=n,l.Provider=l.__l=(l.Consumer=function(n,l){return n.children(l)}).contextType=l,l}n=v.slice,l={__e:function(n,l,u,t){for(var i,o,r;l=l.__;)if((i=l.__c)&&!i.__)try{if((o=i.constructor)&&null!=o.getDerivedStateFromError&&(i.setState(o.getDerivedStateFromError(n)),r=i.__d),null!=i.componentDidCatch&&(i.componentDidCatch(n,t||{}),r=i.__d),r)return i.__E=i}catch(l){n=l}throw n}},u=0,t=function(n){return null!=n&&void 0===n.constructor},x.prototype.setState=function(n,l){var u;u=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=w({},this.state),"function"==typeof n&&(n=n(w({},u),this.props)),n&&w(u,n),null!=n&&this.__v&&(l&&this._sb.push(l),M(this))},x.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),M(this))},x.prototype.render=k,i=[],r="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,e=function(n,l){return n.__v.__b-l.__v.__b},$.__r=0,f=/(PointerCapture)$|Capture$/i,c=0,s=F(!1),a=F(!0),h=0;export{x as Component,k as Fragment,K as cloneElement,Q as createContext,_ as createElement,b as createRef,_ as h,J as hydrate,t as isValidElement,l as options,G as render,H as toChildArray}; +//# sourceMappingURL=preact.module.js.map diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/dist/preact.module.js.map b/browser/base/content/assistant/ui-preact/node_modules/preact/dist/preact.module.js.map new file mode 100644 index 0000000000000..9bd81e275e289 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/dist/preact.module.js.map @@ -0,0 +1 @@ +{"version":3,"file":"preact.module.js","sources":["../src/constants.js","../src/util.js","../src/options.js","../src/create-element.js","../src/component.js","../src/diff/props.js","../src/create-context.js","../src/diff/children.js","../src/diff/index.js","../src/render.js","../src/clone-element.js","../src/diff/catch-error.js"],"sourcesContent":["/** Normal hydration that attaches to a DOM tree but does not diff it. */\nexport const MODE_HYDRATE = 1 << 5;\n/** Signifies this VNode suspended on the previous render */\nexport const MODE_SUSPENDED = 1 << 7;\n/** Indicates that this node needs to be inserted while patching children */\nexport const INSERT_VNODE = 1 << 2;\n/** Indicates a VNode has been matched with another VNode in the diff */\nexport const MATCHED = 1 << 1;\n\n/** Reset all mode flags */\nexport const RESET_MODE = ~(MODE_HYDRATE | MODE_SUSPENDED);\n\nexport const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\nexport const XHTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\nexport const MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n\nexport const NULL = null;\nexport const UNDEFINED = undefined;\nexport const EMPTY_OBJ = /** @type {any} */ ({});\nexport const EMPTY_ARR = [];\nexport const IS_NON_DIMENSIONAL =\n\t/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;\n","import { EMPTY_ARR } from './constants';\n\nexport const isArray = Array.isArray;\n\n/**\n * Assign properties from `props` to `obj`\n * @template O, P The obj and props types\n * @param {O} obj The object to copy properties to\n * @param {P} props The object to copy properties from\n * @returns {O & P}\n */\nexport function assign(obj, props) {\n\t// @ts-expect-error We change the type of `obj` to be `O & P`\n\tfor (let i in props) obj[i] = props[i];\n\treturn /** @type {O & P} */ (obj);\n}\n\n/**\n * Remove a child node from its parent if attached. This is a workaround for\n * IE11 which doesn't support `Element.prototype.remove()`. Using this function\n * is smaller than including a dedicated polyfill.\n * @param {import('./index').ContainerNode} node The node to remove\n */\nexport function removeNode(node) {\n\tif (node && node.parentNode) node.parentNode.removeChild(node);\n}\n\nexport const slice = EMPTY_ARR.slice;\n","import { _catchError } from './diff/catch-error';\n\n/**\n * The `option` object can potentially contain callback functions\n * that are called during various stages of our renderer. This is the\n * foundation on which all our addons like `preact/debug`, `preact/compat`,\n * and `preact/hooks` are based on. See the `Options` type in `internal.d.ts`\n * for a full list of available option hooks (most editors/IDEs allow you to\n * ctrl+click or cmd+click on mac the type definition below).\n * @type {import('./internal').Options}\n */\nconst options = {\n\t_catchError\n};\n\nexport default options;\n","import { slice } from './util';\nimport options from './options';\nimport { NULL, UNDEFINED } from './constants';\n\nlet vnodeId = 0;\n\n/**\n * Create an virtual node (used for JSX)\n * @param {import('./internal').VNode[\"type\"]} type The node name or Component constructor for this\n * virtual node\n * @param {object | null | undefined} [props] The properties of the virtual node\n * @param {Array} [children] The children of the\n * virtual node\n * @returns {import('./internal').VNode}\n */\nexport function createElement(type, props, children) {\n\tlet normalizedProps = {},\n\t\tkey,\n\t\tref,\n\t\ti;\n\tfor (i in props) {\n\t\tif (i == 'key') key = props[i];\n\t\telse if (i == 'ref') ref = props[i];\n\t\telse normalizedProps[i] = props[i];\n\t}\n\n\tif (arguments.length > 2) {\n\t\tnormalizedProps.children =\n\t\t\targuments.length > 3 ? slice.call(arguments, 2) : children;\n\t}\n\n\t// If a Component VNode, check for and apply defaultProps\n\t// Note: type may be undefined in development, must never error here.\n\tif (typeof type == 'function' && type.defaultProps != NULL) {\n\t\tfor (i in type.defaultProps) {\n\t\t\tif (normalizedProps[i] === UNDEFINED) {\n\t\t\t\tnormalizedProps[i] = type.defaultProps[i];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn createVNode(type, normalizedProps, key, ref, NULL);\n}\n\n/**\n * Create a VNode (used internally by Preact)\n * @param {import('./internal').VNode[\"type\"]} type The node name or Component\n * Constructor for this virtual node\n * @param {object | string | number | null} props The properties of this virtual node.\n * If this virtual node represents a text node, this is the text of the node (string or number).\n * @param {string | number | null} key The key for this virtual node, used when\n * diffing it against its children\n * @param {import('./internal').VNode[\"ref\"]} ref The ref property that will\n * receive a reference to its created child\n * @returns {import('./internal').VNode}\n */\nexport function createVNode(type, props, key, ref, original) {\n\t// V8 seems to be better at detecting type shapes if the object is allocated from the same call site\n\t// Do not inline into createElement and coerceToVNode!\n\t/** @type {import('./internal').VNode} */\n\tconst vnode = {\n\t\ttype,\n\t\tprops,\n\t\tkey,\n\t\tref,\n\t\t_children: NULL,\n\t\t_parent: NULL,\n\t\t_depth: 0,\n\t\t_dom: NULL,\n\t\t_component: NULL,\n\t\tconstructor: UNDEFINED,\n\t\t_original: original == NULL ? ++vnodeId : original,\n\t\t_index: -1,\n\t\t_flags: 0\n\t};\n\n\t// Only invoke the vnode hook if this was *not* a direct copy:\n\tif (original == NULL && options.vnode != NULL) options.vnode(vnode);\n\n\treturn vnode;\n}\n\nexport function createRef() {\n\treturn { current: NULL };\n}\n\nexport function Fragment(props) {\n\treturn props.children;\n}\n\n/**\n * Check if a the argument is a valid Preact VNode.\n * @param {*} vnode\n * @returns {vnode is VNode}\n */\nexport const isValidElement = vnode =>\n\tvnode != NULL && vnode.constructor === UNDEFINED;\n","import { assign } from './util';\nimport { diff, commitRoot } from './diff/index';\nimport options from './options';\nimport { Fragment } from './create-element';\nimport { MODE_HYDRATE, NULL } from './constants';\n\n/**\n * Base Component class. Provides `setState()` and `forceUpdate()`, which\n * trigger rendering\n * @param {object} props The initial component props\n * @param {object} context The initial context from parent components'\n * getChildContext\n */\nexport function BaseComponent(props, context) {\n\tthis.props = props;\n\tthis.context = context;\n}\n\n/**\n * Update component state and schedule a re-render.\n * @this {import('./internal').Component}\n * @param {object | ((s: object, p: object) => object)} update A hash of state\n * properties to update with new values or a function that given the current\n * state and props returns a new partial state\n * @param {() => void} [callback] A function to be called once component state is\n * updated\n */\nBaseComponent.prototype.setState = function (update, callback) {\n\t// only clone state when copying to nextState the first time.\n\tlet s;\n\tif (this._nextState != NULL && this._nextState != this.state) {\n\t\ts = this._nextState;\n\t} else {\n\t\ts = this._nextState = assign({}, this.state);\n\t}\n\n\tif (typeof update == 'function') {\n\t\t// Some libraries like `immer` mark the current state as readonly,\n\t\t// preventing us from mutating it, so we need to clone it. See #2716\n\t\tupdate = update(assign({}, s), this.props);\n\t}\n\n\tif (update) {\n\t\tassign(s, update);\n\t}\n\n\t// Skip update if updater function returned null\n\tif (update == NULL) return;\n\n\tif (this._vnode) {\n\t\tif (callback) {\n\t\t\tthis._stateCallbacks.push(callback);\n\t\t}\n\t\tenqueueRender(this);\n\t}\n};\n\n/**\n * Immediately perform a synchronous re-render of the component\n * @this {import('./internal').Component}\n * @param {() => void} [callback] A function to be called after component is\n * re-rendered\n */\nBaseComponent.prototype.forceUpdate = function (callback) {\n\tif (this._vnode) {\n\t\t// Set render mode so that we can differentiate where the render request\n\t\t// is coming from. We need this because forceUpdate should never call\n\t\t// shouldComponentUpdate\n\t\tthis._force = true;\n\t\tif (callback) this._renderCallbacks.push(callback);\n\t\tenqueueRender(this);\n\t}\n};\n\n/**\n * Accepts `props` and `state`, and returns a new Virtual DOM tree to build.\n * Virtual DOM is generally constructed via [JSX](https://jasonformat.com/wtf-is-jsx).\n * @param {object} props Props (eg: JSX attributes) received from parent\n * element/component\n * @param {object} state The component's current state\n * @param {object} context Context object, as returned by the nearest\n * ancestor's `getChildContext()`\n * @returns {ComponentChildren | void}\n */\nBaseComponent.prototype.render = Fragment;\n\n/**\n * @param {import('./internal').VNode} vnode\n * @param {number | null} [childIndex]\n */\nexport function getDomSibling(vnode, childIndex) {\n\tif (childIndex == NULL) {\n\t\t// Use childIndex==null as a signal to resume the search from the vnode's sibling\n\t\treturn vnode._parent\n\t\t\t? getDomSibling(vnode._parent, vnode._index + 1)\n\t\t\t: NULL;\n\t}\n\n\tlet sibling;\n\tfor (; childIndex < vnode._children.length; childIndex++) {\n\t\tsibling = vnode._children[childIndex];\n\n\t\tif (sibling != NULL && sibling._dom != NULL) {\n\t\t\t// Since updateParentDomPointers keeps _dom pointer correct,\n\t\t\t// we can rely on _dom to tell us if this subtree contains a\n\t\t\t// rendered DOM node, and what the first rendered DOM node is\n\t\t\treturn sibling._dom;\n\t\t}\n\t}\n\n\t// If we get here, we have not found a DOM node in this vnode's children.\n\t// We must resume from this vnode's sibling (in it's parent _children array)\n\t// Only climb up and search the parent if we aren't searching through a DOM\n\t// VNode (meaning we reached the DOM parent of the original vnode that began\n\t// the search)\n\treturn typeof vnode.type == 'function' ? getDomSibling(vnode) : NULL;\n}\n\n/**\n * Trigger in-place re-rendering of a component.\n * @param {import('./internal').Component} component The component to rerender\n */\nfunction renderComponent(component) {\n\tlet oldVNode = component._vnode,\n\t\toldDom = oldVNode._dom,\n\t\tcommitQueue = [],\n\t\trefQueue = [];\n\n\tif (component._parentDom) {\n\t\tconst newVNode = assign({}, oldVNode);\n\t\tnewVNode._original = oldVNode._original + 1;\n\t\tif (options.vnode) options.vnode(newVNode);\n\n\t\tdiff(\n\t\t\tcomponent._parentDom,\n\t\t\tnewVNode,\n\t\t\toldVNode,\n\t\t\tcomponent._globalContext,\n\t\t\tcomponent._parentDom.namespaceURI,\n\t\t\toldVNode._flags & MODE_HYDRATE ? [oldDom] : NULL,\n\t\t\tcommitQueue,\n\t\t\toldDom == NULL ? getDomSibling(oldVNode) : oldDom,\n\t\t\t!!(oldVNode._flags & MODE_HYDRATE),\n\t\t\trefQueue\n\t\t);\n\n\t\tnewVNode._original = oldVNode._original;\n\t\tnewVNode._parent._children[newVNode._index] = newVNode;\n\t\tcommitRoot(commitQueue, newVNode, refQueue);\n\t\toldVNode._dom = oldVNode._parent = null;\n\n\t\tif (newVNode._dom != oldDom) {\n\t\t\tupdateParentDomPointers(newVNode);\n\t\t}\n\t}\n}\n\n/**\n * @param {import('./internal').VNode} vnode\n */\nfunction updateParentDomPointers(vnode) {\n\tif ((vnode = vnode._parent) != NULL && vnode._component != NULL) {\n\t\tvnode._dom = vnode._component.base = NULL;\n\t\tfor (let i = 0; i < vnode._children.length; i++) {\n\t\t\tlet child = vnode._children[i];\n\t\t\tif (child != NULL && child._dom != NULL) {\n\t\t\t\tvnode._dom = vnode._component.base = child._dom;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn updateParentDomPointers(vnode);\n\t}\n}\n\n/**\n * The render queue\n * @type {Array}\n */\nlet rerenderQueue = [];\n\n/*\n * The value of `Component.debounce` must asynchronously invoke the passed in callback. It is\n * important that contributors to Preact can consistently reason about what calls to `setState`, etc.\n * do, and when their effects will be applied. See the links below for some further reading on designing\n * asynchronous APIs.\n * * [Designing APIs for Asynchrony](https://blog.izs.me/2013/08/designing-apis-for-asynchrony)\n * * [Callbacks synchronous and asynchronous](https://blog.ometer.com/2011/07/24/callbacks-synchronous-and-asynchronous/)\n */\n\nlet prevDebounce;\n\nconst defer =\n\ttypeof Promise == 'function'\n\t\t? Promise.prototype.then.bind(Promise.resolve())\n\t\t: setTimeout;\n\n/**\n * Enqueue a rerender of a component\n * @param {import('./internal').Component} c The component to rerender\n */\nexport function enqueueRender(c) {\n\tif (\n\t\t(!c._dirty &&\n\t\t\t(c._dirty = true) &&\n\t\t\trerenderQueue.push(c) &&\n\t\t\t!process._rerenderCount++) ||\n\t\tprevDebounce != options.debounceRendering\n\t) {\n\t\tprevDebounce = options.debounceRendering;\n\t\t(prevDebounce || defer)(process);\n\t}\n}\n\n/**\n * @param {import('./internal').Component} a\n * @param {import('./internal').Component} b\n */\nconst depthSort = (a, b) => a._vnode._depth - b._vnode._depth;\n\n/** Flush the render queue by rerendering all queued components */\nfunction process() {\n\tlet c,\n\t\tl = 1;\n\n\t// Don't update `renderCount` yet. Keep its value non-zero to prevent unnecessary\n\t// process() calls from getting scheduled while `queue` is still being consumed.\n\twhile (rerenderQueue.length) {\n\t\t// Keep the rerender queue sorted by (depth, insertion order). The queue\n\t\t// will initially be sorted on the first iteration only if it has more than 1 item.\n\t\t//\n\t\t// New items can be added to the queue e.g. when rerendering a provider, so we want to\n\t\t// keep the order from top to bottom with those new items so we can handle them in a\n\t\t// single pass\n\t\tif (rerenderQueue.length > l) {\n\t\t\trerenderQueue.sort(depthSort);\n\t\t}\n\n\t\tc = rerenderQueue.shift();\n\t\tl = rerenderQueue.length;\n\n\t\tif (c._dirty) {\n\t\t\trenderComponent(c);\n\t\t}\n\t}\n\tprocess._rerenderCount = 0;\n}\n\nprocess._rerenderCount = 0;\n","import { IS_NON_DIMENSIONAL, NULL, SVG_NAMESPACE } from '../constants';\nimport options from '../options';\n\nfunction setStyle(style, key, value) {\n\tif (key[0] == '-') {\n\t\tstyle.setProperty(key, value == NULL ? '' : value);\n\t} else if (value == NULL) {\n\t\tstyle[key] = '';\n\t} else if (typeof value != 'number' || IS_NON_DIMENSIONAL.test(key)) {\n\t\tstyle[key] = value;\n\t} else {\n\t\tstyle[key] = value + 'px';\n\t}\n}\n\nconst CAPTURE_REGEX = /(PointerCapture)$|Capture$/i;\n\n// A logical clock to solve issues like https://github.com/preactjs/preact/issues/3927.\n// When the DOM performs an event it leaves micro-ticks in between bubbling up which means that\n// an event can trigger on a newly reated DOM-node while the event bubbles up.\n//\n// Originally inspired by Vue\n// (https://github.com/vuejs/core/blob/caeb8a68811a1b0f79/packages/runtime-dom/src/modules/events.ts#L90-L101),\n// but modified to use a logical clock instead of Date.now() in case event handlers get attached\n// and events get dispatched during the same millisecond.\n//\n// The clock is incremented after each new event dispatch. This allows 1 000 000 new events\n// per second for over 280 years before the value reaches Number.MAX_SAFE_INTEGER (2**53 - 1).\nlet eventClock = 0;\n\n/**\n * Set a property value on a DOM node\n * @param {import('../internal').PreactElement} dom The DOM node to modify\n * @param {string} name The name of the property to set\n * @param {*} value The value to set the property to\n * @param {*} oldValue The old value the property had\n * @param {string} namespace Whether or not this DOM node is an SVG node or not\n */\nexport function setProperty(dom, name, value, oldValue, namespace) {\n\tlet useCapture;\n\n\to: if (name == 'style') {\n\t\tif (typeof value == 'string') {\n\t\t\tdom.style.cssText = value;\n\t\t} else {\n\t\t\tif (typeof oldValue == 'string') {\n\t\t\t\tdom.style.cssText = oldValue = '';\n\t\t\t}\n\n\t\t\tif (oldValue) {\n\t\t\t\tfor (name in oldValue) {\n\t\t\t\t\tif (!(value && name in value)) {\n\t\t\t\t\t\tsetStyle(dom.style, name, '');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (value) {\n\t\t\t\tfor (name in value) {\n\t\t\t\t\tif (!oldValue || value[name] != oldValue[name]) {\n\t\t\t\t\t\tsetStyle(dom.style, name, value[name]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// Benchmark for comparison: https://esbench.com/bench/574c954bdb965b9a00965ac6\n\telse if (name[0] == 'o' && name[1] == 'n') {\n\t\tuseCapture = name != (name = name.replace(CAPTURE_REGEX, '$1'));\n\t\tconst lowerCaseName = name.toLowerCase();\n\n\t\t// Infer correct casing for DOM built-in events:\n\t\tif (lowerCaseName in dom || name == 'onFocusOut' || name == 'onFocusIn')\n\t\t\tname = lowerCaseName.slice(2);\n\t\telse name = name.slice(2);\n\n\t\tif (!dom._listeners) dom._listeners = {};\n\t\tdom._listeners[name + useCapture] = value;\n\n\t\tif (value) {\n\t\t\tif (!oldValue) {\n\t\t\t\tvalue._attached = eventClock;\n\t\t\t\tdom.addEventListener(\n\t\t\t\t\tname,\n\t\t\t\t\tuseCapture ? eventProxyCapture : eventProxy,\n\t\t\t\t\tuseCapture\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tvalue._attached = oldValue._attached;\n\t\t\t}\n\t\t} else {\n\t\t\tdom.removeEventListener(\n\t\t\t\tname,\n\t\t\t\tuseCapture ? eventProxyCapture : eventProxy,\n\t\t\t\tuseCapture\n\t\t\t);\n\t\t}\n\t} else {\n\t\tif (namespace == SVG_NAMESPACE) {\n\t\t\t// Normalize incorrect prop usage for SVG:\n\t\t\t// - xlink:href / xlinkHref --> href (xlink:href was removed from SVG and isn't needed)\n\t\t\t// - className --> class\n\t\t\tname = name.replace(/xlink(H|:h)/, 'h').replace(/sName$/, 's');\n\t\t} else if (\n\t\t\tname != 'width' &&\n\t\t\tname != 'height' &&\n\t\t\tname != 'href' &&\n\t\t\tname != 'list' &&\n\t\t\tname != 'form' &&\n\t\t\t// Default value in browsers is `-1` and an empty string is\n\t\t\t// cast to `0` instead\n\t\t\tname != 'tabIndex' &&\n\t\t\tname != 'download' &&\n\t\t\tname != 'rowSpan' &&\n\t\t\tname != 'colSpan' &&\n\t\t\tname != 'role' &&\n\t\t\tname != 'popover' &&\n\t\t\tname in dom\n\t\t) {\n\t\t\ttry {\n\t\t\t\tdom[name] = value == NULL ? '' : value;\n\t\t\t\t// labelled break is 1b smaller here than a return statement (sorry)\n\t\t\t\tbreak o;\n\t\t\t} catch (e) {}\n\t\t}\n\n\t\t// aria- and data- attributes have no boolean representation.\n\t\t// A `false` value is different from the attribute not being\n\t\t// present, so we can't remove it. For non-boolean aria\n\t\t// attributes we could treat false as a removal, but the\n\t\t// amount of exceptions would cost too many bytes. On top of\n\t\t// that other frameworks generally stringify `false`.\n\n\t\tif (typeof value == 'function') {\n\t\t\t// never serialize functions as attribute values\n\t\t} else if (value != NULL && (value !== false || name[4] == '-')) {\n\t\t\tdom.setAttribute(name, name == 'popover' && value == true ? '' : value);\n\t\t} else {\n\t\t\tdom.removeAttribute(name);\n\t\t}\n\t}\n}\n\n/**\n * Create an event proxy function.\n * @param {boolean} useCapture Is the event handler for the capture phase.\n * @private\n */\nfunction createEventProxy(useCapture) {\n\t/**\n\t * Proxy an event to hooked event handlers\n\t * @param {import('../internal').PreactEvent} e The event object from the browser\n\t * @private\n\t */\n\treturn function (e) {\n\t\tif (this._listeners) {\n\t\t\tconst eventHandler = this._listeners[e.type + useCapture];\n\t\t\tif (e._dispatched == NULL) {\n\t\t\t\te._dispatched = eventClock++;\n\n\t\t\t\t// When `e._dispatched` is smaller than the time when the targeted event\n\t\t\t\t// handler was attached we know we have bubbled up to an element that was added\n\t\t\t\t// during patching the DOM.\n\t\t\t} else if (e._dispatched < eventHandler._attached) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treturn eventHandler(options.event ? options.event(e) : e);\n\t\t}\n\t};\n}\n\nconst eventProxy = createEventProxy(false);\nconst eventProxyCapture = createEventProxy(true);\n","import { enqueueRender } from './component';\nimport { NULL } from './constants';\n\nexport let i = 0;\n\nexport function createContext(defaultValue) {\n\tfunction Context(props) {\n\t\tif (!this.getChildContext) {\n\t\t\t/** @type {Set | null} */\n\t\t\tlet subs = new Set();\n\t\t\tlet ctx = {};\n\t\t\tctx[Context._id] = this;\n\n\t\t\tthis.getChildContext = () => ctx;\n\n\t\t\tthis.componentWillUnmount = () => {\n\t\t\t\tsubs = NULL;\n\t\t\t};\n\n\t\t\tthis.shouldComponentUpdate = function (_props) {\n\t\t\t\t// @ts-expect-error even\n\t\t\t\tif (this.props.value != _props.value) {\n\t\t\t\t\tsubs.forEach(c => {\n\t\t\t\t\t\tc._force = true;\n\t\t\t\t\t\tenqueueRender(c);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tthis.sub = c => {\n\t\t\t\tsubs.add(c);\n\t\t\t\tlet old = c.componentWillUnmount;\n\t\t\t\tc.componentWillUnmount = () => {\n\t\t\t\t\tif (subs) {\n\t\t\t\t\t\tsubs.delete(c);\n\t\t\t\t\t}\n\t\t\t\t\tif (old) old.call(c);\n\t\t\t\t};\n\t\t\t};\n\t\t}\n\n\t\treturn props.children;\n\t}\n\n\tContext._id = '__cC' + i++;\n\tContext._defaultValue = defaultValue;\n\n\t/** @type {import('./internal').FunctionComponent} */\n\tContext.Consumer = (props, contextValue) => {\n\t\treturn props.children(contextValue);\n\t};\n\n\t// we could also get rid of _contextRef entirely\n\tContext.Provider =\n\t\tContext._contextRef =\n\t\tContext.Consumer.contextType =\n\t\t\tContext;\n\n\treturn Context;\n}\n","import { diff, unmount, applyRef } from './index';\nimport { createVNode, Fragment } from '../create-element';\nimport {\n\tEMPTY_OBJ,\n\tEMPTY_ARR,\n\tINSERT_VNODE,\n\tMATCHED,\n\tUNDEFINED,\n\tNULL\n} from '../constants';\nimport { isArray } from '../util';\nimport { getDomSibling } from '../component';\n\n/**\n * @typedef {import('../internal').ComponentChildren} ComponentChildren\n * @typedef {import('../internal').Component} Component\n * @typedef {import('../internal').PreactElement} PreactElement\n * @typedef {import('../internal').VNode} VNode\n */\n\n/**\n * Diff the children of a virtual node\n * @param {PreactElement} parentDom The DOM element whose children are being\n * diffed\n * @param {ComponentChildren[]} renderResult\n * @param {VNode} newParentVNode The new virtual node whose children should be\n * diff'ed against oldParentVNode\n * @param {VNode} oldParentVNode The old virtual node whose children should be\n * diff'ed against newParentVNode\n * @param {object} globalContext The current context object - modified by\n * getChildContext\n * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML)\n * @param {Array} excessDomChildren\n * @param {Array} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {PreactElement} oldDom The current attached DOM element any new dom\n * elements should be placed around. Likely `null` on first render (except when\n * hydrating). Can be a sibling DOM element when diffing Fragments that have\n * siblings. In most cases, it starts out as `oldChildren[0]._dom`.\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n */\nexport function diffChildren(\n\tparentDom,\n\trenderResult,\n\tnewParentVNode,\n\toldParentVNode,\n\tglobalContext,\n\tnamespace,\n\texcessDomChildren,\n\tcommitQueue,\n\toldDom,\n\tisHydrating,\n\trefQueue\n) {\n\tlet i,\n\t\t/** @type {VNode} */\n\t\toldVNode,\n\t\t/** @type {VNode} */\n\t\tchildVNode,\n\t\t/** @type {PreactElement} */\n\t\tnewDom,\n\t\t/** @type {PreactElement} */\n\t\tfirstChildDom;\n\n\t// This is a compression of oldParentVNode!=null && oldParentVNode != EMPTY_OBJ && oldParentVNode._children || EMPTY_ARR\n\t// as EMPTY_OBJ._children should be `undefined`.\n\t/** @type {VNode[]} */\n\tlet oldChildren = (oldParentVNode && oldParentVNode._children) || EMPTY_ARR;\n\n\tlet newChildrenLength = renderResult.length;\n\n\toldDom = constructNewChildrenArray(\n\t\tnewParentVNode,\n\t\trenderResult,\n\t\toldChildren,\n\t\toldDom,\n\t\tnewChildrenLength\n\t);\n\n\tfor (i = 0; i < newChildrenLength; i++) {\n\t\tchildVNode = newParentVNode._children[i];\n\t\tif (childVNode == NULL) continue;\n\n\t\t// At this point, constructNewChildrenArray has assigned _index to be the\n\t\t// matchingIndex for this VNode's oldVNode (or -1 if there is no oldVNode).\n\t\tif (childVNode._index == -1) {\n\t\t\toldVNode = EMPTY_OBJ;\n\t\t} else {\n\t\t\toldVNode = oldChildren[childVNode._index] || EMPTY_OBJ;\n\t\t}\n\n\t\t// Update childVNode._index to its final index\n\t\tchildVNode._index = i;\n\n\t\t// Morph the old element into the new one, but don't append it to the dom yet\n\t\tlet result = diff(\n\t\t\tparentDom,\n\t\t\tchildVNode,\n\t\t\toldVNode,\n\t\t\tglobalContext,\n\t\t\tnamespace,\n\t\t\texcessDomChildren,\n\t\t\tcommitQueue,\n\t\t\toldDom,\n\t\t\tisHydrating,\n\t\t\trefQueue\n\t\t);\n\n\t\t// Adjust DOM nodes\n\t\tnewDom = childVNode._dom;\n\t\tif (childVNode.ref && oldVNode.ref != childVNode.ref) {\n\t\t\tif (oldVNode.ref) {\n\t\t\t\tapplyRef(oldVNode.ref, NULL, childVNode);\n\t\t\t}\n\t\t\trefQueue.push(\n\t\t\t\tchildVNode.ref,\n\t\t\t\tchildVNode._component || newDom,\n\t\t\t\tchildVNode\n\t\t\t);\n\t\t}\n\n\t\tif (firstChildDom == NULL && newDom != NULL) {\n\t\t\tfirstChildDom = newDom;\n\t\t}\n\n\t\tlet shouldPlace = !!(childVNode._flags & INSERT_VNODE);\n\t\tif (shouldPlace || oldVNode._children === childVNode._children) {\n\t\t\toldDom = insert(childVNode, oldDom, parentDom, shouldPlace);\n\t\t} else if (typeof childVNode.type == 'function' && result !== UNDEFINED) {\n\t\t\toldDom = result;\n\t\t} else if (newDom) {\n\t\t\toldDom = newDom.nextSibling;\n\t\t}\n\n\t\t// Unset diffing flags\n\t\tchildVNode._flags &= ~(INSERT_VNODE | MATCHED);\n\t}\n\n\tnewParentVNode._dom = firstChildDom;\n\n\treturn oldDom;\n}\n\n/**\n * @param {VNode} newParentVNode\n * @param {ComponentChildren[]} renderResult\n * @param {VNode[]} oldChildren\n */\nfunction constructNewChildrenArray(\n\tnewParentVNode,\n\trenderResult,\n\toldChildren,\n\toldDom,\n\tnewChildrenLength\n) {\n\t/** @type {number} */\n\tlet i;\n\t/** @type {VNode} */\n\tlet childVNode;\n\t/** @type {VNode} */\n\tlet oldVNode;\n\n\tlet oldChildrenLength = oldChildren.length,\n\t\tremainingOldChildren = oldChildrenLength;\n\n\tlet skew = 0;\n\n\tnewParentVNode._children = new Array(newChildrenLength);\n\tfor (i = 0; i < newChildrenLength; i++) {\n\t\t// @ts-expect-error We are reusing the childVNode variable to hold both the\n\t\t// pre and post normalized childVNode\n\t\tchildVNode = renderResult[i];\n\n\t\tif (\n\t\t\tchildVNode == NULL ||\n\t\t\ttypeof childVNode == 'boolean' ||\n\t\t\ttypeof childVNode == 'function'\n\t\t) {\n\t\t\tnewParentVNode._children[i] = NULL;\n\t\t\tcontinue;\n\t\t}\n\t\t// If this newVNode is being reused (e.g.
    {reuse}{reuse}
    ) in the same diff,\n\t\t// or we are rendering a component (e.g. setState) copy the oldVNodes so it can have\n\t\t// it's own DOM & etc. pointers\n\t\telse if (\n\t\t\ttypeof childVNode == 'string' ||\n\t\t\ttypeof childVNode == 'number' ||\n\t\t\t// eslint-disable-next-line valid-typeof\n\t\t\ttypeof childVNode == 'bigint' ||\n\t\t\tchildVNode.constructor == String\n\t\t) {\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tNULL,\n\t\t\t\tchildVNode,\n\t\t\t\tNULL,\n\t\t\t\tNULL,\n\t\t\t\tNULL\n\t\t\t);\n\t\t} else if (isArray(childVNode)) {\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tFragment,\n\t\t\t\t{ children: childVNode },\n\t\t\t\tNULL,\n\t\t\t\tNULL,\n\t\t\t\tNULL\n\t\t\t);\n\t\t} else if (childVNode.constructor === UNDEFINED && childVNode._depth > 0) {\n\t\t\t// VNode is already in use, clone it. This can happen in the following\n\t\t\t// scenario:\n\t\t\t// const reuse =
    \n\t\t\t//
    {reuse}{reuse}
    \n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tchildVNode.type,\n\t\t\t\tchildVNode.props,\n\t\t\t\tchildVNode.key,\n\t\t\t\tchildVNode.ref ? childVNode.ref : NULL,\n\t\t\t\tchildVNode._original\n\t\t\t);\n\t\t} else {\n\t\t\tnewParentVNode._children[i] = childVNode;\n\t\t}\n\n\t\tconst skewedIndex = i + skew;\n\t\tchildVNode._parent = newParentVNode;\n\t\tchildVNode._depth = newParentVNode._depth + 1;\n\n\t\t// Temporarily store the matchingIndex on the _index property so we can pull\n\t\t// out the oldVNode in diffChildren. We'll override this to the VNode's\n\t\t// final index after using this property to get the oldVNode\n\t\tconst matchingIndex = (childVNode._index = findMatchingIndex(\n\t\t\tchildVNode,\n\t\t\toldChildren,\n\t\t\tskewedIndex,\n\t\t\tremainingOldChildren\n\t\t));\n\n\t\toldVNode = NULL;\n\t\tif (matchingIndex != -1) {\n\t\t\toldVNode = oldChildren[matchingIndex];\n\t\t\tremainingOldChildren--;\n\t\t\tif (oldVNode) {\n\t\t\t\toldVNode._flags |= MATCHED;\n\t\t\t}\n\t\t}\n\n\t\t// Here, we define isMounting for the purposes of the skew diffing\n\t\t// algorithm. Nodes that are unsuspending are considered mounting and we detect\n\t\t// this by checking if oldVNode._original == null\n\t\tconst isMounting = oldVNode == NULL || oldVNode._original == NULL;\n\n\t\tif (isMounting) {\n\t\t\tif (matchingIndex == -1) {\n\t\t\t\t// When the array of children is growing we need to decrease the skew\n\t\t\t\t// as we are adding a new element to the array.\n\t\t\t\t// Example:\n\t\t\t\t// [1, 2, 3] --> [0, 1, 2, 3]\n\t\t\t\t// oldChildren newChildren\n\t\t\t\t//\n\t\t\t\t// The new element is at index 0, so our skew is 0,\n\t\t\t\t// we need to decrease the skew as we are adding a new element.\n\t\t\t\t// The decrease will cause us to compare the element at position 1\n\t\t\t\t// with value 1 with the element at position 0 with value 0.\n\t\t\t\t//\n\t\t\t\t// A linear concept is applied when the array is shrinking,\n\t\t\t\t// if the length is unchanged we can assume that no skew\n\t\t\t\t// changes are needed.\n\t\t\t\tif (newChildrenLength > oldChildrenLength) {\n\t\t\t\t\tskew--;\n\t\t\t\t} else if (newChildrenLength < oldChildrenLength) {\n\t\t\t\t\tskew++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If we are mounting a DOM VNode, mark it for insertion\n\t\t\tif (typeof childVNode.type != 'function') {\n\t\t\t\tchildVNode._flags |= INSERT_VNODE;\n\t\t\t}\n\t\t} else if (matchingIndex != skewedIndex) {\n\t\t\t// When we move elements around i.e. [0, 1, 2] --> [1, 0, 2]\n\t\t\t// --> we diff 1, we find it at position 1 while our skewed index is 0 and our skew is 0\n\t\t\t// we set the skew to 1 as we found an offset.\n\t\t\t// --> we diff 0, we find it at position 0 while our skewed index is at 2 and our skew is 1\n\t\t\t// this makes us increase the skew again.\n\t\t\t// --> we diff 2, we find it at position 2 while our skewed index is at 4 and our skew is 2\n\t\t\t//\n\t\t\t// this becomes an optimization question where currently we see a 1 element offset as an insertion\n\t\t\t// or deletion i.e. we optimize for [0, 1, 2] --> [9, 0, 1, 2]\n\t\t\t// while a more than 1 offset we see as a swap.\n\t\t\t// We could probably build heuristics for having an optimized course of action here as well, but\n\t\t\t// might go at the cost of some bytes.\n\t\t\t//\n\t\t\t// If we wanted to optimize for i.e. only swaps we'd just do the last two code-branches and have\n\t\t\t// only the first item be a re-scouting and all the others fall in their skewed counter-part.\n\t\t\t// We could also further optimize for swaps\n\t\t\tif (matchingIndex == skewedIndex - 1) {\n\t\t\t\tskew--;\n\t\t\t} else if (matchingIndex == skewedIndex + 1) {\n\t\t\t\tskew++;\n\t\t\t} else {\n\t\t\t\tif (matchingIndex > skewedIndex) {\n\t\t\t\t\tskew--;\n\t\t\t\t} else {\n\t\t\t\t\tskew++;\n\t\t\t\t}\n\n\t\t\t\t// Move this VNode's DOM if the original index (matchingIndex) doesn't\n\t\t\t\t// match the new skew index (i + new skew)\n\t\t\t\t// In the former two branches we know that it matches after skewing\n\t\t\t\tchildVNode._flags |= INSERT_VNODE;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Remove remaining oldChildren if there are any. Loop forwards so that as we\n\t// unmount DOM from the beginning of the oldChildren, we can adjust oldDom to\n\t// point to the next child, which needs to be the first DOM node that won't be\n\t// unmounted.\n\tif (remainingOldChildren) {\n\t\tfor (i = 0; i < oldChildrenLength; i++) {\n\t\t\toldVNode = oldChildren[i];\n\t\t\tif (oldVNode != NULL && (oldVNode._flags & MATCHED) == 0) {\n\t\t\t\tif (oldVNode._dom == oldDom) {\n\t\t\t\t\toldDom = getDomSibling(oldVNode);\n\t\t\t\t}\n\n\t\t\t\tunmount(oldVNode, oldVNode);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn oldDom;\n}\n\n/**\n * @param {VNode} parentVNode\n * @param {PreactElement} oldDom\n * @param {PreactElement} parentDom\n * @param {boolean} shouldPlace\n * @returns {PreactElement}\n */\nfunction insert(parentVNode, oldDom, parentDom, shouldPlace) {\n\t// Note: VNodes in nested suspended trees may be missing _children.\n\n\tif (typeof parentVNode.type == 'function') {\n\t\tlet children = parentVNode._children;\n\t\tfor (let i = 0; children && i < children.length; i++) {\n\t\t\tif (children[i]) {\n\t\t\t\t// If we enter this code path on sCU bailout, where we copy\n\t\t\t\t// oldVNode._children to newVNode._children, we need to update the old\n\t\t\t\t// children's _parent pointer to point to the newVNode (parentVNode\n\t\t\t\t// here).\n\t\t\t\tchildren[i]._parent = parentVNode;\n\t\t\t\toldDom = insert(children[i], oldDom, parentDom, shouldPlace);\n\t\t\t}\n\t\t}\n\n\t\treturn oldDom;\n\t} else if (parentVNode._dom != oldDom) {\n\t\tif (shouldPlace) {\n\t\t\tif (oldDom && parentVNode.type && !oldDom.parentNode) {\n\t\t\t\toldDom = getDomSibling(parentVNode);\n\t\t\t}\n\t\t\tparentDom.insertBefore(parentVNode._dom, oldDom || NULL);\n\t\t}\n\t\toldDom = parentVNode._dom;\n\t}\n\n\tdo {\n\t\toldDom = oldDom && oldDom.nextSibling;\n\t} while (oldDom != NULL && oldDom.nodeType == 8);\n\n\treturn oldDom;\n}\n\n/**\n * Flatten and loop through the children of a virtual node\n * @param {ComponentChildren} children The unflattened children of a virtual\n * node\n * @returns {VNode[]}\n */\nexport function toChildArray(children, out) {\n\tout = out || [];\n\tif (children == NULL || typeof children == 'boolean') {\n\t} else if (isArray(children)) {\n\t\tchildren.some(child => {\n\t\t\ttoChildArray(child, out);\n\t\t});\n\t} else {\n\t\tout.push(children);\n\t}\n\treturn out;\n}\n\n/**\n * @param {VNode} childVNode\n * @param {VNode[]} oldChildren\n * @param {number} skewedIndex\n * @param {number} remainingOldChildren\n * @returns {number}\n */\nfunction findMatchingIndex(\n\tchildVNode,\n\toldChildren,\n\tskewedIndex,\n\tremainingOldChildren\n) {\n\tconst key = childVNode.key;\n\tconst type = childVNode.type;\n\tlet oldVNode = oldChildren[skewedIndex];\n\tconst matched = oldVNode != NULL && (oldVNode._flags & MATCHED) == 0;\n\n\t// We only need to perform a search if there are more children\n\t// (remainingOldChildren) to search. However, if the oldVNode we just looked\n\t// at skewedIndex was not already used in this diff, then there must be at\n\t// least 1 other (so greater than 1) remainingOldChildren to attempt to match\n\t// against. So the following condition checks that ensuring\n\t// remainingOldChildren > 1 if the oldVNode is not already used/matched. Else\n\t// if the oldVNode was null or matched, then there could needs to be at least\n\t// 1 (aka `remainingOldChildren > 0`) children to find and compare against.\n\t//\n\t// If there is an unkeyed functional VNode, that isn't a built-in like our Fragment,\n\t// we should not search as we risk re-using state of an unrelated VNode. (reverted for now)\n\tlet shouldSearch =\n\t\t// (typeof type != 'function' || type === Fragment || key) &&\n\t\tremainingOldChildren > (matched ? 1 : 0);\n\n\tif (\n\t\t(oldVNode === NULL && key == null) ||\n\t\t(matched && key == oldVNode.key && type == oldVNode.type)\n\t) {\n\t\treturn skewedIndex;\n\t} else if (shouldSearch) {\n\t\tlet x = skewedIndex - 1;\n\t\tlet y = skewedIndex + 1;\n\t\twhile (x >= 0 || y < oldChildren.length) {\n\t\t\tconst childIndex = x >= 0 ? x-- : y++;\n\t\t\toldVNode = oldChildren[childIndex];\n\t\t\tif (\n\t\t\t\toldVNode != NULL &&\n\t\t\t\t(oldVNode._flags & MATCHED) == 0 &&\n\t\t\t\tkey == oldVNode.key &&\n\t\t\t\ttype == oldVNode.type\n\t\t\t) {\n\t\t\t\treturn childIndex;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn -1;\n}\n","import {\n\tEMPTY_OBJ,\n\tMATH_NAMESPACE,\n\tMODE_HYDRATE,\n\tMODE_SUSPENDED,\n\tNULL,\n\tRESET_MODE,\n\tSVG_NAMESPACE,\n\tUNDEFINED,\n\tXHTML_NAMESPACE\n} from '../constants';\nimport { BaseComponent, getDomSibling } from '../component';\nimport { Fragment } from '../create-element';\nimport { diffChildren } from './children';\nimport { setProperty } from './props';\nimport { assign, isArray, removeNode, slice } from '../util';\nimport options from '../options';\n\n/**\n * @typedef {import('../internal').ComponentChildren} ComponentChildren\n * @typedef {import('../internal').Component} Component\n * @typedef {import('../internal').PreactElement} PreactElement\n * @typedef {import('../internal').VNode} VNode\n */\n\n/**\n * @template {any} T\n * @typedef {import('../internal').Ref} Ref\n */\n\n/**\n * Diff two virtual nodes and apply proper changes to the DOM\n * @param {PreactElement} parentDom The parent of the DOM element\n * @param {VNode} newVNode The new virtual node\n * @param {VNode} oldVNode The old virtual node\n * @param {object} globalContext The current context object. Modified by\n * getChildContext\n * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML)\n * @param {Array} excessDomChildren\n * @param {Array} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {PreactElement} oldDom The current attached DOM element any new dom\n * elements should be placed around. Likely `null` on first render (except when\n * hydrating). Can be a sibling DOM element when diffing Fragments that have\n * siblings. In most cases, it starts out as `oldChildren[0]._dom`.\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n */\nexport function diff(\n\tparentDom,\n\tnewVNode,\n\toldVNode,\n\tglobalContext,\n\tnamespace,\n\texcessDomChildren,\n\tcommitQueue,\n\toldDom,\n\tisHydrating,\n\trefQueue\n) {\n\t/** @type {any} */\n\tlet tmp,\n\t\tnewType = newVNode.type;\n\n\t// When passing through createElement it assigns the object\n\t// constructor as undefined. This to prevent JSON-injection.\n\tif (newVNode.constructor !== UNDEFINED) return NULL;\n\n\t// If the previous diff bailed out, resume creating/hydrating.\n\tif (oldVNode._flags & MODE_SUSPENDED) {\n\t\tisHydrating = !!(oldVNode._flags & MODE_HYDRATE);\n\t\toldDom = newVNode._dom = oldVNode._dom;\n\t\texcessDomChildren = [oldDom];\n\t}\n\n\tif ((tmp = options._diff)) tmp(newVNode);\n\n\touter: if (typeof newType == 'function') {\n\t\ttry {\n\t\t\tlet c, isNew, oldProps, oldState, snapshot, clearProcessingException;\n\t\t\tlet newProps = newVNode.props;\n\t\t\tconst isClassComponent =\n\t\t\t\t'prototype' in newType && newType.prototype.render;\n\n\t\t\t// Necessary for createContext api. Setting this property will pass\n\t\t\t// the context value as `this.context` just for this component.\n\t\t\ttmp = newType.contextType;\n\t\t\tlet provider = tmp && globalContext[tmp._id];\n\t\t\tlet componentContext = tmp\n\t\t\t\t? provider\n\t\t\t\t\t? provider.props.value\n\t\t\t\t\t: tmp._defaultValue\n\t\t\t\t: globalContext;\n\n\t\t\t// Get component and set it to `c`\n\t\t\tif (oldVNode._component) {\n\t\t\t\tc = newVNode._component = oldVNode._component;\n\t\t\t\tclearProcessingException = c._processingException = c._pendingError;\n\t\t\t} else {\n\t\t\t\t// Instantiate the new component\n\t\t\t\tif (isClassComponent) {\n\t\t\t\t\t// @ts-expect-error The check above verifies that newType is suppose to be constructed\n\t\t\t\t\tnewVNode._component = c = new newType(newProps, componentContext); // eslint-disable-line new-cap\n\t\t\t\t} else {\n\t\t\t\t\t// @ts-expect-error Trust me, Component implements the interface we want\n\t\t\t\t\tnewVNode._component = c = new BaseComponent(\n\t\t\t\t\t\tnewProps,\n\t\t\t\t\t\tcomponentContext\n\t\t\t\t\t);\n\t\t\t\t\tc.constructor = newType;\n\t\t\t\t\tc.render = doRender;\n\t\t\t\t}\n\t\t\t\tif (provider) provider.sub(c);\n\n\t\t\t\tif (!c.state) c.state = {};\n\t\t\t\tc._globalContext = globalContext;\n\t\t\t\tisNew = c._dirty = true;\n\t\t\t\tc._renderCallbacks = [];\n\t\t\t\tc._stateCallbacks = [];\n\t\t\t}\n\n\t\t\t// Invoke getDerivedStateFromProps\n\t\t\tif (isClassComponent && c._nextState == NULL) {\n\t\t\t\tc._nextState = c.state;\n\t\t\t}\n\n\t\t\tif (isClassComponent && newType.getDerivedStateFromProps != NULL) {\n\t\t\t\tif (c._nextState == c.state) {\n\t\t\t\t\tc._nextState = assign({}, c._nextState);\n\t\t\t\t}\n\n\t\t\t\tassign(\n\t\t\t\t\tc._nextState,\n\t\t\t\t\tnewType.getDerivedStateFromProps(newProps, c._nextState)\n\t\t\t\t);\n\t\t\t}\n\n\t\t\toldProps = c.props;\n\t\t\toldState = c.state;\n\t\t\tc._vnode = newVNode;\n\n\t\t\t// Invoke pre-render lifecycle methods\n\t\t\tif (isNew) {\n\t\t\t\tif (\n\t\t\t\t\tisClassComponent &&\n\t\t\t\t\tnewType.getDerivedStateFromProps == NULL &&\n\t\t\t\t\tc.componentWillMount != NULL\n\t\t\t\t) {\n\t\t\t\t\tc.componentWillMount();\n\t\t\t\t}\n\n\t\t\t\tif (isClassComponent && c.componentDidMount != NULL) {\n\t\t\t\t\tc._renderCallbacks.push(c.componentDidMount);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (\n\t\t\t\t\tisClassComponent &&\n\t\t\t\t\tnewType.getDerivedStateFromProps == NULL &&\n\t\t\t\t\tnewProps !== oldProps &&\n\t\t\t\t\tc.componentWillReceiveProps != NULL\n\t\t\t\t) {\n\t\t\t\t\tc.componentWillReceiveProps(newProps, componentContext);\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\tnewVNode._original == oldVNode._original ||\n\t\t\t\t\t(!c._force &&\n\t\t\t\t\t\tc.shouldComponentUpdate != NULL &&\n\t\t\t\t\t\tc.shouldComponentUpdate(\n\t\t\t\t\t\t\tnewProps,\n\t\t\t\t\t\t\tc._nextState,\n\t\t\t\t\t\t\tcomponentContext\n\t\t\t\t\t\t) === false)\n\t\t\t\t) {\n\t\t\t\t\t// More info about this here: https://gist.github.com/JoviDeCroock/bec5f2ce93544d2e6070ef8e0036e4e8\n\t\t\t\t\tif (newVNode._original != oldVNode._original) {\n\t\t\t\t\t\t// When we are dealing with a bail because of sCU we have to update\n\t\t\t\t\t\t// the props, state and dirty-state.\n\t\t\t\t\t\t// when we are dealing with strict-equality we don't as the child could still\n\t\t\t\t\t\t// be dirtied see #3883\n\t\t\t\t\t\tc.props = newProps;\n\t\t\t\t\t\tc.state = c._nextState;\n\t\t\t\t\t\tc._dirty = false;\n\t\t\t\t\t}\n\n\t\t\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t\t\t\tnewVNode._children = oldVNode._children;\n\t\t\t\t\tnewVNode._children.some(vnode => {\n\t\t\t\t\t\tif (vnode) vnode._parent = newVNode;\n\t\t\t\t\t});\n\n\t\t\t\t\tfor (let i = 0; i < c._stateCallbacks.length; i++) {\n\t\t\t\t\t\tc._renderCallbacks.push(c._stateCallbacks[i]);\n\t\t\t\t\t}\n\t\t\t\t\tc._stateCallbacks = [];\n\n\t\t\t\t\tif (c._renderCallbacks.length) {\n\t\t\t\t\t\tcommitQueue.push(c);\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak outer;\n\t\t\t\t}\n\n\t\t\t\tif (c.componentWillUpdate != NULL) {\n\t\t\t\t\tc.componentWillUpdate(newProps, c._nextState, componentContext);\n\t\t\t\t}\n\n\t\t\t\tif (isClassComponent && c.componentDidUpdate != NULL) {\n\t\t\t\t\tc._renderCallbacks.push(() => {\n\t\t\t\t\t\tc.componentDidUpdate(oldProps, oldState, snapshot);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tc.context = componentContext;\n\t\t\tc.props = newProps;\n\t\t\tc._parentDom = parentDom;\n\t\t\tc._force = false;\n\n\t\t\tlet renderHook = options._render,\n\t\t\t\tcount = 0;\n\t\t\tif (isClassComponent) {\n\t\t\t\tc.state = c._nextState;\n\t\t\t\tc._dirty = false;\n\n\t\t\t\tif (renderHook) renderHook(newVNode);\n\n\t\t\t\ttmp = c.render(c.props, c.state, c.context);\n\n\t\t\t\tfor (let i = 0; i < c._stateCallbacks.length; i++) {\n\t\t\t\t\tc._renderCallbacks.push(c._stateCallbacks[i]);\n\t\t\t\t}\n\t\t\t\tc._stateCallbacks = [];\n\t\t\t} else {\n\t\t\t\tdo {\n\t\t\t\t\tc._dirty = false;\n\t\t\t\t\tif (renderHook) renderHook(newVNode);\n\n\t\t\t\t\ttmp = c.render(c.props, c.state, c.context);\n\n\t\t\t\t\t// Handle setState called in render, see #2553\n\t\t\t\t\tc.state = c._nextState;\n\t\t\t\t} while (c._dirty && ++count < 25);\n\t\t\t}\n\n\t\t\t// Handle setState called in render, see #2553\n\t\t\tc.state = c._nextState;\n\n\t\t\tif (c.getChildContext != NULL) {\n\t\t\t\tglobalContext = assign(assign({}, globalContext), c.getChildContext());\n\t\t\t}\n\n\t\t\tif (isClassComponent && !isNew && c.getSnapshotBeforeUpdate != NULL) {\n\t\t\t\tsnapshot = c.getSnapshotBeforeUpdate(oldProps, oldState);\n\t\t\t}\n\n\t\t\tlet isTopLevelFragment =\n\t\t\t\ttmp != NULL && tmp.type === Fragment && tmp.key == NULL;\n\t\t\tlet renderResult = tmp;\n\n\t\t\tif (isTopLevelFragment) {\n\t\t\t\trenderResult = cloneNode(tmp.props.children);\n\t\t\t}\n\n\t\t\toldDom = diffChildren(\n\t\t\t\tparentDom,\n\t\t\t\tisArray(renderResult) ? renderResult : [renderResult],\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tnamespace,\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\toldDom,\n\t\t\t\tisHydrating,\n\t\t\t\trefQueue\n\t\t\t);\n\n\t\t\tc.base = newVNode._dom;\n\n\t\t\t// We successfully rendered this VNode, unset any stored hydration/bailout state:\n\t\t\tnewVNode._flags &= RESET_MODE;\n\n\t\t\tif (c._renderCallbacks.length) {\n\t\t\t\tcommitQueue.push(c);\n\t\t\t}\n\n\t\t\tif (clearProcessingException) {\n\t\t\t\tc._pendingError = c._processingException = NULL;\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tnewVNode._original = NULL;\n\t\t\t// if hydrating or creating initial tree, bailout preserves DOM:\n\t\t\tif (isHydrating || excessDomChildren != NULL) {\n\t\t\t\tif (e.then) {\n\t\t\t\t\tnewVNode._flags |= isHydrating\n\t\t\t\t\t\t? MODE_HYDRATE | MODE_SUSPENDED\n\t\t\t\t\t\t: MODE_SUSPENDED;\n\n\t\t\t\t\twhile (oldDom && oldDom.nodeType == 8 && oldDom.nextSibling) {\n\t\t\t\t\t\toldDom = oldDom.nextSibling;\n\t\t\t\t\t}\n\n\t\t\t\t\texcessDomChildren[excessDomChildren.indexOf(oldDom)] = NULL;\n\t\t\t\t\tnewVNode._dom = oldDom;\n\t\t\t\t} else {\n\t\t\t\t\tfor (let i = excessDomChildren.length; i--; ) {\n\t\t\t\t\t\tremoveNode(excessDomChildren[i]);\n\t\t\t\t\t}\n\t\t\t\t\tmarkAsForce(newVNode);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t\t\tnewVNode._children = oldVNode._children;\n\t\t\t\tif (!e.then) markAsForce(newVNode);\n\t\t\t}\n\t\t\toptions._catchError(e, newVNode, oldVNode);\n\t\t}\n\t} else if (\n\t\texcessDomChildren == NULL &&\n\t\tnewVNode._original == oldVNode._original\n\t) {\n\t\tnewVNode._children = oldVNode._children;\n\t\tnewVNode._dom = oldVNode._dom;\n\t} else {\n\t\toldDom = newVNode._dom = diffElementNodes(\n\t\t\toldVNode._dom,\n\t\t\tnewVNode,\n\t\t\toldVNode,\n\t\t\tglobalContext,\n\t\t\tnamespace,\n\t\t\texcessDomChildren,\n\t\t\tcommitQueue,\n\t\t\tisHydrating,\n\t\t\trefQueue\n\t\t);\n\t}\n\n\tif ((tmp = options.diffed)) tmp(newVNode);\n\n\treturn newVNode._flags & MODE_SUSPENDED ? undefined : oldDom;\n}\n\nfunction markAsForce(vnode) {\n\tif (vnode && vnode._component) vnode._component._force = true;\n\tif (vnode && vnode._children) vnode._children.forEach(markAsForce);\n}\n\n/**\n * @param {Array} commitQueue List of components\n * which have callbacks to invoke in commitRoot\n * @param {VNode} root\n */\nexport function commitRoot(commitQueue, root, refQueue) {\n\tfor (let i = 0; i < refQueue.length; i++) {\n\t\tapplyRef(refQueue[i], refQueue[++i], refQueue[++i]);\n\t}\n\n\tif (options._commit) options._commit(root, commitQueue);\n\n\tcommitQueue.some(c => {\n\t\ttry {\n\t\t\t// @ts-expect-error Reuse the commitQueue variable here so the type changes\n\t\t\tcommitQueue = c._renderCallbacks;\n\t\t\tc._renderCallbacks = [];\n\t\t\tcommitQueue.some(cb => {\n\t\t\t\t// @ts-expect-error See above comment on commitQueue\n\t\t\t\tcb.call(c);\n\t\t\t});\n\t\t} catch (e) {\n\t\t\toptions._catchError(e, c._vnode);\n\t\t}\n\t});\n}\n\nfunction cloneNode(node) {\n\tif (\n\t\ttypeof node != 'object' ||\n\t\tnode == NULL ||\n\t\t(node._depth && node._depth > 0)\n\t) {\n\t\treturn node;\n\t}\n\n\tif (isArray(node)) {\n\t\treturn node.map(cloneNode);\n\t}\n\n\treturn assign({}, node);\n}\n\n/**\n * Diff two virtual nodes representing DOM element\n * @param {PreactElement} dom The DOM element representing the virtual nodes\n * being diffed\n * @param {VNode} newVNode The new virtual node\n * @param {VNode} oldVNode The old virtual node\n * @param {object} globalContext The current context object\n * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML)\n * @param {Array} excessDomChildren\n * @param {Array} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n * @returns {PreactElement}\n */\nfunction diffElementNodes(\n\tdom,\n\tnewVNode,\n\toldVNode,\n\tglobalContext,\n\tnamespace,\n\texcessDomChildren,\n\tcommitQueue,\n\tisHydrating,\n\trefQueue\n) {\n\tlet oldProps = oldVNode.props || EMPTY_OBJ;\n\tlet newProps = newVNode.props;\n\tlet nodeType = /** @type {string} */ (newVNode.type);\n\t/** @type {any} */\n\tlet i;\n\t/** @type {{ __html?: string }} */\n\tlet newHtml;\n\t/** @type {{ __html?: string }} */\n\tlet oldHtml;\n\t/** @type {ComponentChildren} */\n\tlet newChildren;\n\tlet value;\n\tlet inputValue;\n\tlet checked;\n\n\t// Tracks entering and exiting namespaces when descending through the tree.\n\tif (nodeType == 'svg') namespace = SVG_NAMESPACE;\n\telse if (nodeType == 'math') namespace = MATH_NAMESPACE;\n\telse if (!namespace) namespace = XHTML_NAMESPACE;\n\n\tif (excessDomChildren != NULL) {\n\t\tfor (i = 0; i < excessDomChildren.length; i++) {\n\t\t\tvalue = excessDomChildren[i];\n\n\t\t\t// if newVNode matches an element in excessDomChildren or the `dom`\n\t\t\t// argument matches an element in excessDomChildren, remove it from\n\t\t\t// excessDomChildren so it isn't later removed in diffChildren\n\t\t\tif (\n\t\t\t\tvalue &&\n\t\t\t\t'setAttribute' in value == !!nodeType &&\n\t\t\t\t(nodeType ? value.localName == nodeType : value.nodeType == 3)\n\t\t\t) {\n\t\t\t\tdom = value;\n\t\t\t\texcessDomChildren[i] = NULL;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (dom == NULL) {\n\t\tif (nodeType == NULL) {\n\t\t\treturn document.createTextNode(newProps);\n\t\t}\n\n\t\tdom = document.createElementNS(\n\t\t\tnamespace,\n\t\t\tnodeType,\n\t\t\tnewProps.is && newProps\n\t\t);\n\n\t\t// we are creating a new node, so we can assume this is a new subtree (in\n\t\t// case we are hydrating), this deopts the hydrate\n\t\tif (isHydrating) {\n\t\t\tif (options._hydrationMismatch)\n\t\t\t\toptions._hydrationMismatch(newVNode, excessDomChildren);\n\t\t\tisHydrating = false;\n\t\t}\n\t\t// we created a new parent, so none of the previously attached children can be reused:\n\t\texcessDomChildren = NULL;\n\t}\n\n\tif (nodeType == NULL) {\n\t\t// During hydration, we still have to split merged text from SSR'd HTML.\n\t\tif (oldProps !== newProps && (!isHydrating || dom.data != newProps)) {\n\t\t\tdom.data = newProps;\n\t\t}\n\t} else {\n\t\t// If excessDomChildren was not null, repopulate it with the current element's children:\n\t\texcessDomChildren = excessDomChildren && slice.call(dom.childNodes);\n\n\t\t// If we are in a situation where we are not hydrating but are using\n\t\t// existing DOM (e.g. replaceNode) we should read the existing DOM\n\t\t// attributes to diff them\n\t\tif (!isHydrating && excessDomChildren != NULL) {\n\t\t\toldProps = {};\n\t\t\tfor (i = 0; i < dom.attributes.length; i++) {\n\t\t\t\tvalue = dom.attributes[i];\n\t\t\t\toldProps[value.name] = value.value;\n\t\t\t}\n\t\t}\n\n\t\tfor (i in oldProps) {\n\t\t\tvalue = oldProps[i];\n\t\t\tif (i == 'children') {\n\t\t\t} else if (i == 'dangerouslySetInnerHTML') {\n\t\t\t\toldHtml = value;\n\t\t\t} else if (!(i in newProps)) {\n\t\t\t\tif (\n\t\t\t\t\t(i == 'value' && 'defaultValue' in newProps) ||\n\t\t\t\t\t(i == 'checked' && 'defaultChecked' in newProps)\n\t\t\t\t) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tsetProperty(dom, i, NULL, value, namespace);\n\t\t\t}\n\t\t}\n\n\t\t// During hydration, props are not diffed at all (including dangerouslySetInnerHTML)\n\t\t// @TODO we should warn in debug mode when props don't match here.\n\t\tfor (i in newProps) {\n\t\t\tvalue = newProps[i];\n\t\t\tif (i == 'children') {\n\t\t\t\tnewChildren = value;\n\t\t\t} else if (i == 'dangerouslySetInnerHTML') {\n\t\t\t\tnewHtml = value;\n\t\t\t} else if (i == 'value') {\n\t\t\t\tinputValue = value;\n\t\t\t} else if (i == 'checked') {\n\t\t\t\tchecked = value;\n\t\t\t} else if (\n\t\t\t\t(!isHydrating || typeof value == 'function') &&\n\t\t\t\toldProps[i] !== value\n\t\t\t) {\n\t\t\t\tsetProperty(dom, i, value, oldProps[i], namespace);\n\t\t\t}\n\t\t}\n\n\t\t// If the new vnode didn't have dangerouslySetInnerHTML, diff its children\n\t\tif (newHtml) {\n\t\t\t// Avoid re-applying the same '__html' if it did not changed between re-render\n\t\t\tif (\n\t\t\t\t!isHydrating &&\n\t\t\t\t(!oldHtml ||\n\t\t\t\t\t(newHtml.__html != oldHtml.__html && newHtml.__html != dom.innerHTML))\n\t\t\t) {\n\t\t\t\tdom.innerHTML = newHtml.__html;\n\t\t\t}\n\n\t\t\tnewVNode._children = [];\n\t\t} else {\n\t\t\tif (oldHtml) dom.innerHTML = '';\n\n\t\t\tdiffChildren(\n\t\t\t\t// @ts-expect-error\n\t\t\t\tnewVNode.type == 'template' ? dom.content : dom,\n\t\t\t\tisArray(newChildren) ? newChildren : [newChildren],\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tnodeType == 'foreignObject' ? XHTML_NAMESPACE : namespace,\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\texcessDomChildren\n\t\t\t\t\t? excessDomChildren[0]\n\t\t\t\t\t: oldVNode._children && getDomSibling(oldVNode, 0),\n\t\t\t\tisHydrating,\n\t\t\t\trefQueue\n\t\t\t);\n\n\t\t\t// Remove children that are not part of any vnode.\n\t\t\tif (excessDomChildren != NULL) {\n\t\t\t\tfor (i = excessDomChildren.length; i--; ) {\n\t\t\t\t\tremoveNode(excessDomChildren[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// As above, don't diff props during hydration\n\t\tif (!isHydrating) {\n\t\t\ti = 'value';\n\t\t\tif (nodeType == 'progress' && inputValue == NULL) {\n\t\t\t\tdom.removeAttribute('value');\n\t\t\t} else if (\n\t\t\t\tinputValue != UNDEFINED &&\n\t\t\t\t// #2756 For the -element the initial value is 0,\n\t\t\t\t// despite the attribute not being present. When the attribute\n\t\t\t\t// is missing the progress bar is treated as indeterminate.\n\t\t\t\t// To fix that we'll always update it when it is 0 for progress elements\n\t\t\t\t(inputValue !== dom[i] ||\n\t\t\t\t\t(nodeType == 'progress' && !inputValue) ||\n\t\t\t\t\t// This is only for IE 11 to fix value not being updated.\n\t\t\t\t\t// To avoid a stale select value we need to set the option.value\n\t\t\t\t\t// again, which triggers IE11 to re-evaluate the select value\n\t\t\t\t\t(nodeType == 'option' && inputValue != oldProps[i]))\n\t\t\t) {\n\t\t\t\tsetProperty(dom, i, inputValue, oldProps[i], namespace);\n\t\t\t}\n\n\t\t\ti = 'checked';\n\t\t\tif (checked != UNDEFINED && checked != dom[i]) {\n\t\t\t\tsetProperty(dom, i, checked, oldProps[i], namespace);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dom;\n}\n\n/**\n * Invoke or update a ref, depending on whether it is a function or object ref.\n * @param {Ref & { _unmount?: unknown }} ref\n * @param {any} value\n * @param {VNode} vnode\n */\nexport function applyRef(ref, value, vnode) {\n\ttry {\n\t\tif (typeof ref == 'function') {\n\t\t\tlet hasRefUnmount = typeof ref._unmount == 'function';\n\t\t\tif (hasRefUnmount) {\n\t\t\t\t// @ts-ignore TS doesn't like moving narrowing checks into variables\n\t\t\t\tref._unmount();\n\t\t\t}\n\n\t\t\tif (!hasRefUnmount || value != NULL) {\n\t\t\t\t// Store the cleanup function on the function\n\t\t\t\t// instance object itself to avoid shape\n\t\t\t\t// transitioning vnode\n\t\t\t\tref._unmount = ref(value);\n\t\t\t}\n\t\t} else ref.current = value;\n\t} catch (e) {\n\t\toptions._catchError(e, vnode);\n\t}\n}\n\n/**\n * Unmount a virtual node from the tree and apply DOM changes\n * @param {VNode} vnode The virtual node to unmount\n * @param {VNode} parentVNode The parent of the VNode that initiated the unmount\n * @param {boolean} [skipRemove] Flag that indicates that a parent node of the\n * current element is already detached from the DOM.\n */\nexport function unmount(vnode, parentVNode, skipRemove) {\n\tlet r;\n\tif (options.unmount) options.unmount(vnode);\n\n\tif ((r = vnode.ref)) {\n\t\tif (!r.current || r.current == vnode._dom) {\n\t\t\tapplyRef(r, NULL, parentVNode);\n\t\t}\n\t}\n\n\tif ((r = vnode._component) != NULL) {\n\t\tif (r.componentWillUnmount) {\n\t\t\ttry {\n\t\t\t\tr.componentWillUnmount();\n\t\t\t} catch (e) {\n\t\t\t\toptions._catchError(e, parentVNode);\n\t\t\t}\n\t\t}\n\n\t\tr.base = r._parentDom = NULL;\n\t}\n\n\tif ((r = vnode._children)) {\n\t\tfor (let i = 0; i < r.length; i++) {\n\t\t\tif (r[i]) {\n\t\t\t\tunmount(\n\t\t\t\t\tr[i],\n\t\t\t\t\tparentVNode,\n\t\t\t\t\tskipRemove || typeof vnode.type != 'function'\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!skipRemove) {\n\t\tremoveNode(vnode._dom);\n\t}\n\n\tvnode._component = vnode._parent = vnode._dom = UNDEFINED;\n}\n\n/** The `.render()` method for a PFC backing instance. */\nfunction doRender(props, state, context) {\n\treturn this.constructor(props, context);\n}\n","import { EMPTY_OBJ, NULL } from './constants';\nimport { commitRoot, diff } from './diff/index';\nimport { createElement, Fragment } from './create-element';\nimport options from './options';\nimport { slice } from './util';\n\n/**\n * Render a Preact virtual node into a DOM element\n * @param {import('./internal').ComponentChild} vnode The virtual node to render\n * @param {import('./internal').PreactElement} parentDom The DOM element to render into\n * @param {import('./internal').PreactElement | object} [replaceNode] Optional: Attempt to re-use an\n * existing DOM tree rooted at `replaceNode`\n */\nexport function render(vnode, parentDom, replaceNode) {\n\t// https://github.com/preactjs/preact/issues/3794\n\tif (parentDom == document) {\n\t\tparentDom = document.documentElement;\n\t}\n\n\tif (options._root) options._root(vnode, parentDom);\n\n\t// We abuse the `replaceNode` parameter in `hydrate()` to signal if we are in\n\t// hydration mode or not by passing the `hydrate` function instead of a DOM\n\t// element..\n\tlet isHydrating = typeof replaceNode == 'function';\n\n\t// To be able to support calling `render()` multiple times on the same\n\t// DOM node, we need to obtain a reference to the previous tree. We do\n\t// this by assigning a new `_children` property to DOM nodes which points\n\t// to the last rendered tree. By default this property is not present, which\n\t// means that we are mounting a new tree for the first time.\n\tlet oldVNode = isHydrating\n\t\t? NULL\n\t\t: (replaceNode && replaceNode._children) || parentDom._children;\n\n\tvnode = ((!isHydrating && replaceNode) || parentDom)._children =\n\t\tcreateElement(Fragment, NULL, [vnode]);\n\n\t// List of effects that need to be called after diffing.\n\tlet commitQueue = [],\n\t\trefQueue = [];\n\tdiff(\n\t\tparentDom,\n\t\t// Determine the new vnode tree and store it on the DOM element on\n\t\t// our custom `_children` property.\n\t\tvnode,\n\t\toldVNode || EMPTY_OBJ,\n\t\tEMPTY_OBJ,\n\t\tparentDom.namespaceURI,\n\t\t!isHydrating && replaceNode\n\t\t\t? [replaceNode]\n\t\t\t: oldVNode\n\t\t\t\t? NULL\n\t\t\t\t: parentDom.firstChild\n\t\t\t\t\t? slice.call(parentDom.childNodes)\n\t\t\t\t\t: NULL,\n\t\tcommitQueue,\n\t\t!isHydrating && replaceNode\n\t\t\t? replaceNode\n\t\t\t: oldVNode\n\t\t\t\t? oldVNode._dom\n\t\t\t\t: parentDom.firstChild,\n\t\tisHydrating,\n\t\trefQueue\n\t);\n\n\t// Flush all queued effects\n\tcommitRoot(commitQueue, vnode, refQueue);\n}\n\n/**\n * Update an existing DOM element with data from a Preact virtual node\n * @param {import('./internal').ComponentChild} vnode The virtual node to render\n * @param {import('./internal').PreactElement} parentDom The DOM element to update\n */\nexport function hydrate(vnode, parentDom) {\n\trender(vnode, parentDom, hydrate);\n}\n","import { NULL } from '../constants';\n\n/**\n * Find the closest error boundary to a thrown error and call it\n * @param {object} error The thrown value\n * @param {import('../internal').VNode} vnode The vnode that threw the error that was caught (except\n * for unmounting when this parameter is the highest parent that was being\n * unmounted)\n * @param {import('../internal').VNode} [oldVNode]\n * @param {import('../internal').ErrorInfo} [errorInfo]\n */\nexport function _catchError(error, vnode, oldVNode, errorInfo) {\n\t/** @type {import('../internal').Component} */\n\tlet component,\n\t\t/** @type {import('../internal').ComponentType} */\n\t\tctor,\n\t\t/** @type {boolean} */\n\t\thandled;\n\n\tfor (; (vnode = vnode._parent); ) {\n\t\tif ((component = vnode._component) && !component._processingException) {\n\t\t\ttry {\n\t\t\t\tctor = component.constructor;\n\n\t\t\t\tif (ctor && ctor.getDerivedStateFromError != NULL) {\n\t\t\t\t\tcomponent.setState(ctor.getDerivedStateFromError(error));\n\t\t\t\t\thandled = component._dirty;\n\t\t\t\t}\n\n\t\t\t\tif (component.componentDidCatch != NULL) {\n\t\t\t\t\tcomponent.componentDidCatch(error, errorInfo || {});\n\t\t\t\t\thandled = component._dirty;\n\t\t\t\t}\n\n\t\t\t\t// This is an error boundary. Mark it as having bailed out, and whether it was mid-hydration.\n\t\t\t\tif (handled) {\n\t\t\t\t\treturn (component._pendingError = component);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\terror = e;\n\t\t\t}\n\t\t}\n\t}\n\n\tthrow error;\n}\n","import { assign, slice } from './util';\nimport { createVNode } from './create-element';\nimport { NULL, UNDEFINED } from './constants';\n\n/**\n * Clones the given VNode, optionally adding attributes/props and replacing its\n * children.\n * @param {import('./internal').VNode} vnode The virtual DOM element to clone\n * @param {object} props Attributes/props to add when cloning\n * @param {Array} rest Any additional arguments will be used\n * as replacement children.\n * @returns {import('./internal').VNode}\n */\nexport function cloneElement(vnode, props, children) {\n\tlet normalizedProps = assign({}, vnode.props),\n\t\tkey,\n\t\tref,\n\t\ti;\n\n\tlet defaultProps;\n\n\tif (vnode.type && vnode.type.defaultProps) {\n\t\tdefaultProps = vnode.type.defaultProps;\n\t}\n\n\tfor (i in props) {\n\t\tif (i == 'key') key = props[i];\n\t\telse if (i == 'ref') ref = props[i];\n\t\telse if (props[i] === UNDEFINED && defaultProps != UNDEFINED) {\n\t\t\tnormalizedProps[i] = defaultProps[i];\n\t\t} else {\n\t\t\tnormalizedProps[i] = props[i];\n\t\t}\n\t}\n\n\tif (arguments.length > 2) {\n\t\tnormalizedProps.children =\n\t\t\targuments.length > 3 ? slice.call(arguments, 2) : children;\n\t}\n\n\treturn createVNode(\n\t\tvnode.type,\n\t\tnormalizedProps,\n\t\tkey || vnode.key,\n\t\tref || vnode.ref,\n\t\tNULL\n\t);\n}\n"],"names":["slice","options","vnodeId","isValidElement","rerenderQueue","prevDebounce","defer","depthSort","CAPTURE_REGEX","eventClock","eventProxy","eventProxyCapture","i","SVG_NAMESPACE","XHTML_NAMESPACE","NULL","UNDEFINED","undefined","EMPTY_OBJ","EMPTY_ARR","IS_NON_DIMENSIONAL","isArray","Array","assign","obj","props","removeNode","node","parentNode","removeChild","createElement","type","children","key","ref","normalizedProps","arguments","length","call","defaultProps","createVNode","original","vnode","__k","__","__b","__e","__c","constructor","__v","__i","__u","Fragment","BaseComponent","context","this","getDomSibling","childIndex","sibling","updateParentDomPointers","child","base","enqueueRender","c","__d","push","process","__r","debounceRendering","component","newVNode","oldVNode","oldDom","commitQueue","refQueue","l","sort","shift","__P","diff","__n","namespaceURI","commitRoot","diffChildren","parentDom","renderResult","newParentVNode","oldParentVNode","globalContext","namespace","excessDomChildren","isHydrating","childVNode","newDom","firstChildDom","result","shouldPlace","oldChildren","newChildrenLength","constructNewChildrenArray","applyRef","insert","nextSibling","skewedIndex","matchingIndex","oldChildrenLength","remainingOldChildren","skew","String","findMatchingIndex","unmount","parentVNode","insertBefore","nodeType","x","y","matched","setStyle","style","value","setProperty","test","dom","name","oldValue","useCapture","lowerCaseName","o","cssText","replace","toLowerCase","_attached","addEventListener","removeEventListener","e","removeAttribute","setAttribute","createEventProxy","eventHandler","_dispatched","event","tmp","isNew","oldProps","oldState","snapshot","clearProcessingException","newProps","isClassComponent","provider","componentContext","renderHook","count","newType","outer","prototype","render","contextType","__E","doRender","sub","state","__h","_sb","__s","getDerivedStateFromProps","componentWillMount","componentDidMount","componentWillReceiveProps","shouldComponentUpdate","some","componentWillUpdate","componentDidUpdate","getChildContext","getSnapshotBeforeUpdate","cloneNode","then","MODE_HYDRATE","indexOf","markAsForce","diffElementNodes","diffed","forEach","root","cb","map","newHtml","oldHtml","newChildren","inputValue","checked","localName","document","createTextNode","createElementNS","is","__m","data","childNodes","attributes","__html","innerHTML","content","hasRefUnmount","current","skipRemove","r","componentWillUnmount","replaceNode","documentElement","firstChild","error","errorInfo","ctor","handled","getDerivedStateFromError","setState","componentDidCatch","update","callback","s","forceUpdate","Promise","bind","resolve","setTimeout","a","b","defaultValue","Context","subs","ctx","Set","_props","add","old","delete","Provider","__l","Consumer","contextValue","hydrate","toChildArray","out"],"mappings":"oOA2BaA,EChBPC,ECPFC,EA2FSC,ECoFTC,EAWAC,EAEEC,EA0BAC,EC3MAC,EAaFC,EA+IEC,EACAC,ECzKKC,ECSEC,EAAgB,6BAChBC,EAAkB,+BAGlBC,EAAO,KACPC,OAAYC,EACZC,EAAgC,CAAG,EACnCC,EAAY,GACZC,EACZ,oENnBYC,EAAUC,MAAMD,QAStB,SAASE,EAAOC,EAAKC,GAE3B,IAAK,IAAIb,KAAKa,EAAOD,EAAIZ,GAAKa,EAAMb,GACpC,OAA6BY,CAC9B,CAQgB,SAAAE,EAAWC,GACtBA,GAAQA,EAAKC,YAAYD,EAAKC,WAAWC,YAAYF,EAC1D,CEVgB,SAAAG,EAAcC,EAAMN,EAAOO,GAC1C,IACCC,EACAC,EACAtB,EAHGuB,EAAkB,CAAA,EAItB,IAAKvB,KAAKa,EACA,OAALb,EAAYqB,EAAMR,EAAMb,GACd,OAALA,EAAYsB,EAAMT,EAAMb,GAC5BuB,EAAgBvB,GAAKa,EAAMb,GAUjC,GAPIwB,UAAUC,OAAS,IACtBF,EAAgBH,SACfI,UAAUC,OAAS,EAAIrC,EAAMsC,KAAKF,UAAW,GAAKJ,GAKjC,mBAARD,GAAsBA,EAAKQ,cAAgBxB,EACrD,IAAKH,KAAKmB,EAAKQ,aACVJ,EAAgBvB,KAAOI,IAC1BmB,EAAgBvB,GAAKmB,EAAKQ,aAAa3B,IAK1C,OAAO4B,EAAYT,EAAMI,EAAiBF,EAAKC,EAAKnB,EACrD,CAcgB,SAAAyB,EAAYT,EAAMN,EAAOQ,EAAKC,EAAKO,GAIlD,IAAMC,EAAQ,CACbX,KAAAA,EACAN,MAAAA,EACAQ,IAAAA,EACAC,IAAAA,EACAS,IAAW5B,EACX6B,GAAS7B,EACT8B,IAAQ,EACRC,IAAM/B,EACNgC,IAAYhC,EACZiC,YAAahC,EACbiC,IAAWR,GAAY1B,IAASb,EAAUuC,EAC1CS,KAAS,EACTC,IAAQ,GAMT,OAFIV,GAAY1B,GAAQd,EAAQyC,OAAS3B,GAAMd,EAAQyC,MAAMA,GAEtDA,CACR,CAMgB,SAAAU,EAAS3B,GACxB,OAAOA,EAAMO,QACd,CC3EO,SAASqB,EAAc5B,EAAO6B,GACpCC,KAAK9B,MAAQA,EACb8B,KAAKD,QAAUA,CAChB,UA0EgBE,EAAcd,EAAOe,GACpC,GAAIA,GAAc1C,EAEjB,OAAO2B,EAAKE,GACTY,EAAcd,EAAKE,GAAUF,EAAKQ,IAAU,GAC5CnC,EAIJ,IADA,IAAI2C,EACGD,EAAaf,EAAKC,IAAWN,OAAQoB,IAG3C,IAFAC,EAAUhB,EAAKC,IAAWc,KAEX1C,GAAQ2C,EAAOZ,KAAS/B,EAItC,OAAO2C,EAAOZ,IAShB,MAA4B,mBAAdJ,EAAMX,KAAqByB,EAAcd,GAAS3B,CACjE,CA4CA,SAAS4C,EAAwBjB,GAAjC,IAGW9B,EACJgD,EAHN,IAAKlB,EAAQA,EAAKE,KAAa7B,GAAQ2B,EAAKK,KAAehC,EAAM,CAEhE,IADA2B,EAAKI,IAAQJ,EAAKK,IAAYc,KAAO9C,EAC5BH,EAAI,EAAGA,EAAI8B,EAAKC,IAAWN,OAAQzB,IAE3C,IADIgD,EAAQlB,EAAKC,IAAW/B,KACfG,GAAQ6C,EAAKd,KAAS/B,EAAM,CACxC2B,EAAKI,IAAQJ,EAAKK,IAAYc,KAAOD,EAAKd,IAC1C,KACD,CAGD,OAAOa,EAAwBjB,EAChC,CACD,CA4BO,SAASoB,EAAcC,KAE1BA,EAACC,MACDD,EAACC,KAAU,IACZ5D,EAAc6D,KAAKF,KAClBG,EAAOC,OACT9D,GAAgBJ,EAAQmE,sBAExB/D,EAAeJ,EAAQmE,oBACN9D,GAAO4D,EAE1B,CASA,SAASA,IAMR,IALA,IAAIH,EApGoBM,EAOjBC,EANHC,EACHC,EACAC,EACAC,EAiGAC,EAAI,EAIEvE,EAAciC,QAOhBjC,EAAciC,OAASsC,GAC1BvE,EAAcwE,KAAKrE,GAGpBwD,EAAI3D,EAAcyE,QAClBF,EAAIvE,EAAciC,OAEd0B,EAACC,MAhHCM,SANHC,SACHC,GADGD,GADoBF,EAwHNN,GAvHMd,KACNH,IACjB2B,EAAc,GACdC,EAAW,GAERL,EAASS,OACNR,EAAW/C,EAAO,CAAE,EAAEgD,IACpBtB,IAAasB,EAAQtB,IAAa,EACtChD,EAAQyC,OAAOzC,EAAQyC,MAAM4B,GAEjCS,EACCV,EAASS,IACTR,EACAC,EACAF,EAASW,IACTX,EAASS,IAAYG,aGzII,GH0IzBV,EAAQpB,IAAyB,CAACqB,GAAUzD,EAC5C0D,EACAD,GAAUzD,EAAOyC,EAAce,GAAYC,KG5IlB,GH6ItBD,EAAQpB,KACXuB,GAGDJ,EAAQrB,IAAasB,EAAQtB,IAC7BqB,EAAQ1B,GAAAD,IAAmB2B,EAAQpB,KAAWoB,EAC9CY,EAAWT,EAAaH,EAAUI,GAClCH,EAAQzB,IAAQyB,EAAQ3B,GAAW,KAE/B0B,EAAQxB,KAAS0B,GACpBb,EAAwBW,KA6F1BJ,EAAOC,IAAkB,CAC1B,CI5MgB,SAAAgB,EACfC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAjB,EACAD,EACAmB,EACAjB,GAXe,IAaX9D,EAEH2D,EAEAqB,EAEAC,EAEAC,EAiCIC,EA8BAC,EA1DDC,EAAeV,GAAkBA,EAAc5C,KAAexB,EAE9D+E,EAAoBb,EAAahD,OAUrC,IARAmC,EAAS2B,EACRb,EACAD,EACAY,EACAzB,EACA0B,GAGItF,EAAI,EAAGA,EAAIsF,EAAmBtF,KAClCgF,EAAaN,EAAc3C,IAAW/B,KACpBG,IAKjBwD,GADyB,GAAtBqB,EAAU1C,IACFhC,EAEA+E,EAAYL,EAAU1C,MAAYhC,EAI9C0E,EAAU1C,IAAUtC,EAGhBmF,EAAShB,EACZK,EACAQ,EACArB,EACAiB,EACAC,EACAC,EACAjB,EACAD,EACAmB,EACAjB,GAIDmB,EAASD,EAAU9C,IACf8C,EAAW1D,KAAOqC,EAASrC,KAAO0D,EAAW1D,MAC5CqC,EAASrC,KACZkE,EAAS7B,EAASrC,IAAKnB,EAAM6E,GAE9BlB,EAAST,KACR2B,EAAW1D,IACX0D,EAAU7C,KAAe8C,EACzBD,IAIEE,GAAiB/E,GAAQ8E,GAAU9E,IACtC+E,EAAgBD,IAGbG,KDzHsB,ECyHLJ,EAAUzC,OACZoB,EAAQ5B,MAAeiD,EAAUjD,IACnD6B,EAAS6B,EAAOT,EAAYpB,EAAQY,EAAWY,GACX,mBAAnBJ,EAAW7D,MAAsBgE,IAAW/E,EAC7DwD,EAASuB,EACCF,IACVrB,EAASqB,EAAOS,aAIjBV,EAAUzC,MAAW,GAKtB,OAFAmC,EAAcxC,IAAQgD,EAEftB,CACR,CAOA,SAAS2B,EACRb,EACAD,EACAY,EACAzB,EACA0B,GALD,IAQKtF,EAEAgF,EAEArB,EA8DGgC,EAOAC,EAnEHC,EAAoBR,EAAY5D,OACnCqE,EAAuBD,EAEpBE,EAAO,EAGX,IADArB,EAAc3C,IAAa,IAAIrB,MAAM4E,GAChCtF,EAAI,EAAGA,EAAIsF,EAAmBtF,KAGlCgF,EAAaP,EAAazE,KAGXG,GACO,kBAAd6E,GACc,mBAAdA,GASc,iBAAdA,GACc,iBAAdA,GAEc,iBAAdA,GACPA,EAAW5C,aAAe4D,OAE1BhB,EAAaN,EAAc3C,IAAW/B,GAAK4B,EAC1CzB,EACA6E,EACA7E,EACAA,EACAA,GAESM,EAAQuE,GAClBA,EAAaN,EAAc3C,IAAW/B,GAAK4B,EAC1CY,EACA,CAAEpB,SAAU4D,GACZ7E,EACAA,EACAA,GAES6E,EAAW5C,cAAgBhC,GAAa4E,EAAU/C,IAAU,EAKtE+C,EAAaN,EAAc3C,IAAW/B,GAAK4B,EAC1CoD,EAAW7D,KACX6D,EAAWnE,MACXmE,EAAW3D,IACX2D,EAAW1D,IAAM0D,EAAW1D,IAAMnB,EAClC6E,EAAU3C,KAGXqC,EAAc3C,IAAW/B,GAAKgF,EAGzBW,EAAc3F,EAAI+F,EACxBf,EAAUhD,GAAW0C,EACrBM,EAAU/C,IAAUyC,EAAczC,IAAU,EAKtC2D,EAAiBZ,EAAU1C,IAAU2D,EAC1CjB,EACAK,EACAM,EACAG,GAGDnC,EAAWxD,GACW,GAAlByF,IAEHE,KADAnC,EAAW0B,EAAYO,MAGtBjC,EAAQpB,KD3OW,ICkPFoB,GAAYxD,GAAQwD,EAAQtB,KAAclC,IAGtC,GAAlByF,IAeCN,EAAoBO,EACvBE,IACUT,EAAoBO,GAC9BE,KAK4B,mBAAnBf,EAAW7D,OACrB6D,EAAUzC,KD/Qc,ICiRfqD,GAAiBD,IAiBvBC,GAAiBD,EAAc,EAClCI,IACUH,GAAiBD,EAAc,EACzCI,KAEIH,EAAgBD,EACnBI,IAEAA,IAMDf,EAAUzC,KDhTc,KC8KzBmC,EAAc3C,IAAW/B,GAAKG,EA2IhC,GAAI2F,EACH,IAAK9F,EAAI,EAAGA,EAAI6F,EAAmB7F,KAClC2D,EAAW0B,EAAYrF,KACPG,GAAuC,ID1TnC,EC0TKwD,EAAQpB,OAC5BoB,EAAQzB,KAAS0B,IACpBA,EAAShB,EAAce,IAGxBuC,EAAQvC,EAAUA,IAKrB,OAAOC,CACR,CASA,SAAS6B,EAAOU,EAAavC,EAAQY,EAAWY,GAAhD,IAIMhE,EACKpB,EAFV,GAA+B,mBAApBmG,EAAYhF,KAAoB,CAE1C,IADIC,EAAW+E,EAAWpE,IACjB/B,EAAI,EAAGoB,GAAYpB,EAAIoB,EAASK,OAAQzB,IAC5CoB,EAASpB,KAKZoB,EAASpB,GAAEgC,GAAWmE,EACtBvC,EAAS6B,EAAOrE,EAASpB,GAAI4D,EAAQY,EAAWY,IAIlD,OAAOxB,CACR,CAAWuC,EAAWjE,KAAS0B,IAC1BwB,IACCxB,GAAUuC,EAAYhF,OAASyC,EAAO5C,aACzC4C,EAAShB,EAAcuD,IAExB3B,EAAU4B,aAAaD,EAAWjE,IAAO0B,GAAUzD,IAEpDyD,EAASuC,EAAWjE,KAGrB,GACC0B,EAASA,GAAUA,EAAO8B,kBAClB9B,GAAUzD,GAA2B,GAAnByD,EAAOyC,UAElC,OAAOzC,CACR,CA4BA,SAASqC,EACRjB,EACAK,EACAM,EACAG,GAJD,IAgCMQ,EACAC,EAEG1D,EA7BFxB,EAAM2D,EAAW3D,IACjBF,EAAO6D,EAAW7D,KACpBwC,EAAW0B,EAAYM,GACrBa,EAAU7C,GAAYxD,GAAuC,IDnZ7C,ECmZewD,EAAQpB,KAiB7C,GACEoB,IAAaxD,GAAe,MAAPkB,GACrBmF,GAAWnF,GAAOsC,EAAStC,KAAOF,GAAQwC,EAASxC,KAEpD,OAAOwE,EACD,GAPNG,GAAwBU,EAAU,EAAI,GAUtC,IAFIF,EAAIX,EAAc,EAClBY,EAAIZ,EAAc,EACfW,GAAK,GAAKC,EAAIlB,EAAY5D,QAGhC,IADAkC,EAAW0B,EADLxC,EAAayD,GAAK,EAAIA,IAAMC,OAGrBpG,GACmB,IDjbZ,ECiblBwD,EAAQpB,MACTlB,GAAOsC,EAAStC,KAChBF,GAAQwC,EAASxC,KAEjB,OAAO0B,EAKV,OAAQ,CACT,CH/bA,SAAS4D,EAASC,EAAOrF,EAAKsF,GACf,KAAVtF,EAAI,GACPqF,EAAME,YAAYvF,EAAKsF,GAASxG,EAAO,GAAKwG,GAE5CD,EAAMrF,GADIsF,GAASxG,EACN,GACa,iBAATwG,GAAqBnG,EAAmBqG,KAAKxF,GACjDsF,EAEAA,EAAQ,IAEvB,CAyBgB,SAAAC,EAAYE,EAAKC,EAAMJ,EAAOK,EAAUnC,GAAxC,IACXoC,EA8BGC,EA5BPC,EAAG,GAAY,SAARJ,EACN,GAAoB,iBAATJ,EACVG,EAAIJ,MAAMU,QAAUT,MACd,CAKN,GAJuB,iBAAZK,IACVF,EAAIJ,MAAMU,QAAUJ,EAAW,IAG5BA,EACH,IAAKD,KAAQC,EACNL,GAASI,KAAQJ,GACtBF,EAASK,EAAIJ,MAAOK,EAAM,IAK7B,GAAIJ,EACH,IAAKI,KAAQJ,EACPK,GAAYL,EAAMI,IAASC,EAASD,IACxCN,EAASK,EAAIJ,MAAOK,EAAMJ,EAAMI,GAIpC,MAGI,GAAe,KAAXA,EAAK,IAAwB,KAAXA,EAAK,GAC/BE,EAAaF,IAASA,EAAOA,EAAKM,QAAQzH,EAAe,OACnDsH,EAAgBH,EAAKO,cAI1BP,EADGG,KAAiBJ,GAAe,cAARC,GAAgC,aAARA,EAC5CG,EAAc9H,MAAM,GAChB2H,EAAK3H,MAAM,GAElB0H,EAAG/C,IAAa+C,EAAG/C,EAAc,CAAE,GACxC+C,EAAG/C,EAAYgD,EAAOE,GAAcN,EAEhCA,EACEK,EAQJL,EAAMY,EAAYP,EAASO,GAP3BZ,EAAMY,EAAY1H,EAClBiH,EAAIU,iBACHT,EACAE,EAAalH,EAAoBD,EACjCmH,IAMFH,EAAIW,oBACHV,EACAE,EAAalH,EAAoBD,EACjCmH,OAGI,CACN,GAAIpC,GAAa5E,EAIhB8G,EAAOA,EAAKM,QAAQ,cAAe,KAAKA,QAAQ,SAAU,UAE1DN,GAAQ,SAARA,GACQ,UAARA,GACQ,QAARA,GACQ,QAARA,GACQ,QAARA,GAGQ,YAARA,GACQ,YAARA,GACQ,WAARA,GACQ,WAARA,GACQ,QAARA,GACQ,WAARA,GACAA,KAAQD,EAER,IACCA,EAAIC,GAAQJ,GAASxG,EAAO,GAAKwG,EAEjC,MAAMQ,CAER,CADG,MAAOO,GACV,CASoB,mBAATf,IAEAA,GAASxG,IAAmB,IAAVwG,GAA8B,KAAXI,EAAK,GAGpDD,EAAIa,gBAAgBZ,GAFpBD,EAAIc,aAAab,EAAc,WAARA,GAA8B,GAATJ,EAAgB,GAAKA,GAInE,CACD,CAOA,SAASkB,EAAiBZ,GAMzB,gBAAiBS,GAChB,GAAI/E,KAAIoB,EAAa,CACpB,IAAM+D,EAAenF,KAAIoB,EAAY2D,EAAEvG,KAAO8F,GAC9C,GAAIS,EAAEK,GAAe5H,EACpBuH,EAAEK,EAAclI,SAKV,GAAI6H,EAAEK,EAAcD,EAAaP,EACvC,OAED,OAAOO,EAAazI,EAAQ2I,MAAQ3I,EAAQ2I,MAAMN,GAAKA,EACxD,CACD,CACD,UIzHgBvD,EACfK,EACAd,EACAC,EACAiB,EACAC,EACAC,EACAjB,EACAD,EACAmB,EACAjB,OAGImE,EAkBE9E,EAAG+E,EAAOC,EAAUC,EAAUC,EAAUC,EACxCC,EACEC,EAMFC,EACAC,EAuGO1I,EA4BP2I,EACHC,EASS5I,EA6BNyE,EAgDOzE,EApPZ6I,EAAUnF,EAASvC,KAIpB,GAAIuC,EAAStB,cAAgBhC,EAAW,OAAOD,EF/DlB,IEkEzBwD,EAAQpB,MACXwC,KFrE0B,GEqETpB,EAAQpB,KAEzBuC,EAAoB,CADpBlB,EAASF,EAAQxB,IAAQyB,EAAQzB,OAI7B+F,EAAM5I,EAAO4C,MAASgG,EAAIvE,GAE/BoF,EAAO,GAAsB,mBAAXD,EACjB,IAgEC,GA9DIN,EAAW7E,EAAS7C,MAClB2H,EACL,cAAeK,GAAWA,EAAQE,UAAUC,OAKzCP,GADJR,EAAMY,EAAQI,cACQrE,EAAcqD,EAAG9F,KACnCuG,EAAmBT,EACpBQ,EACCA,EAAS5H,MAAM8F,MACfsB,EAAGjG,GACJ4C,EAGCjB,EAAQxB,IAEXmG,GADAnF,EAAIO,EAAQvB,IAAcwB,EAAQxB,KACNH,GAAwBmB,EAAC+F,KAGjDV,EAEH9E,EAAQvB,IAAcgB,EAAI,IAAI0F,EAAQN,EAAUG,IAGhDhF,EAAQvB,IAAcgB,EAAI,IAAIV,EAC7B8F,EACAG,GAEDvF,EAAEf,YAAcyG,EAChB1F,EAAE6F,OAASG,GAERV,GAAUA,EAASW,IAAIjG,GAEtBA,EAAEkG,QAAOlG,EAAEkG,MAAQ,CAAE,GAC1BlG,EAACiB,IAAkBQ,EACnBsD,EAAQ/E,EAACC,KAAU,EACnBD,EAACmG,IAAoB,GACrBnG,EAACoG,IAAmB,IAIjBf,GAAoBrF,EAACqG,KAAerJ,IACvCgD,EAACqG,IAAcrG,EAAEkG,OAGdb,GAAoBK,EAAQY,0BAA4BtJ,IACvDgD,EAACqG,KAAerG,EAAEkG,QACrBlG,EAACqG,IAAc7I,EAAO,CAAE,EAAEwC,EAACqG,MAG5B7I,EACCwC,EAACqG,IACDX,EAAQY,yBAAyBlB,EAAUpF,EAACqG,OAI9CrB,EAAWhF,EAAEtC,MACbuH,EAAWjF,EAAEkG,MACblG,EAACd,IAAUqB,EAGPwE,EAEFM,GACAK,EAAQY,0BAA4BtJ,GACpCgD,EAAEuG,oBAAsBvJ,GAExBgD,EAAEuG,qBAGClB,GAAoBrF,EAAEwG,mBAAqBxJ,GAC9CgD,EAACmG,IAAkBjG,KAAKF,EAAEwG,uBAErB,CAUN,GARCnB,GACAK,EAAQY,0BAA4BtJ,GACpCoI,IAAaJ,GACbhF,EAAEyG,2BAA6BzJ,GAE/BgD,EAAEyG,0BAA0BrB,EAAUG,GAItChF,EAAQrB,KAAcsB,EAAQtB,MAC5Bc,EAACjB,KACFiB,EAAE0G,uBAAyB1J,IAKrB,IAJNgD,EAAE0G,sBACDtB,EACApF,EAACqG,IACDd,GAED,CAkBD,IAhBIhF,EAAQrB,KAAcsB,EAAQtB,MAKjCc,EAAEtC,MAAQ0H,EACVpF,EAAEkG,MAAQlG,EAACqG,IACXrG,EAACC,KAAU,GAGZM,EAAQxB,IAAQyB,EAAQzB,IACxBwB,EAAQ3B,IAAa4B,EAAQ5B,IAC7B2B,EAAQ3B,IAAW+H,KAAK,SAAAhI,GACnBA,IAAOA,EAAKE,GAAW0B,EAC5B,GAES1D,EAAI,EAAGA,EAAImD,EAACoG,IAAiB9H,OAAQzB,IAC7CmD,EAACmG,IAAkBjG,KAAKF,EAACoG,IAAiBvJ,IAE3CmD,EAACoG,IAAmB,GAEhBpG,EAACmG,IAAkB7H,QACtBoC,EAAYR,KAAKF,GAGlB,MAAM2F,CACP,CAEI3F,EAAE4G,qBAAuB5J,GAC5BgD,EAAE4G,oBAAoBxB,EAAUpF,EAACqG,IAAad,GAG3CF,GAAoBrF,EAAE6G,oBAAsB7J,GAC/CgD,EAACmG,IAAkBjG,KAAK,WACvBF,EAAE6G,mBAAmB7B,EAAUC,EAAUC,EAC1C,EAEF,CASA,GAPAlF,EAAET,QAAUgG,EACZvF,EAAEtC,MAAQ0H,EACVpF,EAACe,IAAcM,EACfrB,EAACjB,KAAU,EAEPyG,EAAatJ,EAAOkE,IACvBqF,EAAQ,EACLJ,EAAkB,CAQrB,IAPArF,EAAEkG,MAAQlG,EAACqG,IACXrG,EAACC,KAAU,EAEPuF,GAAYA,EAAWjF,GAE3BuE,EAAM9E,EAAE6F,OAAO7F,EAAEtC,MAAOsC,EAAEkG,MAAOlG,EAAET,SAE1B1C,EAAI,EAAGA,EAAImD,EAACoG,IAAiB9H,OAAQzB,IAC7CmD,EAACmG,IAAkBjG,KAAKF,EAACoG,IAAiBvJ,IAE3CmD,EAACoG,IAAmB,EACrB,MACC,GACCpG,EAACC,KAAU,EACPuF,GAAYA,EAAWjF,GAE3BuE,EAAM9E,EAAE6F,OAAO7F,EAAEtC,MAAOsC,EAAEkG,MAAOlG,EAAET,SAGnCS,EAAEkG,MAAQlG,EAACqG,UACHrG,EAACC,OAAawF,EAAQ,IAIhCzF,EAAEkG,MAAQlG,EAACqG,IAEPrG,EAAE8G,iBAAmB9J,IACxByE,EAAgBjE,EAAOA,EAAO,CAAE,EAAEiE,GAAgBzB,EAAE8G,oBAGjDzB,IAAqBN,GAAS/E,EAAE+G,yBAA2B/J,IAC9DkI,EAAWlF,EAAE+G,wBAAwB/B,EAAUC,IAK5C3D,EAAewD,EADlBA,GAAO9H,GAAQ8H,EAAI9G,OAASqB,GAAYyF,EAAI5G,KAAOlB,IAInDsE,EAAe0F,EAAUlC,EAAIpH,MAAMO,WAGpCwC,EAASW,EACRC,EACA/D,EAAQgE,GAAgBA,EAAe,CAACA,GACxCf,EACAC,EACAiB,EACAC,EACAC,EACAjB,EACAD,EACAmB,EACAjB,GAGDX,EAAEF,KAAOS,EAAQxB,IAGjBwB,EAAQnB,MF/Qe,IEiRnBY,EAACmG,IAAkB7H,QACtBoC,EAAYR,KAAKF,GAGdmF,IACHnF,EAAC+F,IAAiB/F,EAACnB,GAAwB7B,EA6B7C,CA3BE,MAAOuH,GAGR,GAFAhE,EAAQrB,IAAalC,EAEjB4E,GAAeD,GAAqB3E,EACvC,GAAIuH,EAAE0C,KAAM,CAKX,IAJA1G,EAAQnB,KAAWwC,EAChBsF,IFrSsB,IEwSlBzG,GAA6B,GAAnBA,EAAOyC,UAAiBzC,EAAO8B,aAC/C9B,EAASA,EAAO8B,YAGjBZ,EAAkBA,EAAkBwF,QAAQ1G,IAAWzD,EACvDuD,EAAQxB,IAAQ0B,CACjB,KAAO,CACN,IAAS5D,EAAI8E,EAAkBrD,OAAQzB,KACtCc,EAAWgE,EAAkB9E,IAE9BuK,EAAY7G,EACb,MAEAA,EAAQxB,IAAQyB,EAAQzB,IACxBwB,EAAQ3B,IAAa4B,EAAQ5B,IACxB2F,EAAE0C,MAAMG,EAAY7G,GAE1BrE,EAAO6C,IAAawF,EAAGhE,EAAUC,EAClC,MAEAmB,GAAqB3E,GACrBuD,EAAQrB,KAAcsB,EAAQtB,KAE9BqB,EAAQ3B,IAAa4B,EAAQ5B,IAC7B2B,EAAQxB,IAAQyB,EAAQzB,KAExB0B,EAASF,EAAQxB,IAAQsI,EACxB7G,EAAQzB,IACRwB,EACAC,EACAiB,EACAC,EACAC,EACAjB,EACAkB,EACAjB,GAMF,OAFKmE,EAAM5I,EAAQoL,SAASxC,EAAIvE,GF/UH,IEiVtBA,EAAQnB,SAA2BlC,EAAYuD,CACvD,CAEA,SAAS2G,EAAYzI,GAChBA,GAASA,EAAKK,MAAaL,EAAKK,IAAAD,KAAqB,GACrDJ,GAASA,EAAKC,KAAYD,EAAKC,IAAW2I,QAAQH,EACvD,CAOO,SAASjG,EAAWT,EAAa8G,EAAM7G,GAC7C,IAAK,IAAI9D,EAAI,EAAGA,EAAI8D,EAASrC,OAAQzB,IACpCwF,EAAS1B,EAAS9D,GAAI8D,IAAW9D,GAAI8D,IAAW9D,IAG7CX,EAAO8C,KAAU9C,EAAO8C,IAASwI,EAAM9G,GAE3CA,EAAYiG,KAAK,SAAA3G,GAChB,IAECU,EAAcV,EAACmG,IACfnG,EAACmG,IAAoB,GACrBzF,EAAYiG,KAAK,SAAAc,GAEhBA,EAAGlJ,KAAKyB,EACT,EAGD,CAFE,MAAOuE,GACRrI,EAAO6C,IAAawF,EAAGvE,EAACd,IACzB,CACD,EACD,CAEA,SAAS8H,EAAUpJ,GAClB,MACgB,iBAARA,GACPA,GAAQZ,GACPY,EAAIkB,KAAWlB,EAAIkB,IAAU,EAEvBlB,EAGJN,EAAQM,GACJA,EAAK8J,IAAIV,GAGVxJ,EAAO,GAAII,EACnB,CAiBA,SAASyJ,EACR1D,EACApD,EACAC,EACAiB,EACAC,EACAC,EACAjB,EACAkB,EACAjB,GATD,IAeK9D,EAEA8K,EAEAC,EAEAC,EACArE,EACAsE,EACAC,EAbA/C,EAAWxE,EAAS9C,OAASP,EAC7BiI,EAAW7E,EAAS7C,MACpBwF,EAAkC3C,EAASvC,KAkB/C,GAJgB,OAAZkF,EAAmBxB,EAAY5E,EACd,QAAZoG,EAAoBxB,EFpaA,qCEqanBA,IAAWA,EAAY3E,GAE7B4E,GAAqB3E,EACxB,IAAKH,EAAI,EAAGA,EAAI8E,EAAkBrD,OAAQzB,IAMzC,IALA2G,EAAQ7B,EAAkB9E,KAOzB,iBAAkB2G,KAAWN,IAC5BA,EAAWM,EAAMwE,WAAa9E,EAA6B,GAAlBM,EAAMN,UAC/C,CACDS,EAAMH,EACN7B,EAAkB9E,GAAKG,EACvB,KACD,CAIF,GAAI2G,GAAO3G,EAAM,CAChB,GAAIkG,GAAYlG,EACf,OAAOiL,SAASC,eAAe9C,GAGhCzB,EAAMsE,SAASE,gBACdzG,EACAwB,EACAkC,EAASgD,IAAMhD,GAKZxD,IACC1F,EAAOmM,KACVnM,EAAOmM,IAAoB9H,EAAUoB,GACtCC,GAAc,GAGfD,EAAoB3E,CACrB,CAEA,GAAIkG,GAAYlG,EAEXgI,IAAaI,GAAcxD,GAAe+B,EAAI2E,MAAQlD,IACzDzB,EAAI2E,KAAOlD,OAEN,CAON,GALAzD,EAAoBA,GAAqB1F,EAAMsC,KAAKoF,EAAI4E,aAKnD3G,GAAeD,GAAqB3E,EAExC,IADAgI,EAAW,GACNnI,EAAI,EAAGA,EAAI8G,EAAI6E,WAAWlK,OAAQzB,IAEtCmI,GADAxB,EAAQG,EAAI6E,WAAW3L,IACR+G,MAAQJ,EAAMA,MAI/B,IAAK3G,KAAKmI,EAET,GADAxB,EAAQwB,EAASnI,GACR,YAALA,QACOA,GAAK,2BAALA,EACV+K,EAAUpE,OACA,KAAE3G,KAAKuI,GAAW,CAC5B,GACO,SAALvI,GAAgB,iBAAkBuI,GAC7B,WAALvI,GAAkB,mBAAoBuI,EAEvC,SAED3B,EAAYE,EAAK9G,EAAGG,EAAMwG,EAAO9B,EAClC,CAKD,IAAK7E,KAAKuI,EACT5B,EAAQ4B,EAASvI,GACR,YAALA,EACHgL,EAAcrE,EACC,2BAAL3G,EACV8K,EAAUnE,EACK,SAAL3G,EACViL,EAAatE,EACE,WAAL3G,EACVkL,EAAUvE,EAER5B,GAA+B,mBAAT4B,GACxBwB,EAASnI,KAAO2G,GAEhBC,EAAYE,EAAK9G,EAAG2G,EAAOwB,EAASnI,GAAI6E,GAK1C,GAAIiG,EAGD/F,GACCgG,IACAD,EAAOc,QAAWb,EAAOa,QAAWd,EAAOc,QAAW9E,EAAI+E,aAE5D/E,EAAI+E,UAAYf,EAAOc,QAGxBlI,EAAQ3B,IAAa,QAsBrB,GApBIgJ,IAASjE,EAAI+E,UAAY,IAE7BtH,EAEkB,YAAjBb,EAASvC,KAAqB2F,EAAIgF,QAAUhF,EAC5CrG,EAAQuK,GAAeA,EAAc,CAACA,GACtCtH,EACAC,EACAiB,EACY,iBAAZyB,EAA8BnG,EAAkB2E,EAChDC,EACAjB,EACAiB,EACGA,EAAkB,GAClBnB,EAAQ5B,KAAca,EAAce,EAAU,GACjDoB,EACAjB,GAIGgB,GAAqB3E,EACxB,IAAKH,EAAI8E,EAAkBrD,OAAQzB,KAClCc,EAAWgE,EAAkB9E,IAM3B+E,IACJ/E,EAAI,QACY,YAAZqG,GAA0B4E,GAAc9K,EAC3C2G,EAAIa,gBAAgB,SAEpBsD,GAAc7K,IAKb6K,IAAenE,EAAI9G,IACN,YAAZqG,IAA2B4E,GAIf,UAAZ5E,GAAwB4E,GAAc9C,EAASnI,KAEjD4G,EAAYE,EAAK9G,EAAGiL,EAAY9C,EAASnI,GAAI6E,GAG9C7E,EAAI,UACAkL,GAAW9K,GAAa8K,GAAWpE,EAAI9G,IAC1C4G,EAAYE,EAAK9G,EAAGkL,EAAS/C,EAASnI,GAAI6E,GAG7C,CAEA,OAAOiC,CACR,CAQgB,SAAAtB,EAASlE,EAAKqF,EAAO7E,GACpC,IACC,GAAkB,mBAAPR,EAAmB,CAC7B,IAAIyK,EAAuC,mBAAhBzK,EAAGiB,IAC1BwJ,GAEHzK,EAAGiB,MAGCwJ,GAAiBpF,GAASxG,IAI9BmB,EAAGiB,IAAYjB,EAAIqF,GAErB,MAAOrF,EAAI0K,QAAUrF,CAGtB,CAFE,MAAOe,GACRrI,EAAO6C,IAAawF,EAAG5F,EACxB,CACD,CASgB,SAAAoE,EAAQpE,EAAOqE,EAAa8F,GAA5B,IACXC,EAsBMlM,EAbV,GARIX,EAAQ6G,SAAS7G,EAAQ6G,QAAQpE,IAEhCoK,EAAIpK,EAAMR,OACT4K,EAAEF,SAAWE,EAAEF,SAAWlK,EAAKI,KACnCsD,EAAS0G,EAAG/L,EAAMgG,KAIf+F,EAAIpK,EAAKK,MAAgBhC,EAAM,CACnC,GAAI+L,EAAEC,qBACL,IACCD,EAAEC,sBAGH,CAFE,MAAOzE,GACRrI,EAAO6C,IAAawF,EAAGvB,EACxB,CAGD+F,EAAEjJ,KAAOiJ,EAAChI,IAAc/D,CACzB,CAEA,GAAK+L,EAAIpK,EAAKC,IACb,IAAS/B,EAAI,EAAGA,EAAIkM,EAAEzK,OAAQzB,IACzBkM,EAAElM,IACLkG,EACCgG,EAAElM,GACFmG,EACA8F,GAAmC,mBAAdnK,EAAMX,MAM1B8K,GACJnL,EAAWgB,EAAKI,KAGjBJ,EAAKK,IAAcL,EAAKE,GAAWF,EAAKI,IAAQ9B,CACjD,CAGA,SAAS+I,EAAStI,EAAOwI,EAAO3G,GAC/B,YAAYN,YAAYvB,EAAO6B,EAChC,CC9pBO,SAASsG,EAAOlH,EAAO0C,EAAW4H,GAAlC,IAWFrH,EAOApB,EAQAE,EACHC,EAzBGU,GAAa4G,WAChB5G,EAAY4G,SAASiB,iBAGlBhN,EAAO2C,IAAQ3C,EAAO2C,GAAOF,EAAO0C,GAYpCb,GAPAoB,EAAoC,mBAAfqH,GAQtBjM,EACCiM,GAAeA,EAAWrK,KAAeyC,EAASzC,IAMlD8B,EAAc,GACjBC,EAAW,GACZK,EACCK,EAPD1C,IAAWiD,GAAeqH,GAAgB5H,GAASzC,IAClDb,EAAcsB,EAAUrC,EAAM,CAAC2B,IAU/B6B,GAAYrD,EACZA,EACAkE,EAAUH,cACTU,GAAeqH,EACb,CAACA,GACDzI,EACCxD,EACAqE,EAAU8H,WACTlN,EAAMsC,KAAK8C,EAAUkH,YACrBvL,EACL0D,GACCkB,GAAeqH,EACbA,EACAzI,EACCA,EAAQzB,IACRsC,EAAU8H,WACdvH,EACAjB,GAIDQ,EAAWT,EAAa/B,EAAOgC,EAChC,CTzCa1E,EAAQmB,EAAUnB,MChBzBC,EAAU,CACf6C,ISDM,SAAqBqK,EAAOzK,EAAO6B,EAAU6I,GAQnD,IANA,IAAI/I,EAEHgJ,EAEAC,EAEO5K,EAAQA,EAAKE,IACpB,IAAKyB,EAAY3B,EAAKK,OAAiBsB,EAASzB,GAC/C,IAcC,IAbAyK,EAAOhJ,EAAUrB,cAELqK,EAAKE,0BAA4BxM,IAC5CsD,EAAUmJ,SAASH,EAAKE,yBAAyBJ,IACjDG,EAAUjJ,EAASL,KAGhBK,EAAUoJ,mBAAqB1M,IAClCsD,EAAUoJ,kBAAkBN,EAAOC,GAAa,CAAE,GAClDE,EAAUjJ,EAASL,KAIhBsJ,EACH,OAAQjJ,EAASyF,IAAiBzF,CAIpC,CAFE,MAAOiE,GACR6E,EAAQ7E,CACT,CAIF,MAAM6E,CACP,GRzCIjN,EAAU,EA2FDC,EAAiB,SAAAuC,GAAK,OAClCA,GAAS3B,GAAQ2B,EAAMM,cAAgBhC,CAAS,ECrEjDqC,EAAcsG,UAAU6D,SAAW,SAAUE,EAAQC,GAEpD,IAAIC,EAEHA,EADGrK,KAAI6G,KAAerJ,GAAQwC,KAAI6G,KAAe7G,KAAK0G,MAClD1G,KAAI6G,IAEJ7G,KAAI6G,IAAc7I,EAAO,CAAA,EAAIgC,KAAK0G,OAGlB,mBAAVyD,IAGVA,EAASA,EAAOnM,EAAO,CAAA,EAAIqM,GAAIrK,KAAK9B,QAGjCiM,GACHnM,EAAOqM,EAAGF,GAIPA,GAAU3M,GAEVwC,KAAIN,MACH0K,GACHpK,KAAI4G,IAAiBlG,KAAK0J,GAE3B7J,EAAcP,MAEhB,EAQAF,EAAcsG,UAAUkE,YAAc,SAAUF,GAC3CpK,KAAIN,MAIPM,KAAIT,KAAU,EACV6K,GAAUpK,KAAI2G,IAAkBjG,KAAK0J,GACzC7J,EAAcP,MAEhB,EAYAF,EAAcsG,UAAUC,OAASxG,EA+F7BhD,EAAgB,GAadE,EACa,mBAAXwN,QACJA,QAAQnE,UAAUqB,KAAK+C,KAAKD,QAAQE,WACpCC,WAuBE1N,EAAY,SAAC2N,EAAGC,GAAM,OAAAD,EAACjL,IAAAJ,IAAiBsL,EAAClL,IAAAJ,GAAc,EA8B7DqB,EAAOC,IAAkB,ECzOnB3D,EAAgB,8BAalBC,EAAa,EA+IXC,EAAa+H,GAAiB,GAC9B9H,EAAoB8H,GAAiB,GCzKhC7H,EAAI,qDMUc8B,EAAOjB,EAAOO,OAEzCC,EACAC,EACAtB,EAEG2B,EALAJ,EAAkBZ,EAAO,CAAE,EAAEmB,EAAMjB,OAWvC,IAAKb,KAJD8B,EAAMX,MAAQW,EAAMX,KAAKQ,eAC5BA,EAAeG,EAAMX,KAAKQ,cAGjBd,EACA,OAALb,EAAYqB,EAAMR,EAAMb,GACd,OAALA,EAAYsB,EAAMT,EAAMb,GAEhCuB,EAAgBvB,GADRa,EAAMb,KAAOI,GAAauB,GAAgBvB,EAC7BuB,EAAa3B,GAEba,EAAMb,GAS7B,OALIwB,UAAUC,OAAS,IACtBF,EAAgBH,SACfI,UAAUC,OAAS,EAAIrC,EAAMsC,KAAKF,UAAW,GAAKJ,GAG7CQ,EACNE,EAAMX,KACNI,EACAF,GAAOS,EAAMT,IACbC,GAAOQ,EAAMR,IACbnB,EAEF,kBN1CgB,SAAcqN,GAC7B,SAASC,EAAQ5M,GAAjB,IAGM6M,EACAC,EA+BL,OAlCKhL,KAAKsH,kBAELyD,EAAO,IAAIE,KACXD,EAAM,CAAE,GACRF,EAAOtL,KAAQQ,KAEnBA,KAAKsH,gBAAkB,WAAM,OAAA0D,CAAG,EAEhChL,KAAKwJ,qBAAuB,WAC3BuB,EAAOvN,CACR,EAEAwC,KAAKkH,sBAAwB,SAAUgE,GAElClL,KAAK9B,MAAM8F,OAASkH,EAAOlH,OAC9B+G,EAAKhD,QAAQ,SAAAvH,GACZA,EAACjB,KAAU,EACXgB,EAAcC,EACf,EAEF,EAEAR,KAAKyG,IAAM,SAAAjG,GACVuK,EAAKI,IAAI3K,GACT,IAAI4K,EAAM5K,EAAEgJ,qBACZhJ,EAAEgJ,qBAAuB,WACpBuB,GACHA,EAAKM,OAAO7K,GAET4K,GAAKA,EAAIrM,KAAKyB,EACnB,CACD,GAGMtC,EAAMO,QACd,CAgBA,OAdAqM,EAAOtL,IAAO,OAASnC,IACvByN,EAAOzL,GAAiBwL,EAQxBC,EAAQQ,SACPR,EAAOS,KANRT,EAAQU,SAAW,SAACtN,EAAOuN,GAC1B,OAAOvN,EAAMO,SAASgN,EACvB,GAKkBnF,YAChBwE,EAEKA,CACR,2CHwBC,MAAO,CAAEzB,QAAS7L,EACnB,kBOTO,SAASkO,EAAQvM,EAAO0C,GAC9BwE,EAAOlH,EAAO0C,EAAW6J,EAC1B,2DFgTO,SAASC,EAAalN,EAAUmN,GAUtC,OATAA,EAAMA,GAAO,GACTnN,GAAYjB,GAA2B,kBAAZiB,IACpBX,EAAQW,GAClBA,EAAS0I,KAAK,SAAA9G,GACbsL,EAAatL,EAAOuL,EACrB,GAEAA,EAAIlL,KAAKjC,IAEHmN,CACR"} \ No newline at end of file diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/dist/hooks.js b/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/dist/hooks.js new file mode 100644 index 0000000000000..b3fd8f42163c7 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/dist/hooks.js @@ -0,0 +1,2 @@ +var n,t,r,u,o=require("preact"),i=0,f=[],c=o.options,e=c.__b,a=c.__r,v=c.diffed,s=c.__c,l=c.unmount,p=c.__;function x(n,r){c.__h&&c.__h(t,n,i||r),i=0;var u=t.__H||(t.__H={__:[],__h:[]});return n>=u.__.length&&u.__.push({}),u.__[n]}function m(n){return i=1,d(b,n)}function d(r,u,o){var i=x(n++,2);if(i.t=r,!i.__c&&(i.__=[o?o(u):b(void 0,u),function(n){var t=i.__N?i.__N[0]:i.__[0],r=i.t(t,n);t!==r&&(i.__N=[r,i.__[1]],i.__c.setState({}))}],i.__c=t,!t.__f)){var f=function(n,t,r){if(!i.__c.__H)return!0;var u=i.__c.__H.__.filter(function(n){return!!n.__c});if(u.every(function(n){return!n.__N}))return!c||c.call(this,n,t,r);var o=i.__c.props!==n;return u.forEach(function(n){if(n.__N){var t=n.__[0];n.__=n.__N,n.__N=void 0,t!==n.__[0]&&(o=!0)}}),c&&c.call(this,n,t,r)||o};t.__f=!0;var c=t.shouldComponentUpdate,e=t.componentWillUpdate;t.componentWillUpdate=function(n,t,r){if(this.__e){var u=c;c=void 0,f(n,t,r),c=u}e&&e.call(this,n,t,r)},t.shouldComponentUpdate=f}return i.__N||i.__}function h(r,u){var o=x(n++,4);!c.__s&&P(o.__H,u)&&(o.__=r,o.u=u,t.__h.push(o))}function y(t,r){var u=x(n++,7);return P(u.__H,r)&&(u.__=t(),u.__H=r,u.__h=t),u.__}function _(){for(var n;n=f.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(F),n.__H.__h.forEach(T),n.__H.__h=[]}catch(t){n.__H.__h=[],c.__e(t,n.__v)}}c.__b=function(n){t=null,e&&e(n)},c.__=function(n,t){n&&t.__k&&t.__k.__m&&(n.__m=t.__k.__m),p&&p(n,t)},c.__r=function(u){a&&a(u),n=0;var o=(t=u.__c).__H;o&&(r===t?(o.__h=[],t.__h=[],o.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(o.__h.forEach(F),o.__h.forEach(T),o.__h=[],n=0)),r=t},c.diffed=function(n){v&&v(n);var o=n.__c;o&&o.__H&&(o.__H.__h.length&&(1!==f.push(o)&&u===c.requestAnimationFrame||((u=c.requestAnimationFrame)||A)(_)),o.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),r=t=null},c.__c=function(n,t){t.some(function(n){try{n.__h.forEach(F),n.__h=n.__h.filter(function(n){return!n.__||T(n)})}catch(r){t.some(function(n){n.__h&&(n.__h=[])}),t=[],c.__e(r,n.__v)}}),s&&s(n,t)},c.unmount=function(n){l&&l(n);var t,r=n.__c;r&&r.__H&&(r.__H.__.forEach(function(n){try{F(n)}catch(n){t=n}}),r.__H=void 0,t&&c.__e(t,r.__v))};var q="function"==typeof requestAnimationFrame;function A(n){var t,r=function(){clearTimeout(u),q&&cancelAnimationFrame(t),setTimeout(n)},u=setTimeout(r,35);q&&(t=requestAnimationFrame(r))}function F(n){var r=t,u=n.__c;"function"==typeof u&&(n.__c=void 0,u()),t=r}function T(n){var r=t;n.__c=n.__(),t=r}function P(n,t){return!n||n.length!==t.length||t.some(function(t,r){return t!==n[r]})}function b(n,t){return"function"==typeof t?t(n):t}exports.useCallback=function(n,t){return i=8,y(function(){return n},t)},exports.useContext=function(r){var u=t.context[r.__c],o=x(n++,9);return o.c=r,u?(null==o.__&&(o.__=!0,u.sub(t)),u.props.value):r.__},exports.useDebugValue=function(n,t){c.useDebugValue&&c.useDebugValue(t?t(n):n)},exports.useEffect=function(r,u){var o=x(n++,3);!c.__s&&P(o.__H,u)&&(o.__=r,o.u=u,t.__H.__h.push(o))},exports.useErrorBoundary=function(r){var u=x(n++,10),o=m();return u.__=r,t.componentDidCatch||(t.componentDidCatch=function(n,t){u.__&&u.__(n,t),o[1](n)}),[o[0],function(){o[1](void 0)}]},exports.useId=function(){var r=x(n++,11);if(!r.__){for(var u=t.__v;null!==u&&!u.__m&&null!==u.__;)u=u.__;var o=u.__m||(u.__m=[0,0]);r.__="P"+o[0]+"-"+o[1]++}return r.__},exports.useImperativeHandle=function(n,t,r){i=6,h(function(){if("function"==typeof n){var r=n(t());return function(){n(null),r&&"function"==typeof r&&r()}}if(n)return n.current=t(),function(){return n.current=null}},null==r?r:r.concat(n))},exports.useLayoutEffect=h,exports.useMemo=y,exports.useReducer=d,exports.useRef=function(n){return i=5,y(function(){return{current:n}},[])},exports.useState=m; +//# sourceMappingURL=hooks.js.map diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/dist/hooks.js.map b/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/dist/hooks.js.map new file mode 100644 index 0000000000000..e3434dfc040f1 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/dist/hooks.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hooks.js","sources":["../src/index.js"],"sourcesContent":["import { options as _options } from 'preact';\n\n/** @type {number} */\nlet currentIndex;\n\n/** @type {import('./internal').Component} */\nlet currentComponent;\n\n/** @type {import('./internal').Component} */\nlet previousComponent;\n\n/** @type {number} */\nlet currentHook = 0;\n\n/** @type {Array} */\nlet afterPaintEffects = [];\n\n// Cast to use internal Options type\nconst options = /** @type {import('./internal').Options} */ (_options);\n\nlet oldBeforeDiff = options._diff;\nlet oldBeforeRender = options._render;\nlet oldAfterDiff = options.diffed;\nlet oldCommit = options._commit;\nlet oldBeforeUnmount = options.unmount;\nlet oldRoot = options._root;\n\n// We take the minimum timeout for requestAnimationFrame to ensure that\n// the callback is invoked after the next frame. 35ms is based on a 30hz\n// refresh rate, which is the minimum rate for a smooth user experience.\nconst RAF_TIMEOUT = 35;\nlet prevRaf;\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions._diff = vnode => {\n\tcurrentComponent = null;\n\tif (oldBeforeDiff) oldBeforeDiff(vnode);\n};\n\noptions._root = (vnode, parentDom) => {\n\tif (vnode && parentDom._children && parentDom._children._mask) {\n\t\tvnode._mask = parentDom._children._mask;\n\t}\n\n\tif (oldRoot) oldRoot(vnode, parentDom);\n};\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions._render = vnode => {\n\tif (oldBeforeRender) oldBeforeRender(vnode);\n\n\tcurrentComponent = vnode._component;\n\tcurrentIndex = 0;\n\n\tconst hooks = currentComponent.__hooks;\n\tif (hooks) {\n\t\tif (previousComponent === currentComponent) {\n\t\t\thooks._pendingEffects = [];\n\t\t\tcurrentComponent._renderCallbacks = [];\n\t\t\thooks._list.forEach(hookItem => {\n\t\t\t\tif (hookItem._nextValue) {\n\t\t\t\t\thookItem._value = hookItem._nextValue;\n\t\t\t\t}\n\t\t\t\thookItem._pendingArgs = hookItem._nextValue = undefined;\n\t\t\t});\n\t\t} else {\n\t\t\thooks._pendingEffects.forEach(invokeCleanup);\n\t\t\thooks._pendingEffects.forEach(invokeEffect);\n\t\t\thooks._pendingEffects = [];\n\t\t\tcurrentIndex = 0;\n\t\t}\n\t}\n\tpreviousComponent = currentComponent;\n};\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions.diffed = vnode => {\n\tif (oldAfterDiff) oldAfterDiff(vnode);\n\n\tconst c = vnode._component;\n\tif (c && c.__hooks) {\n\t\tif (c.__hooks._pendingEffects.length) afterPaint(afterPaintEffects.push(c));\n\t\tc.__hooks._list.forEach(hookItem => {\n\t\t\tif (hookItem._pendingArgs) {\n\t\t\t\thookItem._args = hookItem._pendingArgs;\n\t\t\t}\n\t\t\thookItem._pendingArgs = undefined;\n\t\t});\n\t}\n\tpreviousComponent = currentComponent = null;\n};\n\n// TODO: Improve typing of commitQueue parameter\n/** @type {(vnode: import('./internal').VNode, commitQueue: any) => void} */\noptions._commit = (vnode, commitQueue) => {\n\tcommitQueue.some(component => {\n\t\ttry {\n\t\t\tcomponent._renderCallbacks.forEach(invokeCleanup);\n\t\t\tcomponent._renderCallbacks = component._renderCallbacks.filter(cb =>\n\t\t\t\tcb._value ? invokeEffect(cb) : true\n\t\t\t);\n\t\t} catch (e) {\n\t\t\tcommitQueue.some(c => {\n\t\t\t\tif (c._renderCallbacks) c._renderCallbacks = [];\n\t\t\t});\n\t\t\tcommitQueue = [];\n\t\t\toptions._catchError(e, component._vnode);\n\t\t}\n\t});\n\n\tif (oldCommit) oldCommit(vnode, commitQueue);\n};\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions.unmount = vnode => {\n\tif (oldBeforeUnmount) oldBeforeUnmount(vnode);\n\n\tconst c = vnode._component;\n\tif (c && c.__hooks) {\n\t\tlet hasErrored;\n\t\tc.__hooks._list.forEach(s => {\n\t\t\ttry {\n\t\t\t\tinvokeCleanup(s);\n\t\t\t} catch (e) {\n\t\t\t\thasErrored = e;\n\t\t\t}\n\t\t});\n\t\tc.__hooks = undefined;\n\t\tif (hasErrored) options._catchError(hasErrored, c._vnode);\n\t}\n};\n\n/**\n * Get a hook's state from the currentComponent\n * @param {number} index The index of the hook to get\n * @param {number} type The index of the hook to get\n * @returns {any}\n */\nfunction getHookState(index, type) {\n\tif (options._hook) {\n\t\toptions._hook(currentComponent, index, currentHook || type);\n\t}\n\tcurrentHook = 0;\n\n\t// Largely inspired by:\n\t// * https://github.com/michael-klein/funcy.js/blob/f6be73468e6ec46b0ff5aa3cc4c9baf72a29025a/src/hooks/core_hooks.mjs\n\t// * https://github.com/michael-klein/funcy.js/blob/650beaa58c43c33a74820a3c98b3c7079cf2e333/src/renderer.mjs\n\t// Other implementations to look at:\n\t// * https://codesandbox.io/s/mnox05qp8\n\tconst hooks =\n\t\tcurrentComponent.__hooks ||\n\t\t(currentComponent.__hooks = {\n\t\t\t_list: [],\n\t\t\t_pendingEffects: []\n\t\t});\n\n\tif (index >= hooks._list.length) {\n\t\thooks._list.push({});\n\t}\n\n\treturn hooks._list[index];\n}\n\n/**\n * @template {unknown} S\n * @param {import('./index').Dispatch>} [initialState]\n * @returns {[S, (state: S) => void]}\n */\nexport function useState(initialState) {\n\tcurrentHook = 1;\n\treturn useReducer(invokeOrReturn, initialState);\n}\n\n/**\n * @template {unknown} S\n * @template {unknown} A\n * @param {import('./index').Reducer} reducer\n * @param {import('./index').Dispatch>} initialState\n * @param {(initialState: any) => void} [init]\n * @returns {[ S, (state: S) => void ]}\n */\nexport function useReducer(reducer, initialState, init) {\n\t/** @type {import('./internal').ReducerHookState} */\n\tconst hookState = getHookState(currentIndex++, 2);\n\thookState._reducer = reducer;\n\tif (!hookState._component) {\n\t\thookState._value = [\n\t\t\t!init ? invokeOrReturn(undefined, initialState) : init(initialState),\n\n\t\t\taction => {\n\t\t\t\tconst currentValue = hookState._nextValue\n\t\t\t\t\t? hookState._nextValue[0]\n\t\t\t\t\t: hookState._value[0];\n\t\t\t\tconst nextValue = hookState._reducer(currentValue, action);\n\n\t\t\t\tif (currentValue !== nextValue) {\n\t\t\t\t\thookState._nextValue = [nextValue, hookState._value[1]];\n\t\t\t\t\thookState._component.setState({});\n\t\t\t\t}\n\t\t\t}\n\t\t];\n\n\t\thookState._component = currentComponent;\n\n\t\tif (!currentComponent._hasScuFromHooks) {\n\t\t\tcurrentComponent._hasScuFromHooks = true;\n\t\t\tlet prevScu = currentComponent.shouldComponentUpdate;\n\t\t\tconst prevCWU = currentComponent.componentWillUpdate;\n\n\t\t\t// If we're dealing with a forced update `shouldComponentUpdate` will\n\t\t\t// not be called. But we use that to update the hook values, so we\n\t\t\t// need to call it.\n\t\t\tcurrentComponent.componentWillUpdate = function (p, s, c) {\n\t\t\t\tif (this._force) {\n\t\t\t\t\tlet tmp = prevScu;\n\t\t\t\t\t// Clear to avoid other sCU hooks from being called\n\t\t\t\t\tprevScu = undefined;\n\t\t\t\t\tupdateHookState(p, s, c);\n\t\t\t\t\tprevScu = tmp;\n\t\t\t\t}\n\n\t\t\t\tif (prevCWU) prevCWU.call(this, p, s, c);\n\t\t\t};\n\n\t\t\t// This SCU has the purpose of bailing out after repeated updates\n\t\t\t// to stateful hooks.\n\t\t\t// we store the next value in _nextValue[0] and keep doing that for all\n\t\t\t// state setters, if we have next states and\n\t\t\t// all next states within a component end up being equal to their original state\n\t\t\t// we are safe to bail out for this specific component.\n\t\t\t/**\n\t\t\t *\n\t\t\t * @type {import('./internal').Component[\"shouldComponentUpdate\"]}\n\t\t\t */\n\t\t\t// @ts-ignore - We don't use TS to downtranspile\n\t\t\t// eslint-disable-next-line no-inner-declarations\n\t\t\tfunction updateHookState(p, s, c) {\n\t\t\t\tif (!hookState._component.__hooks) return true;\n\n\t\t\t\t/** @type {(x: import('./internal').HookState) => x is import('./internal').ReducerHookState} */\n\t\t\t\tconst isStateHook = x => !!x._component;\n\t\t\t\tconst stateHooks =\n\t\t\t\t\thookState._component.__hooks._list.filter(isStateHook);\n\n\t\t\t\tconst allHooksEmpty = stateHooks.every(x => !x._nextValue);\n\t\t\t\t// When we have no updated hooks in the component we invoke the previous SCU or\n\t\t\t\t// traverse the VDOM tree further.\n\t\t\t\tif (allHooksEmpty) {\n\t\t\t\t\treturn prevScu ? prevScu.call(this, p, s, c) : true;\n\t\t\t\t}\n\n\t\t\t\t// We check whether we have components with a nextValue set that\n\t\t\t\t// have values that aren't equal to one another this pushes\n\t\t\t\t// us to update further down the tree\n\t\t\t\tlet shouldUpdate = hookState._component.props !== p;\n\t\t\t\tstateHooks.forEach(hookItem => {\n\t\t\t\t\tif (hookItem._nextValue) {\n\t\t\t\t\t\tconst currentValue = hookItem._value[0];\n\t\t\t\t\t\thookItem._value = hookItem._nextValue;\n\t\t\t\t\t\thookItem._nextValue = undefined;\n\t\t\t\t\t\tif (currentValue !== hookItem._value[0]) shouldUpdate = true;\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\treturn prevScu\n\t\t\t\t\t? prevScu.call(this, p, s, c) || shouldUpdate\n\t\t\t\t\t: shouldUpdate;\n\t\t\t}\n\n\t\t\tcurrentComponent.shouldComponentUpdate = updateHookState;\n\t\t}\n\t}\n\n\treturn hookState._nextValue || hookState._value;\n}\n\n/**\n * @param {import('./internal').Effect} callback\n * @param {unknown[]} args\n * @returns {void}\n */\nexport function useEffect(callback, args) {\n\t/** @type {import('./internal').EffectHookState} */\n\tconst state = getHookState(currentIndex++, 3);\n\tif (!options._skipEffects && argsChanged(state._args, args)) {\n\t\tstate._value = callback;\n\t\tstate._pendingArgs = args;\n\n\t\tcurrentComponent.__hooks._pendingEffects.push(state);\n\t}\n}\n\n/**\n * @param {import('./internal').Effect} callback\n * @param {unknown[]} args\n * @returns {void}\n */\nexport function useLayoutEffect(callback, args) {\n\t/** @type {import('./internal').EffectHookState} */\n\tconst state = getHookState(currentIndex++, 4);\n\tif (!options._skipEffects && argsChanged(state._args, args)) {\n\t\tstate._value = callback;\n\t\tstate._pendingArgs = args;\n\n\t\tcurrentComponent._renderCallbacks.push(state);\n\t}\n}\n\n/** @type {(initialValue: unknown) => unknown} */\nexport function useRef(initialValue) {\n\tcurrentHook = 5;\n\treturn useMemo(() => ({ current: initialValue }), []);\n}\n\n/**\n * @param {object} ref\n * @param {() => object} createHandle\n * @param {unknown[]} args\n * @returns {void}\n */\nexport function useImperativeHandle(ref, createHandle, args) {\n\tcurrentHook = 6;\n\tuseLayoutEffect(\n\t\t() => {\n\t\t\tif (typeof ref == 'function') {\n\t\t\t\tconst result = ref(createHandle());\n\t\t\t\treturn () => {\n\t\t\t\t\tref(null);\n\t\t\t\t\tif (result && typeof result == 'function') result();\n\t\t\t\t};\n\t\t\t} else if (ref) {\n\t\t\t\tref.current = createHandle();\n\t\t\t\treturn () => (ref.current = null);\n\t\t\t}\n\t\t},\n\t\targs == null ? args : args.concat(ref)\n\t);\n}\n\n/**\n * @template {unknown} T\n * @param {() => T} factory\n * @param {unknown[]} args\n * @returns {T}\n */\nexport function useMemo(factory, args) {\n\t/** @type {import('./internal').MemoHookState} */\n\tconst state = getHookState(currentIndex++, 7);\n\tif (argsChanged(state._args, args)) {\n\t\tstate._value = factory();\n\t\tstate._args = args;\n\t\tstate._factory = factory;\n\t}\n\n\treturn state._value;\n}\n\n/**\n * @param {() => void} callback\n * @param {unknown[]} args\n * @returns {() => void}\n */\nexport function useCallback(callback, args) {\n\tcurrentHook = 8;\n\treturn useMemo(() => callback, args);\n}\n\n/**\n * @param {import('./internal').PreactContext} context\n */\nexport function useContext(context) {\n\tconst provider = currentComponent.context[context._id];\n\t// We could skip this call here, but than we'd not call\n\t// `options._hook`. We need to do that in order to make\n\t// the devtools aware of this hook.\n\t/** @type {import('./internal').ContextHookState} */\n\tconst state = getHookState(currentIndex++, 9);\n\t// The devtools needs access to the context object to\n\t// be able to pull of the default value when no provider\n\t// is present in the tree.\n\tstate._context = context;\n\tif (!provider) return context._defaultValue;\n\t// This is probably not safe to convert to \"!\"\n\tif (state._value == null) {\n\t\tstate._value = true;\n\t\tprovider.sub(currentComponent);\n\t}\n\treturn provider.props.value;\n}\n\n/**\n * Display a custom label for a custom hook for the devtools panel\n * @type {(value: T, cb?: (value: T) => string | number) => void}\n */\nexport function useDebugValue(value, formatter) {\n\tif (options.useDebugValue) {\n\t\toptions.useDebugValue(\n\t\t\tformatter ? formatter(value) : /** @type {any}*/ (value)\n\t\t);\n\t}\n}\n\n/**\n * @param {(error: unknown, errorInfo: import('preact').ErrorInfo) => void} cb\n * @returns {[unknown, () => void]}\n */\nexport function useErrorBoundary(cb) {\n\t/** @type {import('./internal').ErrorBoundaryHookState} */\n\tconst state = getHookState(currentIndex++, 10);\n\tconst errState = useState();\n\tstate._value = cb;\n\tif (!currentComponent.componentDidCatch) {\n\t\tcurrentComponent.componentDidCatch = (err, errorInfo) => {\n\t\t\tif (state._value) state._value(err, errorInfo);\n\t\t\terrState[1](err);\n\t\t};\n\t}\n\treturn [\n\t\terrState[0],\n\t\t() => {\n\t\t\terrState[1](undefined);\n\t\t}\n\t];\n}\n\n/** @type {() => string} */\nexport function useId() {\n\t/** @type {import('./internal').IdHookState} */\n\tconst state = getHookState(currentIndex++, 11);\n\tif (!state._value) {\n\t\t// Grab either the root node or the nearest async boundary node.\n\t\t/** @type {import('./internal').VNode} */\n\t\tlet root = currentComponent._vnode;\n\t\twhile (root !== null && !root._mask && root._parent !== null) {\n\t\t\troot = root._parent;\n\t\t}\n\n\t\tlet mask = root._mask || (root._mask = [0, 0]);\n\t\tstate._value = 'P' + mask[0] + '-' + mask[1]++;\n\t}\n\n\treturn state._value;\n}\n\n/**\n * After paint effects consumer.\n */\nfunction flushAfterPaintEffects() {\n\tlet component;\n\twhile ((component = afterPaintEffects.shift())) {\n\t\tif (!component._parentDom || !component.__hooks) continue;\n\t\ttry {\n\t\t\tcomponent.__hooks._pendingEffects.forEach(invokeCleanup);\n\t\t\tcomponent.__hooks._pendingEffects.forEach(invokeEffect);\n\t\t\tcomponent.__hooks._pendingEffects = [];\n\t\t} catch (e) {\n\t\t\tcomponent.__hooks._pendingEffects = [];\n\t\t\toptions._catchError(e, component._vnode);\n\t\t}\n\t}\n}\n\nlet HAS_RAF = typeof requestAnimationFrame == 'function';\n\n/**\n * Schedule a callback to be invoked after the browser has a chance to paint a new frame.\n * Do this by combining requestAnimationFrame (rAF) + setTimeout to invoke a callback after\n * the next browser frame.\n *\n * Also, schedule a timeout in parallel to the the rAF to ensure the callback is invoked\n * even if RAF doesn't fire (for example if the browser tab is not visible)\n *\n * @param {() => void} callback\n */\nfunction afterNextFrame(callback) {\n\tconst done = () => {\n\t\tclearTimeout(timeout);\n\t\tif (HAS_RAF) cancelAnimationFrame(raf);\n\t\tsetTimeout(callback);\n\t};\n\tconst timeout = setTimeout(done, RAF_TIMEOUT);\n\n\tlet raf;\n\tif (HAS_RAF) {\n\t\traf = requestAnimationFrame(done);\n\t}\n}\n\n// Note: if someone used options.debounceRendering = requestAnimationFrame,\n// then effects will ALWAYS run on the NEXT frame instead of the current one, incurring a ~16ms delay.\n// Perhaps this is not such a big deal.\n/**\n * Schedule afterPaintEffects flush after the browser paints\n * @param {number} newQueueLength\n * @returns {void}\n */\nfunction afterPaint(newQueueLength) {\n\tif (newQueueLength === 1 || prevRaf !== options.requestAnimationFrame) {\n\t\tprevRaf = options.requestAnimationFrame;\n\t\t(prevRaf || afterNextFrame)(flushAfterPaintEffects);\n\t}\n}\n\n/**\n * @param {import('./internal').HookState} hook\n * @returns {void}\n */\nfunction invokeCleanup(hook) {\n\t// A hook cleanup can introduce a call to render which creates a new root, this will call options.vnode\n\t// and move the currentComponent away.\n\tconst comp = currentComponent;\n\tlet cleanup = hook._cleanup;\n\tif (typeof cleanup == 'function') {\n\t\thook._cleanup = undefined;\n\t\tcleanup();\n\t}\n\n\tcurrentComponent = comp;\n}\n\n/**\n * Invoke a Hook's effect\n * @param {import('./internal').EffectHookState} hook\n * @returns {void}\n */\nfunction invokeEffect(hook) {\n\t// A hook call can introduce a call to render which creates a new root, this will call options.vnode\n\t// and move the currentComponent away.\n\tconst comp = currentComponent;\n\thook._cleanup = hook._value();\n\tcurrentComponent = comp;\n}\n\n/**\n * @param {unknown[]} oldArgs\n * @param {unknown[]} newArgs\n * @returns {boolean}\n */\nfunction argsChanged(oldArgs, newArgs) {\n\treturn (\n\t\t!oldArgs ||\n\t\toldArgs.length !== newArgs.length ||\n\t\tnewArgs.some((arg, index) => arg !== oldArgs[index])\n\t);\n}\n\n/**\n * @template Arg\n * @param {Arg} arg\n * @param {(arg: Arg) => any} f\n * @returns {any}\n */\nfunction invokeOrReturn(arg, f) {\n\treturn typeof f == 'function' ? f(arg) : f;\n}\n"],"names":["currentIndex","currentComponent","previousComponent","prevRaf","currentHook","afterPaintEffects","options","_options","oldBeforeDiff","__b","oldBeforeRender","__r","oldAfterDiff","diffed","oldCommit","__c","oldBeforeUnmount","unmount","oldRoot","__","getHookState","index","type","__h","hooks","__H","length","push","useState","initialState","useReducer","invokeOrReturn","reducer","init","hookState","_reducer","undefined","action","currentValue","__N","nextValue","setState","__f","updateHookState","p","s","c","stateHooks","filter","x","every","prevScu","call","this","shouldUpdate","props","forEach","hookItem","shouldComponentUpdate","prevCWU","componentWillUpdate","__e","tmp","useLayoutEffect","callback","args","state","__s","argsChanged","_pendingArgs","useMemo","factory","flushAfterPaintEffects","component","shift","__P","invokeCleanup","invokeEffect","e","__v","vnode","parentDom","__k","__m","requestAnimationFrame","afterNextFrame","commitQueue","some","cb","hasErrored","HAS_RAF","raf","done","clearTimeout","timeout","cancelAnimationFrame","setTimeout","hook","comp","cleanup","oldArgs","newArgs","arg","f","context","provider","sub","value","formatter","useDebugValue","errState","componentDidCatch","err","errorInfo","root","mask","ref","createHandle","result","current","concat","initialValue"],"mappings":"IAGIA,EAGAC,EAGAC,EAsBAC,sBAnBAC,EAAc,EAGdC,EAAoB,GAGlBC,EAAuDC,EAAAA,QAEzDC,EAAgBF,EAAOG,IACvBC,EAAkBJ,EAAOK,IACzBC,EAAeN,EAAQO,OACvBC,EAAYR,EAAOS,IACnBC,EAAmBV,EAAQW,QAC3BC,EAAUZ,EAAOa,GAiHrB,SAASC,EAAaC,EAAOC,GACxBhB,EAAOiB,KACVjB,EAAOiB,IAAOtB,EAAkBoB,EAAOjB,GAAekB,GAEvDlB,EAAc,EAOd,IAAMoB,EACLvB,EAAgBwB,MACfxB,EAAgBwB,IAAW,CAC3BN,GAAO,GACPI,IAAiB,KAOnB,OAJIF,GAASG,EAAKL,GAAOO,QACxBF,EAAKL,GAAOQ,KAAK,CAAE,GAGbH,EAAKL,GAAOE,EACpB,CAOO,SAASO,EAASC,GAExB,OADAzB,EAAc,EACP0B,EAAWC,EAAgBF,EACnC,CAUgB,SAAAC,EAAWE,EAASH,EAAcI,GAEjD,IAAMC,EAAYd,EAAapB,IAAgB,GAE/C,GADAkC,EAAUC,EAAWH,GAChBE,EAASnB,MACbmB,EAASf,GAAU,CACjBc,EAAiDA,EAAKJ,GAA/CE,OAAeK,EAAWP,GAElC,SAAAQ,GACC,IAAMC,EAAeJ,EAASK,IAC3BL,EAASK,IAAY,GACrBL,EAASf,GAAQ,GACdqB,EAAYN,EAAUC,EAASG,EAAcD,GAE/CC,IAAiBE,IACpBN,EAASK,IAAc,CAACC,EAAWN,EAASf,GAAQ,IACpDe,EAASnB,IAAY0B,SAAS,CAAE,GAElC,GAGDP,EAASnB,IAAcd,GAElBA,EAAgByC,KAAmB,CAAA,IAgC9BC,EAAT,SAAyBC,EAAGC,EAAGC,GAC9B,IAAKZ,EAASnB,IAAAU,IAAqB,OAAW,EAG9C,IACMsB,EACLb,EAASnB,IAAAU,IAAAN,GAA0B6B,OAFhB,SAAAC,GAAC,QAAMA,EAAClC,GAAW,GAOvC,GAHsBgC,EAAWG,MAAM,SAAAD,GAAC,OAAKA,EAACV,GAAW,GAIxD,OAAOY,GAAUA,EAAQC,KAAKC,KAAMT,EAAGC,EAAGC,GAM3C,IAAIQ,EAAepB,EAASnB,IAAYwC,QAAUX,EAUlD,OATAG,EAAWS,QAAQ,SAAAC,GAClB,GAAIA,EAAQlB,IAAa,CACxB,IAAMD,EAAemB,EAAQtC,GAAQ,GACrCsC,EAAQtC,GAAUsC,EAAQlB,IAC1BkB,EAAQlB,SAAcH,EAClBE,IAAiBmB,EAAQtC,GAAQ,KAAImC,GAAe,EACzD,CACD,GAEOH,GACJA,EAAQC,KAAKC,KAAMT,EAAGC,EAAGC,IACzBQ,CACJ,EA9DArD,EAAgByC,KAAoB,EACpC,IAAIS,EAAUlD,EAAiByD,sBACzBC,EAAU1D,EAAiB2D,oBAKjC3D,EAAiB2D,oBAAsB,SAAUhB,EAAGC,EAAGC,GACtD,GAAIO,KAAIQ,IAAS,CAChB,IAAIC,EAAMX,EAEVA,OAAUf,EACVO,EAAgBC,EAAGC,EAAGC,GACtBK,EAAUW,CACX,CAEIH,GAASA,EAAQP,KAAKC,KAAMT,EAAGC,EAAGC,EACvC,EA+CA7C,EAAiByD,sBAAwBf,CAC1C,CAGD,OAAOT,EAASK,KAAeL,EAASf,EACzC,CAuBgB,SAAA4C,EAAgBC,EAAUC,GAEzC,IAAMC,EAAQ9C,EAAapB,IAAgB,IACtCM,EAAO6D,KAAiBC,EAAYF,EAAKzC,IAAQwC,KACrDC,EAAK/C,GAAU6C,EACfE,EAAMG,EAAeJ,EAErBhE,EAAgBsB,IAAkBI,KAAKuC,GAEzC,CAuCgB,SAAAI,EAAQC,EAASN,GAEhC,IAAMC,EAAQ9C,EAAapB,IAAgB,GAO3C,OANIoE,EAAYF,EAAKzC,IAAQwC,KAC5BC,EAAK/C,GAAUoD,IACfL,EAAKzC,IAASwC,EACdC,EAAK3C,IAAYgD,GAGXL,EAAK/C,EACb,CA4FA,SAASqD,IAER,IADA,IAAIC,EACIA,EAAYpE,EAAkBqE,SACrC,GAAKD,EAASE,KAAgBF,EAAShD,IACvC,IACCgD,EAAShD,IAAAF,IAAyBiC,QAAQoB,GAC1CH,EAAShD,IAAAF,IAAyBiC,QAAQqB,GAC1CJ,EAAShD,IAAAF,IAA2B,EAIrC,CAHE,MAAOuD,GACRL,EAAShD,IAAAF,IAA2B,GACpCjB,EAAOuD,IAAaiB,EAAGL,EAASM,IACjC,CAEF,CA1aAzE,EAAOG,IAAS,SAAAuE,GACf/E,EAAmB,KACfO,GAAeA,EAAcwE,EAClC,EAEA1E,EAAOa,GAAS,SAAC6D,EAAOC,GACnBD,GAASC,EAASC,KAAcD,EAASC,IAAAC,MAC5CH,EAAKG,IAASF,EAASC,IAAAC,KAGpBjE,GAASA,EAAQ8D,EAAOC,EAC7B,EAGA3E,EAAOK,IAAW,SAAAqE,GACbtE,GAAiBA,EAAgBsE,GAGrChF,EAAe,EAEf,IAAMwB,GAHNvB,EAAmB+E,EAAKjE,KAGMU,IAC1BD,IACCtB,IAAsBD,GACzBuB,EAAKD,IAAmB,GACxBtB,EAAgBsB,IAAoB,GACpCC,EAAKL,GAAOqC,QAAQ,SAAAC,GACfA,EAAQlB,MACXkB,EAAQtC,GAAUsC,EAAQlB,KAE3BkB,EAASY,EAAeZ,EAAQlB,SAAcH,CAC/C,KAEAZ,EAAKD,IAAiBiC,QAAQoB,GAC9BpD,EAAKD,IAAiBiC,QAAQqB,GAC9BrD,EAAKD,IAAmB,GACxBvB,EAAe,IAGjBE,EAAoBD,CACrB,EAGAK,EAAQO,OAAS,SAAAmE,GACZpE,GAAcA,EAAaoE,GAE/B,IAAMlC,EAAIkC,EAAKjE,IACX+B,GAAKA,EAACrB,MACLqB,EAACrB,IAAAF,IAAyBG,SAgaR,IAha2BrB,EAAkBsB,KAAKmB,IAga7C3C,IAAYG,EAAQ8E,yBAC/CjF,EAAUG,EAAQ8E,wBACNC,GAAgBb,IAja5B1B,EAACrB,IAAAN,GAAeqC,QAAQ,SAAAC,GACnBA,EAASY,IACZZ,EAAQhC,IAASgC,EAASY,GAE3BZ,EAASY,OAAejC,CACzB,IAEDlC,EAAoBD,EAAmB,IACxC,EAIAK,EAAOS,IAAW,SAACiE,EAAOM,GACzBA,EAAYC,KAAK,SAAAd,GAChB,IACCA,EAASlD,IAAkBiC,QAAQoB,GACnCH,EAASlD,IAAoBkD,EAASlD,IAAkByB,OAAO,SAAAwC,GAAE,OAChEA,EAAErE,IAAU0D,EAAaW,EAAU,EAQrC,CANE,MAAOV,GACRQ,EAAYC,KAAK,SAAAzC,GACZA,EAACvB,MAAmBuB,EAACvB,IAAoB,GAC9C,GACA+D,EAAc,GACdhF,EAAOuD,IAAaiB,EAAGL,EAASM,IACjC,CACD,GAEIjE,GAAWA,EAAUkE,EAAOM,EACjC,EAGAhF,EAAQW,QAAU,SAAA+D,GACbhE,GAAkBA,EAAiBgE,GAEvC,IAEKS,EAFC3C,EAAIkC,EAAKjE,IACX+B,GAAKA,EAACrB,MAETqB,EAACrB,IAAAN,GAAeqC,QAAQ,SAAAX,GACvB,IACC+B,EAAc/B,EAGf,CAFE,MAAOiC,GACRW,EAAaX,CACd,CACD,GACAhC,EAACrB,SAAWW,EACRqD,GAAYnF,EAAOuD,IAAa4B,EAAY3C,EAACiC,KAEnD,EA4UA,IAAIW,EAA0C,mBAAzBN,sBAYrB,SAASC,EAAerB,GACvB,IAOI2B,EAPEC,EAAO,WACZC,aAAaC,GACTJ,GAASK,qBAAqBJ,GAClCK,WAAWhC,EACZ,EACM8B,EAAUE,WAAWJ,EAlcR,IAqcfF,IACHC,EAAMP,sBAAsBQ,GAE9B,CAqBA,SAAShB,EAAcqB,GAGtB,IAAMC,EAAOjG,EACTkG,EAAUF,EAAIlF,IACI,mBAAXoF,IACVF,EAAIlF,SAAYqB,EAChB+D,KAGDlG,EAAmBiG,CACpB,CAOA,SAASrB,EAAaoB,GAGrB,IAAMC,EAAOjG,EACbgG,EAAIlF,IAAYkF,EAAI9E,KACpBlB,EAAmBiG,CACpB,CAOA,SAAS9B,EAAYgC,EAASC,GAC7B,OACED,GACDA,EAAQ1E,SAAW2E,EAAQ3E,QAC3B2E,EAAQd,KAAK,SAACe,EAAKjF,GAAU,OAAAiF,IAAQF,EAAQ/E,EAAM,EAErD,CAQA,SAASU,EAAeuE,EAAKC,GAC5B,MAAmB,mBAALA,EAAkBA,EAAED,GAAOC,CAC1C,qBAhMO,SAAqBvC,EAAUC,GAErC,OADA7D,EAAc,EACPkE,EAAQ,WAAA,OAAMN,CAAQ,EAAEC,EAChC,qBAKO,SAAoBuC,GAC1B,IAAMC,EAAWxG,EAAiBuG,QAAQA,EAAOzF,KAK3CmD,EAAQ9C,EAAapB,IAAgB,GAK3C,OADAkE,EAAKpB,EAAY0D,EACZC,GAEe,MAAhBvC,EAAK/C,KACR+C,EAAK/C,IAAU,EACfsF,EAASC,IAAIzG,IAEPwG,EAASlD,MAAMoD,OANAH,EAAOrF,EAO9B,wBAMgB,SAAcwF,EAAOC,GAChCtG,EAAQuG,eACXvG,EAAQuG,cACPD,EAAYA,EAAUD,GAAM,EAG/B,oBAvHO,SAAmB3C,EAAUC,GAEnC,IAAMC,EAAQ9C,EAAapB,IAAgB,IACtCM,EAAO6D,KAAiBC,EAAYF,EAAKzC,IAAQwC,KACrDC,EAAK/C,GAAU6C,EACfE,EAAMG,EAAeJ,EAErBhE,EAAgBwB,IAAAF,IAAyBI,KAAKuC,GAEhD,2BAoHO,SAA0BsB,GAEhC,IAAMtB,EAAQ9C,EAAapB,IAAgB,IACrC8G,EAAWlF,IAQjB,OAPAsC,EAAK/C,GAAUqE,EACVvF,EAAiB8G,oBACrB9G,EAAiB8G,kBAAoB,SAACC,EAAKC,GACtC/C,EAAK/C,IAAS+C,EAAK/C,GAAQ6F,EAAKC,GACpCH,EAAS,GAAGE,EACb,GAEM,CACNF,EAAS,GACT,WACCA,EAAS,QAAG1E,EACb,EAEF,gBAGO,WAEN,IAAM8B,EAAQ9C,EAAapB,IAAgB,IAC3C,IAAKkE,EAAK/C,GAAS,CAIlB,IADA,IAAI+F,EAAOjH,EAAgB8E,IACX,OAATmC,IAAkBA,EAAI/B,KAA2B,OAAjB+B,EAAI/F,IAC1C+F,EAAOA,EAAI/F,GAGZ,IAAIgG,EAAOD,EAAI/B,MAAW+B,EAAI/B,IAAS,CAAC,EAAG,IAC3CjB,EAAK/C,GAAU,IAAMgG,EAAK,GAAK,IAAMA,EAAK,IAC3C,CAEA,OAAOjD,EAAK/C,EACb,8BA1HgB,SAAoBiG,EAAKC,EAAcpD,GACtD7D,EAAc,EACd2D,EACC,WACC,GAAkB,mBAAPqD,EAAmB,CAC7B,IAAME,EAASF,EAAIC,KACnB,OAAa,WACZD,EAAI,MACAE,GAA2B,mBAAVA,GAAsBA,GAC5C,CACD,CAAWF,GAAAA,EAEV,OADAA,EAAIG,QAAUF,IACP,WAAA,OAAOD,EAAIG,QAAU,IAAI,CAElC,EACQ,MAARtD,EAAeA,EAAOA,EAAKuD,OAAOJ,GAEpC,kFA5BO,SAAgBK,GAEtB,OADArH,EAAc,EACPkE,EAAQ,WAAO,MAAA,CAAEiD,QAASE,EAAc,EAAG,GACnD"} \ No newline at end of file diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/dist/hooks.mjs b/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/dist/hooks.mjs new file mode 100644 index 0000000000000..49081e030ebf2 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/dist/hooks.mjs @@ -0,0 +1,2 @@ +import{options as n}from"preact";var t,r,u,i,o=0,f=[],c=n,e=c.__b,a=c.__r,v=c.diffed,l=c.__c,m=c.unmount,s=c.__;function p(n,t){c.__h&&c.__h(r,n,o||t),o=0;var u=r.__H||(r.__H={__:[],__h:[]});return n>=u.__.length&&u.__.push({}),u.__[n]}function d(n){return o=1,h(D,n)}function h(n,u,i){var o=p(t++,2);if(o.t=n,!o.__c&&(o.__=[i?i(u):D(void 0,u),function(n){var t=o.__N?o.__N[0]:o.__[0],r=o.t(t,n);t!==r&&(o.__N=[r,o.__[1]],o.__c.setState({}))}],o.__c=r,!r.__f)){var f=function(n,t,r){if(!o.__c.__H)return!0;var u=o.__c.__H.__.filter(function(n){return!!n.__c});if(u.every(function(n){return!n.__N}))return!c||c.call(this,n,t,r);var i=o.__c.props!==n;return u.forEach(function(n){if(n.__N){var t=n.__[0];n.__=n.__N,n.__N=void 0,t!==n.__[0]&&(i=!0)}}),c&&c.call(this,n,t,r)||i};r.__f=!0;var c=r.shouldComponentUpdate,e=r.componentWillUpdate;r.componentWillUpdate=function(n,t,r){if(this.__e){var u=c;c=void 0,f(n,t,r),c=u}e&&e.call(this,n,t,r)},r.shouldComponentUpdate=f}return o.__N||o.__}function y(n,u){var i=p(t++,3);!c.__s&&C(i.__H,u)&&(i.__=n,i.u=u,r.__H.__h.push(i))}function _(n,u){var i=p(t++,4);!c.__s&&C(i.__H,u)&&(i.__=n,i.u=u,r.__h.push(i))}function A(n){return o=5,T(function(){return{current:n}},[])}function F(n,t,r){o=6,_(function(){if("function"==typeof n){var r=n(t());return function(){n(null),r&&"function"==typeof r&&r()}}if(n)return n.current=t(),function(){return n.current=null}},null==r?r:r.concat(n))}function T(n,r){var u=p(t++,7);return C(u.__H,r)&&(u.__=n(),u.__H=r,u.__h=n),u.__}function q(n,t){return o=8,T(function(){return n},t)}function x(n){var u=r.context[n.__c],i=p(t++,9);return i.c=n,u?(null==i.__&&(i.__=!0,u.sub(r)),u.props.value):n.__}function P(n,t){c.useDebugValue&&c.useDebugValue(t?t(n):n)}function b(n){var u=p(t++,10),i=d();return u.__=n,r.componentDidCatch||(r.componentDidCatch=function(n,t){u.__&&u.__(n,t),i[1](n)}),[i[0],function(){i[1](void 0)}]}function g(){var n=p(t++,11);if(!n.__){for(var u=r.__v;null!==u&&!u.__m&&null!==u.__;)u=u.__;var i=u.__m||(u.__m=[0,0]);n.__="P"+i[0]+"-"+i[1]++}return n.__}function j(){for(var n;n=f.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(z),n.__H.__h.forEach(B),n.__H.__h=[]}catch(t){n.__H.__h=[],c.__e(t,n.__v)}}c.__b=function(n){r=null,e&&e(n)},c.__=function(n,t){n&&t.__k&&t.__k.__m&&(n.__m=t.__k.__m),s&&s(n,t)},c.__r=function(n){a&&a(n),t=0;var i=(r=n.__c).__H;i&&(u===r?(i.__h=[],r.__h=[],i.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(i.__h.forEach(z),i.__h.forEach(B),i.__h=[],t=0)),u=r},c.diffed=function(n){v&&v(n);var t=n.__c;t&&t.__H&&(t.__H.__h.length&&(1!==f.push(t)&&i===c.requestAnimationFrame||((i=c.requestAnimationFrame)||w)(j)),t.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),u=r=null},c.__c=function(n,t){t.some(function(n){try{n.__h.forEach(z),n.__h=n.__h.filter(function(n){return!n.__||B(n)})}catch(r){t.some(function(n){n.__h&&(n.__h=[])}),t=[],c.__e(r,n.__v)}}),l&&l(n,t)},c.unmount=function(n){m&&m(n);var t,r=n.__c;r&&r.__H&&(r.__H.__.forEach(function(n){try{z(n)}catch(n){t=n}}),r.__H=void 0,t&&c.__e(t,r.__v))};var k="function"==typeof requestAnimationFrame;function w(n){var t,r=function(){clearTimeout(u),k&&cancelAnimationFrame(t),setTimeout(n)},u=setTimeout(r,35);k&&(t=requestAnimationFrame(r))}function z(n){var t=r,u=n.__c;"function"==typeof u&&(n.__c=void 0,u()),r=t}function B(n){var t=r;n.__c=n.__(),r=t}function C(n,t){return!n||n.length!==t.length||t.some(function(t,r){return t!==n[r]})}function D(n,t){return"function"==typeof t?t(n):t}export{q as useCallback,x as useContext,P as useDebugValue,y as useEffect,b as useErrorBoundary,g as useId,F as useImperativeHandle,_ as useLayoutEffect,T as useMemo,h as useReducer,A as useRef,d as useState}; +//# sourceMappingURL=hooks.module.js.map diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/dist/hooks.module.js b/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/dist/hooks.module.js new file mode 100644 index 0000000000000..49081e030ebf2 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/dist/hooks.module.js @@ -0,0 +1,2 @@ +import{options as n}from"preact";var t,r,u,i,o=0,f=[],c=n,e=c.__b,a=c.__r,v=c.diffed,l=c.__c,m=c.unmount,s=c.__;function p(n,t){c.__h&&c.__h(r,n,o||t),o=0;var u=r.__H||(r.__H={__:[],__h:[]});return n>=u.__.length&&u.__.push({}),u.__[n]}function d(n){return o=1,h(D,n)}function h(n,u,i){var o=p(t++,2);if(o.t=n,!o.__c&&(o.__=[i?i(u):D(void 0,u),function(n){var t=o.__N?o.__N[0]:o.__[0],r=o.t(t,n);t!==r&&(o.__N=[r,o.__[1]],o.__c.setState({}))}],o.__c=r,!r.__f)){var f=function(n,t,r){if(!o.__c.__H)return!0;var u=o.__c.__H.__.filter(function(n){return!!n.__c});if(u.every(function(n){return!n.__N}))return!c||c.call(this,n,t,r);var i=o.__c.props!==n;return u.forEach(function(n){if(n.__N){var t=n.__[0];n.__=n.__N,n.__N=void 0,t!==n.__[0]&&(i=!0)}}),c&&c.call(this,n,t,r)||i};r.__f=!0;var c=r.shouldComponentUpdate,e=r.componentWillUpdate;r.componentWillUpdate=function(n,t,r){if(this.__e){var u=c;c=void 0,f(n,t,r),c=u}e&&e.call(this,n,t,r)},r.shouldComponentUpdate=f}return o.__N||o.__}function y(n,u){var i=p(t++,3);!c.__s&&C(i.__H,u)&&(i.__=n,i.u=u,r.__H.__h.push(i))}function _(n,u){var i=p(t++,4);!c.__s&&C(i.__H,u)&&(i.__=n,i.u=u,r.__h.push(i))}function A(n){return o=5,T(function(){return{current:n}},[])}function F(n,t,r){o=6,_(function(){if("function"==typeof n){var r=n(t());return function(){n(null),r&&"function"==typeof r&&r()}}if(n)return n.current=t(),function(){return n.current=null}},null==r?r:r.concat(n))}function T(n,r){var u=p(t++,7);return C(u.__H,r)&&(u.__=n(),u.__H=r,u.__h=n),u.__}function q(n,t){return o=8,T(function(){return n},t)}function x(n){var u=r.context[n.__c],i=p(t++,9);return i.c=n,u?(null==i.__&&(i.__=!0,u.sub(r)),u.props.value):n.__}function P(n,t){c.useDebugValue&&c.useDebugValue(t?t(n):n)}function b(n){var u=p(t++,10),i=d();return u.__=n,r.componentDidCatch||(r.componentDidCatch=function(n,t){u.__&&u.__(n,t),i[1](n)}),[i[0],function(){i[1](void 0)}]}function g(){var n=p(t++,11);if(!n.__){for(var u=r.__v;null!==u&&!u.__m&&null!==u.__;)u=u.__;var i=u.__m||(u.__m=[0,0]);n.__="P"+i[0]+"-"+i[1]++}return n.__}function j(){for(var n;n=f.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(z),n.__H.__h.forEach(B),n.__H.__h=[]}catch(t){n.__H.__h=[],c.__e(t,n.__v)}}c.__b=function(n){r=null,e&&e(n)},c.__=function(n,t){n&&t.__k&&t.__k.__m&&(n.__m=t.__k.__m),s&&s(n,t)},c.__r=function(n){a&&a(n),t=0;var i=(r=n.__c).__H;i&&(u===r?(i.__h=[],r.__h=[],i.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(i.__h.forEach(z),i.__h.forEach(B),i.__h=[],t=0)),u=r},c.diffed=function(n){v&&v(n);var t=n.__c;t&&t.__H&&(t.__H.__h.length&&(1!==f.push(t)&&i===c.requestAnimationFrame||((i=c.requestAnimationFrame)||w)(j)),t.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),u=r=null},c.__c=function(n,t){t.some(function(n){try{n.__h.forEach(z),n.__h=n.__h.filter(function(n){return!n.__||B(n)})}catch(r){t.some(function(n){n.__h&&(n.__h=[])}),t=[],c.__e(r,n.__v)}}),l&&l(n,t)},c.unmount=function(n){m&&m(n);var t,r=n.__c;r&&r.__H&&(r.__H.__.forEach(function(n){try{z(n)}catch(n){t=n}}),r.__H=void 0,t&&c.__e(t,r.__v))};var k="function"==typeof requestAnimationFrame;function w(n){var t,r=function(){clearTimeout(u),k&&cancelAnimationFrame(t),setTimeout(n)},u=setTimeout(r,35);k&&(t=requestAnimationFrame(r))}function z(n){var t=r,u=n.__c;"function"==typeof u&&(n.__c=void 0,u()),r=t}function B(n){var t=r;n.__c=n.__(),r=t}function C(n,t){return!n||n.length!==t.length||t.some(function(t,r){return t!==n[r]})}function D(n,t){return"function"==typeof t?t(n):t}export{q as useCallback,x as useContext,P as useDebugValue,y as useEffect,b as useErrorBoundary,g as useId,F as useImperativeHandle,_ as useLayoutEffect,T as useMemo,h as useReducer,A as useRef,d as useState}; +//# sourceMappingURL=hooks.module.js.map diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/dist/hooks.module.js.map b/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/dist/hooks.module.js.map new file mode 100644 index 0000000000000..ee1971141d5a4 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/dist/hooks.module.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hooks.module.js","sources":["../src/index.js"],"sourcesContent":["import { options as _options } from 'preact';\n\n/** @type {number} */\nlet currentIndex;\n\n/** @type {import('./internal').Component} */\nlet currentComponent;\n\n/** @type {import('./internal').Component} */\nlet previousComponent;\n\n/** @type {number} */\nlet currentHook = 0;\n\n/** @type {Array} */\nlet afterPaintEffects = [];\n\n// Cast to use internal Options type\nconst options = /** @type {import('./internal').Options} */ (_options);\n\nlet oldBeforeDiff = options._diff;\nlet oldBeforeRender = options._render;\nlet oldAfterDiff = options.diffed;\nlet oldCommit = options._commit;\nlet oldBeforeUnmount = options.unmount;\nlet oldRoot = options._root;\n\n// We take the minimum timeout for requestAnimationFrame to ensure that\n// the callback is invoked after the next frame. 35ms is based on a 30hz\n// refresh rate, which is the minimum rate for a smooth user experience.\nconst RAF_TIMEOUT = 35;\nlet prevRaf;\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions._diff = vnode => {\n\tcurrentComponent = null;\n\tif (oldBeforeDiff) oldBeforeDiff(vnode);\n};\n\noptions._root = (vnode, parentDom) => {\n\tif (vnode && parentDom._children && parentDom._children._mask) {\n\t\tvnode._mask = parentDom._children._mask;\n\t}\n\n\tif (oldRoot) oldRoot(vnode, parentDom);\n};\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions._render = vnode => {\n\tif (oldBeforeRender) oldBeforeRender(vnode);\n\n\tcurrentComponent = vnode._component;\n\tcurrentIndex = 0;\n\n\tconst hooks = currentComponent.__hooks;\n\tif (hooks) {\n\t\tif (previousComponent === currentComponent) {\n\t\t\thooks._pendingEffects = [];\n\t\t\tcurrentComponent._renderCallbacks = [];\n\t\t\thooks._list.forEach(hookItem => {\n\t\t\t\tif (hookItem._nextValue) {\n\t\t\t\t\thookItem._value = hookItem._nextValue;\n\t\t\t\t}\n\t\t\t\thookItem._pendingArgs = hookItem._nextValue = undefined;\n\t\t\t});\n\t\t} else {\n\t\t\thooks._pendingEffects.forEach(invokeCleanup);\n\t\t\thooks._pendingEffects.forEach(invokeEffect);\n\t\t\thooks._pendingEffects = [];\n\t\t\tcurrentIndex = 0;\n\t\t}\n\t}\n\tpreviousComponent = currentComponent;\n};\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions.diffed = vnode => {\n\tif (oldAfterDiff) oldAfterDiff(vnode);\n\n\tconst c = vnode._component;\n\tif (c && c.__hooks) {\n\t\tif (c.__hooks._pendingEffects.length) afterPaint(afterPaintEffects.push(c));\n\t\tc.__hooks._list.forEach(hookItem => {\n\t\t\tif (hookItem._pendingArgs) {\n\t\t\t\thookItem._args = hookItem._pendingArgs;\n\t\t\t}\n\t\t\thookItem._pendingArgs = undefined;\n\t\t});\n\t}\n\tpreviousComponent = currentComponent = null;\n};\n\n// TODO: Improve typing of commitQueue parameter\n/** @type {(vnode: import('./internal').VNode, commitQueue: any) => void} */\noptions._commit = (vnode, commitQueue) => {\n\tcommitQueue.some(component => {\n\t\ttry {\n\t\t\tcomponent._renderCallbacks.forEach(invokeCleanup);\n\t\t\tcomponent._renderCallbacks = component._renderCallbacks.filter(cb =>\n\t\t\t\tcb._value ? invokeEffect(cb) : true\n\t\t\t);\n\t\t} catch (e) {\n\t\t\tcommitQueue.some(c => {\n\t\t\t\tif (c._renderCallbacks) c._renderCallbacks = [];\n\t\t\t});\n\t\t\tcommitQueue = [];\n\t\t\toptions._catchError(e, component._vnode);\n\t\t}\n\t});\n\n\tif (oldCommit) oldCommit(vnode, commitQueue);\n};\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions.unmount = vnode => {\n\tif (oldBeforeUnmount) oldBeforeUnmount(vnode);\n\n\tconst c = vnode._component;\n\tif (c && c.__hooks) {\n\t\tlet hasErrored;\n\t\tc.__hooks._list.forEach(s => {\n\t\t\ttry {\n\t\t\t\tinvokeCleanup(s);\n\t\t\t} catch (e) {\n\t\t\t\thasErrored = e;\n\t\t\t}\n\t\t});\n\t\tc.__hooks = undefined;\n\t\tif (hasErrored) options._catchError(hasErrored, c._vnode);\n\t}\n};\n\n/**\n * Get a hook's state from the currentComponent\n * @param {number} index The index of the hook to get\n * @param {number} type The index of the hook to get\n * @returns {any}\n */\nfunction getHookState(index, type) {\n\tif (options._hook) {\n\t\toptions._hook(currentComponent, index, currentHook || type);\n\t}\n\tcurrentHook = 0;\n\n\t// Largely inspired by:\n\t// * https://github.com/michael-klein/funcy.js/blob/f6be73468e6ec46b0ff5aa3cc4c9baf72a29025a/src/hooks/core_hooks.mjs\n\t// * https://github.com/michael-klein/funcy.js/blob/650beaa58c43c33a74820a3c98b3c7079cf2e333/src/renderer.mjs\n\t// Other implementations to look at:\n\t// * https://codesandbox.io/s/mnox05qp8\n\tconst hooks =\n\t\tcurrentComponent.__hooks ||\n\t\t(currentComponent.__hooks = {\n\t\t\t_list: [],\n\t\t\t_pendingEffects: []\n\t\t});\n\n\tif (index >= hooks._list.length) {\n\t\thooks._list.push({});\n\t}\n\n\treturn hooks._list[index];\n}\n\n/**\n * @template {unknown} S\n * @param {import('./index').Dispatch>} [initialState]\n * @returns {[S, (state: S) => void]}\n */\nexport function useState(initialState) {\n\tcurrentHook = 1;\n\treturn useReducer(invokeOrReturn, initialState);\n}\n\n/**\n * @template {unknown} S\n * @template {unknown} A\n * @param {import('./index').Reducer} reducer\n * @param {import('./index').Dispatch>} initialState\n * @param {(initialState: any) => void} [init]\n * @returns {[ S, (state: S) => void ]}\n */\nexport function useReducer(reducer, initialState, init) {\n\t/** @type {import('./internal').ReducerHookState} */\n\tconst hookState = getHookState(currentIndex++, 2);\n\thookState._reducer = reducer;\n\tif (!hookState._component) {\n\t\thookState._value = [\n\t\t\t!init ? invokeOrReturn(undefined, initialState) : init(initialState),\n\n\t\t\taction => {\n\t\t\t\tconst currentValue = hookState._nextValue\n\t\t\t\t\t? hookState._nextValue[0]\n\t\t\t\t\t: hookState._value[0];\n\t\t\t\tconst nextValue = hookState._reducer(currentValue, action);\n\n\t\t\t\tif (currentValue !== nextValue) {\n\t\t\t\t\thookState._nextValue = [nextValue, hookState._value[1]];\n\t\t\t\t\thookState._component.setState({});\n\t\t\t\t}\n\t\t\t}\n\t\t];\n\n\t\thookState._component = currentComponent;\n\n\t\tif (!currentComponent._hasScuFromHooks) {\n\t\t\tcurrentComponent._hasScuFromHooks = true;\n\t\t\tlet prevScu = currentComponent.shouldComponentUpdate;\n\t\t\tconst prevCWU = currentComponent.componentWillUpdate;\n\n\t\t\t// If we're dealing with a forced update `shouldComponentUpdate` will\n\t\t\t// not be called. But we use that to update the hook values, so we\n\t\t\t// need to call it.\n\t\t\tcurrentComponent.componentWillUpdate = function (p, s, c) {\n\t\t\t\tif (this._force) {\n\t\t\t\t\tlet tmp = prevScu;\n\t\t\t\t\t// Clear to avoid other sCU hooks from being called\n\t\t\t\t\tprevScu = undefined;\n\t\t\t\t\tupdateHookState(p, s, c);\n\t\t\t\t\tprevScu = tmp;\n\t\t\t\t}\n\n\t\t\t\tif (prevCWU) prevCWU.call(this, p, s, c);\n\t\t\t};\n\n\t\t\t// This SCU has the purpose of bailing out after repeated updates\n\t\t\t// to stateful hooks.\n\t\t\t// we store the next value in _nextValue[0] and keep doing that for all\n\t\t\t// state setters, if we have next states and\n\t\t\t// all next states within a component end up being equal to their original state\n\t\t\t// we are safe to bail out for this specific component.\n\t\t\t/**\n\t\t\t *\n\t\t\t * @type {import('./internal').Component[\"shouldComponentUpdate\"]}\n\t\t\t */\n\t\t\t// @ts-ignore - We don't use TS to downtranspile\n\t\t\t// eslint-disable-next-line no-inner-declarations\n\t\t\tfunction updateHookState(p, s, c) {\n\t\t\t\tif (!hookState._component.__hooks) return true;\n\n\t\t\t\t/** @type {(x: import('./internal').HookState) => x is import('./internal').ReducerHookState} */\n\t\t\t\tconst isStateHook = x => !!x._component;\n\t\t\t\tconst stateHooks =\n\t\t\t\t\thookState._component.__hooks._list.filter(isStateHook);\n\n\t\t\t\tconst allHooksEmpty = stateHooks.every(x => !x._nextValue);\n\t\t\t\t// When we have no updated hooks in the component we invoke the previous SCU or\n\t\t\t\t// traverse the VDOM tree further.\n\t\t\t\tif (allHooksEmpty) {\n\t\t\t\t\treturn prevScu ? prevScu.call(this, p, s, c) : true;\n\t\t\t\t}\n\n\t\t\t\t// We check whether we have components with a nextValue set that\n\t\t\t\t// have values that aren't equal to one another this pushes\n\t\t\t\t// us to update further down the tree\n\t\t\t\tlet shouldUpdate = hookState._component.props !== p;\n\t\t\t\tstateHooks.forEach(hookItem => {\n\t\t\t\t\tif (hookItem._nextValue) {\n\t\t\t\t\t\tconst currentValue = hookItem._value[0];\n\t\t\t\t\t\thookItem._value = hookItem._nextValue;\n\t\t\t\t\t\thookItem._nextValue = undefined;\n\t\t\t\t\t\tif (currentValue !== hookItem._value[0]) shouldUpdate = true;\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\treturn prevScu\n\t\t\t\t\t? prevScu.call(this, p, s, c) || shouldUpdate\n\t\t\t\t\t: shouldUpdate;\n\t\t\t}\n\n\t\t\tcurrentComponent.shouldComponentUpdate = updateHookState;\n\t\t}\n\t}\n\n\treturn hookState._nextValue || hookState._value;\n}\n\n/**\n * @param {import('./internal').Effect} callback\n * @param {unknown[]} args\n * @returns {void}\n */\nexport function useEffect(callback, args) {\n\t/** @type {import('./internal').EffectHookState} */\n\tconst state = getHookState(currentIndex++, 3);\n\tif (!options._skipEffects && argsChanged(state._args, args)) {\n\t\tstate._value = callback;\n\t\tstate._pendingArgs = args;\n\n\t\tcurrentComponent.__hooks._pendingEffects.push(state);\n\t}\n}\n\n/**\n * @param {import('./internal').Effect} callback\n * @param {unknown[]} args\n * @returns {void}\n */\nexport function useLayoutEffect(callback, args) {\n\t/** @type {import('./internal').EffectHookState} */\n\tconst state = getHookState(currentIndex++, 4);\n\tif (!options._skipEffects && argsChanged(state._args, args)) {\n\t\tstate._value = callback;\n\t\tstate._pendingArgs = args;\n\n\t\tcurrentComponent._renderCallbacks.push(state);\n\t}\n}\n\n/** @type {(initialValue: unknown) => unknown} */\nexport function useRef(initialValue) {\n\tcurrentHook = 5;\n\treturn useMemo(() => ({ current: initialValue }), []);\n}\n\n/**\n * @param {object} ref\n * @param {() => object} createHandle\n * @param {unknown[]} args\n * @returns {void}\n */\nexport function useImperativeHandle(ref, createHandle, args) {\n\tcurrentHook = 6;\n\tuseLayoutEffect(\n\t\t() => {\n\t\t\tif (typeof ref == 'function') {\n\t\t\t\tconst result = ref(createHandle());\n\t\t\t\treturn () => {\n\t\t\t\t\tref(null);\n\t\t\t\t\tif (result && typeof result == 'function') result();\n\t\t\t\t};\n\t\t\t} else if (ref) {\n\t\t\t\tref.current = createHandle();\n\t\t\t\treturn () => (ref.current = null);\n\t\t\t}\n\t\t},\n\t\targs == null ? args : args.concat(ref)\n\t);\n}\n\n/**\n * @template {unknown} T\n * @param {() => T} factory\n * @param {unknown[]} args\n * @returns {T}\n */\nexport function useMemo(factory, args) {\n\t/** @type {import('./internal').MemoHookState} */\n\tconst state = getHookState(currentIndex++, 7);\n\tif (argsChanged(state._args, args)) {\n\t\tstate._value = factory();\n\t\tstate._args = args;\n\t\tstate._factory = factory;\n\t}\n\n\treturn state._value;\n}\n\n/**\n * @param {() => void} callback\n * @param {unknown[]} args\n * @returns {() => void}\n */\nexport function useCallback(callback, args) {\n\tcurrentHook = 8;\n\treturn useMemo(() => callback, args);\n}\n\n/**\n * @param {import('./internal').PreactContext} context\n */\nexport function useContext(context) {\n\tconst provider = currentComponent.context[context._id];\n\t// We could skip this call here, but than we'd not call\n\t// `options._hook`. We need to do that in order to make\n\t// the devtools aware of this hook.\n\t/** @type {import('./internal').ContextHookState} */\n\tconst state = getHookState(currentIndex++, 9);\n\t// The devtools needs access to the context object to\n\t// be able to pull of the default value when no provider\n\t// is present in the tree.\n\tstate._context = context;\n\tif (!provider) return context._defaultValue;\n\t// This is probably not safe to convert to \"!\"\n\tif (state._value == null) {\n\t\tstate._value = true;\n\t\tprovider.sub(currentComponent);\n\t}\n\treturn provider.props.value;\n}\n\n/**\n * Display a custom label for a custom hook for the devtools panel\n * @type {(value: T, cb?: (value: T) => string | number) => void}\n */\nexport function useDebugValue(value, formatter) {\n\tif (options.useDebugValue) {\n\t\toptions.useDebugValue(\n\t\t\tformatter ? formatter(value) : /** @type {any}*/ (value)\n\t\t);\n\t}\n}\n\n/**\n * @param {(error: unknown, errorInfo: import('preact').ErrorInfo) => void} cb\n * @returns {[unknown, () => void]}\n */\nexport function useErrorBoundary(cb) {\n\t/** @type {import('./internal').ErrorBoundaryHookState} */\n\tconst state = getHookState(currentIndex++, 10);\n\tconst errState = useState();\n\tstate._value = cb;\n\tif (!currentComponent.componentDidCatch) {\n\t\tcurrentComponent.componentDidCatch = (err, errorInfo) => {\n\t\t\tif (state._value) state._value(err, errorInfo);\n\t\t\terrState[1](err);\n\t\t};\n\t}\n\treturn [\n\t\terrState[0],\n\t\t() => {\n\t\t\terrState[1](undefined);\n\t\t}\n\t];\n}\n\n/** @type {() => string} */\nexport function useId() {\n\t/** @type {import('./internal').IdHookState} */\n\tconst state = getHookState(currentIndex++, 11);\n\tif (!state._value) {\n\t\t// Grab either the root node or the nearest async boundary node.\n\t\t/** @type {import('./internal').VNode} */\n\t\tlet root = currentComponent._vnode;\n\t\twhile (root !== null && !root._mask && root._parent !== null) {\n\t\t\troot = root._parent;\n\t\t}\n\n\t\tlet mask = root._mask || (root._mask = [0, 0]);\n\t\tstate._value = 'P' + mask[0] + '-' + mask[1]++;\n\t}\n\n\treturn state._value;\n}\n\n/**\n * After paint effects consumer.\n */\nfunction flushAfterPaintEffects() {\n\tlet component;\n\twhile ((component = afterPaintEffects.shift())) {\n\t\tif (!component._parentDom || !component.__hooks) continue;\n\t\ttry {\n\t\t\tcomponent.__hooks._pendingEffects.forEach(invokeCleanup);\n\t\t\tcomponent.__hooks._pendingEffects.forEach(invokeEffect);\n\t\t\tcomponent.__hooks._pendingEffects = [];\n\t\t} catch (e) {\n\t\t\tcomponent.__hooks._pendingEffects = [];\n\t\t\toptions._catchError(e, component._vnode);\n\t\t}\n\t}\n}\n\nlet HAS_RAF = typeof requestAnimationFrame == 'function';\n\n/**\n * Schedule a callback to be invoked after the browser has a chance to paint a new frame.\n * Do this by combining requestAnimationFrame (rAF) + setTimeout to invoke a callback after\n * the next browser frame.\n *\n * Also, schedule a timeout in parallel to the the rAF to ensure the callback is invoked\n * even if RAF doesn't fire (for example if the browser tab is not visible)\n *\n * @param {() => void} callback\n */\nfunction afterNextFrame(callback) {\n\tconst done = () => {\n\t\tclearTimeout(timeout);\n\t\tif (HAS_RAF) cancelAnimationFrame(raf);\n\t\tsetTimeout(callback);\n\t};\n\tconst timeout = setTimeout(done, RAF_TIMEOUT);\n\n\tlet raf;\n\tif (HAS_RAF) {\n\t\traf = requestAnimationFrame(done);\n\t}\n}\n\n// Note: if someone used options.debounceRendering = requestAnimationFrame,\n// then effects will ALWAYS run on the NEXT frame instead of the current one, incurring a ~16ms delay.\n// Perhaps this is not such a big deal.\n/**\n * Schedule afterPaintEffects flush after the browser paints\n * @param {number} newQueueLength\n * @returns {void}\n */\nfunction afterPaint(newQueueLength) {\n\tif (newQueueLength === 1 || prevRaf !== options.requestAnimationFrame) {\n\t\tprevRaf = options.requestAnimationFrame;\n\t\t(prevRaf || afterNextFrame)(flushAfterPaintEffects);\n\t}\n}\n\n/**\n * @param {import('./internal').HookState} hook\n * @returns {void}\n */\nfunction invokeCleanup(hook) {\n\t// A hook cleanup can introduce a call to render which creates a new root, this will call options.vnode\n\t// and move the currentComponent away.\n\tconst comp = currentComponent;\n\tlet cleanup = hook._cleanup;\n\tif (typeof cleanup == 'function') {\n\t\thook._cleanup = undefined;\n\t\tcleanup();\n\t}\n\n\tcurrentComponent = comp;\n}\n\n/**\n * Invoke a Hook's effect\n * @param {import('./internal').EffectHookState} hook\n * @returns {void}\n */\nfunction invokeEffect(hook) {\n\t// A hook call can introduce a call to render which creates a new root, this will call options.vnode\n\t// and move the currentComponent away.\n\tconst comp = currentComponent;\n\thook._cleanup = hook._value();\n\tcurrentComponent = comp;\n}\n\n/**\n * @param {unknown[]} oldArgs\n * @param {unknown[]} newArgs\n * @returns {boolean}\n */\nfunction argsChanged(oldArgs, newArgs) {\n\treturn (\n\t\t!oldArgs ||\n\t\toldArgs.length !== newArgs.length ||\n\t\tnewArgs.some((arg, index) => arg !== oldArgs[index])\n\t);\n}\n\n/**\n * @template Arg\n * @param {Arg} arg\n * @param {(arg: Arg) => any} f\n * @returns {any}\n */\nfunction invokeOrReturn(arg, f) {\n\treturn typeof f == 'function' ? f(arg) : f;\n}\n"],"names":["currentIndex","currentComponent","previousComponent","prevRaf","currentHook","afterPaintEffects","options","_options","oldBeforeDiff","__b","oldBeforeRender","__r","oldAfterDiff","diffed","oldCommit","__c","oldBeforeUnmount","unmount","oldRoot","__","getHookState","index","type","__h","hooks","__H","length","push","useState","initialState","useReducer","invokeOrReturn","reducer","init","hookState","_reducer","undefined","action","currentValue","__N","nextValue","setState","__f","updateHookState","p","s","c","stateHooks","filter","x","every","prevScu","call","this","shouldUpdate","props","forEach","hookItem","shouldComponentUpdate","prevCWU","componentWillUpdate","__e","tmp","useEffect","callback","args","state","__s","argsChanged","_pendingArgs","useLayoutEffect","useRef","initialValue","useMemo","current","useImperativeHandle","ref","createHandle","result","concat","factory","useCallback","useContext","context","provider","sub","value","useDebugValue","formatter","useErrorBoundary","cb","errState","componentDidCatch","err","errorInfo","useId","root","__v","__m","mask","flushAfterPaintEffects","component","shift","__P","invokeCleanup","invokeEffect","e","vnode","parentDom","__k","requestAnimationFrame","afterNextFrame","commitQueue","some","hasErrored","HAS_RAF","raf","done","clearTimeout","timeout","cancelAnimationFrame","setTimeout","hook","comp","cleanup","oldArgs","newArgs","arg","f"],"mappings":"iCAGA,IAAIA,EAGAC,EAGAC,EAsBAC,EAnBAC,EAAc,EAGdC,EAAoB,GAGlBC,EAAuDC,EAEzDC,EAAgBF,EAAOG,IACvBC,EAAkBJ,EAAOK,IACzBC,EAAeN,EAAQO,OACvBC,EAAYR,EAAOS,IACnBC,EAAmBV,EAAQW,QAC3BC,EAAUZ,EAAOa,GAiHrB,SAASC,EAAaC,EAAOC,GACxBhB,EAAOiB,KACVjB,EAAOiB,IAAOtB,EAAkBoB,EAAOjB,GAAekB,GAEvDlB,EAAc,EAOd,IAAMoB,EACLvB,EAAgBwB,MACfxB,EAAgBwB,IAAW,CAC3BN,GAAO,GACPI,IAAiB,KAOnB,OAJIF,GAASG,EAAKL,GAAOO,QACxBF,EAAKL,GAAOQ,KAAK,CAAE,GAGbH,EAAKL,GAAOE,EACpB,CAOO,SAASO,EAASC,GAExB,OADAzB,EAAc,EACP0B,EAAWC,EAAgBF,EACnC,CAUgB,SAAAC,EAAWE,EAASH,EAAcI,GAEjD,IAAMC,EAAYd,EAAapB,IAAgB,GAE/C,GADAkC,EAAUC,EAAWH,GAChBE,EAASnB,MACbmB,EAASf,GAAU,CACjBc,EAAiDA,EAAKJ,GAA/CE,OAAeK,EAAWP,GAElC,SAAAQ,GACC,IAAMC,EAAeJ,EAASK,IAC3BL,EAASK,IAAY,GACrBL,EAASf,GAAQ,GACdqB,EAAYN,EAAUC,EAASG,EAAcD,GAE/CC,IAAiBE,IACpBN,EAASK,IAAc,CAACC,EAAWN,EAASf,GAAQ,IACpDe,EAASnB,IAAY0B,SAAS,CAAE,GAElC,GAGDP,EAASnB,IAAcd,GAElBA,EAAgByC,KAAmB,CAAA,IAgC9BC,EAAT,SAAyBC,EAAGC,EAAGC,GAC9B,IAAKZ,EAASnB,IAAAU,IAAqB,OAAW,EAG9C,IACMsB,EACLb,EAASnB,IAAAU,IAAAN,GAA0B6B,OAFhB,SAAAC,GAAC,QAAMA,EAAClC,GAAW,GAOvC,GAHsBgC,EAAWG,MAAM,SAAAD,GAAC,OAAKA,EAACV,GAAW,GAIxD,OAAOY,GAAUA,EAAQC,KAAKC,KAAMT,EAAGC,EAAGC,GAM3C,IAAIQ,EAAepB,EAASnB,IAAYwC,QAAUX,EAUlD,OATAG,EAAWS,QAAQ,SAAAC,GAClB,GAAIA,EAAQlB,IAAa,CACxB,IAAMD,EAAemB,EAAQtC,GAAQ,GACrCsC,EAAQtC,GAAUsC,EAAQlB,IAC1BkB,EAAQlB,SAAcH,EAClBE,IAAiBmB,EAAQtC,GAAQ,KAAImC,GAAe,EACzD,CACD,GAEOH,GACJA,EAAQC,KAAKC,KAAMT,EAAGC,EAAGC,IACzBQ,CACJ,EA9DArD,EAAgByC,KAAoB,EACpC,IAAIS,EAAUlD,EAAiByD,sBACzBC,EAAU1D,EAAiB2D,oBAKjC3D,EAAiB2D,oBAAsB,SAAUhB,EAAGC,EAAGC,GACtD,GAAIO,KAAIQ,IAAS,CAChB,IAAIC,EAAMX,EAEVA,OAAUf,EACVO,EAAgBC,EAAGC,EAAGC,GACtBK,EAAUW,CACX,CAEIH,GAASA,EAAQP,KAAKC,KAAMT,EAAGC,EAAGC,EACvC,EA+CA7C,EAAiByD,sBAAwBf,CAC1C,CAGD,OAAOT,EAASK,KAAeL,EAASf,EACzC,CAOO,SAAS4C,EAAUC,EAAUC,GAEnC,IAAMC,EAAQ9C,EAAapB,IAAgB,IACtCM,EAAO6D,KAAiBC,EAAYF,EAAKzC,IAAQwC,KACrDC,EAAK/C,GAAU6C,EACfE,EAAMG,EAAeJ,EAErBhE,EAAgBwB,IAAAF,IAAyBI,KAAKuC,GAEhD,CAOgB,SAAAI,EAAgBN,EAAUC,GAEzC,IAAMC,EAAQ9C,EAAapB,IAAgB,IACtCM,EAAO6D,KAAiBC,EAAYF,EAAKzC,IAAQwC,KACrDC,EAAK/C,GAAU6C,EACfE,EAAMG,EAAeJ,EAErBhE,EAAgBsB,IAAkBI,KAAKuC,GAEzC,CAGO,SAASK,EAAOC,GAEtB,OADApE,EAAc,EACPqE,EAAQ,WAAO,MAAA,CAAEC,QAASF,EAAc,EAAG,GACnD,CAQgB,SAAAG,EAAoBC,EAAKC,EAAcZ,GACtD7D,EAAc,EACdkE,EACC,WACC,GAAkB,mBAAPM,EAAmB,CAC7B,IAAME,EAASF,EAAIC,KACnB,OAAa,WACZD,EAAI,MACAE,GAA2B,mBAAVA,GAAsBA,GAC5C,CACD,CAAWF,GAAAA,EAEV,OADAA,EAAIF,QAAUG,IACP,WAAA,OAAOD,EAAIF,QAAU,IAAI,CAElC,EACQ,MAART,EAAeA,EAAOA,EAAKc,OAAOH,GAEpC,CAQgB,SAAAH,EAAQO,EAASf,GAEhC,IAAMC,EAAQ9C,EAAapB,IAAgB,GAO3C,OANIoE,EAAYF,EAAKzC,IAAQwC,KAC5BC,EAAK/C,GAAU6D,IACfd,EAAKzC,IAASwC,EACdC,EAAK3C,IAAYyD,GAGXd,EAAK/C,EACb,CAOO,SAAS8D,EAAYjB,EAAUC,GAErC,OADA7D,EAAc,EACPqE,EAAQ,WAAA,OAAMT,CAAQ,EAAEC,EAChC,CAKO,SAASiB,EAAWC,GAC1B,IAAMC,EAAWnF,EAAiBkF,QAAQA,EAAOpE,KAK3CmD,EAAQ9C,EAAapB,IAAgB,GAK3C,OADAkE,EAAKpB,EAAYqC,EACZC,GAEe,MAAhBlB,EAAK/C,KACR+C,EAAK/C,IAAU,EACfiE,EAASC,IAAIpF,IAEPmF,EAAS7B,MAAM+B,OANAH,EAAOhE,EAO9B,CAMgB,SAAAoE,EAAcD,EAAOE,GAChClF,EAAQiF,eACXjF,EAAQiF,cACPC,EAAYA,EAAUF,GAAM,EAG/B,CAMO,SAASG,EAAiBC,GAEhC,IAAMxB,EAAQ9C,EAAapB,IAAgB,IACrC2F,EAAW/D,IAQjB,OAPAsC,EAAK/C,GAAUuE,EACVzF,EAAiB2F,oBACrB3F,EAAiB2F,kBAAoB,SAACC,EAAKC,GACtC5B,EAAK/C,IAAS+C,EAAK/C,GAAQ0E,EAAKC,GACpCH,EAAS,GAAGE,EACb,GAEM,CACNF,EAAS,GACT,WACCA,EAAS,QAAGvD,EACb,EAEF,CAGO,SAAS2D,IAEf,IAAM7B,EAAQ9C,EAAapB,IAAgB,IAC3C,IAAKkE,EAAK/C,GAAS,CAIlB,IADA,IAAI6E,EAAO/F,EAAgBgG,IACX,OAATD,IAAkBA,EAAIE,KAA2B,OAAjBF,EAAI7E,IAC1C6E,EAAOA,EAAI7E,GAGZ,IAAIgF,EAAOH,EAAIE,MAAWF,EAAIE,IAAS,CAAC,EAAG,IAC3ChC,EAAK/C,GAAU,IAAMgF,EAAK,GAAK,IAAMA,EAAK,IAC3C,CAEA,OAAOjC,EAAK/C,EACb,CAKA,SAASiF,IAER,IADA,IAAIC,EACIA,EAAYhG,EAAkBiG,SACrC,GAAKD,EAASE,KAAgBF,EAAS5E,IACvC,IACC4E,EAAS5E,IAAAF,IAAyBiC,QAAQgD,GAC1CH,EAAS5E,IAAAF,IAAyBiC,QAAQiD,GAC1CJ,EAAS5E,IAAAF,IAA2B,EAIrC,CAHE,MAAOmF,GACRL,EAAS5E,IAAAF,IAA2B,GACpCjB,EAAOuD,IAAa6C,EAAGL,EAASJ,IACjC,CAEF,CA1aA3F,EAAOG,IAAS,SAAAkG,GACf1G,EAAmB,KACfO,GAAeA,EAAcmG,EAClC,EAEArG,EAAOa,GAAS,SAACwF,EAAOC,GACnBD,GAASC,EAASC,KAAcD,EAASC,IAAAX,MAC5CS,EAAKT,IAASU,EAASC,IAAAX,KAGpBhF,GAASA,EAAQyF,EAAOC,EAC7B,EAGAtG,EAAOK,IAAW,SAAAgG,GACbjG,GAAiBA,EAAgBiG,GAGrC3G,EAAe,EAEf,IAAMwB,GAHNvB,EAAmB0G,EAAK5F,KAGMU,IAC1BD,IACCtB,IAAsBD,GACzBuB,EAAKD,IAAmB,GACxBtB,EAAgBsB,IAAoB,GACpCC,EAAKL,GAAOqC,QAAQ,SAAAC,GACfA,EAAQlB,MACXkB,EAAQtC,GAAUsC,EAAQlB,KAE3BkB,EAASY,EAAeZ,EAAQlB,SAAcH,CAC/C,KAEAZ,EAAKD,IAAiBiC,QAAQgD,GAC9BhF,EAAKD,IAAiBiC,QAAQiD,GAC9BjF,EAAKD,IAAmB,GACxBvB,EAAe,IAGjBE,EAAoBD,CACrB,EAGAK,EAAQO,OAAS,SAAA8F,GACZ/F,GAAcA,EAAa+F,GAE/B,IAAM7D,EAAI6D,EAAK5F,IACX+B,GAAKA,EAACrB,MACLqB,EAACrB,IAAAF,IAAyBG,SAgaR,IAha2BrB,EAAkBsB,KAAKmB,IAga7C3C,IAAYG,EAAQwG,yBAC/C3G,EAAUG,EAAQwG,wBACNC,GAAgBX,IAja5BtD,EAACrB,IAAAN,GAAeqC,QAAQ,SAAAC,GACnBA,EAASY,IACZZ,EAAQhC,IAASgC,EAASY,GAE3BZ,EAASY,OAAejC,CACzB,IAEDlC,EAAoBD,EAAmB,IACxC,EAIAK,EAAOS,IAAW,SAAC4F,EAAOK,GACzBA,EAAYC,KAAK,SAAAZ,GAChB,IACCA,EAAS9E,IAAkBiC,QAAQgD,GACnCH,EAAS9E,IAAoB8E,EAAS9E,IAAkByB,OAAO,SAAA0C,GAAE,OAChEA,EAAEvE,IAAUsF,EAAaf,EAAU,EAQrC,CANE,MAAOgB,GACRM,EAAYC,KAAK,SAAAnE,GACZA,EAACvB,MAAmBuB,EAACvB,IAAoB,GAC9C,GACAyF,EAAc,GACd1G,EAAOuD,IAAa6C,EAAGL,EAASJ,IACjC,CACD,GAEInF,GAAWA,EAAU6F,EAAOK,EACjC,EAGA1G,EAAQW,QAAU,SAAA0F,GACb3F,GAAkBA,EAAiB2F,GAEvC,IAEKO,EAFCpE,EAAI6D,EAAK5F,IACX+B,GAAKA,EAACrB,MAETqB,EAACrB,IAAAN,GAAeqC,QAAQ,SAAAX,GACvB,IACC2D,EAAc3D,EAGf,CAFE,MAAO6D,GACRQ,EAAaR,CACd,CACD,GACA5D,EAACrB,SAAWW,EACR8E,GAAY5G,EAAOuD,IAAaqD,EAAYpE,EAACmD,KAEnD,EA4UA,IAAIkB,EAA0C,mBAAzBL,sBAYrB,SAASC,EAAe/C,GACvB,IAOIoD,EAPEC,EAAO,WACZC,aAAaC,GACTJ,GAASK,qBAAqBJ,GAClCK,WAAWzD,EACZ,EACMuD,EAAUE,WAAWJ,EAlcR,IAqcfF,IACHC,EAAMN,sBAAsBO,GAE9B,CAqBA,SAASb,EAAckB,GAGtB,IAAMC,EAAO1H,EACT2H,EAAUF,EAAI3G,IACI,mBAAX6G,IACVF,EAAI3G,SAAYqB,EAChBwF,KAGD3H,EAAmB0H,CACpB,CAOA,SAASlB,EAAaiB,GAGrB,IAAMC,EAAO1H,EACbyH,EAAI3G,IAAY2G,EAAIvG,KACpBlB,EAAmB0H,CACpB,CAOA,SAASvD,EAAYyD,EAASC,GAC7B,OACED,GACDA,EAAQnG,SAAWoG,EAAQpG,QAC3BoG,EAAQb,KAAK,SAACc,EAAK1G,GAAU,OAAA0G,IAAQF,EAAQxG,EAAM,EAErD,CAQA,SAASU,EAAegG,EAAKC,GAC5B,MAAmB,mBAALA,EAAkBA,EAAED,GAAOC,CAC1C"} \ No newline at end of file diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/dist/hooks.umd.js b/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/dist/hooks.umd.js new file mode 100644 index 0000000000000..f140f2b3fed38 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/dist/hooks.umd.js @@ -0,0 +1,2 @@ +!function(n,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("preact")):"function"==typeof define&&define.amd?define(["exports","preact"],t):t((n||self).preactHooks={},n.preact)}(this,function(n,t){var u,i,r,o,f=0,c=[],e=t.options,a=e.__b,v=e.__r,l=e.diffed,d=e.__c,s=e.unmount,p=e.__;function y(n,t){e.__h&&e.__h(i,n,f||t),f=0;var u=i.__H||(i.__H={__:[],__h:[]});return n>=u.__.length&&u.__.push({}),u.__[n]}function h(n){return f=1,m(j,n)}function m(n,t,r){var o=y(u++,2);if(o.t=n,!o.__c&&(o.__=[r?r(t):j(void 0,t),function(n){var t=o.__N?o.__N[0]:o.__[0],u=o.t(t,n);t!==u&&(o.__N=[u,o.__[1]],o.__c.setState({}))}],o.__c=i,!i.__f)){var f=function(n,t,u){if(!o.__c.__H)return!0;var i=o.__c.__H.__.filter(function(n){return!!n.__c});if(i.every(function(n){return!n.__N}))return!c||c.call(this,n,t,u);var r=o.__c.props!==n;return i.forEach(function(n){if(n.__N){var t=n.__[0];n.__=n.__N,n.__N=void 0,t!==n.__[0]&&(r=!0)}}),c&&c.call(this,n,t,u)||r};i.__f=!0;var c=i.shouldComponentUpdate,e=i.componentWillUpdate;i.componentWillUpdate=function(n,t,u){if(this.__e){var i=c;c=void 0,f(n,t,u),c=i}e&&e.call(this,n,t,u)},i.shouldComponentUpdate=f}return o.__N||o.__}function T(n,t){var r=y(u++,4);!e.__s&&g(r.__H,t)&&(r.__=n,r.u=t,i.__h.push(r))}function _(n,t){var i=y(u++,7);return g(i.__H,t)&&(i.__=n(),i.__H=t,i.__h=n),i.__}function b(){for(var n;n=c.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(A),n.__H.__h.forEach(F),n.__H.__h=[]}catch(t){n.__H.__h=[],e.__e(t,n.__v)}}e.__b=function(n){i=null,a&&a(n)},e.__=function(n,t){n&&t.__k&&t.__k.__m&&(n.__m=t.__k.__m),p&&p(n,t)},e.__r=function(n){v&&v(n),u=0;var t=(i=n.__c).__H;t&&(r===i?(t.__h=[],i.__h=[],t.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.forEach(A),t.__h.forEach(F),t.__h=[],u=0)),r=i},e.diffed=function(n){l&&l(n);var t=n.__c;t&&t.__H&&(t.__H.__h.length&&(1!==c.push(t)&&o===e.requestAnimationFrame||((o=e.requestAnimationFrame)||x)(b)),t.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),r=i=null},e.__c=function(n,t){t.some(function(n){try{n.__h.forEach(A),n.__h=n.__h.filter(function(n){return!n.__||F(n)})}catch(u){t.some(function(n){n.__h&&(n.__h=[])}),t=[],e.__e(u,n.__v)}}),d&&d(n,t)},e.unmount=function(n){s&&s(n);var t,u=n.__c;u&&u.__H&&(u.__H.__.forEach(function(n){try{A(n)}catch(n){t=n}}),u.__H=void 0,t&&e.__e(t,u.__v))};var q="function"==typeof requestAnimationFrame;function x(n){var t,u=function(){clearTimeout(i),q&&cancelAnimationFrame(t),setTimeout(n)},i=setTimeout(u,35);q&&(t=requestAnimationFrame(u))}function A(n){var t=i,u=n.__c;"function"==typeof u&&(n.__c=void 0,u()),i=t}function F(n){var t=i;n.__c=n.__(),i=t}function g(n,t){return!n||n.length!==t.length||t.some(function(t,u){return t!==n[u]})}function j(n,t){return"function"==typeof t?t(n):t}n.useCallback=function(n,t){return f=8,_(function(){return n},t)},n.useContext=function(n){var t=i.context[n.__c],r=y(u++,9);return r.c=n,t?(null==r.__&&(r.__=!0,t.sub(i)),t.props.value):n.__},n.useDebugValue=function(n,t){e.useDebugValue&&e.useDebugValue(t?t(n):n)},n.useEffect=function(n,t){var r=y(u++,3);!e.__s&&g(r.__H,t)&&(r.__=n,r.u=t,i.__H.__h.push(r))},n.useErrorBoundary=function(n){var t=y(u++,10),r=h();return t.__=n,i.componentDidCatch||(i.componentDidCatch=function(n,u){t.__&&t.__(n,u),r[1](n)}),[r[0],function(){r[1](void 0)}]},n.useId=function(){var n=y(u++,11);if(!n.__){for(var t=i.__v;null!==t&&!t.__m&&null!==t.__;)t=t.__;var r=t.__m||(t.__m=[0,0]);n.__="P"+r[0]+"-"+r[1]++}return n.__},n.useImperativeHandle=function(n,t,u){f=6,T(function(){if("function"==typeof n){var u=n(t());return function(){n(null),u&&"function"==typeof u&&u()}}if(n)return n.current=t(),function(){return n.current=null}},null==u?u:u.concat(n))},n.useLayoutEffect=T,n.useMemo=_,n.useReducer=m,n.useRef=function(n){return f=5,_(function(){return{current:n}},[])},n.useState=h}); +//# sourceMappingURL=hooks.umd.js.map diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/dist/hooks.umd.js.map b/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/dist/hooks.umd.js.map new file mode 100644 index 0000000000000..45d93dcee57a9 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/dist/hooks.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hooks.umd.js","sources":["../src/index.js"],"sourcesContent":["import { options as _options } from 'preact';\n\n/** @type {number} */\nlet currentIndex;\n\n/** @type {import('./internal').Component} */\nlet currentComponent;\n\n/** @type {import('./internal').Component} */\nlet previousComponent;\n\n/** @type {number} */\nlet currentHook = 0;\n\n/** @type {Array} */\nlet afterPaintEffects = [];\n\n// Cast to use internal Options type\nconst options = /** @type {import('./internal').Options} */ (_options);\n\nlet oldBeforeDiff = options._diff;\nlet oldBeforeRender = options._render;\nlet oldAfterDiff = options.diffed;\nlet oldCommit = options._commit;\nlet oldBeforeUnmount = options.unmount;\nlet oldRoot = options._root;\n\n// We take the minimum timeout for requestAnimationFrame to ensure that\n// the callback is invoked after the next frame. 35ms is based on a 30hz\n// refresh rate, which is the minimum rate for a smooth user experience.\nconst RAF_TIMEOUT = 35;\nlet prevRaf;\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions._diff = vnode => {\n\tcurrentComponent = null;\n\tif (oldBeforeDiff) oldBeforeDiff(vnode);\n};\n\noptions._root = (vnode, parentDom) => {\n\tif (vnode && parentDom._children && parentDom._children._mask) {\n\t\tvnode._mask = parentDom._children._mask;\n\t}\n\n\tif (oldRoot) oldRoot(vnode, parentDom);\n};\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions._render = vnode => {\n\tif (oldBeforeRender) oldBeforeRender(vnode);\n\n\tcurrentComponent = vnode._component;\n\tcurrentIndex = 0;\n\n\tconst hooks = currentComponent.__hooks;\n\tif (hooks) {\n\t\tif (previousComponent === currentComponent) {\n\t\t\thooks._pendingEffects = [];\n\t\t\tcurrentComponent._renderCallbacks = [];\n\t\t\thooks._list.forEach(hookItem => {\n\t\t\t\tif (hookItem._nextValue) {\n\t\t\t\t\thookItem._value = hookItem._nextValue;\n\t\t\t\t}\n\t\t\t\thookItem._pendingArgs = hookItem._nextValue = undefined;\n\t\t\t});\n\t\t} else {\n\t\t\thooks._pendingEffects.forEach(invokeCleanup);\n\t\t\thooks._pendingEffects.forEach(invokeEffect);\n\t\t\thooks._pendingEffects = [];\n\t\t\tcurrentIndex = 0;\n\t\t}\n\t}\n\tpreviousComponent = currentComponent;\n};\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions.diffed = vnode => {\n\tif (oldAfterDiff) oldAfterDiff(vnode);\n\n\tconst c = vnode._component;\n\tif (c && c.__hooks) {\n\t\tif (c.__hooks._pendingEffects.length) afterPaint(afterPaintEffects.push(c));\n\t\tc.__hooks._list.forEach(hookItem => {\n\t\t\tif (hookItem._pendingArgs) {\n\t\t\t\thookItem._args = hookItem._pendingArgs;\n\t\t\t}\n\t\t\thookItem._pendingArgs = undefined;\n\t\t});\n\t}\n\tpreviousComponent = currentComponent = null;\n};\n\n// TODO: Improve typing of commitQueue parameter\n/** @type {(vnode: import('./internal').VNode, commitQueue: any) => void} */\noptions._commit = (vnode, commitQueue) => {\n\tcommitQueue.some(component => {\n\t\ttry {\n\t\t\tcomponent._renderCallbacks.forEach(invokeCleanup);\n\t\t\tcomponent._renderCallbacks = component._renderCallbacks.filter(cb =>\n\t\t\t\tcb._value ? invokeEffect(cb) : true\n\t\t\t);\n\t\t} catch (e) {\n\t\t\tcommitQueue.some(c => {\n\t\t\t\tif (c._renderCallbacks) c._renderCallbacks = [];\n\t\t\t});\n\t\t\tcommitQueue = [];\n\t\t\toptions._catchError(e, component._vnode);\n\t\t}\n\t});\n\n\tif (oldCommit) oldCommit(vnode, commitQueue);\n};\n\n/** @type {(vnode: import('./internal').VNode) => void} */\noptions.unmount = vnode => {\n\tif (oldBeforeUnmount) oldBeforeUnmount(vnode);\n\n\tconst c = vnode._component;\n\tif (c && c.__hooks) {\n\t\tlet hasErrored;\n\t\tc.__hooks._list.forEach(s => {\n\t\t\ttry {\n\t\t\t\tinvokeCleanup(s);\n\t\t\t} catch (e) {\n\t\t\t\thasErrored = e;\n\t\t\t}\n\t\t});\n\t\tc.__hooks = undefined;\n\t\tif (hasErrored) options._catchError(hasErrored, c._vnode);\n\t}\n};\n\n/**\n * Get a hook's state from the currentComponent\n * @param {number} index The index of the hook to get\n * @param {number} type The index of the hook to get\n * @returns {any}\n */\nfunction getHookState(index, type) {\n\tif (options._hook) {\n\t\toptions._hook(currentComponent, index, currentHook || type);\n\t}\n\tcurrentHook = 0;\n\n\t// Largely inspired by:\n\t// * https://github.com/michael-klein/funcy.js/blob/f6be73468e6ec46b0ff5aa3cc4c9baf72a29025a/src/hooks/core_hooks.mjs\n\t// * https://github.com/michael-klein/funcy.js/blob/650beaa58c43c33a74820a3c98b3c7079cf2e333/src/renderer.mjs\n\t// Other implementations to look at:\n\t// * https://codesandbox.io/s/mnox05qp8\n\tconst hooks =\n\t\tcurrentComponent.__hooks ||\n\t\t(currentComponent.__hooks = {\n\t\t\t_list: [],\n\t\t\t_pendingEffects: []\n\t\t});\n\n\tif (index >= hooks._list.length) {\n\t\thooks._list.push({});\n\t}\n\n\treturn hooks._list[index];\n}\n\n/**\n * @template {unknown} S\n * @param {import('./index').Dispatch>} [initialState]\n * @returns {[S, (state: S) => void]}\n */\nexport function useState(initialState) {\n\tcurrentHook = 1;\n\treturn useReducer(invokeOrReturn, initialState);\n}\n\n/**\n * @template {unknown} S\n * @template {unknown} A\n * @param {import('./index').Reducer} reducer\n * @param {import('./index').Dispatch>} initialState\n * @param {(initialState: any) => void} [init]\n * @returns {[ S, (state: S) => void ]}\n */\nexport function useReducer(reducer, initialState, init) {\n\t/** @type {import('./internal').ReducerHookState} */\n\tconst hookState = getHookState(currentIndex++, 2);\n\thookState._reducer = reducer;\n\tif (!hookState._component) {\n\t\thookState._value = [\n\t\t\t!init ? invokeOrReturn(undefined, initialState) : init(initialState),\n\n\t\t\taction => {\n\t\t\t\tconst currentValue = hookState._nextValue\n\t\t\t\t\t? hookState._nextValue[0]\n\t\t\t\t\t: hookState._value[0];\n\t\t\t\tconst nextValue = hookState._reducer(currentValue, action);\n\n\t\t\t\tif (currentValue !== nextValue) {\n\t\t\t\t\thookState._nextValue = [nextValue, hookState._value[1]];\n\t\t\t\t\thookState._component.setState({});\n\t\t\t\t}\n\t\t\t}\n\t\t];\n\n\t\thookState._component = currentComponent;\n\n\t\tif (!currentComponent._hasScuFromHooks) {\n\t\t\tcurrentComponent._hasScuFromHooks = true;\n\t\t\tlet prevScu = currentComponent.shouldComponentUpdate;\n\t\t\tconst prevCWU = currentComponent.componentWillUpdate;\n\n\t\t\t// If we're dealing with a forced update `shouldComponentUpdate` will\n\t\t\t// not be called. But we use that to update the hook values, so we\n\t\t\t// need to call it.\n\t\t\tcurrentComponent.componentWillUpdate = function (p, s, c) {\n\t\t\t\tif (this._force) {\n\t\t\t\t\tlet tmp = prevScu;\n\t\t\t\t\t// Clear to avoid other sCU hooks from being called\n\t\t\t\t\tprevScu = undefined;\n\t\t\t\t\tupdateHookState(p, s, c);\n\t\t\t\t\tprevScu = tmp;\n\t\t\t\t}\n\n\t\t\t\tif (prevCWU) prevCWU.call(this, p, s, c);\n\t\t\t};\n\n\t\t\t// This SCU has the purpose of bailing out after repeated updates\n\t\t\t// to stateful hooks.\n\t\t\t// we store the next value in _nextValue[0] and keep doing that for all\n\t\t\t// state setters, if we have next states and\n\t\t\t// all next states within a component end up being equal to their original state\n\t\t\t// we are safe to bail out for this specific component.\n\t\t\t/**\n\t\t\t *\n\t\t\t * @type {import('./internal').Component[\"shouldComponentUpdate\"]}\n\t\t\t */\n\t\t\t// @ts-ignore - We don't use TS to downtranspile\n\t\t\t// eslint-disable-next-line no-inner-declarations\n\t\t\tfunction updateHookState(p, s, c) {\n\t\t\t\tif (!hookState._component.__hooks) return true;\n\n\t\t\t\t/** @type {(x: import('./internal').HookState) => x is import('./internal').ReducerHookState} */\n\t\t\t\tconst isStateHook = x => !!x._component;\n\t\t\t\tconst stateHooks =\n\t\t\t\t\thookState._component.__hooks._list.filter(isStateHook);\n\n\t\t\t\tconst allHooksEmpty = stateHooks.every(x => !x._nextValue);\n\t\t\t\t// When we have no updated hooks in the component we invoke the previous SCU or\n\t\t\t\t// traverse the VDOM tree further.\n\t\t\t\tif (allHooksEmpty) {\n\t\t\t\t\treturn prevScu ? prevScu.call(this, p, s, c) : true;\n\t\t\t\t}\n\n\t\t\t\t// We check whether we have components with a nextValue set that\n\t\t\t\t// have values that aren't equal to one another this pushes\n\t\t\t\t// us to update further down the tree\n\t\t\t\tlet shouldUpdate = hookState._component.props !== p;\n\t\t\t\tstateHooks.forEach(hookItem => {\n\t\t\t\t\tif (hookItem._nextValue) {\n\t\t\t\t\t\tconst currentValue = hookItem._value[0];\n\t\t\t\t\t\thookItem._value = hookItem._nextValue;\n\t\t\t\t\t\thookItem._nextValue = undefined;\n\t\t\t\t\t\tif (currentValue !== hookItem._value[0]) shouldUpdate = true;\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\treturn prevScu\n\t\t\t\t\t? prevScu.call(this, p, s, c) || shouldUpdate\n\t\t\t\t\t: shouldUpdate;\n\t\t\t}\n\n\t\t\tcurrentComponent.shouldComponentUpdate = updateHookState;\n\t\t}\n\t}\n\n\treturn hookState._nextValue || hookState._value;\n}\n\n/**\n * @param {import('./internal').Effect} callback\n * @param {unknown[]} args\n * @returns {void}\n */\nexport function useEffect(callback, args) {\n\t/** @type {import('./internal').EffectHookState} */\n\tconst state = getHookState(currentIndex++, 3);\n\tif (!options._skipEffects && argsChanged(state._args, args)) {\n\t\tstate._value = callback;\n\t\tstate._pendingArgs = args;\n\n\t\tcurrentComponent.__hooks._pendingEffects.push(state);\n\t}\n}\n\n/**\n * @param {import('./internal').Effect} callback\n * @param {unknown[]} args\n * @returns {void}\n */\nexport function useLayoutEffect(callback, args) {\n\t/** @type {import('./internal').EffectHookState} */\n\tconst state = getHookState(currentIndex++, 4);\n\tif (!options._skipEffects && argsChanged(state._args, args)) {\n\t\tstate._value = callback;\n\t\tstate._pendingArgs = args;\n\n\t\tcurrentComponent._renderCallbacks.push(state);\n\t}\n}\n\n/** @type {(initialValue: unknown) => unknown} */\nexport function useRef(initialValue) {\n\tcurrentHook = 5;\n\treturn useMemo(() => ({ current: initialValue }), []);\n}\n\n/**\n * @param {object} ref\n * @param {() => object} createHandle\n * @param {unknown[]} args\n * @returns {void}\n */\nexport function useImperativeHandle(ref, createHandle, args) {\n\tcurrentHook = 6;\n\tuseLayoutEffect(\n\t\t() => {\n\t\t\tif (typeof ref == 'function') {\n\t\t\t\tconst result = ref(createHandle());\n\t\t\t\treturn () => {\n\t\t\t\t\tref(null);\n\t\t\t\t\tif (result && typeof result == 'function') result();\n\t\t\t\t};\n\t\t\t} else if (ref) {\n\t\t\t\tref.current = createHandle();\n\t\t\t\treturn () => (ref.current = null);\n\t\t\t}\n\t\t},\n\t\targs == null ? args : args.concat(ref)\n\t);\n}\n\n/**\n * @template {unknown} T\n * @param {() => T} factory\n * @param {unknown[]} args\n * @returns {T}\n */\nexport function useMemo(factory, args) {\n\t/** @type {import('./internal').MemoHookState} */\n\tconst state = getHookState(currentIndex++, 7);\n\tif (argsChanged(state._args, args)) {\n\t\tstate._value = factory();\n\t\tstate._args = args;\n\t\tstate._factory = factory;\n\t}\n\n\treturn state._value;\n}\n\n/**\n * @param {() => void} callback\n * @param {unknown[]} args\n * @returns {() => void}\n */\nexport function useCallback(callback, args) {\n\tcurrentHook = 8;\n\treturn useMemo(() => callback, args);\n}\n\n/**\n * @param {import('./internal').PreactContext} context\n */\nexport function useContext(context) {\n\tconst provider = currentComponent.context[context._id];\n\t// We could skip this call here, but than we'd not call\n\t// `options._hook`. We need to do that in order to make\n\t// the devtools aware of this hook.\n\t/** @type {import('./internal').ContextHookState} */\n\tconst state = getHookState(currentIndex++, 9);\n\t// The devtools needs access to the context object to\n\t// be able to pull of the default value when no provider\n\t// is present in the tree.\n\tstate._context = context;\n\tif (!provider) return context._defaultValue;\n\t// This is probably not safe to convert to \"!\"\n\tif (state._value == null) {\n\t\tstate._value = true;\n\t\tprovider.sub(currentComponent);\n\t}\n\treturn provider.props.value;\n}\n\n/**\n * Display a custom label for a custom hook for the devtools panel\n * @type {(value: T, cb?: (value: T) => string | number) => void}\n */\nexport function useDebugValue(value, formatter) {\n\tif (options.useDebugValue) {\n\t\toptions.useDebugValue(\n\t\t\tformatter ? formatter(value) : /** @type {any}*/ (value)\n\t\t);\n\t}\n}\n\n/**\n * @param {(error: unknown, errorInfo: import('preact').ErrorInfo) => void} cb\n * @returns {[unknown, () => void]}\n */\nexport function useErrorBoundary(cb) {\n\t/** @type {import('./internal').ErrorBoundaryHookState} */\n\tconst state = getHookState(currentIndex++, 10);\n\tconst errState = useState();\n\tstate._value = cb;\n\tif (!currentComponent.componentDidCatch) {\n\t\tcurrentComponent.componentDidCatch = (err, errorInfo) => {\n\t\t\tif (state._value) state._value(err, errorInfo);\n\t\t\terrState[1](err);\n\t\t};\n\t}\n\treturn [\n\t\terrState[0],\n\t\t() => {\n\t\t\terrState[1](undefined);\n\t\t}\n\t];\n}\n\n/** @type {() => string} */\nexport function useId() {\n\t/** @type {import('./internal').IdHookState} */\n\tconst state = getHookState(currentIndex++, 11);\n\tif (!state._value) {\n\t\t// Grab either the root node or the nearest async boundary node.\n\t\t/** @type {import('./internal').VNode} */\n\t\tlet root = currentComponent._vnode;\n\t\twhile (root !== null && !root._mask && root._parent !== null) {\n\t\t\troot = root._parent;\n\t\t}\n\n\t\tlet mask = root._mask || (root._mask = [0, 0]);\n\t\tstate._value = 'P' + mask[0] + '-' + mask[1]++;\n\t}\n\n\treturn state._value;\n}\n\n/**\n * After paint effects consumer.\n */\nfunction flushAfterPaintEffects() {\n\tlet component;\n\twhile ((component = afterPaintEffects.shift())) {\n\t\tif (!component._parentDom || !component.__hooks) continue;\n\t\ttry {\n\t\t\tcomponent.__hooks._pendingEffects.forEach(invokeCleanup);\n\t\t\tcomponent.__hooks._pendingEffects.forEach(invokeEffect);\n\t\t\tcomponent.__hooks._pendingEffects = [];\n\t\t} catch (e) {\n\t\t\tcomponent.__hooks._pendingEffects = [];\n\t\t\toptions._catchError(e, component._vnode);\n\t\t}\n\t}\n}\n\nlet HAS_RAF = typeof requestAnimationFrame == 'function';\n\n/**\n * Schedule a callback to be invoked after the browser has a chance to paint a new frame.\n * Do this by combining requestAnimationFrame (rAF) + setTimeout to invoke a callback after\n * the next browser frame.\n *\n * Also, schedule a timeout in parallel to the the rAF to ensure the callback is invoked\n * even if RAF doesn't fire (for example if the browser tab is not visible)\n *\n * @param {() => void} callback\n */\nfunction afterNextFrame(callback) {\n\tconst done = () => {\n\t\tclearTimeout(timeout);\n\t\tif (HAS_RAF) cancelAnimationFrame(raf);\n\t\tsetTimeout(callback);\n\t};\n\tconst timeout = setTimeout(done, RAF_TIMEOUT);\n\n\tlet raf;\n\tif (HAS_RAF) {\n\t\traf = requestAnimationFrame(done);\n\t}\n}\n\n// Note: if someone used options.debounceRendering = requestAnimationFrame,\n// then effects will ALWAYS run on the NEXT frame instead of the current one, incurring a ~16ms delay.\n// Perhaps this is not such a big deal.\n/**\n * Schedule afterPaintEffects flush after the browser paints\n * @param {number} newQueueLength\n * @returns {void}\n */\nfunction afterPaint(newQueueLength) {\n\tif (newQueueLength === 1 || prevRaf !== options.requestAnimationFrame) {\n\t\tprevRaf = options.requestAnimationFrame;\n\t\t(prevRaf || afterNextFrame)(flushAfterPaintEffects);\n\t}\n}\n\n/**\n * @param {import('./internal').HookState} hook\n * @returns {void}\n */\nfunction invokeCleanup(hook) {\n\t// A hook cleanup can introduce a call to render which creates a new root, this will call options.vnode\n\t// and move the currentComponent away.\n\tconst comp = currentComponent;\n\tlet cleanup = hook._cleanup;\n\tif (typeof cleanup == 'function') {\n\t\thook._cleanup = undefined;\n\t\tcleanup();\n\t}\n\n\tcurrentComponent = comp;\n}\n\n/**\n * Invoke a Hook's effect\n * @param {import('./internal').EffectHookState} hook\n * @returns {void}\n */\nfunction invokeEffect(hook) {\n\t// A hook call can introduce a call to render which creates a new root, this will call options.vnode\n\t// and move the currentComponent away.\n\tconst comp = currentComponent;\n\thook._cleanup = hook._value();\n\tcurrentComponent = comp;\n}\n\n/**\n * @param {unknown[]} oldArgs\n * @param {unknown[]} newArgs\n * @returns {boolean}\n */\nfunction argsChanged(oldArgs, newArgs) {\n\treturn (\n\t\t!oldArgs ||\n\t\toldArgs.length !== newArgs.length ||\n\t\tnewArgs.some((arg, index) => arg !== oldArgs[index])\n\t);\n}\n\n/**\n * @template Arg\n * @param {Arg} arg\n * @param {(arg: Arg) => any} f\n * @returns {any}\n */\nfunction invokeOrReturn(arg, f) {\n\treturn typeof f == 'function' ? f(arg) : f;\n}\n"],"names":["currentIndex","currentComponent","previousComponent","prevRaf","currentHook","afterPaintEffects","options","_options","oldBeforeDiff","__b","oldBeforeRender","__r","oldAfterDiff","diffed","oldCommit","__c","oldBeforeUnmount","unmount","oldRoot","__","getHookState","index","type","__h","hooks","__H","length","push","useState","initialState","useReducer","invokeOrReturn","reducer","init","hookState","_reducer","undefined","action","currentValue","__N","nextValue","setState","__f","updateHookState","p","s","c","stateHooks","filter","x","every","prevScu","call","this","shouldUpdate","props","forEach","hookItem","shouldComponentUpdate","prevCWU","componentWillUpdate","__e","tmp","useLayoutEffect","callback","args","state","__s","argsChanged","_pendingArgs","useMemo","factory","flushAfterPaintEffects","component","shift","__P","invokeCleanup","invokeEffect","e","__v","vnode","parentDom","__k","__m","requestAnimationFrame","afterNextFrame","commitQueue","some","cb","hasErrored","HAS_RAF","raf","done","clearTimeout","timeout","cancelAnimationFrame","setTimeout","hook","comp","cleanup","oldArgs","newArgs","arg","f","context","provider","sub","value","formatter","useDebugValue","errState","componentDidCatch","err","errorInfo","root","mask","ref","createHandle","result","current","concat","initialValue"],"mappings":"2QAGA,IAAIA,EAGAC,EAGAC,EAsBAC,EAnBAC,EAAc,EAGdC,EAAoB,GAGlBC,EAAuDC,EAAAA,QAEzDC,EAAgBF,EAAOG,IACvBC,EAAkBJ,EAAOK,IACzBC,EAAeN,EAAQO,OACvBC,EAAYR,EAAOS,IACnBC,EAAmBV,EAAQW,QAC3BC,EAAUZ,EAAOa,GAiHrB,SAASC,EAAaC,EAAOC,GACxBhB,EAAOiB,KACVjB,EAAOiB,IAAOtB,EAAkBoB,EAAOjB,GAAekB,GAEvDlB,EAAc,EAOd,IAAMoB,EACLvB,EAAgBwB,MACfxB,EAAgBwB,IAAW,CAC3BN,GAAO,GACPI,IAAiB,KAOnB,OAJIF,GAASG,EAAKL,GAAOO,QACxBF,EAAKL,GAAOQ,KAAK,CAAE,GAGbH,EAAKL,GAAOE,EACpB,CAOO,SAASO,EAASC,GAExB,OADAzB,EAAc,EACP0B,EAAWC,EAAgBF,EACnC,CAUgB,SAAAC,EAAWE,EAASH,EAAcI,GAEjD,IAAMC,EAAYd,EAAapB,IAAgB,GAE/C,GADAkC,EAAUC,EAAWH,GAChBE,EAASnB,MACbmB,EAASf,GAAU,CACjBc,EAAiDA,EAAKJ,GAA/CE,OAAeK,EAAWP,GAElC,SAAAQ,GACC,IAAMC,EAAeJ,EAASK,IAC3BL,EAASK,IAAY,GACrBL,EAASf,GAAQ,GACdqB,EAAYN,EAAUC,EAASG,EAAcD,GAE/CC,IAAiBE,IACpBN,EAASK,IAAc,CAACC,EAAWN,EAASf,GAAQ,IACpDe,EAASnB,IAAY0B,SAAS,CAAE,GAElC,GAGDP,EAASnB,IAAcd,GAElBA,EAAgByC,KAAmB,CAAA,IAgC9BC,EAAT,SAAyBC,EAAGC,EAAGC,GAC9B,IAAKZ,EAASnB,IAAAU,IAAqB,OAAW,EAG9C,IACMsB,EACLb,EAASnB,IAAAU,IAAAN,GAA0B6B,OAFhB,SAAAC,GAAC,QAAMA,EAAClC,GAAW,GAOvC,GAHsBgC,EAAWG,MAAM,SAAAD,GAAC,OAAKA,EAACV,GAAW,GAIxD,OAAOY,GAAUA,EAAQC,KAAKC,KAAMT,EAAGC,EAAGC,GAM3C,IAAIQ,EAAepB,EAASnB,IAAYwC,QAAUX,EAUlD,OATAG,EAAWS,QAAQ,SAAAC,GAClB,GAAIA,EAAQlB,IAAa,CACxB,IAAMD,EAAemB,EAAQtC,GAAQ,GACrCsC,EAAQtC,GAAUsC,EAAQlB,IAC1BkB,EAAQlB,SAAcH,EAClBE,IAAiBmB,EAAQtC,GAAQ,KAAImC,GAAe,EACzD,CACD,GAEOH,GACJA,EAAQC,KAAKC,KAAMT,EAAGC,EAAGC,IACzBQ,CACJ,EA9DArD,EAAgByC,KAAoB,EACpC,IAAIS,EAAUlD,EAAiByD,sBACzBC,EAAU1D,EAAiB2D,oBAKjC3D,EAAiB2D,oBAAsB,SAAUhB,EAAGC,EAAGC,GACtD,GAAIO,KAAIQ,IAAS,CAChB,IAAIC,EAAMX,EAEVA,OAAUf,EACVO,EAAgBC,EAAGC,EAAGC,GACtBK,EAAUW,CACX,CAEIH,GAASA,EAAQP,KAAKC,KAAMT,EAAGC,EAAGC,EACvC,EA+CA7C,EAAiByD,sBAAwBf,CAC1C,CAGD,OAAOT,EAASK,KAAeL,EAASf,EACzC,CAuBgB,SAAA4C,EAAgBC,EAAUC,GAEzC,IAAMC,EAAQ9C,EAAapB,IAAgB,IACtCM,EAAO6D,KAAiBC,EAAYF,EAAKzC,IAAQwC,KACrDC,EAAK/C,GAAU6C,EACfE,EAAMG,EAAeJ,EAErBhE,EAAgBsB,IAAkBI,KAAKuC,GAEzC,CAuCgB,SAAAI,EAAQC,EAASN,GAEhC,IAAMC,EAAQ9C,EAAapB,IAAgB,GAO3C,OANIoE,EAAYF,EAAKzC,IAAQwC,KAC5BC,EAAK/C,GAAUoD,IACfL,EAAKzC,IAASwC,EACdC,EAAK3C,IAAYgD,GAGXL,EAAK/C,EACb,CA4FA,SAASqD,IAER,IADA,IAAIC,EACIA,EAAYpE,EAAkBqE,SACrC,GAAKD,EAASE,KAAgBF,EAAShD,IACvC,IACCgD,EAAShD,IAAAF,IAAyBiC,QAAQoB,GAC1CH,EAAShD,IAAAF,IAAyBiC,QAAQqB,GAC1CJ,EAAShD,IAAAF,IAA2B,EAIrC,CAHE,MAAOuD,GACRL,EAAShD,IAAAF,IAA2B,GACpCjB,EAAOuD,IAAaiB,EAAGL,EAASM,IACjC,CAEF,CA1aAzE,EAAOG,IAAS,SAAAuE,GACf/E,EAAmB,KACfO,GAAeA,EAAcwE,EAClC,EAEA1E,EAAOa,GAAS,SAAC6D,EAAOC,GACnBD,GAASC,EAASC,KAAcD,EAASC,IAAAC,MAC5CH,EAAKG,IAASF,EAASC,IAAAC,KAGpBjE,GAASA,EAAQ8D,EAAOC,EAC7B,EAGA3E,EAAOK,IAAW,SAAAqE,GACbtE,GAAiBA,EAAgBsE,GAGrChF,EAAe,EAEf,IAAMwB,GAHNvB,EAAmB+E,EAAKjE,KAGMU,IAC1BD,IACCtB,IAAsBD,GACzBuB,EAAKD,IAAmB,GACxBtB,EAAgBsB,IAAoB,GACpCC,EAAKL,GAAOqC,QAAQ,SAAAC,GACfA,EAAQlB,MACXkB,EAAQtC,GAAUsC,EAAQlB,KAE3BkB,EAASY,EAAeZ,EAAQlB,SAAcH,CAC/C,KAEAZ,EAAKD,IAAiBiC,QAAQoB,GAC9BpD,EAAKD,IAAiBiC,QAAQqB,GAC9BrD,EAAKD,IAAmB,GACxBvB,EAAe,IAGjBE,EAAoBD,CACrB,EAGAK,EAAQO,OAAS,SAAAmE,GACZpE,GAAcA,EAAaoE,GAE/B,IAAMlC,EAAIkC,EAAKjE,IACX+B,GAAKA,EAACrB,MACLqB,EAACrB,IAAAF,IAAyBG,SAgaR,IAha2BrB,EAAkBsB,KAAKmB,IAga7C3C,IAAYG,EAAQ8E,yBAC/CjF,EAAUG,EAAQ8E,wBACNC,GAAgBb,IAja5B1B,EAACrB,IAAAN,GAAeqC,QAAQ,SAAAC,GACnBA,EAASY,IACZZ,EAAQhC,IAASgC,EAASY,GAE3BZ,EAASY,OAAejC,CACzB,IAEDlC,EAAoBD,EAAmB,IACxC,EAIAK,EAAOS,IAAW,SAACiE,EAAOM,GACzBA,EAAYC,KAAK,SAAAd,GAChB,IACCA,EAASlD,IAAkBiC,QAAQoB,GACnCH,EAASlD,IAAoBkD,EAASlD,IAAkByB,OAAO,SAAAwC,GAAE,OAChEA,EAAErE,IAAU0D,EAAaW,EAAU,EAQrC,CANE,MAAOV,GACRQ,EAAYC,KAAK,SAAAzC,GACZA,EAACvB,MAAmBuB,EAACvB,IAAoB,GAC9C,GACA+D,EAAc,GACdhF,EAAOuD,IAAaiB,EAAGL,EAASM,IACjC,CACD,GAEIjE,GAAWA,EAAUkE,EAAOM,EACjC,EAGAhF,EAAQW,QAAU,SAAA+D,GACbhE,GAAkBA,EAAiBgE,GAEvC,IAEKS,EAFC3C,EAAIkC,EAAKjE,IACX+B,GAAKA,EAACrB,MAETqB,EAACrB,IAAAN,GAAeqC,QAAQ,SAAAX,GACvB,IACC+B,EAAc/B,EAGf,CAFE,MAAOiC,GACRW,EAAaX,CACd,CACD,GACAhC,EAACrB,SAAWW,EACRqD,GAAYnF,EAAOuD,IAAa4B,EAAY3C,EAACiC,KAEnD,EA4UA,IAAIW,EAA0C,mBAAzBN,sBAYrB,SAASC,EAAerB,GACvB,IAOI2B,EAPEC,EAAO,WACZC,aAAaC,GACTJ,GAASK,qBAAqBJ,GAClCK,WAAWhC,EACZ,EACM8B,EAAUE,WAAWJ,EAlcR,IAqcfF,IACHC,EAAMP,sBAAsBQ,GAE9B,CAqBA,SAAShB,EAAcqB,GAGtB,IAAMC,EAAOjG,EACTkG,EAAUF,EAAIlF,IACI,mBAAXoF,IACVF,EAAIlF,SAAYqB,EAChB+D,KAGDlG,EAAmBiG,CACpB,CAOA,SAASrB,EAAaoB,GAGrB,IAAMC,EAAOjG,EACbgG,EAAIlF,IAAYkF,EAAI9E,KACpBlB,EAAmBiG,CACpB,CAOA,SAAS9B,EAAYgC,EAASC,GAC7B,OACED,GACDA,EAAQ1E,SAAW2E,EAAQ3E,QAC3B2E,EAAQd,KAAK,SAACe,EAAKjF,GAAU,OAAAiF,IAAQF,EAAQ/E,EAAM,EAErD,CAQA,SAASU,EAAeuE,EAAKC,GAC5B,MAAmB,mBAALA,EAAkBA,EAAED,GAAOC,CAC1C,eAhMO,SAAqBvC,EAAUC,GAErC,OADA7D,EAAc,EACPkE,EAAQ,WAAA,OAAMN,CAAQ,EAAEC,EAChC,eAKO,SAAoBuC,GAC1B,IAAMC,EAAWxG,EAAiBuG,QAAQA,EAAOzF,KAK3CmD,EAAQ9C,EAAapB,IAAgB,GAK3C,OADAkE,EAAKpB,EAAY0D,EACZC,GAEe,MAAhBvC,EAAK/C,KACR+C,EAAK/C,IAAU,EACfsF,EAASC,IAAIzG,IAEPwG,EAASlD,MAAMoD,OANAH,EAAOrF,EAO9B,kBAMgB,SAAcwF,EAAOC,GAChCtG,EAAQuG,eACXvG,EAAQuG,cACPD,EAAYA,EAAUD,GAAM,EAG/B,cAvHO,SAAmB3C,EAAUC,GAEnC,IAAMC,EAAQ9C,EAAapB,IAAgB,IACtCM,EAAO6D,KAAiBC,EAAYF,EAAKzC,IAAQwC,KACrDC,EAAK/C,GAAU6C,EACfE,EAAMG,EAAeJ,EAErBhE,EAAgBwB,IAAAF,IAAyBI,KAAKuC,GAEhD,qBAoHO,SAA0BsB,GAEhC,IAAMtB,EAAQ9C,EAAapB,IAAgB,IACrC8G,EAAWlF,IAQjB,OAPAsC,EAAK/C,GAAUqE,EACVvF,EAAiB8G,oBACrB9G,EAAiB8G,kBAAoB,SAACC,EAAKC,GACtC/C,EAAK/C,IAAS+C,EAAK/C,GAAQ6F,EAAKC,GACpCH,EAAS,GAAGE,EACb,GAEM,CACNF,EAAS,GACT,WACCA,EAAS,QAAG1E,EACb,EAEF,UAGO,WAEN,IAAM8B,EAAQ9C,EAAapB,IAAgB,IAC3C,IAAKkE,EAAK/C,GAAS,CAIlB,IADA,IAAI+F,EAAOjH,EAAgB8E,IACX,OAATmC,IAAkBA,EAAI/B,KAA2B,OAAjB+B,EAAI/F,IAC1C+F,EAAOA,EAAI/F,GAGZ,IAAIgG,EAAOD,EAAI/B,MAAW+B,EAAI/B,IAAS,CAAC,EAAG,IAC3CjB,EAAK/C,GAAU,IAAMgG,EAAK,GAAK,IAAMA,EAAK,IAC3C,CAEA,OAAOjD,EAAK/C,EACb,wBA1HgB,SAAoBiG,EAAKC,EAAcpD,GACtD7D,EAAc,EACd2D,EACC,WACC,GAAkB,mBAAPqD,EAAmB,CAC7B,IAAME,EAASF,EAAIC,KACnB,OAAa,WACZD,EAAI,MACAE,GAA2B,mBAAVA,GAAsBA,GAC5C,CACD,CAAWF,GAAAA,EAEV,OADAA,EAAIG,QAAUF,IACP,WAAA,OAAOD,EAAIG,QAAU,IAAI,CAElC,EACQ,MAARtD,EAAeA,EAAOA,EAAKuD,OAAOJ,GAEpC,0DA5BO,SAAgBK,GAEtB,OADArH,EAAc,EACPkE,EAAQ,WAAO,MAAA,CAAEiD,QAASE,EAAc,EAAG,GACnD"} \ No newline at end of file diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/package.json b/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/package.json new file mode 100644 index 0000000000000..787927573e955 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/package.json @@ -0,0 +1,35 @@ +{ + "name": "preact-hooks", + "amdName": "preactHooks", + "version": "0.1.0", + "private": true, + "description": "Hook addon for Preact", + "main": "dist/hooks.js", + "module": "dist/hooks.module.js", + "umd:main": "dist/hooks.umd.js", + "source": "src/index.js", + "license": "MIT", + "types": "src/index.d.ts", + "scripts": { + "build": "microbundle build --raw", + "dev": "microbundle watch --raw --format cjs", + "test": "npm-run-all build --parallel test:karma", + "test:karma": "karma start test/karma.conf.js --single-run", + "test:karma:watch": "karma start test/karma.conf.js --no-single-run" + }, + "peerDependencies": { + "preact": "^10.0.0" + }, + "mangle": { + "regex": "^_" + }, + "exports": { + ".": { + "types": "./src/index.d.ts", + "browser": "./dist/hooks.module.js", + "umd": "./dist/hooks.umd.js", + "import": "./dist/hooks.mjs", + "require": "./dist/hooks.js" + } + } +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/src/index.d.ts b/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/src/index.d.ts new file mode 100644 index 0000000000000..d7f77dbb49fb3 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/src/index.d.ts @@ -0,0 +1,145 @@ +// Intentionally not using a relative path to take advantage of +// the TS version resolution mechanism +import { ErrorInfo, PreactContext, Ref, RefObject } from 'preact'; + +type Inputs = ReadonlyArray; + +export type Dispatch = (value: A) => void; +export type StateUpdater = S | ((prevState: S) => S); + +/** + * Returns a stateful value, and a function to update it. + * @param initialState The initial value (or a function that returns the initial value) + */ +export function useState( + initialState: S | (() => S) +): [S, Dispatch>]; + +export function useState(): [ + S | undefined, + Dispatch> +]; + +export type Reducer = (prevState: S, action: A) => S; + +/** + * An alternative to `useState`. + * + * `useReducer` is usually preferable to `useState` when you have complex state logic that involves + * multiple sub-values. It also lets you optimize performance for components that trigger deep + * updates because you can pass `dispatch` down instead of callbacks. + * @param reducer Given the current state and an action, returns the new state + * @param initialState The initial value to store as state + */ +export function useReducer( + reducer: Reducer, + initialState: S +): [S, Dispatch]; + +/** + * An alternative to `useState`. + * + * `useReducer` is usually preferable to `useState` when you have complex state logic that involves + * multiple sub-values. It also lets you optimize performance for components that trigger deep + * updates because you can pass `dispatch` down instead of callbacks. + * @param reducer Given the current state and an action, returns the new state + * @param initialArg The initial argument to pass to the `init` function + * @param init A function that, given the `initialArg`, returns the initial value to store as state + */ +export function useReducer( + reducer: Reducer, + initialArg: I, + init: (arg: I) => S +): [S, Dispatch]; + +/** @deprecated Use the `Ref` type instead. */ +type PropRef = MutableRef; + +interface MutableRef { + current: T; +} + +/** + * `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument + * (`initialValue`). The returned object will persist for the full lifetime of the component. + * + * Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable + * value around similar to how you’d use instance fields in classes. + * + * @param initialValue the initial value to store in the ref object + */ +export function useRef(initialValue: T): MutableRef; +export function useRef(initialValue: T | null): RefObject; +export function useRef(): MutableRef; + +type EffectCallback = () => void | (() => void); +/** + * Accepts a function that contains imperative, possibly effectful code. + * The effects run after browser paint, without blocking it. + * + * @param effect Imperative function that can return a cleanup function + * @param inputs If present, effect will only activate if the values in the list change (using ===). + */ +export function useEffect(effect: EffectCallback, inputs?: Inputs): void; + +type CreateHandle = () => object; + +/** + * @param ref The ref that will be mutated + * @param create The function that will be executed to get the value that will be attached to + * ref.current + * @param inputs If present, effect will only activate if the values in the list change (using ===). + */ +export function useImperativeHandle( + ref: Ref, + create: () => R, + inputs?: Inputs +): void; + +/** + * Accepts a function that contains imperative, possibly effectful code. + * Use this to read layout from the DOM and synchronously re-render. + * Updates scheduled inside `useLayoutEffect` will be flushed synchronously, after all DOM mutations but before the browser has a chance to paint. + * Prefer the standard `useEffect` hook when possible to avoid blocking visual updates. + * + * @param effect Imperative function that can return a cleanup function + * @param inputs If present, effect will only activate if the values in the list change (using ===). + */ +export function useLayoutEffect(effect: EffectCallback, inputs?: Inputs): void; + +/** + * Returns a memoized version of the callback that only changes if one of the `inputs` + * has changed (using ===). + */ +export function useCallback(callback: T, inputs: Inputs): T; + +/** + * Pass a factory function and an array of inputs. + * useMemo will only recompute the memoized value when one of the inputs has changed. + * This optimization helps to avoid expensive calculations on every render. + * If no array is provided, a new value will be computed whenever a new function instance is passed as the first argument. + */ +// for `inputs`, allow undefined, but don't make it optional as that is very likely a mistake +export function useMemo(factory: () => T, inputs: Inputs | undefined): T; + +/** + * Returns the current context value, as given by the nearest context provider for the given context. + * When the provider updates, this Hook will trigger a rerender with the latest context value. + * + * @param context The context you want to use + */ +export function useContext(context: PreactContext): T; + +/** + * Customize the displayed value in the devtools panel. + * + * @param value Custom hook name or object that is passed to formatter + * @param formatter Formatter to modify value before sending it to the devtools + */ +export function useDebugValue(value: T, formatter?: (value: T) => any): void; + +export function useErrorBoundary( + callback?: (error: any, errorInfo: ErrorInfo) => Promise | void +): [any, () => void]; + +export function useId(): string; diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/src/index.js b/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/src/index.js new file mode 100644 index 0000000000000..b98b1988aebf4 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/src/index.js @@ -0,0 +1,555 @@ +import { options as _options } from 'preact'; + +/** @type {number} */ +let currentIndex; + +/** @type {import('./internal').Component} */ +let currentComponent; + +/** @type {import('./internal').Component} */ +let previousComponent; + +/** @type {number} */ +let currentHook = 0; + +/** @type {Array} */ +let afterPaintEffects = []; + +// Cast to use internal Options type +const options = /** @type {import('./internal').Options} */ (_options); + +let oldBeforeDiff = options._diff; +let oldBeforeRender = options._render; +let oldAfterDiff = options.diffed; +let oldCommit = options._commit; +let oldBeforeUnmount = options.unmount; +let oldRoot = options._root; + +// We take the minimum timeout for requestAnimationFrame to ensure that +// the callback is invoked after the next frame. 35ms is based on a 30hz +// refresh rate, which is the minimum rate for a smooth user experience. +const RAF_TIMEOUT = 35; +let prevRaf; + +/** @type {(vnode: import('./internal').VNode) => void} */ +options._diff = vnode => { + currentComponent = null; + if (oldBeforeDiff) oldBeforeDiff(vnode); +}; + +options._root = (vnode, parentDom) => { + if (vnode && parentDom._children && parentDom._children._mask) { + vnode._mask = parentDom._children._mask; + } + + if (oldRoot) oldRoot(vnode, parentDom); +}; + +/** @type {(vnode: import('./internal').VNode) => void} */ +options._render = vnode => { + if (oldBeforeRender) oldBeforeRender(vnode); + + currentComponent = vnode._component; + currentIndex = 0; + + const hooks = currentComponent.__hooks; + if (hooks) { + if (previousComponent === currentComponent) { + hooks._pendingEffects = []; + currentComponent._renderCallbacks = []; + hooks._list.forEach(hookItem => { + if (hookItem._nextValue) { + hookItem._value = hookItem._nextValue; + } + hookItem._pendingArgs = hookItem._nextValue = undefined; + }); + } else { + hooks._pendingEffects.forEach(invokeCleanup); + hooks._pendingEffects.forEach(invokeEffect); + hooks._pendingEffects = []; + currentIndex = 0; + } + } + previousComponent = currentComponent; +}; + +/** @type {(vnode: import('./internal').VNode) => void} */ +options.diffed = vnode => { + if (oldAfterDiff) oldAfterDiff(vnode); + + const c = vnode._component; + if (c && c.__hooks) { + if (c.__hooks._pendingEffects.length) afterPaint(afterPaintEffects.push(c)); + c.__hooks._list.forEach(hookItem => { + if (hookItem._pendingArgs) { + hookItem._args = hookItem._pendingArgs; + } + hookItem._pendingArgs = undefined; + }); + } + previousComponent = currentComponent = null; +}; + +// TODO: Improve typing of commitQueue parameter +/** @type {(vnode: import('./internal').VNode, commitQueue: any) => void} */ +options._commit = (vnode, commitQueue) => { + commitQueue.some(component => { + try { + component._renderCallbacks.forEach(invokeCleanup); + component._renderCallbacks = component._renderCallbacks.filter(cb => + cb._value ? invokeEffect(cb) : true + ); + } catch (e) { + commitQueue.some(c => { + if (c._renderCallbacks) c._renderCallbacks = []; + }); + commitQueue = []; + options._catchError(e, component._vnode); + } + }); + + if (oldCommit) oldCommit(vnode, commitQueue); +}; + +/** @type {(vnode: import('./internal').VNode) => void} */ +options.unmount = vnode => { + if (oldBeforeUnmount) oldBeforeUnmount(vnode); + + const c = vnode._component; + if (c && c.__hooks) { + let hasErrored; + c.__hooks._list.forEach(s => { + try { + invokeCleanup(s); + } catch (e) { + hasErrored = e; + } + }); + c.__hooks = undefined; + if (hasErrored) options._catchError(hasErrored, c._vnode); + } +}; + +/** + * Get a hook's state from the currentComponent + * @param {number} index The index of the hook to get + * @param {number} type The index of the hook to get + * @returns {any} + */ +function getHookState(index, type) { + if (options._hook) { + options._hook(currentComponent, index, currentHook || type); + } + currentHook = 0; + + // Largely inspired by: + // * https://github.com/michael-klein/funcy.js/blob/f6be73468e6ec46b0ff5aa3cc4c9baf72a29025a/src/hooks/core_hooks.mjs + // * https://github.com/michael-klein/funcy.js/blob/650beaa58c43c33a74820a3c98b3c7079cf2e333/src/renderer.mjs + // Other implementations to look at: + // * https://codesandbox.io/s/mnox05qp8 + const hooks = + currentComponent.__hooks || + (currentComponent.__hooks = { + _list: [], + _pendingEffects: [] + }); + + if (index >= hooks._list.length) { + hooks._list.push({}); + } + + return hooks._list[index]; +} + +/** + * @template {unknown} S + * @param {import('./index').Dispatch>} [initialState] + * @returns {[S, (state: S) => void]} + */ +export function useState(initialState) { + currentHook = 1; + return useReducer(invokeOrReturn, initialState); +} + +/** + * @template {unknown} S + * @template {unknown} A + * @param {import('./index').Reducer} reducer + * @param {import('./index').Dispatch>} initialState + * @param {(initialState: any) => void} [init] + * @returns {[ S, (state: S) => void ]} + */ +export function useReducer(reducer, initialState, init) { + /** @type {import('./internal').ReducerHookState} */ + const hookState = getHookState(currentIndex++, 2); + hookState._reducer = reducer; + if (!hookState._component) { + hookState._value = [ + !init ? invokeOrReturn(undefined, initialState) : init(initialState), + + action => { + const currentValue = hookState._nextValue + ? hookState._nextValue[0] + : hookState._value[0]; + const nextValue = hookState._reducer(currentValue, action); + + if (currentValue !== nextValue) { + hookState._nextValue = [nextValue, hookState._value[1]]; + hookState._component.setState({}); + } + } + ]; + + hookState._component = currentComponent; + + if (!currentComponent._hasScuFromHooks) { + currentComponent._hasScuFromHooks = true; + let prevScu = currentComponent.shouldComponentUpdate; + const prevCWU = currentComponent.componentWillUpdate; + + // If we're dealing with a forced update `shouldComponentUpdate` will + // not be called. But we use that to update the hook values, so we + // need to call it. + currentComponent.componentWillUpdate = function (p, s, c) { + if (this._force) { + let tmp = prevScu; + // Clear to avoid other sCU hooks from being called + prevScu = undefined; + updateHookState(p, s, c); + prevScu = tmp; + } + + if (prevCWU) prevCWU.call(this, p, s, c); + }; + + // This SCU has the purpose of bailing out after repeated updates + // to stateful hooks. + // we store the next value in _nextValue[0] and keep doing that for all + // state setters, if we have next states and + // all next states within a component end up being equal to their original state + // we are safe to bail out for this specific component. + /** + * + * @type {import('./internal').Component["shouldComponentUpdate"]} + */ + // @ts-ignore - We don't use TS to downtranspile + // eslint-disable-next-line no-inner-declarations + function updateHookState(p, s, c) { + if (!hookState._component.__hooks) return true; + + /** @type {(x: import('./internal').HookState) => x is import('./internal').ReducerHookState} */ + const isStateHook = x => !!x._component; + const stateHooks = + hookState._component.__hooks._list.filter(isStateHook); + + const allHooksEmpty = stateHooks.every(x => !x._nextValue); + // When we have no updated hooks in the component we invoke the previous SCU or + // traverse the VDOM tree further. + if (allHooksEmpty) { + return prevScu ? prevScu.call(this, p, s, c) : true; + } + + // We check whether we have components with a nextValue set that + // have values that aren't equal to one another this pushes + // us to update further down the tree + let shouldUpdate = hookState._component.props !== p; + stateHooks.forEach(hookItem => { + if (hookItem._nextValue) { + const currentValue = hookItem._value[0]; + hookItem._value = hookItem._nextValue; + hookItem._nextValue = undefined; + if (currentValue !== hookItem._value[0]) shouldUpdate = true; + } + }); + + return prevScu + ? prevScu.call(this, p, s, c) || shouldUpdate + : shouldUpdate; + } + + currentComponent.shouldComponentUpdate = updateHookState; + } + } + + return hookState._nextValue || hookState._value; +} + +/** + * @param {import('./internal').Effect} callback + * @param {unknown[]} args + * @returns {void} + */ +export function useEffect(callback, args) { + /** @type {import('./internal').EffectHookState} */ + const state = getHookState(currentIndex++, 3); + if (!options._skipEffects && argsChanged(state._args, args)) { + state._value = callback; + state._pendingArgs = args; + + currentComponent.__hooks._pendingEffects.push(state); + } +} + +/** + * @param {import('./internal').Effect} callback + * @param {unknown[]} args + * @returns {void} + */ +export function useLayoutEffect(callback, args) { + /** @type {import('./internal').EffectHookState} */ + const state = getHookState(currentIndex++, 4); + if (!options._skipEffects && argsChanged(state._args, args)) { + state._value = callback; + state._pendingArgs = args; + + currentComponent._renderCallbacks.push(state); + } +} + +/** @type {(initialValue: unknown) => unknown} */ +export function useRef(initialValue) { + currentHook = 5; + return useMemo(() => ({ current: initialValue }), []); +} + +/** + * @param {object} ref + * @param {() => object} createHandle + * @param {unknown[]} args + * @returns {void} + */ +export function useImperativeHandle(ref, createHandle, args) { + currentHook = 6; + useLayoutEffect( + () => { + if (typeof ref == 'function') { + const result = ref(createHandle()); + return () => { + ref(null); + if (result && typeof result == 'function') result(); + }; + } else if (ref) { + ref.current = createHandle(); + return () => (ref.current = null); + } + }, + args == null ? args : args.concat(ref) + ); +} + +/** + * @template {unknown} T + * @param {() => T} factory + * @param {unknown[]} args + * @returns {T} + */ +export function useMemo(factory, args) { + /** @type {import('./internal').MemoHookState} */ + const state = getHookState(currentIndex++, 7); + if (argsChanged(state._args, args)) { + state._value = factory(); + state._args = args; + state._factory = factory; + } + + return state._value; +} + +/** + * @param {() => void} callback + * @param {unknown[]} args + * @returns {() => void} + */ +export function useCallback(callback, args) { + currentHook = 8; + return useMemo(() => callback, args); +} + +/** + * @param {import('./internal').PreactContext} context + */ +export function useContext(context) { + const provider = currentComponent.context[context._id]; + // We could skip this call here, but than we'd not call + // `options._hook`. We need to do that in order to make + // the devtools aware of this hook. + /** @type {import('./internal').ContextHookState} */ + const state = getHookState(currentIndex++, 9); + // The devtools needs access to the context object to + // be able to pull of the default value when no provider + // is present in the tree. + state._context = context; + if (!provider) return context._defaultValue; + // This is probably not safe to convert to "!" + if (state._value == null) { + state._value = true; + provider.sub(currentComponent); + } + return provider.props.value; +} + +/** + * Display a custom label for a custom hook for the devtools panel + * @type {(value: T, cb?: (value: T) => string | number) => void} + */ +export function useDebugValue(value, formatter) { + if (options.useDebugValue) { + options.useDebugValue( + formatter ? formatter(value) : /** @type {any}*/ (value) + ); + } +} + +/** + * @param {(error: unknown, errorInfo: import('preact').ErrorInfo) => void} cb + * @returns {[unknown, () => void]} + */ +export function useErrorBoundary(cb) { + /** @type {import('./internal').ErrorBoundaryHookState} */ + const state = getHookState(currentIndex++, 10); + const errState = useState(); + state._value = cb; + if (!currentComponent.componentDidCatch) { + currentComponent.componentDidCatch = (err, errorInfo) => { + if (state._value) state._value(err, errorInfo); + errState[1](err); + }; + } + return [ + errState[0], + () => { + errState[1](undefined); + } + ]; +} + +/** @type {() => string} */ +export function useId() { + /** @type {import('./internal').IdHookState} */ + const state = getHookState(currentIndex++, 11); + if (!state._value) { + // Grab either the root node or the nearest async boundary node. + /** @type {import('./internal').VNode} */ + let root = currentComponent._vnode; + while (root !== null && !root._mask && root._parent !== null) { + root = root._parent; + } + + let mask = root._mask || (root._mask = [0, 0]); + state._value = 'P' + mask[0] + '-' + mask[1]++; + } + + return state._value; +} + +/** + * After paint effects consumer. + */ +function flushAfterPaintEffects() { + let component; + while ((component = afterPaintEffects.shift())) { + if (!component._parentDom || !component.__hooks) continue; + try { + component.__hooks._pendingEffects.forEach(invokeCleanup); + component.__hooks._pendingEffects.forEach(invokeEffect); + component.__hooks._pendingEffects = []; + } catch (e) { + component.__hooks._pendingEffects = []; + options._catchError(e, component._vnode); + } + } +} + +let HAS_RAF = typeof requestAnimationFrame == 'function'; + +/** + * Schedule a callback to be invoked after the browser has a chance to paint a new frame. + * Do this by combining requestAnimationFrame (rAF) + setTimeout to invoke a callback after + * the next browser frame. + * + * Also, schedule a timeout in parallel to the the rAF to ensure the callback is invoked + * even if RAF doesn't fire (for example if the browser tab is not visible) + * + * @param {() => void} callback + */ +function afterNextFrame(callback) { + const done = () => { + clearTimeout(timeout); + if (HAS_RAF) cancelAnimationFrame(raf); + setTimeout(callback); + }; + const timeout = setTimeout(done, RAF_TIMEOUT); + + let raf; + if (HAS_RAF) { + raf = requestAnimationFrame(done); + } +} + +// Note: if someone used options.debounceRendering = requestAnimationFrame, +// then effects will ALWAYS run on the NEXT frame instead of the current one, incurring a ~16ms delay. +// Perhaps this is not such a big deal. +/** + * Schedule afterPaintEffects flush after the browser paints + * @param {number} newQueueLength + * @returns {void} + */ +function afterPaint(newQueueLength) { + if (newQueueLength === 1 || prevRaf !== options.requestAnimationFrame) { + prevRaf = options.requestAnimationFrame; + (prevRaf || afterNextFrame)(flushAfterPaintEffects); + } +} + +/** + * @param {import('./internal').HookState} hook + * @returns {void} + */ +function invokeCleanup(hook) { + // A hook cleanup can introduce a call to render which creates a new root, this will call options.vnode + // and move the currentComponent away. + const comp = currentComponent; + let cleanup = hook._cleanup; + if (typeof cleanup == 'function') { + hook._cleanup = undefined; + cleanup(); + } + + currentComponent = comp; +} + +/** + * Invoke a Hook's effect + * @param {import('./internal').EffectHookState} hook + * @returns {void} + */ +function invokeEffect(hook) { + // A hook call can introduce a call to render which creates a new root, this will call options.vnode + // and move the currentComponent away. + const comp = currentComponent; + hook._cleanup = hook._value(); + currentComponent = comp; +} + +/** + * @param {unknown[]} oldArgs + * @param {unknown[]} newArgs + * @returns {boolean} + */ +function argsChanged(oldArgs, newArgs) { + return ( + !oldArgs || + oldArgs.length !== newArgs.length || + newArgs.some((arg, index) => arg !== oldArgs[index]) + ); +} + +/** + * @template Arg + * @param {Arg} arg + * @param {(arg: Arg) => any} f + * @returns {any} + */ +function invokeOrReturn(arg, f) { + return typeof f == 'function' ? f(arg) : f; +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/src/internal.d.ts b/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/src/internal.d.ts new file mode 100644 index 0000000000000..76cd97812b0a9 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/hooks/src/internal.d.ts @@ -0,0 +1,103 @@ +import { + Options as PreactOptions, + Component as PreactComponent, + VNode as PreactVNode, + PreactContext, + HookType, + ErrorInfo, +} from '../../src/internal'; +import { Reducer, StateUpdater } from '.'; + +export { PreactContext }; + +export interface Options extends PreactOptions { + /** Attach a hook that is invoked before a vnode is diffed. */ + _diff?(vnode: VNode): void; + diffed?(vnode: VNode): void; + /** Attach a hook that is invoked before a vnode has rendered. */ + _render?(vnode: VNode): void; + /** Attach a hook that is invoked after a tree was mounted or was updated. */ + _commit?(vnode: VNode, commitQueue: Component[]): void; + _unmount?(vnode: VNode): void; + /** Attach a hook that is invoked before a hook's state is queried. */ + _hook?(component: Component, index: number, type: HookType): void; +} + +// Hook tracking + +export interface ComponentHooks { + /** The list of hooks a component uses */ + _list: HookState[]; + /** List of Effects to be invoked after the next frame is rendered */ + _pendingEffects: EffectHookState[]; +} + +export interface Component extends Omit, '_renderCallbacks'> { + __hooks?: ComponentHooks; + // Extend to include HookStates + _renderCallbacks?: Array void)>; + _hasScuFromHooks?: boolean; +} + +export interface VNode extends Omit { + _mask?: [number, number]; + _component?: Component; // Override with our specific Component type +} + +export type HookState = + | EffectHookState + | MemoHookState + | ReducerHookState + | ContextHookState + | ErrorBoundaryHookState + | IdHookState; + +interface BaseHookState { + _value?: unknown; + _nextValue?: unknown; + _pendingValue?: unknown; + _args?: unknown; + _pendingArgs?: unknown; + _component?: unknown; + _cleanup?: unknown; +} + +export type Effect = () => void | Cleanup; +export type Cleanup = () => void; + +export interface EffectHookState extends BaseHookState { + _value?: Effect; + _args?: unknown[]; + _pendingArgs?: unknown[]; + _cleanup?: Cleanup | void; +} + +export interface MemoHookState extends BaseHookState { + _value?: T; + _pendingValue?: T; + _args?: unknown[]; + _pendingArgs?: unknown[]; + _factory?: () => T; +} + +export interface ReducerHookState + extends BaseHookState { + _nextValue?: [S, StateUpdater]; + _value?: [S, StateUpdater]; + _component?: Component; + _reducer?: Reducer; +} + +export interface ContextHookState extends BaseHookState { + /** Whether this hooks as subscribed to updates yet */ + _value?: boolean; + _context?: PreactContext; +} + +export interface ErrorBoundaryHookState extends BaseHookState { + _value?: (error: unknown, errorInfo: ErrorInfo) => void; +} + +export interface IdHookState extends BaseHookState { + _value?: string; +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/jsx-runtime/dist/jsxRuntime.js b/browser/base/content/assistant/ui-preact/node_modules/preact/jsx-runtime/dist/jsxRuntime.js new file mode 100644 index 0000000000000..9ed698115278d --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/jsx-runtime/dist/jsxRuntime.js @@ -0,0 +1,2 @@ +var r=require("preact"),e=/["&<]/;function t(r){if(0===r.length||!1===e.test(r))return r;for(var t=0,n=0,o="",f="";n} exprs\n * @returns {VNode}\n */\nfunction jsxTemplate(templates, ...exprs) {\n\tconst vnode = createVNode(Fragment, { tpl: templates, exprs });\n\t// Bypass render to string top level Fragment optimization\n\tvnode.key = vnode._vnode;\n\treturn vnode;\n}\n\nconst JS_TO_CSS = {};\nconst CSS_REGEX = /[A-Z]/g;\n\n/**\n * Unwrap potential signals.\n * @param {*} value\n * @returns {*}\n */\nfunction normalizeAttrValue(value) {\n\treturn value !== null &&\n\t\ttypeof value === 'object' &&\n\t\ttypeof value.valueOf === 'function'\n\t\t? value.valueOf()\n\t\t: value;\n}\n\n/**\n * Serialize an HTML attribute to a string. This function is not\n * expected to be used directly, but rather through a precompile\n * JSX transform\n * @param {string} name The attribute name\n * @param {*} value The attribute value\n * @returns {string}\n */\nfunction jsxAttr(name, value) {\n\tif (options.attr) {\n\t\tconst result = options.attr(name, value);\n\t\tif (typeof result === 'string') return result;\n\t}\n\n\tvalue = normalizeAttrValue(value);\n\n\tif (name === 'ref' || name === 'key') return '';\n\tif (name === 'style' && typeof value === 'object') {\n\t\tlet str = '';\n\t\tfor (let prop in value) {\n\t\t\tlet val = value[prop];\n\t\t\tif (val != null && val !== '') {\n\t\t\t\tconst name =\n\t\t\t\t\tprop[0] == '-'\n\t\t\t\t\t\t? prop\n\t\t\t\t\t\t: JS_TO_CSS[prop] ||\n\t\t\t\t\t\t\t(JS_TO_CSS[prop] = prop.replace(CSS_REGEX, '-$&').toLowerCase());\n\n\t\t\t\tlet suffix = ';';\n\t\t\t\tif (\n\t\t\t\t\ttypeof val === 'number' &&\n\t\t\t\t\t// Exclude custom-attributes\n\t\t\t\t\t!name.startsWith('--') &&\n\t\t\t\t\t!IS_NON_DIMENSIONAL.test(name)\n\t\t\t\t) {\n\t\t\t\t\tsuffix = 'px;';\n\t\t\t\t}\n\t\t\t\tstr = str + name + ':' + val + suffix;\n\t\t\t}\n\t\t}\n\t\treturn name + '=\"' + encodeEntities(str) + '\"';\n\t}\n\n\tif (\n\t\tvalue == null ||\n\t\tvalue === false ||\n\t\ttypeof value === 'function' ||\n\t\ttypeof value === 'object'\n\t) {\n\t\treturn '';\n\t} else if (value === true) return name;\n\n\treturn name + '=\"' + encodeEntities('' + value) + '\"';\n}\n\n/**\n * Escape a dynamic child passed to `jsxTemplate`. This function\n * is not expected to be used directly, but rather through a\n * precompile JSX transform\n * @param {*} value\n * @returns {string | null | VNode | Array}\n */\nfunction jsxEscape(value) {\n\tif (\n\t\tvalue == null ||\n\t\ttypeof value === 'boolean' ||\n\t\ttypeof value === 'function'\n\t) {\n\t\treturn null;\n\t}\n\n\tif (typeof value === 'object') {\n\t\t// Check for VNode\n\t\tif (value.constructor === undefined) return value;\n\n\t\tif (isArray(value)) {\n\t\t\tfor (let i = 0; i < value.length; i++) {\n\t\t\t\tvalue[i] = jsxEscape(value[i]);\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\t}\n\n\treturn encodeEntities('' + value);\n}\n\nexport {\n\tcreateVNode as jsx,\n\tcreateVNode as jsxs,\n\tcreateVNode as jsxDEV,\n\tFragment,\n\t// precompiled JSX transform\n\tjsxTemplate,\n\tjsxAttr,\n\tjsxEscape\n};\n"],"names":["ENCODED_ENTITIES","encodeEntities","str","length","test","last","i","out","ch","charCodeAt","slice","IS_NON_DIMENSIONAL","vnodeId","isArray","Array","createVNode","type","props","key","isStaticChildren","__source","__self","ref","normalizedProps","vnode","__k","__","__b","__e","__c","constructor","undefined","__v","__i","__u","defaultProps","options","JS_TO_CSS","CSS_REGEX","name","value","attr","result","valueOf","normalizeAttrValue","prop","val","replace","toLowerCase","suffix","startsWith","jsxEscape","templates","Fragment","tpl","exprs","call","arguments"],"mappings":"wBAAMA,EAAmB,QAGlB,SAASC,EAAeC,GAE9B,GAAmB,IAAfA,EAAIC,SAA+C,IAA/BH,EAAiBI,KAAKF,GAAgB,OAAOA,EAQrE,IANA,IAAIG,EAAO,EACVC,EAAI,EACJC,EAAM,GACNC,EAAK,GAGCF,EAAIJ,EAAIC,OAAQG,IAAK,CAC3B,OAAQJ,EAAIO,WAAWH,IACtB,KAAK,GACJE,EAAK,SACL,MACD,KAAO,GACNA,EAAK,QACL,MACD,KAAK,GACJA,EAAK,OACL,MACD,QACC,SAGEF,IAAMD,IAAME,GAAOL,EAAIQ,MAAML,EAAMC,IACvCC,GAAOC,EAEPH,EAAOC,EAAI,CACZ,CAEA,OADIA,IAAMD,IAAME,GAAOL,EAAIQ,MAAML,EAAMC,IAChCC,CACR,CCfa,IAAAI,EACZ,oECjBGC,EAAU,EAERC,EAAUC,MAAMD,QAsBtB,SAASE,EAAYC,EAAMC,EAAOC,EAAKC,EAAkBC,EAAUC,GAC7DJ,IAAOA,EAAQ,IAIpB,IACCK,EACAhB,EAFGiB,EAAkBN,EAItB,GAAI,QAASM,EAEZ,IAAKjB,KADLiB,EAAkB,GACRN,EACA,OAALX,EACHgB,EAAML,EAAMX,GAEZiB,EAAgBjB,GAAKW,EAAMX,GAM9B,IAAMkB,EAAQ,CACbR,KAAAA,EACAC,MAAOM,EACPL,IAAAA,EACAI,IAAAA,EACAG,IAAW,KACXC,GAAS,KACTC,IAAQ,EACRC,IAAM,KACNC,IAAY,KACZC,iBAAaC,EACbC,MAAapB,EACbqB,KAAS,EACTC,IAAQ,EACRd,SAAAA,EACAC,OAAAA,GAKD,GAAoB,mBAATL,IAAwBM,EAAMN,EAAKmB,cAC7C,IAAK7B,KAAKgB,OACkBS,IAAvBR,EAAgBjB,KACnBiB,EAAgBjB,GAAKgB,EAAIhB,IAK5B,OADI8B,EAAOA,QAACZ,OAAOY,EAAAA,QAAQZ,MAAMA,GAC1BA,CACR,CAgBA,IAAMa,EAAY,CAAE,EACdC,EAAY,mIAuBlB,SAAiBC,EAAMC,GACtB,GAAIJ,EAAOA,QAACK,KAAM,CACjB,IAAMC,EAASN,EAAAA,QAAQK,KAAKF,EAAMC,GAClC,GAAsB,iBAAXE,EAAqB,OAAOA,CACxC,CAIA,GAFAF,EAtBD,SAA4BA,GAC3B,OAAiB,OAAVA,GACW,iBAAVA,GACkB,mBAAlBA,EAAMG,QACXH,EAAMG,UACNH,CACJ,CAgBSI,CAAmBJ,GAEd,QAATD,GAA2B,QAATA,EAAgB,MAAO,GAC7C,GAAa,UAATA,GAAqC,iBAAVC,EAAoB,CAClD,IAAItC,EAAM,GACV,IAAK,IAAI2C,KAAQL,EAAO,CACvB,IAAIM,EAAMN,EAAMK,GAChB,GAAW,MAAPC,GAAuB,KAARA,EAAY,CAC9B,IAAMP,EACM,KAAXM,EAAK,GACFA,EACAR,EAAUQ,KACVR,EAAUQ,GAAQA,EAAKE,QAAQT,EAAW,OAAOU,eAEjDC,EAAS,IAEG,iBAARH,GAENP,EAAKW,WAAW,OAChBvC,EAAmBP,KAAKmC,KAEzBU,EAAS,OAEV/C,EAAMA,EAAMqC,EAAO,IAAMO,EAAMG,CAChC,CACD,CACA,OAAOV,EAAO,KAAOtC,EAAeC,GAAO,GAC5C,CAEA,OACU,MAATsC,IACU,IAAVA,GACiB,mBAAVA,GACU,iBAAVA,EAEA,IACa,IAAVA,EAAuBD,EAE3BA,EAAO,KAAOtC,EAAe,GAAKuC,GAAS,GACnD,qCASA,SAASW,EAAUX,GAClB,GACU,MAATA,GACiB,kBAAVA,GACU,mBAAVA,EAEP,OACD,KAEA,GAAqB,iBAAVA,EAAoB,CAE9B,QAA0BT,IAAtBS,EAAMV,YAA2B,OAAOU,EAE5C,GAAI3B,EAAQ2B,GAAQ,CACnB,IAAK,IAAIlC,EAAI,EAAGA,EAAIkC,EAAMrC,OAAQG,IACjCkC,EAAMlC,GAAK6C,EAAUX,EAAMlC,IAE5B,OAAOkC,CACR,CACD,CAEA,OAAOvC,EAAe,GAAKuC,EAC5B,sBA3GA,SAAqBY,GACpB,IAAM5B,EAAQT,EAAYsC,EAAQA,SAAE,CAAEC,IAAKF,EAAWG,SAAK7C,MAAA8C,KAAAC,UAAC,KAG5D,OADAjC,EAAMN,IAAMM,EAAKQ,IACVR,CACR"} \ No newline at end of file diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/jsx-runtime/dist/jsxRuntime.mjs b/browser/base/content/assistant/ui-preact/node_modules/preact/jsx-runtime/dist/jsxRuntime.mjs new file mode 100644 index 0000000000000..15cafef3fcd0a --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/jsx-runtime/dist/jsxRuntime.mjs @@ -0,0 +1,2 @@ +import{options as r,Fragment as e}from"preact";export{Fragment}from"preact";var t=/["&<]/;function n(r){if(0===r.length||!1===t.test(r))return r;for(var e=0,n=0,o="",f="";n} exprs\n * @returns {VNode}\n */\nfunction jsxTemplate(templates, ...exprs) {\n\tconst vnode = createVNode(Fragment, { tpl: templates, exprs });\n\t// Bypass render to string top level Fragment optimization\n\tvnode.key = vnode._vnode;\n\treturn vnode;\n}\n\nconst JS_TO_CSS = {};\nconst CSS_REGEX = /[A-Z]/g;\n\n/**\n * Unwrap potential signals.\n * @param {*} value\n * @returns {*}\n */\nfunction normalizeAttrValue(value) {\n\treturn value !== null &&\n\t\ttypeof value === 'object' &&\n\t\ttypeof value.valueOf === 'function'\n\t\t? value.valueOf()\n\t\t: value;\n}\n\n/**\n * Serialize an HTML attribute to a string. This function is not\n * expected to be used directly, but rather through a precompile\n * JSX transform\n * @param {string} name The attribute name\n * @param {*} value The attribute value\n * @returns {string}\n */\nfunction jsxAttr(name, value) {\n\tif (options.attr) {\n\t\tconst result = options.attr(name, value);\n\t\tif (typeof result === 'string') return result;\n\t}\n\n\tvalue = normalizeAttrValue(value);\n\n\tif (name === 'ref' || name === 'key') return '';\n\tif (name === 'style' && typeof value === 'object') {\n\t\tlet str = '';\n\t\tfor (let prop in value) {\n\t\t\tlet val = value[prop];\n\t\t\tif (val != null && val !== '') {\n\t\t\t\tconst name =\n\t\t\t\t\tprop[0] == '-'\n\t\t\t\t\t\t? prop\n\t\t\t\t\t\t: JS_TO_CSS[prop] ||\n\t\t\t\t\t\t\t(JS_TO_CSS[prop] = prop.replace(CSS_REGEX, '-$&').toLowerCase());\n\n\t\t\t\tlet suffix = ';';\n\t\t\t\tif (\n\t\t\t\t\ttypeof val === 'number' &&\n\t\t\t\t\t// Exclude custom-attributes\n\t\t\t\t\t!name.startsWith('--') &&\n\t\t\t\t\t!IS_NON_DIMENSIONAL.test(name)\n\t\t\t\t) {\n\t\t\t\t\tsuffix = 'px;';\n\t\t\t\t}\n\t\t\t\tstr = str + name + ':' + val + suffix;\n\t\t\t}\n\t\t}\n\t\treturn name + '=\"' + encodeEntities(str) + '\"';\n\t}\n\n\tif (\n\t\tvalue == null ||\n\t\tvalue === false ||\n\t\ttypeof value === 'function' ||\n\t\ttypeof value === 'object'\n\t) {\n\t\treturn '';\n\t} else if (value === true) return name;\n\n\treturn name + '=\"' + encodeEntities('' + value) + '\"';\n}\n\n/**\n * Escape a dynamic child passed to `jsxTemplate`. This function\n * is not expected to be used directly, but rather through a\n * precompile JSX transform\n * @param {*} value\n * @returns {string | null | VNode | Array}\n */\nfunction jsxEscape(value) {\n\tif (\n\t\tvalue == null ||\n\t\ttypeof value === 'boolean' ||\n\t\ttypeof value === 'function'\n\t) {\n\t\treturn null;\n\t}\n\n\tif (typeof value === 'object') {\n\t\t// Check for VNode\n\t\tif (value.constructor === undefined) return value;\n\n\t\tif (isArray(value)) {\n\t\t\tfor (let i = 0; i < value.length; i++) {\n\t\t\t\tvalue[i] = jsxEscape(value[i]);\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\t}\n\n\treturn encodeEntities('' + value);\n}\n\nexport {\n\tcreateVNode as jsx,\n\tcreateVNode as jsxs,\n\tcreateVNode as jsxDEV,\n\tFragment,\n\t// precompiled JSX transform\n\tjsxTemplate,\n\tjsxAttr,\n\tjsxEscape\n};\n"],"names":["ENCODED_ENTITIES","encodeEntities","str","length","test","last","i","out","ch","charCodeAt","slice","IS_NON_DIMENSIONAL","vnodeId","isArray","Array","createVNode","type","props","key","isStaticChildren","__source","__self","ref","normalizedProps","vnode","__k","__","__b","__e","__c","constructor","undefined","__v","__i","__u","defaultProps","options","jsxTemplate","templates","Fragment","tpl","exprs","call","arguments","JS_TO_CSS","CSS_REGEX","jsxAttr","name","value","attr","result","valueOf","normalizeAttrValue","prop","val","replace","toLowerCase","suffix","startsWith","jsxEscape"],"mappings":"4EAAA,IAAMA,EAAmB,QAGlB,SAASC,EAAeC,GAE9B,GAAmB,IAAfA,EAAIC,SAA+C,IAA/BH,EAAiBI,KAAKF,GAAgB,OAAOA,EAQrE,IANA,IAAIG,EAAO,EACVC,EAAI,EACJC,EAAM,GACNC,EAAK,GAGCF,EAAIJ,EAAIC,OAAQG,IAAK,CAC3B,OAAQJ,EAAIO,WAAWH,IACtB,KAAK,GACJE,EAAK,SACL,MACD,KAAO,GACNA,EAAK,QACL,MACD,KAAK,GACJA,EAAK,OACL,MACD,QACC,SAGEF,IAAMD,IAAME,GAAOL,EAAIQ,MAAML,EAAMC,IACvCC,GAAOC,EAEPH,EAAOC,EAAI,CACZ,CAEA,OADIA,IAAMD,IAAME,GAAOL,EAAIQ,MAAML,EAAMC,IAChCC,CACR,CCfa,IAAAI,EACZ,oECjBGC,EAAU,EAERC,EAAUC,MAAMD,QAsBtB,SAASE,EAAYC,EAAMC,EAAOC,EAAKC,EAAkBC,EAAUC,GAC7DJ,IAAOA,EAAQ,IAIpB,IACCK,EACAhB,EAFGiB,EAAkBN,EAItB,GAAI,QAASM,EAEZ,IAAKjB,KADLiB,EAAkB,GACRN,EACA,OAALX,EACHgB,EAAML,EAAMX,GAEZiB,EAAgBjB,GAAKW,EAAMX,GAM9B,IAAMkB,EAAQ,CACbR,KAAAA,EACAC,MAAOM,EACPL,IAAAA,EACAI,IAAAA,EACAG,IAAW,KACXC,GAAS,KACTC,IAAQ,EACRC,IAAM,KACNC,IAAY,KACZC,iBAAaC,EACbC,MAAapB,EACbqB,KAAS,EACTC,IAAQ,EACRd,SAAAA,EACAC,OAAAA,GAKD,GAAoB,mBAATL,IAAwBM,EAAMN,EAAKmB,cAC7C,IAAK7B,KAAKgB,OACkBS,IAAvBR,EAAgBjB,KACnBiB,EAAgBjB,GAAKgB,EAAIhB,IAK5B,OADI8B,EAAQZ,OAAOY,EAAQZ,MAAMA,GAC1BA,CACR,CASA,SAASa,EAAYC,GACpB,IAAMd,EAAQT,EAAYwB,EAAU,CAAEC,IAAKF,EAAWG,SAAK/B,MAAAgC,KAAAC,UAAC,KAG5D,OADAnB,EAAMN,IAAMM,EAAKQ,IACVR,CACR,CAEA,IAAMoB,EAAY,CAAE,EACdC,EAAY,SAuBlB,SAASC,EAAQC,EAAMC,GACtB,GAAIZ,EAAQa,KAAM,CACjB,IAAMC,EAASd,EAAQa,KAAKF,EAAMC,GAClC,GAAsB,iBAAXE,EAAqB,OAAOA,CACxC,CAIA,GAFAF,EAtBD,SAA4BA,GAC3B,OAAiB,OAAVA,GACW,iBAAVA,GACkB,mBAAlBA,EAAMG,QACXH,EAAMG,UACNH,CACJ,CAgBSI,CAAmBJ,GAEd,QAATD,GAA2B,QAATA,EAAgB,MAAO,GAC7C,GAAa,UAATA,GAAqC,iBAAVC,EAAoB,CAClD,IAAI9C,EAAM,GACV,IAAK,IAAImD,KAAQL,EAAO,CACvB,IAAIM,EAAMN,EAAMK,GAChB,GAAW,MAAPC,GAAuB,KAARA,EAAY,CAC9B,IAAMP,EACM,KAAXM,EAAK,GACFA,EACAT,EAAUS,KACVT,EAAUS,GAAQA,EAAKE,QAAQV,EAAW,OAAOW,eAEjDC,EAAS,IAEG,iBAARH,GAENP,EAAKW,WAAW,OAChB/C,EAAmBP,KAAK2C,KAEzBU,EAAS,OAEVvD,EAAMA,EAAM6C,EAAO,IAAMO,EAAMG,CAChC,CACD,CACA,OAAOV,EAAO,KAAO9C,EAAeC,GAAO,GAC5C,CAEA,OACU,MAAT8C,IACU,IAAVA,GACiB,mBAAVA,GACU,iBAAVA,EAEA,IACa,IAAVA,EAAuBD,EAE3BA,EAAO,KAAO9C,EAAe,GAAK+C,GAAS,GACnD,CASA,SAASW,EAAUX,GAClB,GACU,MAATA,GACiB,kBAAVA,GACU,mBAAVA,EAEP,OACD,KAEA,GAAqB,iBAAVA,EAAoB,CAE9B,QAA0BjB,IAAtBiB,EAAMlB,YAA2B,OAAOkB,EAE5C,GAAInC,EAAQmC,GAAQ,CACnB,IAAK,IAAI1C,EAAI,EAAGA,EAAI0C,EAAM7C,OAAQG,IACjC0C,EAAM1C,GAAKqD,EAAUX,EAAM1C,IAE5B,OAAO0C,CACR,CACD,CAEA,OAAO/C,EAAe,GAAK+C,EAC5B"} \ No newline at end of file diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/jsx-runtime/dist/jsxRuntime.umd.js b/browser/base/content/assistant/ui-preact/node_modules/preact/jsx-runtime/dist/jsxRuntime.umd.js new file mode 100644 index 0000000000000..0ff5a2ff160c7 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/jsx-runtime/dist/jsxRuntime.umd.js @@ -0,0 +1,2 @@ +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("preact")):"function"==typeof define&&define.amd?define(["exports","preact"],r):r((e||self).jsxRuntime={},e.preact)}(this,function(e,r){var n=/["&<]/;function t(e){if(0===e.length||!1===n.test(e))return e;for(var r=0,t=0,o="",f="";t} exprs\n * @returns {VNode}\n */\nfunction jsxTemplate(templates, ...exprs) {\n\tconst vnode = createVNode(Fragment, { tpl: templates, exprs });\n\t// Bypass render to string top level Fragment optimization\n\tvnode.key = vnode._vnode;\n\treturn vnode;\n}\n\nconst JS_TO_CSS = {};\nconst CSS_REGEX = /[A-Z]/g;\n\n/**\n * Unwrap potential signals.\n * @param {*} value\n * @returns {*}\n */\nfunction normalizeAttrValue(value) {\n\treturn value !== null &&\n\t\ttypeof value === 'object' &&\n\t\ttypeof value.valueOf === 'function'\n\t\t? value.valueOf()\n\t\t: value;\n}\n\n/**\n * Serialize an HTML attribute to a string. This function is not\n * expected to be used directly, but rather through a precompile\n * JSX transform\n * @param {string} name The attribute name\n * @param {*} value The attribute value\n * @returns {string}\n */\nfunction jsxAttr(name, value) {\n\tif (options.attr) {\n\t\tconst result = options.attr(name, value);\n\t\tif (typeof result === 'string') return result;\n\t}\n\n\tvalue = normalizeAttrValue(value);\n\n\tif (name === 'ref' || name === 'key') return '';\n\tif (name === 'style' && typeof value === 'object') {\n\t\tlet str = '';\n\t\tfor (let prop in value) {\n\t\t\tlet val = value[prop];\n\t\t\tif (val != null && val !== '') {\n\t\t\t\tconst name =\n\t\t\t\t\tprop[0] == '-'\n\t\t\t\t\t\t? prop\n\t\t\t\t\t\t: JS_TO_CSS[prop] ||\n\t\t\t\t\t\t\t(JS_TO_CSS[prop] = prop.replace(CSS_REGEX, '-$&').toLowerCase());\n\n\t\t\t\tlet suffix = ';';\n\t\t\t\tif (\n\t\t\t\t\ttypeof val === 'number' &&\n\t\t\t\t\t// Exclude custom-attributes\n\t\t\t\t\t!name.startsWith('--') &&\n\t\t\t\t\t!IS_NON_DIMENSIONAL.test(name)\n\t\t\t\t) {\n\t\t\t\t\tsuffix = 'px;';\n\t\t\t\t}\n\t\t\t\tstr = str + name + ':' + val + suffix;\n\t\t\t}\n\t\t}\n\t\treturn name + '=\"' + encodeEntities(str) + '\"';\n\t}\n\n\tif (\n\t\tvalue == null ||\n\t\tvalue === false ||\n\t\ttypeof value === 'function' ||\n\t\ttypeof value === 'object'\n\t) {\n\t\treturn '';\n\t} else if (value === true) return name;\n\n\treturn name + '=\"' + encodeEntities('' + value) + '\"';\n}\n\n/**\n * Escape a dynamic child passed to `jsxTemplate`. This function\n * is not expected to be used directly, but rather through a\n * precompile JSX transform\n * @param {*} value\n * @returns {string | null | VNode | Array}\n */\nfunction jsxEscape(value) {\n\tif (\n\t\tvalue == null ||\n\t\ttypeof value === 'boolean' ||\n\t\ttypeof value === 'function'\n\t) {\n\t\treturn null;\n\t}\n\n\tif (typeof value === 'object') {\n\t\t// Check for VNode\n\t\tif (value.constructor === undefined) return value;\n\n\t\tif (isArray(value)) {\n\t\t\tfor (let i = 0; i < value.length; i++) {\n\t\t\t\tvalue[i] = jsxEscape(value[i]);\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\t}\n\n\treturn encodeEntities('' + value);\n}\n\nexport {\n\tcreateVNode as jsx,\n\tcreateVNode as jsxs,\n\tcreateVNode as jsxDEV,\n\tFragment,\n\t// precompiled JSX transform\n\tjsxTemplate,\n\tjsxAttr,\n\tjsxEscape\n};\n"],"names":["ENCODED_ENTITIES","encodeEntities","str","length","test","last","i","out","ch","charCodeAt","slice","IS_NON_DIMENSIONAL","vnodeId","isArray","Array","createVNode","type","props","key","isStaticChildren","__source","__self","ref","normalizedProps","vnode","__k","__","__b","__e","__c","constructor","undefined","__v","__i","__u","defaultProps","options","JS_TO_CSS","CSS_REGEX","name","value","attr","result","valueOf","normalizeAttrValue","prop","val","replace","toLowerCase","suffix","startsWith","jsxEscape","templates","Fragment","tpl","exprs","call","arguments"],"mappings":"0QAAA,IAAMA,EAAmB,QAGlB,SAASC,EAAeC,GAE9B,GAAmB,IAAfA,EAAIC,SAA+C,IAA/BH,EAAiBI,KAAKF,GAAgB,OAAOA,EAQrE,IANA,IAAIG,EAAO,EACVC,EAAI,EACJC,EAAM,GACNC,EAAK,GAGCF,EAAIJ,EAAIC,OAAQG,IAAK,CAC3B,OAAQJ,EAAIO,WAAWH,IACtB,KAAK,GACJE,EAAK,SACL,MACD,KAAO,GACNA,EAAK,QACL,MACD,KAAK,GACJA,EAAK,OACL,MACD,QACC,SAGEF,IAAMD,IAAME,GAAOL,EAAIQ,MAAML,EAAMC,IACvCC,GAAOC,EAEPH,EAAOC,EAAI,CACZ,CAEA,OADIA,IAAMD,IAAME,GAAOL,EAAIQ,MAAML,EAAMC,IAChCC,CACR,CCfa,IAAAI,EACZ,oECjBGC,EAAU,EAERC,EAAUC,MAAMD,QAsBtB,SAASE,EAAYC,EAAMC,EAAOC,EAAKC,EAAkBC,EAAUC,GAC7DJ,IAAOA,EAAQ,IAIpB,IACCK,EACAhB,EAFGiB,EAAkBN,EAItB,GAAI,QAASM,EAEZ,IAAKjB,KADLiB,EAAkB,GACRN,EACA,OAALX,EACHgB,EAAML,EAAMX,GAEZiB,EAAgBjB,GAAKW,EAAMX,GAM9B,IAAMkB,EAAQ,CACbR,KAAAA,EACAC,MAAOM,EACPL,IAAAA,EACAI,IAAAA,EACAG,IAAW,KACXC,GAAS,KACTC,IAAQ,EACRC,IAAM,KACNC,IAAY,KACZC,iBAAaC,EACbC,MAAapB,EACbqB,KAAS,EACTC,IAAQ,EACRd,SAAAA,EACAC,OAAAA,GAKD,GAAoB,mBAATL,IAAwBM,EAAMN,EAAKmB,cAC7C,IAAK7B,KAAKgB,OACkBS,IAAvBR,EAAgBjB,KACnBiB,EAAgBjB,GAAKgB,EAAIhB,IAK5B,OADI8B,EAAOA,QAACZ,OAAOY,EAAAA,QAAQZ,MAAMA,GAC1BA,CACR,CAgBA,IAAMa,EAAY,CAAE,EACdC,EAAY,iHAuBlB,SAAiBC,EAAMC,GACtB,GAAIJ,EAAOA,QAACK,KAAM,CACjB,IAAMC,EAASN,EAAAA,QAAQK,KAAKF,EAAMC,GAClC,GAAsB,iBAAXE,EAAqB,OAAOA,CACxC,CAIA,GAFAF,EAtBD,SAA4BA,GAC3B,OAAiB,OAAVA,GACW,iBAAVA,GACkB,mBAAlBA,EAAMG,QACXH,EAAMG,UACNH,CACJ,CAgBSI,CAAmBJ,GAEd,QAATD,GAA2B,QAATA,EAAgB,MAAO,GAC7C,GAAa,UAATA,GAAqC,iBAAVC,EAAoB,CAClD,IAAItC,EAAM,GACV,IAAK,IAAI2C,KAAQL,EAAO,CACvB,IAAIM,EAAMN,EAAMK,GAChB,GAAW,MAAPC,GAAuB,KAARA,EAAY,CAC9B,IAAMP,EACM,KAAXM,EAAK,GACFA,EACAR,EAAUQ,KACVR,EAAUQ,GAAQA,EAAKE,QAAQT,EAAW,OAAOU,eAEjDC,EAAS,IAEG,iBAARH,GAENP,EAAKW,WAAW,OAChBvC,EAAmBP,KAAKmC,KAEzBU,EAAS,OAEV/C,EAAMA,EAAMqC,EAAO,IAAMO,EAAMG,CAChC,CACD,CACA,OAAOV,EAAO,KAAOtC,EAAeC,GAAO,GAC5C,CAEA,OACU,MAATsC,IACU,IAAVA,GACiB,mBAAVA,GACU,iBAAVA,EAEA,IACa,IAAVA,EAAuBD,EAE3BA,EAAO,KAAOtC,EAAe,GAAKuC,GAAS,GACnD,yBASA,SAASW,EAAUX,GAClB,GACU,MAATA,GACiB,kBAAVA,GACU,mBAAVA,EAEP,OACD,KAEA,GAAqB,iBAAVA,EAAoB,CAE9B,QAA0BT,IAAtBS,EAAMV,YAA2B,OAAOU,EAE5C,GAAI3B,EAAQ2B,GAAQ,CACnB,IAAK,IAAIlC,EAAI,EAAGA,EAAIkC,EAAMrC,OAAQG,IACjCkC,EAAMlC,GAAK6C,EAAUX,EAAMlC,IAE5B,OAAOkC,CACR,CACD,CAEA,OAAOvC,EAAe,GAAKuC,EAC5B,gBA3GA,SAAqBY,GACpB,IAAM5B,EAAQT,EAAYsC,EAAQA,SAAE,CAAEC,IAAKF,EAAWG,SAAK7C,MAAA8C,KAAAC,UAAC,KAG5D,OADAjC,EAAMN,IAAMM,EAAKQ,IACVR,CACR"} \ No newline at end of file diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/jsx-runtime/package.json b/browser/base/content/assistant/ui-preact/node_modules/preact/jsx-runtime/package.json new file mode 100644 index 0000000000000..1014de1c8222e --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/jsx-runtime/package.json @@ -0,0 +1,28 @@ +{ + "name": "jsx-runtime", + "amdName": "jsxRuntime", + "version": "1.0.0", + "private": true, + "description": "Preact JSX runtime", + "main": "dist/jsxRuntime.js", + "module": "dist/jsxRuntime.module.js", + "umd:main": "dist/jsxRuntime.umd.js", + "source": "src/index.js", + "types": "src/index.d.ts", + "license": "MIT", + "peerDependencies": { + "preact": "^10.0.0" + }, + "mangle": { + "regex": "^_" + }, + "exports": { + ".": { + "types": "./src/index.d.ts", + "browser": "./dist/jsxRuntime.module.js", + "umd": "./dist/jsxRuntime.umd.js", + "import": "./dist/jsxRuntime.mjs", + "require": "./dist/jsxRuntime.js" + } + } +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/jsx-runtime/src/index.d.ts b/browser/base/content/assistant/ui-preact/node_modules/preact/jsx-runtime/src/index.d.ts new file mode 100644 index 0000000000000..46649e8bdfab6 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/jsx-runtime/src/index.d.ts @@ -0,0 +1,62 @@ +// Intentionally not using a relative path to take advantage of +// the TS version resolution mechanism +export { Fragment } from 'preact'; +import { + ComponentType, + ComponentChild, + ComponentChildren, + VNode, + Attributes +} from 'preact'; +import { JSXInternal } from '../../src/jsx'; + +export function jsx( + type: string, + props: JSXInternal.HTMLAttributes & + JSXInternal.SVGAttributes & + Record & { children?: ComponentChild }, + key?: string +): VNode; +export function jsx

    ( + type: ComponentType

    , + props: Attributes & P & { children?: ComponentChild }, + key?: string +): VNode; + +export function jsxs( + type: string, + props: JSXInternal.HTMLAttributes & + JSXInternal.SVGAttributes & + Record & { children?: ComponentChild[] }, + key?: string +): VNode; +export function jsxs

    ( + type: ComponentType

    , + props: Attributes & P & { children?: ComponentChild[] }, + key?: string +): VNode; + +export function jsxDEV( + type: string, + props: JSXInternal.HTMLAttributes & + JSXInternal.SVGAttributes & + Record & { children?: ComponentChildren }, + key?: string +): VNode; +export function jsxDEV

    ( + type: ComponentType

    , + props: Attributes & P & { children?: ComponentChildren }, + key?: string +): VNode; + +// These are not expected to be used manually, but by a JSX transform +export function jsxTemplate( + template: string[], + ...expressions: any[] +): VNode; +export function jsxAttr(name: string, value: any): string | null; +export function jsxEscape( + value: T +): string | null | VNode | Array; + +export { JSXInternal as JSX }; diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/jsx-runtime/src/index.js b/browser/base/content/assistant/ui-preact/node_modules/preact/jsx-runtime/src/index.js new file mode 100644 index 0000000000000..bfd17bd4fcda2 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/jsx-runtime/src/index.js @@ -0,0 +1,206 @@ +import { options, Fragment } from 'preact'; +import { encodeEntities } from './utils'; +import { IS_NON_DIMENSIONAL } from '../../src/constants'; + +let vnodeId = 0; + +const isArray = Array.isArray; + +/** + * @fileoverview + * This file exports various methods that implement Babel's "automatic" JSX runtime API: + * - jsx(type, props, key) + * - jsxs(type, props, key) + * - jsxDEV(type, props, key, __source, __self) + * + * The implementation of createVNode here is optimized for performance. + * Benchmarks: https://esbench.com/bench/5f6b54a0b4632100a7dcd2b3 + */ + +/** + * JSX.Element factory used by Babel's {runtime:"automatic"} JSX transform + * @param {VNode['type']} type + * @param {VNode['props']} props + * @param {VNode['key']} [key] + * @param {unknown} [isStaticChildren] + * @param {unknown} [__source] + * @param {unknown} [__self] + */ +function createVNode(type, props, key, isStaticChildren, __source, __self) { + if (!props) props = {}; + // We'll want to preserve `ref` in props to get rid of the need for + // forwardRef components in the future, but that should happen via + // a separate PR. + let normalizedProps = props, + ref, + i; + + if ('ref' in normalizedProps) { + normalizedProps = {}; + for (i in props) { + if (i == 'ref') { + ref = props[i]; + } else { + normalizedProps[i] = props[i]; + } + } + } + + /** @type {VNode & { __source: any; __self: any }} */ + const vnode = { + type, + props: normalizedProps, + key, + ref, + _children: null, + _parent: null, + _depth: 0, + _dom: null, + _component: null, + constructor: undefined, + _original: --vnodeId, + _index: -1, + _flags: 0, + __source, + __self + }; + + // If a Component VNode, check for and apply defaultProps. + // Note: `type` is often a String, and can be `undefined` in development. + if (typeof type === 'function' && (ref = type.defaultProps)) { + for (i in ref) + if (normalizedProps[i] === undefined) { + normalizedProps[i] = ref[i]; + } + } + + if (options.vnode) options.vnode(vnode); + return vnode; +} + +/** + * Create a template vnode. This function is not expected to be + * used directly, but rather through a precompile JSX transform + * @param {string[]} templates + * @param {Array} exprs + * @returns {VNode} + */ +function jsxTemplate(templates, ...exprs) { + const vnode = createVNode(Fragment, { tpl: templates, exprs }); + // Bypass render to string top level Fragment optimization + vnode.key = vnode._vnode; + return vnode; +} + +const JS_TO_CSS = {}; +const CSS_REGEX = /[A-Z]/g; + +/** + * Unwrap potential signals. + * @param {*} value + * @returns {*} + */ +function normalizeAttrValue(value) { + return value !== null && + typeof value === 'object' && + typeof value.valueOf === 'function' + ? value.valueOf() + : value; +} + +/** + * Serialize an HTML attribute to a string. This function is not + * expected to be used directly, but rather through a precompile + * JSX transform + * @param {string} name The attribute name + * @param {*} value The attribute value + * @returns {string} + */ +function jsxAttr(name, value) { + if (options.attr) { + const result = options.attr(name, value); + if (typeof result === 'string') return result; + } + + value = normalizeAttrValue(value); + + if (name === 'ref' || name === 'key') return ''; + if (name === 'style' && typeof value === 'object') { + let str = ''; + for (let prop in value) { + let val = value[prop]; + if (val != null && val !== '') { + const name = + prop[0] == '-' + ? prop + : JS_TO_CSS[prop] || + (JS_TO_CSS[prop] = prop.replace(CSS_REGEX, '-$&').toLowerCase()); + + let suffix = ';'; + if ( + typeof val === 'number' && + // Exclude custom-attributes + !name.startsWith('--') && + !IS_NON_DIMENSIONAL.test(name) + ) { + suffix = 'px;'; + } + str = str + name + ':' + val + suffix; + } + } + return name + '="' + encodeEntities(str) + '"'; + } + + if ( + value == null || + value === false || + typeof value === 'function' || + typeof value === 'object' + ) { + return ''; + } else if (value === true) return name; + + return name + '="' + encodeEntities('' + value) + '"'; +} + +/** + * Escape a dynamic child passed to `jsxTemplate`. This function + * is not expected to be used directly, but rather through a + * precompile JSX transform + * @param {*} value + * @returns {string | null | VNode | Array} + */ +function jsxEscape(value) { + if ( + value == null || + typeof value === 'boolean' || + typeof value === 'function' + ) { + return null; + } + + if (typeof value === 'object') { + // Check for VNode + if (value.constructor === undefined) return value; + + if (isArray(value)) { + for (let i = 0; i < value.length; i++) { + value[i] = jsxEscape(value[i]); + } + return value; + } + } + + return encodeEntities('' + value); +} + +export { + createVNode as jsx, + createVNode as jsxs, + createVNode as jsxDEV, + Fragment, + // precompiled JSX transform + jsxTemplate, + jsxAttr, + jsxEscape +}; diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/jsx-runtime/src/utils.js b/browser/base/content/assistant/ui-preact/node_modules/preact/jsx-runtime/src/utils.js new file mode 100644 index 0000000000000..1274998624a5c --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/jsx-runtime/src/utils.js @@ -0,0 +1,36 @@ +const ENCODED_ENTITIES = /["&<]/; + +/** @param {string} str */ +export function encodeEntities(str) { + // Skip all work for strings with no entities needing encoding: + if (str.length === 0 || ENCODED_ENTITIES.test(str) === false) return str; + + let last = 0, + i = 0, + out = '', + ch = ''; + + // Seek forward in str until the next entity char: + for (; i < str.length; i++) { + switch (str.charCodeAt(i)) { + case 34: + ch = '"'; + break; + case 38: + ch = '&'; + break; + case 60: + ch = '<'; + break; + default: + continue; + } + // Append skipped/buffered characters and the encoded entity: + if (i !== last) out += str.slice(last, i); + out += ch; + // Start the next seek/buffer after the entity's offset: + last = i + 1; + } + if (i !== last) out += str.slice(last, i); + return out; +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/package.json b/browser/base/content/assistant/ui-preact/node_modules/preact/package.json new file mode 100644 index 0000000000000..b11dcbaed548a --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/package.json @@ -0,0 +1,258 @@ +{ + "name": "preact", + "amdName": "preact", + "version": "10.28.2", + "private": false, + "description": "Fast 3kb React-compatible Virtual DOM library.", + "main": "dist/preact.js", + "module": "dist/preact.module.js", + "umd:main": "dist/preact.umd.js", + "unpkg": "dist/preact.min.js", + "source": "src/index.js", + "typesVersions": { + "<=5.0": { + ".": ["./src/index-5.d.ts"] + } + }, + "exports": { + ".": { + "types@<=5.0": { + "types": "./src/index-5.d.ts" + }, + "types": "./src/index.d.ts", + "browser": "./dist/preact.module.js", + "umd": "./dist/preact.umd.js", + "import": "./dist/preact.mjs", + "require": "./dist/preact.js" + }, + "./compat": { + "types": "./compat/src/index.d.ts", + "browser": "./compat/dist/compat.module.js", + "umd": "./compat/dist/compat.umd.js", + "import": "./compat/dist/compat.mjs", + "require": "./compat/dist/compat.js" + }, + "./debug": { + "types": "./debug/src/index.d.ts", + "browser": "./debug/dist/debug.module.js", + "umd": "./debug/dist/debug.umd.js", + "import": "./debug/dist/debug.mjs", + "require": "./debug/dist/debug.js" + }, + "./devtools": { + "types": "./devtools/src/index.d.ts", + "browser": "./devtools/dist/devtools.module.js", + "umd": "./devtools/dist/devtools.umd.js", + "import": "./devtools/dist/devtools.mjs", + "require": "./devtools/dist/devtools.js" + }, + "./hooks": { + "types": "./hooks/src/index.d.ts", + "browser": "./hooks/dist/hooks.module.js", + "umd": "./hooks/dist/hooks.umd.js", + "import": "./hooks/dist/hooks.mjs", + "require": "./hooks/dist/hooks.js" + }, + "./test-utils": { + "types": "./test-utils/src/index.d.ts", + "browser": "./test-utils/dist/testUtils.module.js", + "umd": "./test-utils/dist/testUtils.umd.js", + "import": "./test-utils/dist/testUtils.mjs", + "require": "./test-utils/dist/testUtils.js" + }, + "./compat/test-utils": { + "types": "./test-utils/src/index.d.ts", + "browser": "./test-utils/dist/testUtils.module.js", + "umd": "./test-utils/dist/testUtils.umd.js", + "import": "./test-utils/dist/testUtils.mjs", + "require": "./test-utils/dist/testUtils.js" + }, + "./jsx-runtime": { + "types": "./jsx-runtime/src/index.d.ts", + "browser": "./jsx-runtime/dist/jsxRuntime.module.js", + "umd": "./jsx-runtime/dist/jsxRuntime.umd.js", + "import": "./jsx-runtime/dist/jsxRuntime.mjs", + "require": "./jsx-runtime/dist/jsxRuntime.js" + }, + "./jsx-dev-runtime": { + "types": "./jsx-runtime/src/index.d.ts", + "browser": "./jsx-runtime/dist/jsxRuntime.module.js", + "umd": "./jsx-runtime/dist/jsxRuntime.umd.js", + "import": "./jsx-runtime/dist/jsxRuntime.mjs", + "require": "./jsx-runtime/dist/jsxRuntime.js" + }, + "./compat/client": { + "types": "./compat/client.d.ts", + "import": "./compat/client.mjs", + "require": "./compat/client.js" + }, + "./compat/server": { + "browser": "./compat/server.browser.js", + "import": "./compat/server.mjs", + "require": "./compat/server.js" + }, + "./compat/server.browser": { + "types": "./compat/server.d.ts", + "default": "./compat/server.browser.js" + }, + "./compat/jsx-runtime": { + "types": "./jsx-runtime/src/index.d.ts", + "import": "./compat/jsx-runtime.mjs", + "require": "./compat/jsx-runtime.js" + }, + "./compat/jsx-dev-runtime": { + "types": "./jsx-runtime/src/index.d.ts", + "import": "./compat/jsx-dev-runtime.mjs", + "require": "./compat/jsx-dev-runtime.js" + }, + "./compat/scheduler": { + "import": "./compat/scheduler.mjs", + "require": "./compat/scheduler.js" + }, + "./package.json": "./package.json", + "./compat/package.json": "./compat/package.json", + "./debug/package.json": "./debug/package.json", + "./devtools/package.json": "./devtools/package.json", + "./hooks/package.json": "./hooks/package.json", + "./test-utils/package.json": "./test-utils/package.json", + "./jsx-runtime/package.json": "./jsx-runtime/package.json" + }, + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + }, + "types": "src/index.d.ts", + "scripts": { + "prepare": "husky && run-s build", + "build": "npm-run-all --parallel 'build:*'", + "build:core": "microbundle build --raw --no-generateTypes -f cjs,esm,umd", + "build:core-min": "microbundle build --raw --no-generateTypes -f cjs,esm,umd,iife src/cjs.js -o dist/preact.min.js", + "build:debug": "microbundle build --raw --no-generateTypes -f cjs,esm,umd --cwd debug", + "build:devtools": "microbundle build --raw --no-generateTypes -f cjs,esm,umd --cwd devtools", + "build:hooks": "microbundle build --raw --no-generateTypes -f cjs,esm,umd --cwd hooks", + "build:test-utils": "microbundle build --raw --no-generateTypes -f cjs,esm,umd --cwd test-utils", + "build:compat": "microbundle build --raw --no-generateTypes -f cjs,esm,umd --cwd compat --globals 'preact/hooks=preactHooks'", + "build:jsx": "microbundle build --raw --no-generateTypes -f cjs,esm,umd --cwd jsx-runtime", + "postbuild": "node ./config/node-13-exports.js && node ./config/compat-entries.js", + "dev": "microbundle watch --raw --no-generateTypes --format cjs", + "dev:hooks": "microbundle watch --raw --no-generateTypes --format cjs --cwd hooks", + "dev:compat": "microbundle watch --raw --no-generateTypes --format cjs --cwd compat --globals 'preact/hooks=preactHooks'", + "test": "npm-run-all build lint test:unit", + "test:unit": "run-p test:mocha test:vitest:min test:ts", + "test:vitest": "cross-env COVERAGE=true vitest run", + "test:vitest:min": "cross-env MINIFY=true vitest run", + "test:vitest:watch": "vitest", + "test:ts": "run-p 'test:ts:*'", + "test:ts:core": "tsc -p test/ts/ && mocha --require \"@babel/register\" test/ts/**/*-test.js", + "test:ts:compat": "tsc -p compat/test/ts/", + "test:mocha": "mocha --recursive --require \"@babel/register\" test/shared test/node", + "test:mocha:watch": "npm run test:mocha -- --watch", + "lint": "run-s oxlint tsc", + "tsc": "tsc -p jsconfig-lint.json", + "oxlint": "oxlint -c oxlint.json src test/browser test/node test/shared debug compat hooks test-utils", + "format": "biome format --write .", + "format:check": "biome format ." + }, + "nano-staged": { + "**/*.{js,jsx,mjs,cjs,ts,tsx,yml,json,html,md,css,scss}": [ + "biome format --write --no-errors-on-unmatched" + ] + }, + "files": [ + "src", + "dist", + "compat/dist", + "compat/src", + "compat/client.d.ts", + "compat/client.js", + "compat/client.mjs", + "compat/server.browser.js", + "compat/server.js", + "compat/server.mjs", + "compat/scheduler.js", + "compat/scheduler.mjs", + "compat/test-utils.js", + "compat/test-utils.mjs", + "compat/jsx-runtime.js", + "compat/jsx-runtime.mjs", + "compat/jsx-dev-runtime.js", + "compat/jsx-dev-runtime.mjs", + "compat/package.json", + "debug/dist", + "debug/src", + "debug/package.json", + "devtools/dist", + "devtools/src", + "devtools/package.json", + "hooks/dist", + "hooks/src", + "hooks/package.json", + "jsx-runtime/dist", + "jsx-runtime/src", + "jsx-runtime/package.json", + "test-utils/src", + "test-utils/package.json", + "test-utils/dist" + ], + "keywords": [ + "preact", + "react", + "ui", + "user interface", + "virtual dom", + "vdom", + "components", + "dom diff", + "front-end", + "framework" + ], + "authors": [ + "The Preact Authors (https://github.com/preactjs/preact/contributors)" + ], + "repository": "preactjs/preact", + "bugs": "https://github.com/preactjs/preact/issues", + "homepage": "https://preactjs.com", + "devDependencies": { + "@actions/github": "^6.0.0", + "@actions/glob": "^0.5.0", + "@babel/core": "^7.26.0", + "@babel/plugin-transform-react-jsx": "^7.25.9", + "@babel/plugin-transform-react-jsx-source": "^7.25.9", + "@babel/preset-env": "^7.26.0", + "@babel/register": "^7.25.9", + "@biomejs/biome": "^1.9.4", + "@types/chai": "^5.0.1", + "@types/mocha": "^10.0.0", + "@types/node": "^18.19.87", + "@types/sinon": "^17.0.3", + "@vitest/browser": "^3.2.1", + "@vitest/coverage-istanbul": "^3.2.1", + "babel-plugin-transform-rename-properties": "0.1.0", + "chai": "^5.2.0", + "coveralls": "^3.1.1", + "cross-env": "^7.0.3", + "errorstacks": "^2.4.1", + "esbuild": "^0.24.0", + "husky": "^9.1.7", + "kolorist": "^1.8.0", + "microbundle": "^0.15.1", + "mocha": "^11.0.0", + "npm-run-all2": "^7.0.0", + "oxlint": "^0.15.12", + "preact-render-to-string": "^6.5.0", + "prop-types": "^15.8.1", + "sade": "^1.8.1", + "sinon": "^19.0.2", + "sinon-chai": "^4.0.0", + "terser": "5.16.0", + "typescript": "5.1.6", + "undici": "^4.12.0", + "vite": "^6.2.0", + "vitest": "^3.2.1", + "webdriverio": "^9.15.0" + }, + "volta": { + "node": "20.19.1" + } +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/src/cjs.js b/browser/base/content/assistant/ui-preact/node_modules/preact/src/cjs.js new file mode 100644 index 0000000000000..b4721b1d44182 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/src/cjs.js @@ -0,0 +1,3 @@ +import * as preact from './index.js'; +if (typeof module < 'u') module.exports = preact; +else self.preact = preact; diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/src/clone-element.js b/browser/base/content/assistant/ui-preact/node_modules/preact/src/clone-element.js new file mode 100644 index 0000000000000..671eb4e63fced --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/src/clone-element.js @@ -0,0 +1,48 @@ +import { assign, slice } from './util'; +import { createVNode } from './create-element'; +import { NULL, UNDEFINED } from './constants'; + +/** + * Clones the given VNode, optionally adding attributes/props and replacing its + * children. + * @param {import('./internal').VNode} vnode The virtual DOM element to clone + * @param {object} props Attributes/props to add when cloning + * @param {Array} rest Any additional arguments will be used + * as replacement children. + * @returns {import('./internal').VNode} + */ +export function cloneElement(vnode, props, children) { + let normalizedProps = assign({}, vnode.props), + key, + ref, + i; + + let defaultProps; + + if (vnode.type && vnode.type.defaultProps) { + defaultProps = vnode.type.defaultProps; + } + + for (i in props) { + if (i == 'key') key = props[i]; + else if (i == 'ref') ref = props[i]; + else if (props[i] === UNDEFINED && defaultProps != UNDEFINED) { + normalizedProps[i] = defaultProps[i]; + } else { + normalizedProps[i] = props[i]; + } + } + + if (arguments.length > 2) { + normalizedProps.children = + arguments.length > 3 ? slice.call(arguments, 2) : children; + } + + return createVNode( + vnode.type, + normalizedProps, + key || vnode.key, + ref || vnode.ref, + NULL + ); +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/src/component.js b/browser/base/content/assistant/ui-preact/node_modules/preact/src/component.js new file mode 100644 index 0000000000000..23f3f318966bd --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/src/component.js @@ -0,0 +1,249 @@ +import { assign } from './util'; +import { diff, commitRoot } from './diff/index'; +import options from './options'; +import { Fragment } from './create-element'; +import { MODE_HYDRATE, NULL } from './constants'; + +/** + * Base Component class. Provides `setState()` and `forceUpdate()`, which + * trigger rendering + * @param {object} props The initial component props + * @param {object} context The initial context from parent components' + * getChildContext + */ +export function BaseComponent(props, context) { + this.props = props; + this.context = context; +} + +/** + * Update component state and schedule a re-render. + * @this {import('./internal').Component} + * @param {object | ((s: object, p: object) => object)} update A hash of state + * properties to update with new values or a function that given the current + * state and props returns a new partial state + * @param {() => void} [callback] A function to be called once component state is + * updated + */ +BaseComponent.prototype.setState = function (update, callback) { + // only clone state when copying to nextState the first time. + let s; + if (this._nextState != NULL && this._nextState != this.state) { + s = this._nextState; + } else { + s = this._nextState = assign({}, this.state); + } + + if (typeof update == 'function') { + // Some libraries like `immer` mark the current state as readonly, + // preventing us from mutating it, so we need to clone it. See #2716 + update = update(assign({}, s), this.props); + } + + if (update) { + assign(s, update); + } + + // Skip update if updater function returned null + if (update == NULL) return; + + if (this._vnode) { + if (callback) { + this._stateCallbacks.push(callback); + } + enqueueRender(this); + } +}; + +/** + * Immediately perform a synchronous re-render of the component + * @this {import('./internal').Component} + * @param {() => void} [callback] A function to be called after component is + * re-rendered + */ +BaseComponent.prototype.forceUpdate = function (callback) { + if (this._vnode) { + // Set render mode so that we can differentiate where the render request + // is coming from. We need this because forceUpdate should never call + // shouldComponentUpdate + this._force = true; + if (callback) this._renderCallbacks.push(callback); + enqueueRender(this); + } +}; + +/** + * Accepts `props` and `state`, and returns a new Virtual DOM tree to build. + * Virtual DOM is generally constructed via [JSX](https://jasonformat.com/wtf-is-jsx). + * @param {object} props Props (eg: JSX attributes) received from parent + * element/component + * @param {object} state The component's current state + * @param {object} context Context object, as returned by the nearest + * ancestor's `getChildContext()` + * @returns {ComponentChildren | void} + */ +BaseComponent.prototype.render = Fragment; + +/** + * @param {import('./internal').VNode} vnode + * @param {number | null} [childIndex] + */ +export function getDomSibling(vnode, childIndex) { + if (childIndex == NULL) { + // Use childIndex==null as a signal to resume the search from the vnode's sibling + return vnode._parent + ? getDomSibling(vnode._parent, vnode._index + 1) + : NULL; + } + + let sibling; + for (; childIndex < vnode._children.length; childIndex++) { + sibling = vnode._children[childIndex]; + + if (sibling != NULL && sibling._dom != NULL) { + // Since updateParentDomPointers keeps _dom pointer correct, + // we can rely on _dom to tell us if this subtree contains a + // rendered DOM node, and what the first rendered DOM node is + return sibling._dom; + } + } + + // If we get here, we have not found a DOM node in this vnode's children. + // We must resume from this vnode's sibling (in it's parent _children array) + // Only climb up and search the parent if we aren't searching through a DOM + // VNode (meaning we reached the DOM parent of the original vnode that began + // the search) + return typeof vnode.type == 'function' ? getDomSibling(vnode) : NULL; +} + +/** + * Trigger in-place re-rendering of a component. + * @param {import('./internal').Component} component The component to rerender + */ +function renderComponent(component) { + let oldVNode = component._vnode, + oldDom = oldVNode._dom, + commitQueue = [], + refQueue = []; + + if (component._parentDom) { + const newVNode = assign({}, oldVNode); + newVNode._original = oldVNode._original + 1; + if (options.vnode) options.vnode(newVNode); + + diff( + component._parentDom, + newVNode, + oldVNode, + component._globalContext, + component._parentDom.namespaceURI, + oldVNode._flags & MODE_HYDRATE ? [oldDom] : NULL, + commitQueue, + oldDom == NULL ? getDomSibling(oldVNode) : oldDom, + !!(oldVNode._flags & MODE_HYDRATE), + refQueue + ); + + newVNode._original = oldVNode._original; + newVNode._parent._children[newVNode._index] = newVNode; + commitRoot(commitQueue, newVNode, refQueue); + oldVNode._dom = oldVNode._parent = null; + + if (newVNode._dom != oldDom) { + updateParentDomPointers(newVNode); + } + } +} + +/** + * @param {import('./internal').VNode} vnode + */ +function updateParentDomPointers(vnode) { + if ((vnode = vnode._parent) != NULL && vnode._component != NULL) { + vnode._dom = vnode._component.base = NULL; + for (let i = 0; i < vnode._children.length; i++) { + let child = vnode._children[i]; + if (child != NULL && child._dom != NULL) { + vnode._dom = vnode._component.base = child._dom; + break; + } + } + + return updateParentDomPointers(vnode); + } +} + +/** + * The render queue + * @type {Array} + */ +let rerenderQueue = []; + +/* + * The value of `Component.debounce` must asynchronously invoke the passed in callback. It is + * important that contributors to Preact can consistently reason about what calls to `setState`, etc. + * do, and when their effects will be applied. See the links below for some further reading on designing + * asynchronous APIs. + * * [Designing APIs for Asynchrony](https://blog.izs.me/2013/08/designing-apis-for-asynchrony) + * * [Callbacks synchronous and asynchronous](https://blog.ometer.com/2011/07/24/callbacks-synchronous-and-asynchronous/) + */ + +let prevDebounce; + +const defer = + typeof Promise == 'function' + ? Promise.prototype.then.bind(Promise.resolve()) + : setTimeout; + +/** + * Enqueue a rerender of a component + * @param {import('./internal').Component} c The component to rerender + */ +export function enqueueRender(c) { + if ( + (!c._dirty && + (c._dirty = true) && + rerenderQueue.push(c) && + !process._rerenderCount++) || + prevDebounce != options.debounceRendering + ) { + prevDebounce = options.debounceRendering; + (prevDebounce || defer)(process); + } +} + +/** + * @param {import('./internal').Component} a + * @param {import('./internal').Component} b + */ +const depthSort = (a, b) => a._vnode._depth - b._vnode._depth; + +/** Flush the render queue by rerendering all queued components */ +function process() { + let c, + l = 1; + + // Don't update `renderCount` yet. Keep its value non-zero to prevent unnecessary + // process() calls from getting scheduled while `queue` is still being consumed. + while (rerenderQueue.length) { + // Keep the rerender queue sorted by (depth, insertion order). The queue + // will initially be sorted on the first iteration only if it has more than 1 item. + // + // New items can be added to the queue e.g. when rerendering a provider, so we want to + // keep the order from top to bottom with those new items so we can handle them in a + // single pass + if (rerenderQueue.length > l) { + rerenderQueue.sort(depthSort); + } + + c = rerenderQueue.shift(); + l = rerenderQueue.length; + + if (c._dirty) { + renderComponent(c); + } + } + process._rerenderCount = 0; +} + +process._rerenderCount = 0; diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/src/constants.js b/browser/base/content/assistant/ui-preact/node_modules/preact/src/constants.js new file mode 100644 index 0000000000000..c60df07b931bc --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/src/constants.js @@ -0,0 +1,22 @@ +/** Normal hydration that attaches to a DOM tree but does not diff it. */ +export const MODE_HYDRATE = 1 << 5; +/** Signifies this VNode suspended on the previous render */ +export const MODE_SUSPENDED = 1 << 7; +/** Indicates that this node needs to be inserted while patching children */ +export const INSERT_VNODE = 1 << 2; +/** Indicates a VNode has been matched with another VNode in the diff */ +export const MATCHED = 1 << 1; + +/** Reset all mode flags */ +export const RESET_MODE = ~(MODE_HYDRATE | MODE_SUSPENDED); + +export const SVG_NAMESPACE = 'http://www.w3.org/2000/svg'; +export const XHTML_NAMESPACE = 'http://www.w3.org/1999/xhtml'; +export const MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML'; + +export const NULL = null; +export const UNDEFINED = undefined; +export const EMPTY_OBJ = /** @type {any} */ ({}); +export const EMPTY_ARR = []; +export const IS_NON_DIMENSIONAL = + /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i; diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/src/create-context.js b/browser/base/content/assistant/ui-preact/node_modules/preact/src/create-context.js new file mode 100644 index 0000000000000..851b95acbc95c --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/src/create-context.js @@ -0,0 +1,60 @@ +import { enqueueRender } from './component'; +import { NULL } from './constants'; + +export let i = 0; + +export function createContext(defaultValue) { + function Context(props) { + if (!this.getChildContext) { + /** @type {Set | null} */ + let subs = new Set(); + let ctx = {}; + ctx[Context._id] = this; + + this.getChildContext = () => ctx; + + this.componentWillUnmount = () => { + subs = NULL; + }; + + this.shouldComponentUpdate = function (_props) { + // @ts-expect-error even + if (this.props.value != _props.value) { + subs.forEach(c => { + c._force = true; + enqueueRender(c); + }); + } + }; + + this.sub = c => { + subs.add(c); + let old = c.componentWillUnmount; + c.componentWillUnmount = () => { + if (subs) { + subs.delete(c); + } + if (old) old.call(c); + }; + }; + } + + return props.children; + } + + Context._id = '__cC' + i++; + Context._defaultValue = defaultValue; + + /** @type {import('./internal').FunctionComponent} */ + Context.Consumer = (props, contextValue) => { + return props.children(contextValue); + }; + + // we could also get rid of _contextRef entirely + Context.Provider = + Context._contextRef = + Context.Consumer.contextType = + Context; + + return Context; +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/src/create-element.js b/browser/base/content/assistant/ui-preact/node_modules/preact/src/create-element.js new file mode 100644 index 0000000000000..53376382317fa --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/src/create-element.js @@ -0,0 +1,97 @@ +import { slice } from './util'; +import options from './options'; +import { NULL, UNDEFINED } from './constants'; + +let vnodeId = 0; + +/** + * Create an virtual node (used for JSX) + * @param {import('./internal').VNode["type"]} type The node name or Component constructor for this + * virtual node + * @param {object | null | undefined} [props] The properties of the virtual node + * @param {Array} [children] The children of the + * virtual node + * @returns {import('./internal').VNode} + */ +export function createElement(type, props, children) { + let normalizedProps = {}, + key, + ref, + i; + for (i in props) { + if (i == 'key') key = props[i]; + else if (i == 'ref') ref = props[i]; + else normalizedProps[i] = props[i]; + } + + if (arguments.length > 2) { + normalizedProps.children = + arguments.length > 3 ? slice.call(arguments, 2) : children; + } + + // If a Component VNode, check for and apply defaultProps + // Note: type may be undefined in development, must never error here. + if (typeof type == 'function' && type.defaultProps != NULL) { + for (i in type.defaultProps) { + if (normalizedProps[i] === UNDEFINED) { + normalizedProps[i] = type.defaultProps[i]; + } + } + } + + return createVNode(type, normalizedProps, key, ref, NULL); +} + +/** + * Create a VNode (used internally by Preact) + * @param {import('./internal').VNode["type"]} type The node name or Component + * Constructor for this virtual node + * @param {object | string | number | null} props The properties of this virtual node. + * If this virtual node represents a text node, this is the text of the node (string or number). + * @param {string | number | null} key The key for this virtual node, used when + * diffing it against its children + * @param {import('./internal').VNode["ref"]} ref The ref property that will + * receive a reference to its created child + * @returns {import('./internal').VNode} + */ +export function createVNode(type, props, key, ref, original) { + // V8 seems to be better at detecting type shapes if the object is allocated from the same call site + // Do not inline into createElement and coerceToVNode! + /** @type {import('./internal').VNode} */ + const vnode = { + type, + props, + key, + ref, + _children: NULL, + _parent: NULL, + _depth: 0, + _dom: NULL, + _component: NULL, + constructor: UNDEFINED, + _original: original == NULL ? ++vnodeId : original, + _index: -1, + _flags: 0 + }; + + // Only invoke the vnode hook if this was *not* a direct copy: + if (original == NULL && options.vnode != NULL) options.vnode(vnode); + + return vnode; +} + +export function createRef() { + return { current: NULL }; +} + +export function Fragment(props) { + return props.children; +} + +/** + * Check if a the argument is a valid Preact VNode. + * @param {*} vnode + * @returns {vnode is VNode} + */ +export const isValidElement = vnode => + vnode != NULL && vnode.constructor === UNDEFINED; diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/src/diff/catch-error.js b/browser/base/content/assistant/ui-preact/node_modules/preact/src/diff/catch-error.js new file mode 100644 index 0000000000000..ada46f1942cfb --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/src/diff/catch-error.js @@ -0,0 +1,46 @@ +import { NULL } from '../constants'; + +/** + * Find the closest error boundary to a thrown error and call it + * @param {object} error The thrown value + * @param {import('../internal').VNode} vnode The vnode that threw the error that was caught (except + * for unmounting when this parameter is the highest parent that was being + * unmounted) + * @param {import('../internal').VNode} [oldVNode] + * @param {import('../internal').ErrorInfo} [errorInfo] + */ +export function _catchError(error, vnode, oldVNode, errorInfo) { + /** @type {import('../internal').Component} */ + let component, + /** @type {import('../internal').ComponentType} */ + ctor, + /** @type {boolean} */ + handled; + + for (; (vnode = vnode._parent); ) { + if ((component = vnode._component) && !component._processingException) { + try { + ctor = component.constructor; + + if (ctor && ctor.getDerivedStateFromError != NULL) { + component.setState(ctor.getDerivedStateFromError(error)); + handled = component._dirty; + } + + if (component.componentDidCatch != NULL) { + component.componentDidCatch(error, errorInfo || {}); + handled = component._dirty; + } + + // This is an error boundary. Mark it as having bailed out, and whether it was mid-hydration. + if (handled) { + return (component._pendingError = component); + } + } catch (e) { + error = e; + } + } + } + + throw error; +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/src/diff/children.js b/browser/base/content/assistant/ui-preact/node_modules/preact/src/diff/children.js new file mode 100644 index 0000000000000..e8965f2b77204 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/src/diff/children.js @@ -0,0 +1,451 @@ +import { diff, unmount, applyRef } from './index'; +import { createVNode, Fragment } from '../create-element'; +import { + EMPTY_OBJ, + EMPTY_ARR, + INSERT_VNODE, + MATCHED, + UNDEFINED, + NULL +} from '../constants'; +import { isArray } from '../util'; +import { getDomSibling } from '../component'; + +/** + * @typedef {import('../internal').ComponentChildren} ComponentChildren + * @typedef {import('../internal').Component} Component + * @typedef {import('../internal').PreactElement} PreactElement + * @typedef {import('../internal').VNode} VNode + */ + +/** + * Diff the children of a virtual node + * @param {PreactElement} parentDom The DOM element whose children are being + * diffed + * @param {ComponentChildren[]} renderResult + * @param {VNode} newParentVNode The new virtual node whose children should be + * diff'ed against oldParentVNode + * @param {VNode} oldParentVNode The old virtual node whose children should be + * diff'ed against newParentVNode + * @param {object} globalContext The current context object - modified by + * getChildContext + * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML) + * @param {Array} excessDomChildren + * @param {Array} commitQueue List of components which have callbacks + * to invoke in commitRoot + * @param {PreactElement} oldDom The current attached DOM element any new dom + * elements should be placed around. Likely `null` on first render (except when + * hydrating). Can be a sibling DOM element when diffing Fragments that have + * siblings. In most cases, it starts out as `oldChildren[0]._dom`. + * @param {boolean} isHydrating Whether or not we are in hydration + * @param {any[]} refQueue an array of elements needed to invoke refs + */ +export function diffChildren( + parentDom, + renderResult, + newParentVNode, + oldParentVNode, + globalContext, + namespace, + excessDomChildren, + commitQueue, + oldDom, + isHydrating, + refQueue +) { + let i, + /** @type {VNode} */ + oldVNode, + /** @type {VNode} */ + childVNode, + /** @type {PreactElement} */ + newDom, + /** @type {PreactElement} */ + firstChildDom; + + // This is a compression of oldParentVNode!=null && oldParentVNode != EMPTY_OBJ && oldParentVNode._children || EMPTY_ARR + // as EMPTY_OBJ._children should be `undefined`. + /** @type {VNode[]} */ + let oldChildren = (oldParentVNode && oldParentVNode._children) || EMPTY_ARR; + + let newChildrenLength = renderResult.length; + + oldDom = constructNewChildrenArray( + newParentVNode, + renderResult, + oldChildren, + oldDom, + newChildrenLength + ); + + for (i = 0; i < newChildrenLength; i++) { + childVNode = newParentVNode._children[i]; + if (childVNode == NULL) continue; + + // At this point, constructNewChildrenArray has assigned _index to be the + // matchingIndex for this VNode's oldVNode (or -1 if there is no oldVNode). + if (childVNode._index == -1) { + oldVNode = EMPTY_OBJ; + } else { + oldVNode = oldChildren[childVNode._index] || EMPTY_OBJ; + } + + // Update childVNode._index to its final index + childVNode._index = i; + + // Morph the old element into the new one, but don't append it to the dom yet + let result = diff( + parentDom, + childVNode, + oldVNode, + globalContext, + namespace, + excessDomChildren, + commitQueue, + oldDom, + isHydrating, + refQueue + ); + + // Adjust DOM nodes + newDom = childVNode._dom; + if (childVNode.ref && oldVNode.ref != childVNode.ref) { + if (oldVNode.ref) { + applyRef(oldVNode.ref, NULL, childVNode); + } + refQueue.push( + childVNode.ref, + childVNode._component || newDom, + childVNode + ); + } + + if (firstChildDom == NULL && newDom != NULL) { + firstChildDom = newDom; + } + + let shouldPlace = !!(childVNode._flags & INSERT_VNODE); + if (shouldPlace || oldVNode._children === childVNode._children) { + oldDom = insert(childVNode, oldDom, parentDom, shouldPlace); + } else if (typeof childVNode.type == 'function' && result !== UNDEFINED) { + oldDom = result; + } else if (newDom) { + oldDom = newDom.nextSibling; + } + + // Unset diffing flags + childVNode._flags &= ~(INSERT_VNODE | MATCHED); + } + + newParentVNode._dom = firstChildDom; + + return oldDom; +} + +/** + * @param {VNode} newParentVNode + * @param {ComponentChildren[]} renderResult + * @param {VNode[]} oldChildren + */ +function constructNewChildrenArray( + newParentVNode, + renderResult, + oldChildren, + oldDom, + newChildrenLength +) { + /** @type {number} */ + let i; + /** @type {VNode} */ + let childVNode; + /** @type {VNode} */ + let oldVNode; + + let oldChildrenLength = oldChildren.length, + remainingOldChildren = oldChildrenLength; + + let skew = 0; + + newParentVNode._children = new Array(newChildrenLength); + for (i = 0; i < newChildrenLength; i++) { + // @ts-expect-error We are reusing the childVNode variable to hold both the + // pre and post normalized childVNode + childVNode = renderResult[i]; + + if ( + childVNode == NULL || + typeof childVNode == 'boolean' || + typeof childVNode == 'function' + ) { + newParentVNode._children[i] = NULL; + continue; + } + // If this newVNode is being reused (e.g.

    {reuse}{reuse}
    ) in the same diff, + // or we are rendering a component (e.g. setState) copy the oldVNodes so it can have + // it's own DOM & etc. pointers + else if ( + typeof childVNode == 'string' || + typeof childVNode == 'number' || + // eslint-disable-next-line valid-typeof + typeof childVNode == 'bigint' || + childVNode.constructor == String + ) { + childVNode = newParentVNode._children[i] = createVNode( + NULL, + childVNode, + NULL, + NULL, + NULL + ); + } else if (isArray(childVNode)) { + childVNode = newParentVNode._children[i] = createVNode( + Fragment, + { children: childVNode }, + NULL, + NULL, + NULL + ); + } else if (childVNode.constructor === UNDEFINED && childVNode._depth > 0) { + // VNode is already in use, clone it. This can happen in the following + // scenario: + // const reuse =
    + //
    {reuse}{reuse}
    + childVNode = newParentVNode._children[i] = createVNode( + childVNode.type, + childVNode.props, + childVNode.key, + childVNode.ref ? childVNode.ref : NULL, + childVNode._original + ); + } else { + newParentVNode._children[i] = childVNode; + } + + const skewedIndex = i + skew; + childVNode._parent = newParentVNode; + childVNode._depth = newParentVNode._depth + 1; + + // Temporarily store the matchingIndex on the _index property so we can pull + // out the oldVNode in diffChildren. We'll override this to the VNode's + // final index after using this property to get the oldVNode + const matchingIndex = (childVNode._index = findMatchingIndex( + childVNode, + oldChildren, + skewedIndex, + remainingOldChildren + )); + + oldVNode = NULL; + if (matchingIndex != -1) { + oldVNode = oldChildren[matchingIndex]; + remainingOldChildren--; + if (oldVNode) { + oldVNode._flags |= MATCHED; + } + } + + // Here, we define isMounting for the purposes of the skew diffing + // algorithm. Nodes that are unsuspending are considered mounting and we detect + // this by checking if oldVNode._original == null + const isMounting = oldVNode == NULL || oldVNode._original == NULL; + + if (isMounting) { + if (matchingIndex == -1) { + // When the array of children is growing we need to decrease the skew + // as we are adding a new element to the array. + // Example: + // [1, 2, 3] --> [0, 1, 2, 3] + // oldChildren newChildren + // + // The new element is at index 0, so our skew is 0, + // we need to decrease the skew as we are adding a new element. + // The decrease will cause us to compare the element at position 1 + // with value 1 with the element at position 0 with value 0. + // + // A linear concept is applied when the array is shrinking, + // if the length is unchanged we can assume that no skew + // changes are needed. + if (newChildrenLength > oldChildrenLength) { + skew--; + } else if (newChildrenLength < oldChildrenLength) { + skew++; + } + } + + // If we are mounting a DOM VNode, mark it for insertion + if (typeof childVNode.type != 'function') { + childVNode._flags |= INSERT_VNODE; + } + } else if (matchingIndex != skewedIndex) { + // When we move elements around i.e. [0, 1, 2] --> [1, 0, 2] + // --> we diff 1, we find it at position 1 while our skewed index is 0 and our skew is 0 + // we set the skew to 1 as we found an offset. + // --> we diff 0, we find it at position 0 while our skewed index is at 2 and our skew is 1 + // this makes us increase the skew again. + // --> we diff 2, we find it at position 2 while our skewed index is at 4 and our skew is 2 + // + // this becomes an optimization question where currently we see a 1 element offset as an insertion + // or deletion i.e. we optimize for [0, 1, 2] --> [9, 0, 1, 2] + // while a more than 1 offset we see as a swap. + // We could probably build heuristics for having an optimized course of action here as well, but + // might go at the cost of some bytes. + // + // If we wanted to optimize for i.e. only swaps we'd just do the last two code-branches and have + // only the first item be a re-scouting and all the others fall in their skewed counter-part. + // We could also further optimize for swaps + if (matchingIndex == skewedIndex - 1) { + skew--; + } else if (matchingIndex == skewedIndex + 1) { + skew++; + } else { + if (matchingIndex > skewedIndex) { + skew--; + } else { + skew++; + } + + // Move this VNode's DOM if the original index (matchingIndex) doesn't + // match the new skew index (i + new skew) + // In the former two branches we know that it matches after skewing + childVNode._flags |= INSERT_VNODE; + } + } + } + + // Remove remaining oldChildren if there are any. Loop forwards so that as we + // unmount DOM from the beginning of the oldChildren, we can adjust oldDom to + // point to the next child, which needs to be the first DOM node that won't be + // unmounted. + if (remainingOldChildren) { + for (i = 0; i < oldChildrenLength; i++) { + oldVNode = oldChildren[i]; + if (oldVNode != NULL && (oldVNode._flags & MATCHED) == 0) { + if (oldVNode._dom == oldDom) { + oldDom = getDomSibling(oldVNode); + } + + unmount(oldVNode, oldVNode); + } + } + } + + return oldDom; +} + +/** + * @param {VNode} parentVNode + * @param {PreactElement} oldDom + * @param {PreactElement} parentDom + * @param {boolean} shouldPlace + * @returns {PreactElement} + */ +function insert(parentVNode, oldDom, parentDom, shouldPlace) { + // Note: VNodes in nested suspended trees may be missing _children. + + if (typeof parentVNode.type == 'function') { + let children = parentVNode._children; + for (let i = 0; children && i < children.length; i++) { + if (children[i]) { + // If we enter this code path on sCU bailout, where we copy + // oldVNode._children to newVNode._children, we need to update the old + // children's _parent pointer to point to the newVNode (parentVNode + // here). + children[i]._parent = parentVNode; + oldDom = insert(children[i], oldDom, parentDom, shouldPlace); + } + } + + return oldDom; + } else if (parentVNode._dom != oldDom) { + if (shouldPlace) { + if (oldDom && parentVNode.type && !oldDom.parentNode) { + oldDom = getDomSibling(parentVNode); + } + parentDom.insertBefore(parentVNode._dom, oldDom || NULL); + } + oldDom = parentVNode._dom; + } + + do { + oldDom = oldDom && oldDom.nextSibling; + } while (oldDom != NULL && oldDom.nodeType == 8); + + return oldDom; +} + +/** + * Flatten and loop through the children of a virtual node + * @param {ComponentChildren} children The unflattened children of a virtual + * node + * @returns {VNode[]} + */ +export function toChildArray(children, out) { + out = out || []; + if (children == NULL || typeof children == 'boolean') { + } else if (isArray(children)) { + children.some(child => { + toChildArray(child, out); + }); + } else { + out.push(children); + } + return out; +} + +/** + * @param {VNode} childVNode + * @param {VNode[]} oldChildren + * @param {number} skewedIndex + * @param {number} remainingOldChildren + * @returns {number} + */ +function findMatchingIndex( + childVNode, + oldChildren, + skewedIndex, + remainingOldChildren +) { + const key = childVNode.key; + const type = childVNode.type; + let oldVNode = oldChildren[skewedIndex]; + const matched = oldVNode != NULL && (oldVNode._flags & MATCHED) == 0; + + // We only need to perform a search if there are more children + // (remainingOldChildren) to search. However, if the oldVNode we just looked + // at skewedIndex was not already used in this diff, then there must be at + // least 1 other (so greater than 1) remainingOldChildren to attempt to match + // against. So the following condition checks that ensuring + // remainingOldChildren > 1 if the oldVNode is not already used/matched. Else + // if the oldVNode was null or matched, then there could needs to be at least + // 1 (aka `remainingOldChildren > 0`) children to find and compare against. + // + // If there is an unkeyed functional VNode, that isn't a built-in like our Fragment, + // we should not search as we risk re-using state of an unrelated VNode. (reverted for now) + let shouldSearch = + // (typeof type != 'function' || type === Fragment || key) && + remainingOldChildren > (matched ? 1 : 0); + + if ( + (oldVNode === NULL && key == null) || + (matched && key == oldVNode.key && type == oldVNode.type) + ) { + return skewedIndex; + } else if (shouldSearch) { + let x = skewedIndex - 1; + let y = skewedIndex + 1; + while (x >= 0 || y < oldChildren.length) { + const childIndex = x >= 0 ? x-- : y++; + oldVNode = oldChildren[childIndex]; + if ( + oldVNode != NULL && + (oldVNode._flags & MATCHED) == 0 && + key == oldVNode.key && + type == oldVNode.type + ) { + return childIndex; + } + } + } + + return -1; +} diff --git a/browser/base/content/assistant/ui-preact/node_modules/preact/src/diff/index.js b/browser/base/content/assistant/ui-preact/node_modules/preact/src/diff/index.js new file mode 100644 index 0000000000000..1972ccd42c679 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/node_modules/preact/src/diff/index.js @@ -0,0 +1,684 @@ +import { + EMPTY_OBJ, + MATH_NAMESPACE, + MODE_HYDRATE, + MODE_SUSPENDED, + NULL, + RESET_MODE, + SVG_NAMESPACE, + UNDEFINED, + XHTML_NAMESPACE +} from '../constants'; +import { BaseComponent, getDomSibling } from '../component'; +import { Fragment } from '../create-element'; +import { diffChildren } from './children'; +import { setProperty } from './props'; +import { assign, isArray, removeNode, slice } from '../util'; +import options from '../options'; + +/** + * @typedef {import('../internal').ComponentChildren} ComponentChildren + * @typedef {import('../internal').Component} Component + * @typedef {import('../internal').PreactElement} PreactElement + * @typedef {import('../internal').VNode} VNode + */ + +/** + * @template {any} T + * @typedef {import('../internal').Ref} Ref + */ + +/** + * Diff two virtual nodes and apply proper changes to the DOM + * @param {PreactElement} parentDom The parent of the DOM element + * @param {VNode} newVNode The new virtual node + * @param {VNode} oldVNode The old virtual node + * @param {object} globalContext The current context object. Modified by + * getChildContext + * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML) + * @param {Array} excessDomChildren + * @param {Array} commitQueue List of components which have callbacks + * to invoke in commitRoot + * @param {PreactElement} oldDom The current attached DOM element any new dom + * elements should be placed around. Likely `null` on first render (except when + * hydrating). Can be a sibling DOM element when diffing Fragments that have + * siblings. In most cases, it starts out as `oldChildren[0]._dom`. + * @param {boolean} isHydrating Whether or not we are in hydration + * @param {any[]} refQueue an array of elements needed to invoke refs + */ +export function diff( + parentDom, + newVNode, + oldVNode, + globalContext, + namespace, + excessDomChildren, + commitQueue, + oldDom, + isHydrating, + refQueue +) { + /** @type {any} */ + let tmp, + newType = newVNode.type; + + // When passing through createElement it assigns the object + // constructor as undefined. This to prevent JSON-injection. + if (newVNode.constructor !== UNDEFINED) return NULL; + + // If the previous diff bailed out, resume creating/hydrating. + if (oldVNode._flags & MODE_SUSPENDED) { + isHydrating = !!(oldVNode._flags & MODE_HYDRATE); + oldDom = newVNode._dom = oldVNode._dom; + excessDomChildren = [oldDom]; + } + + if ((tmp = options._diff)) tmp(newVNode); + + outer: if (typeof newType == 'function') { + try { + let c, isNew, oldProps, oldState, snapshot, clearProcessingException; + let newProps = newVNode.props; + const isClassComponent = + 'prototype' in newType && newType.prototype.render; + + // Necessary for createContext api. Setting this property will pass + // the context value as `this.context` just for this component. + tmp = newType.contextType; + let provider = tmp && globalContext[tmp._id]; + let componentContext = tmp + ? provider + ? provider.props.value + : tmp._defaultValue + : globalContext; + + // Get component and set it to `c` + if (oldVNode._component) { + c = newVNode._component = oldVNode._component; + clearProcessingException = c._processingException = c._pendingError; + } else { + // Instantiate the new component + if (isClassComponent) { + // @ts-expect-error The check above verifies that newType is suppose to be constructed + newVNode._component = c = new newType(newProps, componentContext); // eslint-disable-line new-cap + } else { + // @ts-expect-error Trust me, Component implements the interface we want + newVNode._component = c = new BaseComponent( + newProps, + componentContext + ); + c.constructor = newType; + c.render = doRender; + } + if (provider) provider.sub(c); + + if (!c.state) c.state = {}; + c._globalContext = globalContext; + isNew = c._dirty = true; + c._renderCallbacks = []; + c._stateCallbacks = []; + } + + // Invoke getDerivedStateFromProps + if (isClassComponent && c._nextState == NULL) { + c._nextState = c.state; + } + + if (isClassComponent && newType.getDerivedStateFromProps != NULL) { + if (c._nextState == c.state) { + c._nextState = assign({}, c._nextState); + } + + assign( + c._nextState, + newType.getDerivedStateFromProps(newProps, c._nextState) + ); + } + + oldProps = c.props; + oldState = c.state; + c._vnode = newVNode; + + // Invoke pre-render lifecycle methods + if (isNew) { + if ( + isClassComponent && + newType.getDerivedStateFromProps == NULL && + c.componentWillMount != NULL + ) { + c.componentWillMount(); + } + + if (isClassComponent && c.componentDidMount != NULL) { + c._renderCallbacks.push(c.componentDidMount); + } + } else { + if ( + isClassComponent && + newType.getDerivedStateFromProps == NULL && + newProps !== oldProps && + c.componentWillReceiveProps != NULL + ) { + c.componentWillReceiveProps(newProps, componentContext); + } + + if ( + newVNode._original == oldVNode._original || + (!c._force && + c.shouldComponentUpdate != NULL && + c.shouldComponentUpdate( + newProps, + c._nextState, + componentContext + ) === false) + ) { + // More info about this here: https://gist.github.com/JoviDeCroock/bec5f2ce93544d2e6070ef8e0036e4e8 + if (newVNode._original != oldVNode._original) { + // When we are dealing with a bail because of sCU we have to update + // the props, state and dirty-state. + // when we are dealing with strict-equality we don't as the child could still + // be dirtied see #3883 + c.props = newProps; + c.state = c._nextState; + c._dirty = false; + } + + newVNode._dom = oldVNode._dom; + newVNode._children = oldVNode._children; + newVNode._children.some(vnode => { + if (vnode) vnode._parent = newVNode; + }); + + for (let i = 0; i < c._stateCallbacks.length; i++) { + c._renderCallbacks.push(c._stateCallbacks[i]); + } + c._stateCallbacks = []; + + if (c._renderCallbacks.length) { + commitQueue.push(c); + } + + break outer; + } + + if (c.componentWillUpdate != NULL) { + c.componentWillUpdate(newProps, c._nextState, componentContext); + } + + if (isClassComponent && c.componentDidUpdate != NULL) { + c._renderCallbacks.push(() => { + c.componentDidUpdate(oldProps, oldState, snapshot); + }); + } + } + + c.context = componentContext; + c.props = newProps; + c._parentDom = parentDom; + c._force = false; + + let renderHook = options._render, + count = 0; + if (isClassComponent) { + c.state = c._nextState; + c._dirty = false; + + if (renderHook) renderHook(newVNode); + + tmp = c.render(c.props, c.state, c.context); + + for (let i = 0; i < c._stateCallbacks.length; i++) { + c._renderCallbacks.push(c._stateCallbacks[i]); + } + c._stateCallbacks = []; + } else { + do { + c._dirty = false; + if (renderHook) renderHook(newVNode); + + tmp = c.render(c.props, c.state, c.context); + + // Handle setState called in render, see #2553 + c.state = c._nextState; + } while (c._dirty && ++count < 25); + } + + // Handle setState called in render, see #2553 + c.state = c._nextState; + + if (c.getChildContext != NULL) { + globalContext = assign(assign({}, globalContext), c.getChildContext()); + } + + if (isClassComponent && !isNew && c.getSnapshotBeforeUpdate != NULL) { + snapshot = c.getSnapshotBeforeUpdate(oldProps, oldState); + } + + let isTopLevelFragment = + tmp != NULL && tmp.type === Fragment && tmp.key == NULL; + let renderResult = tmp; + + if (isTopLevelFragment) { + renderResult = cloneNode(tmp.props.children); + } + + oldDom = diffChildren( + parentDom, + isArray(renderResult) ? renderResult : [renderResult], + newVNode, + oldVNode, + globalContext, + namespace, + excessDomChildren, + commitQueue, + oldDom, + isHydrating, + refQueue + ); + + c.base = newVNode._dom; + + // We successfully rendered this VNode, unset any stored hydration/bailout state: + newVNode._flags &= RESET_MODE; + + if (c._renderCallbacks.length) { + commitQueue.push(c); + } + + if (clearProcessingException) { + c._pendingError = c._processingException = NULL; + } + } catch (e) { + newVNode._original = NULL; + // if hydrating or creating initial tree, bailout preserves DOM: + if (isHydrating || excessDomChildren != NULL) { + if (e.then) { + newVNode._flags |= isHydrating + ? MODE_HYDRATE | MODE_SUSPENDED + : MODE_SUSPENDED; + + while (oldDom && oldDom.nodeType == 8 && oldDom.nextSibling) { + oldDom = oldDom.nextSibling; + } + + excessDomChildren[excessDomChildren.indexOf(oldDom)] = NULL; + newVNode._dom = oldDom; + } else { + for (let i = excessDomChildren.length; i--; ) { + removeNode(excessDomChildren[i]); + } + markAsForce(newVNode); + } + } else { + newVNode._dom = oldVNode._dom; + newVNode._children = oldVNode._children; + if (!e.then) markAsForce(newVNode); + } + options._catchError(e, newVNode, oldVNode); + } + } else if ( + excessDomChildren == NULL && + newVNode._original == oldVNode._original + ) { + newVNode._children = oldVNode._children; + newVNode._dom = oldVNode._dom; + } else { + oldDom = newVNode._dom = diffElementNodes( + oldVNode._dom, + newVNode, + oldVNode, + globalContext, + namespace, + excessDomChildren, + commitQueue, + isHydrating, + refQueue + ); + } + + if ((tmp = options.diffed)) tmp(newVNode); + + return newVNode._flags & MODE_SUSPENDED ? undefined : oldDom; +} + +function markAsForce(vnode) { + if (vnode && vnode._component) vnode._component._force = true; + if (vnode && vnode._children) vnode._children.forEach(markAsForce); +} + +/** + * @param {Array} commitQueue List of components + * which have callbacks to invoke in commitRoot + * @param {VNode} root + */ +export function commitRoot(commitQueue, root, refQueue) { + for (let i = 0; i < refQueue.length; i++) { + applyRef(refQueue[i], refQueue[++i], refQueue[++i]); + } + + if (options._commit) options._commit(root, commitQueue); + + commitQueue.some(c => { + try { + // @ts-expect-error Reuse the commitQueue variable here so the type changes + commitQueue = c._renderCallbacks; + c._renderCallbacks = []; + commitQueue.some(cb => { + // @ts-expect-error See above comment on commitQueue + cb.call(c); + }); + } catch (e) { + options._catchError(e, c._vnode); + } + }); +} + +function cloneNode(node) { + if ( + typeof node != 'object' || + node == NULL || + (node._depth && node._depth > 0) + ) { + return node; + } + + if (isArray(node)) { + return node.map(cloneNode); + } + + return assign({}, node); +} + +/** + * Diff two virtual nodes representing DOM element + * @param {PreactElement} dom The DOM element representing the virtual nodes + * being diffed + * @param {VNode} newVNode The new virtual node + * @param {VNode} oldVNode The old virtual node + * @param {object} globalContext The current context object + * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML) + * @param {Array} excessDomChildren + * @param {Array} commitQueue List of components which have callbacks + * to invoke in commitRoot + * @param {boolean} isHydrating Whether or not we are in hydration + * @param {any[]} refQueue an array of elements needed to invoke refs + * @returns {PreactElement} + */ +function diffElementNodes( + dom, + newVNode, + oldVNode, + globalContext, + namespace, + excessDomChildren, + commitQueue, + isHydrating, + refQueue +) { + let oldProps = oldVNode.props || EMPTY_OBJ; + let newProps = newVNode.props; + let nodeType = /** @type {string} */ (newVNode.type); + /** @type {any} */ + let i; + /** @type {{ __html?: string }} */ + let newHtml; + /** @type {{ __html?: string }} */ + let oldHtml; + /** @type {ComponentChildren} */ + let newChildren; + let value; + let inputValue; + let checked; + + // Tracks entering and exiting namespaces when descending through the tree. + if (nodeType == 'svg') namespace = SVG_NAMESPACE; + else if (nodeType == 'math') namespace = MATH_NAMESPACE; + else if (!namespace) namespace = XHTML_NAMESPACE; + + if (excessDomChildren != NULL) { + for (i = 0; i < excessDomChildren.length; i++) { + value = excessDomChildren[i]; + + // if newVNode matches an element in excessDomChildren or the `dom` + // argument matches an element in excessDomChildren, remove it from + // excessDomChildren so it isn't later removed in diffChildren + if ( + value && + 'setAttribute' in value == !!nodeType && + (nodeType ? value.localName == nodeType : value.nodeType == 3) + ) { + dom = value; + excessDomChildren[i] = NULL; + break; + } + } + } + + if (dom == NULL) { + if (nodeType == NULL) { + return document.createTextNode(newProps); + } + + dom = document.createElementNS( + namespace, + nodeType, + newProps.is && newProps + ); + + // we are creating a new node, so we can assume this is a new subtree (in + // case we are hydrating), this deopts the hydrate + if (isHydrating) { + if (options._hydrationMismatch) + options._hydrationMismatch(newVNode, excessDomChildren); + isHydrating = false; + } + // we created a new parent, so none of the previously attached children can be reused: + excessDomChildren = NULL; + } + + if (nodeType == NULL) { + // During hydration, we still have to split merged text from SSR'd HTML. + if (oldProps !== newProps && (!isHydrating || dom.data != newProps)) { + dom.data = newProps; + } + } else { + // If excessDomChildren was not null, repopulate it with the current element's children: + excessDomChildren = excessDomChildren && slice.call(dom.childNodes); + + // If we are in a situation where we are not hydrating but are using + // existing DOM (e.g. replaceNode) we should read the existing DOM + // attributes to diff them + if (!isHydrating && excessDomChildren != NULL) { + oldProps = {}; + for (i = 0; i < dom.attributes.length; i++) { + value = dom.attributes[i]; + oldProps[value.name] = value.value; + } + } + + for (i in oldProps) { + value = oldProps[i]; + if (i == 'children') { + } else if (i == 'dangerouslySetInnerHTML') { + oldHtml = value; + } else if (!(i in newProps)) { + if ( + (i == 'value' && 'defaultValue' in newProps) || + (i == 'checked' && 'defaultChecked' in newProps) + ) { + continue; + } + setProperty(dom, i, NULL, value, namespace); + } + } + + // During hydration, props are not diffed at all (including dangerouslySetInnerHTML) + // @TODO we should warn in debug mode when props don't match here. + for (i in newProps) { + value = newProps[i]; + if (i == 'children') { + newChildren = value; + } else if (i == 'dangerouslySetInnerHTML') { + newHtml = value; + } else if (i == 'value') { + inputValue = value; + } else if (i == 'checked') { + checked = value; + } else if ( + (!isHydrating || typeof value == 'function') && + oldProps[i] !== value + ) { + setProperty(dom, i, value, oldProps[i], namespace); + } + } + + // If the new vnode didn't have dangerouslySetInnerHTML, diff its children + if (newHtml) { + // Avoid re-applying the same '__html' if it did not changed between re-render + if ( + !isHydrating && + (!oldHtml || + (newHtml.__html != oldHtml.__html && newHtml.__html != dom.innerHTML)) + ) { + dom.innerHTML = newHtml.__html; + } + + newVNode._children = []; + } else { + if (oldHtml) dom.innerHTML = ''; + + diffChildren( + // @ts-expect-error + newVNode.type == 'template' ? dom.content : dom, + isArray(newChildren) ? newChildren : [newChildren], + newVNode, + oldVNode, + globalContext, + nodeType == 'foreignObject' ? XHTML_NAMESPACE : namespace, + excessDomChildren, + commitQueue, + excessDomChildren + ? excessDomChildren[0] + : oldVNode._children && getDomSibling(oldVNode, 0), + isHydrating, + refQueue + ); + + // Remove children that are not part of any vnode. + if (excessDomChildren != NULL) { + for (i = excessDomChildren.length; i--; ) { + removeNode(excessDomChildren[i]); + } + } + } + + // As above, don't diff props during hydration + if (!isHydrating) { + i = 'value'; + if (nodeType == 'progress' && inputValue == NULL) { + dom.removeAttribute('value'); + } else if ( + inputValue != UNDEFINED && + // #2756 For the -element the initial value is 0, + // despite the attribute not being present. When the attribute + // is missing the progress bar is treated as indeterminate. + // To fix that we'll always update it when it is 0 for progress elements + (inputValue !== dom[i] || + (nodeType == 'progress' && !inputValue) || + // This is only for IE 11 to fix ) => + setEmail(e.currentTarget.value) + } + required + className="auth-field-minimal-input" + autoComplete="email" + /> +
    + + {mode !== 'forgotPassword' && ( +
    +
    + + {mode === 'signin' && ( + + )} +
    + ) => + setPassword(e.currentTarget.value) + } + required + className="auth-field-minimal-input" + autoComplete={mode === 'signup' ? 'new-password' : 'current-password'} + /> +
    + )} + + {error && ( +
    {error}
    + )} + + {successMessage && ( +
    {successMessage}
    + )} + + + + )} + + {mode === 'forgotPassword' && ( +
    + +
    + )} +
    +
    + ); +} diff --git a/browser/base/content/assistant/ui-preact/src/components/ChatHistoryPopover.tsx b/browser/base/content/assistant/ui-preact/src/components/ChatHistoryPopover.tsx new file mode 100644 index 0000000000000..f0bc628f85936 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/src/components/ChatHistoryPopover.tsx @@ -0,0 +1,702 @@ +import { h } from "preact"; +import type { JSX } from "preact"; +import { + useCallback, + useEffect, + useLayoutEffect, + useMemo, + useRef, + useState, +} from "preact/hooks"; +import type { ChatConversationRow } from "../chatStore/index"; + +export type ChatHistoryPopoverProps = { + conversations: ChatConversationRow[]; + activeId: string | null; + onSelectConversation: (id: string) => void; + onNewChat: () => void; + onDeleteConversation: (id: string) => void | Promise; +}; + +function startOfLocalDayMs(d: Date): number { + const x = new Date(d); + x.setHours(0, 0, 0, 0); + return x.getTime(); +} + +function groupConversationsByRecency( + conversations: ChatConversationRow[] +): { + today: ChatConversationRow[]; + last7: ChatConversationRow[]; + older: ChatConversationRow[]; +} { + const startToday = startOfLocalDayMs(new Date()); + const startOlderCutoff = startToday - 7 * 86400000; + const today: ChatConversationRow[] = []; + const last7: ChatConversationRow[] = []; + const older: ChatConversationRow[] = []; + for (const c of conversations) { + const t = c.updatedAt; + if (t >= startToday) { + today.push(c); + } else if (t >= startOlderCutoff) { + last7.push(c); + } else { + older.push(c); + } + } + return { today, last7, older }; +} + +const PANEL_ID = "oasis-chat-history-panel"; + +type HistoryPanelLayout = { + top: number; + right: number; + width: number; + maxHeight: string; + transform?: string; +}; + +export function ChatHistoryPopover({ + conversations, + activeId, + onSelectConversation, + onNewChat, + onDeleteConversation, +}: ChatHistoryPopoverProps) { + const [open, setOpen] = useState(false); + const [query, setQuery] = useState(""); + const [searchFocused, setSearchFocused] = useState(false); + const [pendingDelete, setPendingDelete] = useState<{ + id: string; + title: string; + } | null>(null); + const wrapRef = useRef(null); + const panelRef = useRef(null); + const triggerRef = useRef(null); + const searchRef = useRef(null); + const [panelLayout, setPanelLayout] = useState( + null + ); + const lastAppliedKeyRef = useRef(""); + const rafRef = useRef(0); + + const filtered = useMemo(() => { + const q = query.replace(/\s+/g, " ").trim().toLowerCase(); + if (!q) { + return conversations; + } + return conversations.filter(c => + (c.title || "New chat").toLowerCase().includes(q) + ); + }, [conversations, query]); + + const { today, last7, older } = useMemo( + () => groupConversationsByRecency(filtered), + [filtered] + ); + + const close = useCallback(() => { + setOpen(false); + setQuery(""); + setPendingDelete(null); + requestAnimationFrame(() => { + triggerRef.current?.focus(); + }); + }, []); + + const runPendingDelete = useCallback(async () => { + if (!pendingDelete) { + return; + } + const { id } = pendingDelete; + try { + await Promise.resolve(onDeleteConversation(id)); + close(); + } catch (e) { + console.error("oasis delete chat", e); + } + }, [pendingDelete, onDeleteConversation, close]); + + const toggle = useCallback( + (e: MouseEvent) => { + e.preventDefault(); + e.stopPropagation(); + setOpen(o => !o); + }, + [] + ); + + useEffect(() => { + if (!open) { + setSearchFocused(false); + return; + } + const t = window.setTimeout(() => { + searchRef.current?.focus(); + }, 0); + return () => window.clearTimeout(t); + }, [open]); + + const applyPanelLayout = useCallback(() => { + const wrap = wrapRef.current; + const trigger = triggerRef.current; + if (!wrap || !trigger) { + return; + } + const container = wrap.closest(".assistant-container"); + if (!container) { + lastAppliedKeyRef.current = ""; + setPanelLayout(null); + return; + } + const edge = 8; + const cr = container.getBoundingClientRect(); + const tr = trigger.getBoundingClientRect(); + const width = Math.max( + 160, + Math.min(280, Math.floor(cr.width - edge * 2)) + ); + const right = Math.round(window.innerWidth - cr.right + edge); + const top = Math.round(tr.bottom + 6); + const innerW = window.innerWidth; + const leftEdge = innerW - right - width; + const minLeft = cr.left + edge; + const translateX = + leftEdge < minLeft ? Math.round(minLeft - leftEdge) : 0; + const transform = translateX + ? `translateX(${translateX}px)` + : undefined; + const key = `${top}|${right}|${width}|${translateX}`; + if (key === lastAppliedKeyRef.current) { + return; + } + lastAppliedKeyRef.current = key; + setPanelLayout({ + top, + right, + width, + maxHeight: "min(320px, 55vh)", + transform, + }); + }, []); + + useLayoutEffect(() => { + if (!open) { + lastAppliedKeyRef.current = ""; + setPanelLayout(null); + if (rafRef.current) { + cancelAnimationFrame(rafRef.current); + rafRef.current = 0; + } + return; + } + const schedule = () => { + if (rafRef.current) { + cancelAnimationFrame(rafRef.current); + } + rafRef.current = requestAnimationFrame(() => { + rafRef.current = 0; + applyPanelLayout(); + }); + }; + applyPanelLayout(); + const wrap = wrapRef.current; + const container = wrap?.closest(".assistant-container"); + const ro = new ResizeObserver(() => { + schedule(); + }); + if (container) { + ro.observe(container); + } + window.addEventListener("resize", schedule); + return () => { + ro.disconnect(); + window.removeEventListener("resize", schedule); + if (rafRef.current) { + cancelAnimationFrame(rafRef.current); + rafRef.current = 0; + } + }; + }, [open, applyPanelLayout]); + + useEffect(() => { + if (!open) { + return; + } + function onDocMouseDown(ev: MouseEvent) { + const el = wrapRef.current; + if (el && !el.contains(ev.target as Node | null)) { + close(); + } + } + function onKey(ev: KeyboardEvent) { + if (ev.key === "Escape") { + close(); + } + } + document.addEventListener("mousedown", onDocMouseDown); + document.addEventListener("keydown", onKey); + return () => { + document.removeEventListener("mousedown", onDocMouseDown); + document.removeEventListener("keydown", onKey); + }; + }, [open, close]); + + const rowShellStyle = (isActive: boolean): JSX.CSSProperties => ({ + display: "flex", + alignItems: "center", + gap: "2px", + width: "100%", + borderRadius: "var(--border-radius-large)", + boxSizing: "border-box", + background: isActive + ? "color-mix(in srgb, var(--primary-green) 14%, var(--surface-page))" + : "transparent", + }); + + const rowMainStyle: JSX.CSSProperties = { + display: "flex", + alignItems: "center", + gap: "8px", + flex: 1, + minWidth: 0, + padding: "8px 4px 8px 12px", + border: "none", + background: "transparent", + color: "var(--text-headings)", + font: "inherit", + fontSize: "13px", + textAlign: "left", + cursor: "pointer", + borderRadius: "var(--border-radius-large)", + boxSizing: "border-box", + }; + + const deleteBtnStyle: JSX.CSSProperties = { + flexShrink: 0, + width: "32px", + height: "36px", + display: "flex", + alignItems: "center", + justifyContent: "center", + border: "none", + background: "transparent", + color: "var(--text-secondary)", + cursor: "pointer", + borderRadius: "var(--border-radius-large)", + padding: 0, + }; + + const renderSection = (label: string, items: ChatConversationRow[]) => { + if (items.length === 0) { + return null; + } + return ( +
    +
    + {label} +
    +
      + {items.map(c => { + const isActive = c.id === activeId; + const title = c.title?.trim() || "New chat"; + return ( +
    • +
      + ) => { + if (!isActive) { + e.currentTarget.style.background = + "rgba(122, 146, 0, 0.08)"; + } + }} + onMouseLeave={( + e: JSX.TargetedMouseEvent + ) => { + e.currentTarget.style.background = isActive + ? "color-mix(in srgb, var(--primary-green) 14%, var(--surface-page))" + : "transparent"; + }} + > + + +
      +
    • + ); + })} +
    +
    + ); + }; + + const hasAny = + today.length > 0 || last7.length > 0 || older.length > 0; + + return ( +
    + + + {open ? ( + + ) : null} +
    + ); +} diff --git a/browser/base/content/assistant/ui-preact/src/components/ChatTimeline.tsx b/browser/base/content/assistant/ui-preact/src/components/ChatTimeline.tsx new file mode 100644 index 0000000000000..0e36c3d6dbc51 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/src/components/ChatTimeline.tsx @@ -0,0 +1,367 @@ +import { h, Fragment } from 'preact'; +import { useEffect, useRef } from 'preact/hooks'; +import { Feedback } from './Feedback'; +import type { TrainingSubmittedPayload } from './Feedback'; +import { ActiveToolIndicator } from './ActiveToolIndicator'; +import { QuotaLimitCallout } from './QuotaLimitCallout'; +import type { AssistantMessage, OasisWindow } from '../types'; +import { detectQuotaLimitMessage } from '../utils/quotaLimitUi'; +import { + CAPABILITIES_BLOCK_DELIMITER, + CAPABILITIES_OVERVIEW_FIRST_LINE, + OASIS_CAPABILITIES_FEATURES_URL, + OASIS_CAPABILITIES_LINK_LABEL, + OASIS_CAPABILITIES_FEEDBACK_URL, + OASIS_CAPABILITIES_FEEDBACK_LINK_LABEL, +} from '../../../shared/capabilitiesOverviewConstants.js'; + +const oasisWindow: OasisWindow = window; + +function stripTrailingCapabilityUrls(text: string): { + body: string; + showKahana: boolean; + showTally: boolean; +} { + let t = text.trimEnd(); + let showTally = false; + let showKahana = false; + if (t.endsWith(OASIS_CAPABILITIES_FEEDBACK_URL)) { + t = t.slice(0, -OASIS_CAPABILITIES_FEEDBACK_URL.length).trimEnd(); + showTally = true; + } + if (t.endsWith(OASIS_CAPABILITIES_FEATURES_URL)) { + t = t.slice(0, -OASIS_CAPABILITIES_FEATURES_URL.length).trimEnd(); + showKahana = true; + } + return { body: t.trimEnd(), showKahana, showTally }; +} + +function parseCapabilitiesOverviewContent(content: string): { + blocks: string[]; + showKahana: boolean; + showTally: boolean; +} { + const parts = content.split(CAPABILITIES_BLOCK_DELIMITER); + if (parts.length === 0) { + return { blocks: [], showKahana: false, showTally: false }; + } + const lastIdx = parts.length - 1; + const { body, showKahana, showTally } = stripTrailingCapabilityUrls(parts[lastIdx] ?? ''); + const blocks = [...parts.slice(0, lastIdx), body].filter(b => b.trim().length > 0); + return { blocks, showKahana, showTally }; +} + +function userPromptBefore(messages: AssistantMessage[], aiIndex: number): string { + for (let i = aiIndex - 1; i >= 0; i--) { + if (messages[i].role === 'user') { + return messages[i].content; + } + } + return ''; +} + +export function ChatTimeline({ + messages, + isAuthenticated, + busy, + activeToolLabel, + responseStreaming, + onLinkClick, + speakingMsgId, + onTtsClick, + onTrainingSubmitted, + trainingFocusTick, + trainingFocusMessageId, +}: { + messages: AssistantMessage[]; + isAuthenticated: boolean; + busy: boolean; + activeToolLabel: string | null; + responseStreaming: boolean; + onLinkClick: (event: MouseEvent) => void; + speakingMsgId?: string | null; + onTtsClick?: (messageId: string, content: string) => void; + onTrainingSubmitted?: (payload: TrainingSubmittedPayload) => void; + trainingFocusTick?: number; + trainingFocusMessageId?: string; +}) { + const logRef = useRef(null); + const lastAiRef = useRef(null); + + useEffect(() => { + const log = logRef.current; + if (!log) { + return; + } + const last = messages[messages.length - 1]; + const shouldSnapToTopOfLastAi = + !busy && + !responseStreaming && + !activeToolLabel && + last?.role === 'ai' && + last.content.length > 0; + + if (shouldSnapToTopOfLastAi) { + requestAnimationFrame(() => { + lastAiRef.current?.scrollIntoView({ block: 'start', behavior: 'auto', inline: 'nearest' }); + }); + return; + } + log.scrollTop = log.scrollHeight; + }, [messages, busy, activeToolLabel, responseStreaming]); + + useEffect(() => { + const tick = trainingFocusTick ?? 0; + const mid = trainingFocusMessageId ?? ''; + if (tick === 0 || !mid) { + return; + } + const raf = requestAnimationFrame(() => { + const safe = + typeof CSS !== 'undefined' && typeof CSS.escape === 'function' + ? CSS.escape(mid) + : mid.replace(/\\/g, '\\\\').replace(/"/g, '\\"'); + const el = document.querySelector(`[data-oasis-assistant-msg="${safe}"]`); + if (!el || !(el instanceof HTMLElement)) { + return; + } + const log = logRef.current; + el.scrollIntoView({ behavior: 'smooth', block: 'end', inline: 'nearest' }); + requestAnimationFrame(() => { + log?.scrollTo({ top: log.scrollHeight, behavior: 'smooth' }); + }); + }); + return () => { + cancelAnimationFrame(raf); + }; + }, [trainingFocusTick, trainingFocusMessageId]); + + const emptySignedIn = messages.length === 0 && isAuthenticated; + + return ( +
    + {messages.length === 0 && !isAuthenticated && ( +
    +

    + Try a suggestion in the box below, or type your own request. +

    +
    + +
    +
    + )} + + {messages.map((message, index) => { + const isLast = index === messages.length - 1; + + if (message.role === 'user') { + return ( +
    +
    + {message.content} +
    +
    + ); + } + + if (message.role === 'ai') { + const quotaVariant = detectQuotaLimitMessage(message.content); + if (quotaVariant) { + return ( + +
    +
    + +
    +
    +
    + ); + } + + const isCapabilitiesOverview = + message.content.startsWith(CAPABILITIES_OVERVIEW_FIRST_LINE) || + message.content.startsWith('## What Oasis can do'); + const isLegacyCapabilitiesBubbles = + isCapabilitiesOverview && message.content.includes(CAPABILITIES_BLOCK_DELIMITER); + + let useMarkdownHtml = Boolean( + oasisWindow.marked && + oasisWindow.DOMPurify && + !(isCapabilitiesOverview && isLegacyCapabilitiesBubbles) + ); + let htmlContent = ''; + if (useMarkdownHtml) { + try { + const raw = oasisWindow.marked!.parse(message.content); + htmlContent = oasisWindow.DOMPurify!.sanitize(raw); + } catch { + useMarkdownHtml = false; + } + } + + const capabilitiesParsed = isLegacyCapabilitiesBubbles + ? parseCapabilitiesOverviewContent(message.content) + : null; + + const markdownBodyClass = + isCapabilitiesOverview && !isLegacyCapabilitiesBubbles + ? 'markdown-body capabilities-markdown' + : 'markdown-body'; + + return ( + +
    +
    + {useMarkdownHtml && htmlContent ? ( + +
    + {!busy && message.content && onTtsClick && ( + + )} + {message.content && (!isLast || !busy) ? ( + + ) : null} +
    +
    + + ); + } + + return null; + })} + + {(busy || activeToolLabel) && ( + + )} +
    + ); +} diff --git a/browser/base/content/assistant/ui-preact/src/components/Composer.tsx b/browser/base/content/assistant/ui-preact/src/components/Composer.tsx new file mode 100644 index 0000000000000..bfba197bb6f64 --- /dev/null +++ b/browser/base/content/assistant/ui-preact/src/components/Composer.tsx @@ -0,0 +1,308 @@ +import { h } from 'preact'; +import type { Ref } from 'preact'; +import { useState } from 'preact/hooks'; +import { TokenUsageBar } from './TokenUsageBar'; +import { + EXAMPLE_COMMANDS_ROTATION, + type ComposerInlineSuggestion, +} from '../utils/exampleCommands'; +import { useReducedMotionPreference, useTypewriterCycle } from '../hooks/useTypewriterCycle'; + +const COMPOSER_PLACEHOLDER = 'Send follow-up'; + +const COMPOSER_INPUT_ARIA = + 'Message composer. Type a request, use the Up arrow to recall previous commands, or tap a suggestion chip.'; + +export function Composer({ + input, + busy, + isAuthenticated, + chatIsEmpty, + ttsEnabled, + inputRef, + showInlineChips, + inlineSuggestions, + highlightInlineChips, + onInlineSuggestionSend, + onInput, + onKeyDown, + onSend, + onResetSession, + onFeedback, + onToggleTts, + onOpenVoiceAgent, + onRequestSignIn, + onOpenTraining, + showTrainLatestComposerHint, + onDismissTrainLatestHint, + onInsertCapabilities, +}: { + input: string; + busy: boolean; + isAuthenticated: boolean; + chatIsEmpty: boolean; + ttsEnabled: boolean; + inputRef?: Ref; + showInlineChips?: boolean; + inlineSuggestions?: readonly ComposerInlineSuggestion[]; + highlightInlineChips?: boolean; + onInlineSuggestionSend?: (text: string) => void; + onInput: (value: string) => void; + onKeyDown: (event: KeyboardEvent) => void; + onSend: () => void; + onResetSession: () => void; + onFeedback: () => void; + onToggleTts: () => void; + onOpenVoiceAgent: () => void; + onRequestSignIn?: () => void; + onOpenTraining?: () => void; + showTrainLatestComposerHint?: boolean; + onDismissTrainLatestHint?: () => void; + onInsertCapabilities?: () => void; +}) { + const [inputFocused, setInputFocused] = useState(false); + const reducedMotion = useReducedMotionPreference(); + const typewriterActive = + chatIsEmpty && + isAuthenticated && + !busy && + input === '' && + !inputFocused; + const typewriterText = useTypewriterCycle( + EXAMPLE_COMMANDS_ROTATION, + typewriterActive, + reducedMotion + ); + const placeholderText = typewriterActive ? '' : COMPOSER_PLACEHOLDER; + const chipsVisible = + isAuthenticated && + !!showInlineChips && + !busy && + inlineSuggestions && + inlineSuggestions.length > 0; + + const onInlineChipClick = (text: string) => { + if (onInlineSuggestionSend) { + onInlineSuggestionSend(text); + return; + } + onInput(text); + requestAnimationFrame(() => { + if (inputRef && typeof inputRef === 'object' && 'current' in inputRef) { + const ta = inputRef.current; + if (ta) { + ta.focus(); + } + } + }); + }; + + const emptySignedChat = isAuthenticated && chatIsEmpty; + + return ( +
    + {showTrainLatestComposerHint ? ( +
    + + Ask Oasis something first, then use Train on the reply to earn bonus tokens. + + +
    + ) : null} + {isAuthenticated && ( + + )} + {!isAuthenticated ? ( +
    + + +
    + ) : ( +
    { + if (busy) { + return; + } + const t = event.target as HTMLElement | null; + if (!t || t.closest('button') || t.closest('textarea')) { + return; + } + if (inputRef && typeof inputRef === 'object' && 'current' in inputRef) { + inputRef.current?.focus(); + } + }} + > +
    + {typewriterActive && ( + + )} +
    should have a
    should have a